xref: /netbsd-src/external/gpl3/binutils/dist/bfd/elf.c (revision dd7241df2fae9da4ea2bd20a68f001fa86ecf909)
1 /* ELF executable support for BFD.
2 
3    Copyright (C) 1993-2024 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 <limits.h>
39 #include "bfd.h"
40 #include "bfdlink.h"
41 #include "libbfd.h"
42 #define ARCH_SIZE 0
43 #include "elf-bfd.h"
44 #include "libiberty.h"
45 #include "safe-ctype.h"
46 #include "elf-linux-core.h"
47 
48 #ifdef CORE_HEADER
49 #include CORE_HEADER
50 #endif
51 
52 static int elf_sort_sections (const void *, const void *);
53 static bool assign_file_positions_except_relocs (bfd *, struct bfd_link_info *);
54 static bool swap_out_syms (bfd *, struct elf_strtab_hash **, int,
55 			   struct bfd_link_info *);
56 static bool elf_parse_notes (bfd *abfd, char *buf, size_t size,
57 			     file_ptr offset, size_t align);
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   uint32_t h = 0;
200 
201   for (const unsigned char *name = (const unsigned char *) namearg;
202        *name; name++)
203     {
204       h = (h << 4) + *name;
205       h ^= (h >> 24) & 0xf0;
206     }
207   return h & 0x0fffffff;
208 }
209 
210 /* DT_GNU_HASH hash function.  Do not change this function; you will
211    cause invalid hash tables to be generated.  */
212 
213 unsigned long
bfd_elf_gnu_hash(const char * namearg)214 bfd_elf_gnu_hash (const char *namearg)
215 {
216   uint32_t h = 5381;
217 
218   for (const unsigned char *name = (const unsigned char *) namearg;
219        *name; name++)
220     h = (h << 5) + h + *name;
221   return h;
222 }
223 
224 /* Create a tdata field OBJECT_SIZE bytes in length, zeroed out and with
225    the object_id field of an elf_obj_tdata field set to OBJECT_ID.  */
226 bool
bfd_elf_allocate_object(bfd * abfd,size_t object_size,enum elf_target_id object_id)227 bfd_elf_allocate_object (bfd *abfd,
228 			 size_t object_size,
229 			 enum elf_target_id object_id)
230 {
231   BFD_ASSERT (object_size >= sizeof (struct elf_obj_tdata));
232   abfd->tdata.any = bfd_zalloc (abfd, object_size);
233   if (abfd->tdata.any == NULL)
234     return false;
235 
236   elf_object_id (abfd) = object_id;
237   if (abfd->direction != read_direction)
238     {
239       struct output_elf_obj_tdata *o = bfd_zalloc (abfd, sizeof *o);
240       if (o == NULL)
241 	return false;
242       elf_tdata (abfd)->o = o;
243       elf_program_header_size (abfd) = (bfd_size_type) -1;
244     }
245   return true;
246 }
247 
248 
249 bool
bfd_elf_make_object(bfd * abfd)250 bfd_elf_make_object (bfd *abfd)
251 {
252   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
253   return bfd_elf_allocate_object (abfd, sizeof (struct elf_obj_tdata),
254 				  bed->target_id);
255 }
256 
257 bool
bfd_elf_mkcorefile(bfd * abfd)258 bfd_elf_mkcorefile (bfd *abfd)
259 {
260   /* I think this can be done just like an object file.  */
261   if (!abfd->xvec->_bfd_set_format[(int) bfd_object] (abfd))
262     return false;
263   elf_tdata (abfd)->core = bfd_zalloc (abfd, sizeof (*elf_tdata (abfd)->core));
264   return elf_tdata (abfd)->core != NULL;
265 }
266 
267 char *
bfd_elf_get_str_section(bfd * abfd,unsigned int shindex)268 bfd_elf_get_str_section (bfd *abfd, unsigned int shindex)
269 {
270   Elf_Internal_Shdr **i_shdrp;
271   bfd_byte *shstrtab = NULL;
272   file_ptr offset;
273   bfd_size_type shstrtabsize;
274 
275   i_shdrp = elf_elfsections (abfd);
276   if (i_shdrp == 0
277       || shindex >= elf_numsections (abfd)
278       || i_shdrp[shindex] == 0)
279     return NULL;
280 
281   shstrtab = i_shdrp[shindex]->contents;
282   if (shstrtab == NULL)
283     {
284       /* No cached one, attempt to read, and cache what we read.  */
285       offset = i_shdrp[shindex]->sh_offset;
286       shstrtabsize = i_shdrp[shindex]->sh_size;
287 
288       /* Allocate and clear an extra byte at the end, to prevent crashes
289 	 in case the string table is not terminated.  */
290       if (shstrtabsize + 1 <= 1
291 	  || (bfd_get_file_size (abfd) > 0 /* not a character device */
292 		&& shstrtabsize > bfd_get_file_size (abfd))
293 	  || bfd_seek (abfd, offset, SEEK_SET) != 0
294 	  || (shstrtab = _bfd_alloc_and_read (abfd, shstrtabsize + 1,
295 					      shstrtabsize)) == NULL)
296 	{
297 	  /* Once we've failed to read it, make sure we don't keep
298 	     trying.  Otherwise, we'll keep allocating space for
299 	     the string table over and over.  */
300 	  i_shdrp[shindex]->sh_size = 0;
301 	}
302       else
303 	shstrtab[shstrtabsize] = '\0';
304       i_shdrp[shindex]->contents = shstrtab;
305     }
306   return (char *) shstrtab;
307 }
308 
309 char *
bfd_elf_string_from_elf_section(bfd * abfd,unsigned int shindex,unsigned int strindex)310 bfd_elf_string_from_elf_section (bfd *abfd,
311 				 unsigned int shindex,
312 				 unsigned int strindex)
313 {
314   Elf_Internal_Shdr *hdr;
315 
316   if (strindex == 0)
317     return "";
318 
319   if (elf_elfsections (abfd) == NULL || shindex >= elf_numsections (abfd))
320     return NULL;
321 
322   hdr = elf_elfsections (abfd)[shindex];
323 
324   if (hdr->contents == NULL)
325     {
326       if (hdr->sh_type != SHT_STRTAB && hdr->sh_type < SHT_LOOS)
327 	{
328 	  /* PR 17512: file: f057ec89.  */
329 	  /* xgettext:c-format */
330 	  _bfd_error_handler (_("%pB: attempt to load strings from"
331 				" a non-string section (number %d)"),
332 			      abfd, shindex);
333 	  return NULL;
334 	}
335 
336       if (bfd_elf_get_str_section (abfd, shindex) == NULL)
337 	return NULL;
338     }
339   else
340     {
341       /* PR 24273: The string section's contents may have already
342 	 been loaded elsewhere, eg because a corrupt file has the
343 	 string section index in the ELF header pointing at a group
344 	 section.  So be paranoid, and test that the last byte of
345 	 the section is zero.  */
346       if (hdr->sh_size == 0 || hdr->contents[hdr->sh_size - 1] != 0)
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 	/* xgettext:c-format */
355 	(_("%pB: invalid string offset %u >= %" PRIu64 " for section `%s'"),
356 	 abfd, strindex, (uint64_t) hdr->sh_size,
357 	 (shindex == shstrndx && strindex == hdr->sh_name
358 	  ? ".shstrtab"
359 	  : bfd_elf_string_from_elf_section (abfd, shstrndx, hdr->sh_name)));
360       return NULL;
361     }
362 
363   return ((char *) hdr->contents) + strindex;
364 }
365 
366 /* Read and convert symbols to internal format.
367    SYMCOUNT specifies the number of symbols to read, starting from
368    symbol SYMOFFSET.  If any of INTSYM_BUF, EXTSYM_BUF or EXTSHNDX_BUF
369    are non-NULL, they are used to store the internal symbols, external
370    symbols, and symbol section index extensions, respectively.
371    Returns a pointer to the internal symbol buffer (malloced if necessary)
372    or NULL if there were no symbols or some kind of problem.  */
373 
374 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)375 bfd_elf_get_elf_syms (bfd *ibfd,
376 		      Elf_Internal_Shdr *symtab_hdr,
377 		      size_t symcount,
378 		      size_t symoffset,
379 		      Elf_Internal_Sym *intsym_buf,
380 		      void *extsym_buf,
381 		      Elf_External_Sym_Shndx *extshndx_buf)
382 {
383   Elf_Internal_Shdr *shndx_hdr;
384   void *alloc_ext;
385   const bfd_byte *esym;
386   Elf_External_Sym_Shndx *alloc_extshndx;
387   Elf_External_Sym_Shndx *shndx;
388   Elf_Internal_Sym *alloc_intsym;
389   Elf_Internal_Sym *isym;
390   Elf_Internal_Sym *isymend;
391   const struct elf_backend_data *bed;
392   size_t extsym_size;
393   size_t amt;
394   file_ptr pos;
395 
396   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
397     abort ();
398 
399   if (symcount == 0)
400     return intsym_buf;
401 
402   if (elf_use_dt_symtab_p (ibfd))
403     {
404       /* Use dynamic symbol table.  */
405       if (elf_tdata (ibfd)->dt_symtab_count != symcount + symoffset)
406 	{
407 	  bfd_set_error (bfd_error_invalid_operation);
408 	  return NULL;
409 	}
410       return elf_tdata (ibfd)->dt_symtab + symoffset;
411     }
412 
413   /* Normal syms might have section extension entries.  */
414   shndx_hdr = NULL;
415   if (elf_symtab_shndx_list (ibfd) != NULL)
416     {
417       elf_section_list * entry;
418       Elf_Internal_Shdr **sections = elf_elfsections (ibfd);
419 
420       /* Find an index section that is linked to this symtab section.  */
421       for (entry = elf_symtab_shndx_list (ibfd); entry != NULL; entry = entry->next)
422 	{
423 	  /* PR 20063.  */
424 	  if (entry->hdr.sh_link >= elf_numsections (ibfd))
425 	    continue;
426 
427 	  if (sections[entry->hdr.sh_link] == symtab_hdr)
428 	    {
429 	      shndx_hdr = & entry->hdr;
430 	      break;
431 	    };
432 	}
433 
434       if (shndx_hdr == NULL)
435 	{
436 	  if (symtab_hdr == &elf_symtab_hdr (ibfd))
437 	    /* Not really accurate, but this was how the old code used
438 	       to work.  */
439 	    shndx_hdr = &elf_symtab_shndx_list (ibfd)->hdr;
440 	  /* Otherwise we do nothing.  The assumption is that
441 	     the index table will not be needed.  */
442 	}
443     }
444 
445   /* Read the symbols.  */
446   alloc_ext = NULL;
447   alloc_extshndx = NULL;
448   alloc_intsym = NULL;
449   bed = get_elf_backend_data (ibfd);
450   extsym_size = bed->s->sizeof_sym;
451   if (_bfd_mul_overflow (symcount, extsym_size, &amt))
452     {
453       bfd_set_error (bfd_error_file_too_big);
454       intsym_buf = NULL;
455       goto out;
456     }
457   pos = symtab_hdr->sh_offset + symoffset * extsym_size;
458   if (extsym_buf == NULL)
459     {
460       alloc_ext = bfd_malloc (amt);
461       extsym_buf = alloc_ext;
462     }
463   if (extsym_buf == NULL
464       || bfd_seek (ibfd, pos, SEEK_SET) != 0
465       || bfd_read (extsym_buf, amt, ibfd) != amt)
466     {
467       intsym_buf = NULL;
468       goto out;
469     }
470 
471   if (shndx_hdr == NULL || shndx_hdr->sh_size == 0)
472     extshndx_buf = NULL;
473   else
474     {
475       if (_bfd_mul_overflow (symcount, sizeof (Elf_External_Sym_Shndx), &amt))
476 	{
477 	  bfd_set_error (bfd_error_file_too_big);
478 	  intsym_buf = NULL;
479 	  goto out;
480 	}
481       pos = shndx_hdr->sh_offset + symoffset * sizeof (Elf_External_Sym_Shndx);
482       if (extshndx_buf == NULL)
483 	{
484 	  alloc_extshndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
485 	  extshndx_buf = alloc_extshndx;
486 	}
487       if (extshndx_buf == NULL
488 	  || bfd_seek (ibfd, pos, SEEK_SET) != 0
489 	  || bfd_read (extshndx_buf, amt, ibfd) != amt)
490 	{
491 	  intsym_buf = NULL;
492 	  goto out;
493 	}
494     }
495 
496   if (intsym_buf == NULL)
497     {
498       if (_bfd_mul_overflow (symcount, sizeof (Elf_Internal_Sym), &amt))
499 	{
500 	  bfd_set_error (bfd_error_file_too_big);
501 	  goto out;
502 	}
503       alloc_intsym = (Elf_Internal_Sym *) bfd_malloc (amt);
504       intsym_buf = alloc_intsym;
505       if (intsym_buf == NULL)
506 	goto out;
507     }
508 
509   /* Convert the symbols to internal form.  */
510   isymend = intsym_buf + symcount;
511   for (esym = (const bfd_byte *) extsym_buf, isym = intsym_buf,
512 	   shndx = extshndx_buf;
513        isym < isymend;
514        esym += extsym_size, isym++, shndx = shndx != NULL ? shndx + 1 : NULL)
515     if (!(*bed->s->swap_symbol_in) (ibfd, esym, shndx, isym))
516       {
517 	symoffset += (esym - (bfd_byte *) extsym_buf) / extsym_size;
518 	/* xgettext:c-format */
519 	_bfd_error_handler (_("%pB symbol number %lu references"
520 			      " nonexistent SHT_SYMTAB_SHNDX section"),
521 			    ibfd, (unsigned long) symoffset);
522 	free (alloc_intsym);
523 	intsym_buf = NULL;
524 	goto out;
525       }
526 
527  out:
528   free (alloc_ext);
529   free (alloc_extshndx);
530 
531   return intsym_buf;
532 }
533 
534 /* Look up a symbol name.  */
535 const char *
bfd_elf_sym_name(bfd * abfd,Elf_Internal_Shdr * symtab_hdr,Elf_Internal_Sym * isym,asection * sym_sec)536 bfd_elf_sym_name (bfd *abfd,
537 		  Elf_Internal_Shdr *symtab_hdr,
538 		  Elf_Internal_Sym *isym,
539 		  asection *sym_sec)
540 {
541   const char *name;
542   unsigned int iname = isym->st_name;
543   unsigned int shindex = symtab_hdr->sh_link;
544 
545   if (iname == 0 && ELF_ST_TYPE (isym->st_info) == STT_SECTION
546       /* Check for a bogus st_shndx to avoid crashing.  */
547       && isym->st_shndx < elf_numsections (abfd))
548     {
549       iname = elf_elfsections (abfd)[isym->st_shndx]->sh_name;
550       shindex = elf_elfheader (abfd)->e_shstrndx;
551     }
552 
553   name = bfd_elf_string_from_elf_section (abfd, shindex, iname);
554   if (name == NULL)
555     name = "(null)";
556   else if (sym_sec && *name == '\0')
557     name = bfd_section_name (sym_sec);
558 
559   return name;
560 }
561 
562 /* Elf_Internal_Shdr->contents is an array of these for SHT_GROUP
563    sections.  The first element is the flags, the rest are section
564    pointers.  */
565 
566 typedef union elf_internal_group {
567   Elf_Internal_Shdr *shdr;
568   unsigned int flags;
569 } Elf_Internal_Group;
570 
571 /* Return the name of the group signature symbol.  Why isn't the
572    signature just a string?  */
573 
574 static const char *
group_signature(bfd * abfd,Elf_Internal_Shdr * ghdr)575 group_signature (bfd *abfd, Elf_Internal_Shdr *ghdr)
576 {
577   Elf_Internal_Shdr *hdr;
578   unsigned char esym[sizeof (Elf64_External_Sym)];
579   Elf_External_Sym_Shndx eshndx;
580   Elf_Internal_Sym isym;
581 
582   /* First we need to ensure the symbol table is available.  Make sure
583      that it is a symbol table section.  */
584   if (ghdr->sh_link >= elf_numsections (abfd))
585     return NULL;
586   hdr = elf_elfsections (abfd) [ghdr->sh_link];
587   if (hdr->sh_type != SHT_SYMTAB
588       || ! bfd_section_from_shdr (abfd, ghdr->sh_link))
589     return NULL;
590 
591   /* Go read the symbol.  */
592   hdr = &elf_tdata (abfd)->symtab_hdr;
593   if (bfd_elf_get_elf_syms (abfd, hdr, 1, ghdr->sh_info,
594 			    &isym, esym, &eshndx) == NULL)
595     return NULL;
596 
597   return bfd_elf_sym_name (abfd, hdr, &isym, NULL);
598 }
599 
600 /* Set next_in_group list pointer, and group name for NEWSECT.  */
601 
602 static bool
setup_group(bfd * abfd,Elf_Internal_Shdr * hdr,asection * newsect)603 setup_group (bfd *abfd, Elf_Internal_Shdr *hdr, asection *newsect)
604 {
605   unsigned int num_group = elf_tdata (abfd)->num_group;
606 
607   /* If num_group is zero, read in all SHT_GROUP sections.  The count
608      is set to -1 if there are no SHT_GROUP sections.  */
609   if (num_group == 0)
610     {
611       unsigned int i, shnum;
612 
613       /* First count the number of groups.  If we have a SHT_GROUP
614 	 section with just a flag word (ie. sh_size is 4), ignore it.  */
615       shnum = elf_numsections (abfd);
616       num_group = 0;
617 
618 #define IS_VALID_GROUP_SECTION_HEADER(shdr, minsize)	\
619 	(   (shdr)->sh_type == SHT_GROUP		\
620 	 && (shdr)->sh_size >= minsize			\
621 	 && (shdr)->sh_entsize == GRP_ENTRY_SIZE	\
622 	 && ((shdr)->sh_size % GRP_ENTRY_SIZE) == 0)
623 
624       for (i = 0; i < shnum; i++)
625 	{
626 	  Elf_Internal_Shdr *shdr = elf_elfsections (abfd)[i];
627 
628 	  if (IS_VALID_GROUP_SECTION_HEADER (shdr, 2 * GRP_ENTRY_SIZE))
629 	    num_group += 1;
630 	}
631 
632       if (num_group == 0)
633 	{
634 	  num_group = (unsigned) -1;
635 	  elf_tdata (abfd)->num_group = num_group;
636 	  elf_tdata (abfd)->group_sect_ptr = NULL;
637 	}
638       else
639 	{
640 	  /* We keep a list of elf section headers for group sections,
641 	     so we can find them quickly.  */
642 	  size_t amt;
643 
644 	  elf_tdata (abfd)->num_group = num_group;
645 	  amt = num_group * sizeof (Elf_Internal_Shdr *);
646 	  elf_tdata (abfd)->group_sect_ptr
647 	    = (Elf_Internal_Shdr **) bfd_zalloc (abfd, amt);
648 	  if (elf_tdata (abfd)->group_sect_ptr == NULL)
649 	    return false;
650 	  num_group = 0;
651 
652 	  for (i = 0; i < shnum; i++)
653 	    {
654 	      Elf_Internal_Shdr *shdr = elf_elfsections (abfd)[i];
655 
656 	      if (IS_VALID_GROUP_SECTION_HEADER (shdr, 2 * GRP_ENTRY_SIZE))
657 		{
658 		  unsigned char *src;
659 		  Elf_Internal_Group *dest;
660 
661 		  /* Make sure the group section has a BFD section
662 		     attached to it.  */
663 		  if (!bfd_section_from_shdr (abfd, i))
664 		    return false;
665 
666 		  /* Add to list of sections.  */
667 		  elf_tdata (abfd)->group_sect_ptr[num_group] = shdr;
668 		  num_group += 1;
669 
670 		  /* Read the raw contents.  */
671 		  BFD_ASSERT (sizeof (*dest) >= 4 && sizeof (*dest) % 4 == 0);
672 		  shdr->contents = NULL;
673 		  if (_bfd_mul_overflow (shdr->sh_size,
674 					 sizeof (*dest) / 4, &amt)
675 		      || bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0
676 		      || !(shdr->contents
677 			   = _bfd_alloc_and_read (abfd, amt, shdr->sh_size)))
678 		    {
679 		      _bfd_error_handler
680 			/* xgettext:c-format */
681 			(_("%pB: invalid size field in group section"
682 			   " header: %#" PRIx64 ""),
683 			 abfd, (uint64_t) shdr->sh_size);
684 		      bfd_set_error (bfd_error_bad_value);
685 		      -- num_group;
686 		      continue;
687 		    }
688 
689 		  /* Translate raw contents, a flag word followed by an
690 		     array of elf section indices all in target byte order,
691 		     to the flag word followed by an array of elf section
692 		     pointers.  */
693 		  src = shdr->contents + shdr->sh_size;
694 		  dest = (Elf_Internal_Group *) (shdr->contents + amt);
695 
696 		  while (1)
697 		    {
698 		      unsigned int idx;
699 
700 		      src -= 4;
701 		      --dest;
702 		      idx = H_GET_32 (abfd, src);
703 		      if (src == shdr->contents)
704 			{
705 			  dest->shdr = NULL;
706 			  dest->flags = idx;
707 			  if (shdr->bfd_section != NULL && (idx & GRP_COMDAT))
708 			    shdr->bfd_section->flags
709 			      |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
710 			  break;
711 			}
712 		      if (idx < shnum)
713 			{
714 			  dest->shdr = elf_elfsections (abfd)[idx];
715 			  /* PR binutils/23199: All sections in a
716 			     section group should be marked with
717 			     SHF_GROUP.  But some tools generate
718 			     broken objects without SHF_GROUP.  Fix
719 			     them up here.  */
720 			  dest->shdr->sh_flags |= SHF_GROUP;
721 			}
722 		      if (idx >= shnum
723 			  || dest->shdr->sh_type == SHT_GROUP)
724 			{
725 			  _bfd_error_handler
726 			    (_("%pB: invalid entry in SHT_GROUP section [%u]"),
727 			       abfd, i);
728 			  dest->shdr = NULL;
729 			}
730 		    }
731 		}
732 	    }
733 
734 	  /* PR 17510: Corrupt binaries might contain invalid groups.  */
735 	  if (num_group != (unsigned) elf_tdata (abfd)->num_group)
736 	    {
737 	      elf_tdata (abfd)->num_group = num_group;
738 
739 	      /* If all groups are invalid then fail.  */
740 	      if (num_group == 0)
741 		{
742 		  elf_tdata (abfd)->group_sect_ptr = NULL;
743 		  elf_tdata (abfd)->num_group = num_group = -1;
744 		  _bfd_error_handler
745 		    (_("%pB: no valid group sections found"), abfd);
746 		  bfd_set_error (bfd_error_bad_value);
747 		}
748 	    }
749 	}
750     }
751 
752   if (num_group != (unsigned) -1)
753     {
754       unsigned int search_offset = elf_tdata (abfd)->group_search_offset;
755       unsigned int j;
756 
757       for (j = 0; j < num_group; j++)
758 	{
759 	  /* Begin search from previous found group.  */
760 	  unsigned i = (j + search_offset) % num_group;
761 
762 	  Elf_Internal_Shdr *shdr = elf_tdata (abfd)->group_sect_ptr[i];
763 	  Elf_Internal_Group *idx;
764 	  bfd_size_type n_elt;
765 
766 	  if (shdr == NULL)
767 	    continue;
768 
769 	  idx = (Elf_Internal_Group *) shdr->contents;
770 	  if (idx == NULL || shdr->sh_size < 4)
771 	    {
772 	      /* See PR 21957 for a reproducer.  */
773 	      /* xgettext:c-format */
774 	      _bfd_error_handler (_("%pB: group section '%pA' has no contents"),
775 				  abfd, shdr->bfd_section);
776 	      elf_tdata (abfd)->group_sect_ptr[i] = NULL;
777 	      bfd_set_error (bfd_error_bad_value);
778 	      return false;
779 	    }
780 	  n_elt = shdr->sh_size / 4;
781 
782 	  /* Look through this group's sections to see if current
783 	     section is a member.  */
784 	  while (--n_elt != 0)
785 	    if ((++idx)->shdr == hdr)
786 	      {
787 		asection *s = NULL;
788 
789 		/* We are a member of this group.  Go looking through
790 		   other members to see if any others are linked via
791 		   next_in_group.  */
792 		idx = (Elf_Internal_Group *) shdr->contents;
793 		n_elt = shdr->sh_size / 4;
794 		while (--n_elt != 0)
795 		  if ((++idx)->shdr != NULL
796 		      && (s = idx->shdr->bfd_section) != NULL
797 		      && elf_next_in_group (s) != NULL)
798 		    break;
799 		if (n_elt != 0)
800 		  {
801 		    /* Snarf the group name from other member, and
802 		       insert current section in circular list.  */
803 		    elf_group_name (newsect) = elf_group_name (s);
804 		    elf_next_in_group (newsect) = elf_next_in_group (s);
805 		    elf_next_in_group (s) = newsect;
806 		  }
807 		else
808 		  {
809 		    const char *gname;
810 
811 		    gname = group_signature (abfd, shdr);
812 		    if (gname == NULL)
813 		      return false;
814 		    elf_group_name (newsect) = gname;
815 
816 		    /* Start a circular list with one element.  */
817 		    elf_next_in_group (newsect) = newsect;
818 		  }
819 
820 		/* If the group section has been created, point to the
821 		   new member.  */
822 		if (shdr->bfd_section != NULL)
823 		  elf_next_in_group (shdr->bfd_section) = newsect;
824 
825 		elf_tdata (abfd)->group_search_offset = i;
826 		j = num_group - 1;
827 		break;
828 	      }
829 	}
830     }
831 
832   if (elf_group_name (newsect) == NULL)
833     {
834       /* xgettext:c-format */
835       _bfd_error_handler (_("%pB: no group info for section '%pA'"),
836 			  abfd, newsect);
837       /* PR 29532: Return true here, even though the group info has not been
838 	 read.  Separate debug info files can have empty group sections, but
839 	 we do not want this to prevent them from being loaded as otherwise
840 	 GDB will not be able to use them.  */
841       return true;
842     }
843   return true;
844 }
845 
846 bool
_bfd_elf_setup_sections(bfd * abfd)847 _bfd_elf_setup_sections (bfd *abfd)
848 {
849   unsigned int i;
850   unsigned int num_group = elf_tdata (abfd)->num_group;
851   bool result = true;
852   asection *s;
853 
854   /* Process SHF_LINK_ORDER.  */
855   for (s = abfd->sections; s != NULL; s = s->next)
856     {
857       Elf_Internal_Shdr *this_hdr = &elf_section_data (s)->this_hdr;
858       if ((this_hdr->sh_flags & SHF_LINK_ORDER) != 0)
859 	{
860 	  unsigned int elfsec = this_hdr->sh_link;
861 	  /* An sh_link value of 0 is now allowed.  It indicates that linked
862 	     to section has already been discarded, but that the current
863 	     section has been retained for some other reason.  This linking
864 	     section is still a candidate for later garbage collection
865 	     however.  */
866 	  if (elfsec == 0)
867 	    {
868 	      elf_linked_to_section (s) = NULL;
869 	    }
870 	  else
871 	    {
872 	      asection *linksec = NULL;
873 
874 	      if (elfsec < elf_numsections (abfd))
875 		{
876 		  this_hdr = elf_elfsections (abfd)[elfsec];
877 		  linksec = this_hdr->bfd_section;
878 		}
879 
880 	      /* PR 1991, 2008:
881 		 Some strip/objcopy may leave an incorrect value in
882 		 sh_link.  We don't want to proceed.  */
883 	      if (linksec == NULL)
884 		{
885 		  _bfd_error_handler
886 		    /* xgettext:c-format */
887 		    (_("%pB: sh_link [%d] in section `%pA' is incorrect"),
888 		     s->owner, elfsec, s);
889 		  result = false;
890 		}
891 
892 	      elf_linked_to_section (s) = linksec;
893 	    }
894 	}
895       else if (this_hdr->sh_type == SHT_GROUP
896 	       && elf_next_in_group (s) == NULL)
897 	{
898 	  _bfd_error_handler
899 	    /* xgettext:c-format */
900 	    (_("%pB: SHT_GROUP section [index %d] has no SHF_GROUP sections"),
901 	     abfd, elf_section_data (s)->this_idx);
902 	  result = false;
903 	}
904     }
905 
906   /* Process section groups.  */
907   if (num_group == (unsigned) -1)
908     return result;
909 
910   for (i = 0; i < num_group; i++)
911     {
912       Elf_Internal_Shdr *shdr = elf_tdata (abfd)->group_sect_ptr[i];
913       Elf_Internal_Group *idx;
914       unsigned int n_elt;
915 
916       /* PR binutils/18758: Beware of corrupt binaries with invalid
917 	 group data.  */
918       if (shdr == NULL || shdr->bfd_section == NULL || shdr->contents == NULL)
919 	{
920 	  _bfd_error_handler
921 	    /* xgettext:c-format */
922 	    (_("%pB: section group entry number %u is corrupt"),
923 	     abfd, i);
924 	  result = false;
925 	  continue;
926 	}
927 
928       idx = (Elf_Internal_Group *) shdr->contents;
929       n_elt = shdr->sh_size / 4;
930 
931       while (--n_elt != 0)
932 	{
933 	  ++ idx;
934 
935 	  if (idx->shdr == NULL)
936 	    continue;
937 	  else if (idx->shdr->bfd_section)
938 	    elf_sec_group (idx->shdr->bfd_section) = shdr->bfd_section;
939 	  else if (idx->shdr->sh_type != SHT_RELA
940 		   && idx->shdr->sh_type != SHT_REL)
941 	    {
942 	      /* There are some unknown sections in the group.  */
943 	      _bfd_error_handler
944 		/* xgettext:c-format */
945 		(_("%pB: unknown type [%#x] section `%s' in group [%pA]"),
946 		 abfd,
947 		 idx->shdr->sh_type,
948 		 bfd_elf_string_from_elf_section (abfd,
949 						  (elf_elfheader (abfd)
950 						   ->e_shstrndx),
951 						  idx->shdr->sh_name),
952 		 shdr->bfd_section);
953 	      result = false;
954 	    }
955 	}
956     }
957 
958   return result;
959 }
960 
961 bool
bfd_elf_is_group_section(bfd * abfd ATTRIBUTE_UNUSED,const asection * sec)962 bfd_elf_is_group_section (bfd *abfd ATTRIBUTE_UNUSED, const asection *sec)
963 {
964   return elf_next_in_group (sec) != NULL;
965 }
966 
967 const char *
bfd_elf_group_name(bfd * abfd ATTRIBUTE_UNUSED,const asection * sec)968 bfd_elf_group_name (bfd *abfd ATTRIBUTE_UNUSED, const asection *sec)
969 {
970   if (elf_sec_group (sec) != NULL)
971     return elf_group_name (sec);
972   return NULL;
973 }
974 
975 /* This a copy of lto_section defined in GCC (lto-streamer.h).  */
976 
977 struct lto_section
978 {
979   int16_t major_version;
980   int16_t minor_version;
981   unsigned char slim_object;
982 
983   /* Flags is a private field that is not defined publicly.  */
984   uint16_t flags;
985 };
986 
987 /* Make a BFD section from an ELF section.  We store a pointer to the
988    BFD section in the bfd_section field of the header.  */
989 
990 bool
_bfd_elf_make_section_from_shdr(bfd * abfd,Elf_Internal_Shdr * hdr,const char * name,int shindex)991 _bfd_elf_make_section_from_shdr (bfd *abfd,
992 				 Elf_Internal_Shdr *hdr,
993 				 const char *name,
994 				 int shindex)
995 {
996   asection *newsect;
997   flagword flags;
998   const struct elf_backend_data *bed;
999   unsigned int opb = bfd_octets_per_byte (abfd, NULL);
1000 
1001   if (hdr->bfd_section != NULL)
1002     return true;
1003 
1004   newsect = bfd_make_section_anyway (abfd, name);
1005   if (newsect == NULL)
1006     return false;
1007 
1008   hdr->bfd_section = newsect;
1009   elf_section_data (newsect)->this_hdr = *hdr;
1010   elf_section_data (newsect)->this_idx = shindex;
1011 
1012   /* Always use the real type/flags.  */
1013   elf_section_type (newsect) = hdr->sh_type;
1014   elf_section_flags (newsect) = hdr->sh_flags;
1015 
1016   newsect->filepos = hdr->sh_offset;
1017 
1018   flags = SEC_NO_FLAGS;
1019   if (hdr->sh_type != SHT_NOBITS)
1020     flags |= SEC_HAS_CONTENTS;
1021   if (hdr->sh_type == SHT_GROUP)
1022     flags |= SEC_GROUP;
1023   if ((hdr->sh_flags & SHF_ALLOC) != 0)
1024     {
1025       flags |= SEC_ALLOC;
1026       if (hdr->sh_type != SHT_NOBITS)
1027 	flags |= SEC_LOAD;
1028     }
1029   if ((hdr->sh_flags & SHF_WRITE) == 0)
1030     flags |= SEC_READONLY;
1031   if ((hdr->sh_flags & SHF_EXECINSTR) != 0)
1032     flags |= SEC_CODE;
1033   else if ((flags & SEC_LOAD) != 0)
1034     flags |= SEC_DATA;
1035   if ((hdr->sh_flags & SHF_MERGE) != 0)
1036     {
1037       flags |= SEC_MERGE;
1038       newsect->entsize = hdr->sh_entsize;
1039     }
1040   if ((hdr->sh_flags & SHF_STRINGS) != 0)
1041     flags |= SEC_STRINGS;
1042   if (hdr->sh_flags & SHF_GROUP)
1043     if (!setup_group (abfd, hdr, newsect))
1044       return false;
1045   if ((hdr->sh_flags & SHF_TLS) != 0)
1046     flags |= SEC_THREAD_LOCAL;
1047   if ((hdr->sh_flags & SHF_EXCLUDE) != 0)
1048     flags |= SEC_EXCLUDE;
1049 
1050   switch (elf_elfheader (abfd)->e_ident[EI_OSABI])
1051     {
1052       /* FIXME: We should not recognize SHF_GNU_MBIND for ELFOSABI_NONE,
1053 	 but binutils as of 2019-07-23 did not set the EI_OSABI header
1054 	 byte.  */
1055     case ELFOSABI_GNU:
1056     case ELFOSABI_FREEBSD:
1057       if ((hdr->sh_flags & SHF_GNU_RETAIN) != 0)
1058 	elf_tdata (abfd)->has_gnu_osabi |= elf_gnu_osabi_retain;
1059       /* Fall through */
1060     case ELFOSABI_NONE:
1061       if ((hdr->sh_flags & SHF_GNU_MBIND) != 0)
1062 	elf_tdata (abfd)->has_gnu_osabi |= elf_gnu_osabi_mbind;
1063       break;
1064     }
1065 
1066   if ((flags & SEC_ALLOC) == 0)
1067     {
1068       /* The debugging sections appear to be recognized only by name,
1069 	 not any sort of flag.  Their SEC_ALLOC bits are cleared.  */
1070       if (name [0] == '.')
1071 	{
1072 	  if (startswith (name, ".debug")
1073 	      || startswith (name, ".gnu.debuglto_.debug_")
1074 	      || startswith (name, ".gnu.linkonce.wi.")
1075 	      || startswith (name, ".zdebug"))
1076 	    flags |= SEC_DEBUGGING | SEC_ELF_OCTETS;
1077 	  else if (startswith (name, GNU_BUILD_ATTRS_SECTION_NAME)
1078 		   || startswith (name, ".note.gnu"))
1079 	    {
1080 	      flags |= SEC_ELF_OCTETS;
1081 	      opb = 1;
1082 	    }
1083 	  else if (startswith (name, ".line")
1084 		   || startswith (name, ".stab")
1085 		   || strcmp (name, ".gdb_index") == 0)
1086 	    flags |= SEC_DEBUGGING;
1087 	}
1088     }
1089 
1090   if (!bfd_set_section_vma (newsect, hdr->sh_addr / opb)
1091       || !bfd_set_section_size (newsect, hdr->sh_size)
1092       || !bfd_set_section_alignment (newsect, bfd_log2 (hdr->sh_addralign
1093 							& -hdr->sh_addralign)))
1094     return false;
1095 
1096   /* As a GNU extension, if the name begins with .gnu.linkonce, we
1097      only link a single copy of the section.  This is used to support
1098      g++.  g++ will emit each template expansion in its own section.
1099      The symbols will be defined as weak, so that multiple definitions
1100      are permitted.  The GNU linker extension is to actually discard
1101      all but one of the sections.  */
1102   if (startswith (name, ".gnu.linkonce")
1103       && elf_next_in_group (newsect) == NULL)
1104     flags |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
1105 
1106   if (!bfd_set_section_flags (newsect, flags))
1107     return false;
1108 
1109   bed = get_elf_backend_data (abfd);
1110   if (bed->elf_backend_section_flags)
1111     if (!bed->elf_backend_section_flags (hdr))
1112       return false;
1113 
1114   /* We do not parse the PT_NOTE segments as we are interested even in the
1115      separate debug info files which may have the segments offsets corrupted.
1116      PT_NOTEs from the core files are currently not parsed using BFD.  */
1117   if (hdr->sh_type == SHT_NOTE && hdr->sh_size != 0)
1118     {
1119       bfd_byte *contents;
1120 
1121       if (!bfd_malloc_and_get_section (abfd, newsect, &contents))
1122 	return false;
1123 
1124       elf_parse_notes (abfd, (char *) contents, hdr->sh_size,
1125 		       hdr->sh_offset, hdr->sh_addralign);
1126       free (contents);
1127     }
1128 
1129   if ((newsect->flags & SEC_ALLOC) != 0)
1130     {
1131       Elf_Internal_Phdr *phdr;
1132       unsigned int i, nload;
1133 
1134       /* Some ELF linkers produce binaries with all the program header
1135 	 p_paddr fields zero.  If we have such a binary with more than
1136 	 one PT_LOAD header, then leave the section lma equal to vma
1137 	 so that we don't create sections with overlapping lma.  */
1138       phdr = elf_tdata (abfd)->phdr;
1139       for (nload = 0, i = 0; i < elf_elfheader (abfd)->e_phnum; i++, phdr++)
1140 	if (phdr->p_paddr != 0)
1141 	  break;
1142 	else if (phdr->p_type == PT_LOAD && phdr->p_memsz != 0)
1143 	  ++nload;
1144       if (i >= elf_elfheader (abfd)->e_phnum && nload > 1)
1145 	return true;
1146 
1147       phdr = elf_tdata (abfd)->phdr;
1148       for (i = 0; i < elf_elfheader (abfd)->e_phnum; i++, phdr++)
1149 	{
1150 	  if (((phdr->p_type == PT_LOAD
1151 		&& (hdr->sh_flags & SHF_TLS) == 0)
1152 	       || phdr->p_type == PT_TLS)
1153 	      && ELF_SECTION_IN_SEGMENT (hdr, phdr))
1154 	    {
1155 	      if ((newsect->flags & SEC_LOAD) == 0)
1156 		newsect->lma = (phdr->p_paddr
1157 				+ hdr->sh_addr - phdr->p_vaddr) / opb;
1158 	      else
1159 		/* We used to use the same adjustment for SEC_LOAD
1160 		   sections, but that doesn't work if the segment
1161 		   is packed with code from multiple VMAs.
1162 		   Instead we calculate the section LMA based on
1163 		   the segment LMA.  It is assumed that the
1164 		   segment will contain sections with contiguous
1165 		   LMAs, even if the VMAs are not.  */
1166 		newsect->lma = (phdr->p_paddr
1167 				+ hdr->sh_offset - phdr->p_offset) / opb;
1168 
1169 	      /* With contiguous segments, we can't tell from file
1170 		 offsets whether a section with zero size should
1171 		 be placed at the end of one segment or the
1172 		 beginning of the next.  Decide based on vaddr.  */
1173 	      if (hdr->sh_addr >= phdr->p_vaddr
1174 		  && (hdr->sh_addr + hdr->sh_size
1175 		      <= phdr->p_vaddr + phdr->p_memsz))
1176 		break;
1177 	    }
1178 	}
1179     }
1180 
1181   /* Compress/decompress DWARF debug sections with names: .debug_*,
1182      .zdebug_*, .gnu.debuglto_.debug_, after the section flags is set.  */
1183   if ((newsect->flags & SEC_DEBUGGING) != 0
1184       && (newsect->flags & SEC_HAS_CONTENTS) != 0
1185       && (newsect->flags & SEC_ELF_OCTETS) != 0)
1186     {
1187       enum { nothing, compress, decompress } action = nothing;
1188       int compression_header_size;
1189       bfd_size_type uncompressed_size;
1190       unsigned int uncompressed_align_power;
1191       enum compression_type ch_type = ch_none;
1192       bool compressed
1193 	= bfd_is_section_compressed_info (abfd, newsect,
1194 					  &compression_header_size,
1195 					  &uncompressed_size,
1196 					  &uncompressed_align_power,
1197 					  &ch_type);
1198 
1199       /* Should we decompress?  */
1200       if ((abfd->flags & BFD_DECOMPRESS) != 0 && compressed)
1201 	action = decompress;
1202 
1203       /* Should we compress?  Or convert to a different compression?  */
1204       else if ((abfd->flags & BFD_COMPRESS) != 0
1205 	       && newsect->size != 0
1206 	       && compression_header_size >= 0
1207 	       && uncompressed_size > 0)
1208 	{
1209 	  if (!compressed)
1210 	    action = compress;
1211 	  else
1212 	    {
1213 	      enum compression_type new_ch_type = ch_none;
1214 	      if ((abfd->flags & BFD_COMPRESS_GABI) != 0)
1215 		new_ch_type = ((abfd->flags & BFD_COMPRESS_ZSTD) != 0
1216 			       ? ch_compress_zstd : ch_compress_zlib);
1217 	      if (new_ch_type != ch_type)
1218 		action = compress;
1219 	    }
1220 	}
1221 
1222       if (action == compress)
1223 	{
1224 	  if (!bfd_init_section_compress_status (abfd, newsect))
1225 	    {
1226 	      _bfd_error_handler
1227 		/* xgettext:c-format */
1228 		(_("%pB: unable to compress section %s"), abfd, name);
1229 	      return false;
1230 	    }
1231 	}
1232       else if (action == decompress)
1233 	{
1234 	  if (!bfd_init_section_decompress_status (abfd, newsect))
1235 	    {
1236 	      _bfd_error_handler
1237 		/* xgettext:c-format */
1238 		(_("%pB: unable to decompress section %s"), abfd, name);
1239 	      return false;
1240 	    }
1241 #ifndef HAVE_ZSTD
1242 	  if (newsect->compress_status == DECOMPRESS_SECTION_ZSTD)
1243 	    {
1244 	      _bfd_error_handler
1245 		  /* xgettext:c-format */
1246 		  (_ ("%pB: section %s is compressed with zstd, but BFD "
1247 		      "is not built with zstd support"),
1248 		   abfd, name);
1249 	      newsect->compress_status = COMPRESS_SECTION_NONE;
1250 	      return false;
1251 	    }
1252 #endif
1253 	  if (abfd->is_linker_input
1254 	      && name[1] == 'z')
1255 	    {
1256 	      /* Rename section from .zdebug_* to .debug_* so that ld
1257 		 scripts will see this section as a debug section.  */
1258 	      char *new_name = bfd_zdebug_name_to_debug (abfd, name);
1259 	      if (new_name == NULL)
1260 		return false;
1261 	      bfd_rename_section (newsect, new_name);
1262 	    }
1263 	}
1264     }
1265 
1266   /* GCC uses .gnu.lto_.lto.<some_hash> as a LTO bytecode information
1267      section.  */
1268   if (startswith (name, ".gnu.lto_.lto."))
1269     {
1270       struct lto_section lsection;
1271       if (bfd_get_section_contents (abfd, newsect, &lsection, 0,
1272 				    sizeof (struct lto_section)))
1273 	abfd->lto_slim_object = lsection.slim_object;
1274     }
1275 
1276   return true;
1277 }
1278 
1279 const char *const bfd_elf_section_type_names[] =
1280 {
1281   "SHT_NULL", "SHT_PROGBITS", "SHT_SYMTAB", "SHT_STRTAB",
1282   "SHT_RELA", "SHT_HASH", "SHT_DYNAMIC", "SHT_NOTE",
1283   "SHT_NOBITS", "SHT_REL", "SHT_SHLIB", "SHT_DYNSYM",
1284 };
1285 
1286 /* ELF relocs are against symbols.  If we are producing relocatable
1287    output, and the reloc is against an external symbol, and nothing
1288    has given us any additional addend, the resulting reloc will also
1289    be against the same symbol.  In such a case, we don't want to
1290    change anything about the way the reloc is handled, since it will
1291    all be done at final link time.  Rather than put special case code
1292    into bfd_perform_relocation, all the reloc types use this howto
1293    function, or should call this function for relocatable output.  */
1294 
1295 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)1296 bfd_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED,
1297 		       arelent *reloc_entry,
1298 		       asymbol *symbol,
1299 		       void *data ATTRIBUTE_UNUSED,
1300 		       asection *input_section,
1301 		       bfd *output_bfd,
1302 		       char **error_message ATTRIBUTE_UNUSED)
1303 {
1304   if (output_bfd != NULL
1305       && (symbol->flags & BSF_SECTION_SYM) == 0
1306       && (! reloc_entry->howto->partial_inplace
1307 	  || reloc_entry->addend == 0))
1308     {
1309       reloc_entry->address += input_section->output_offset;
1310       return bfd_reloc_ok;
1311     }
1312 
1313   /* In some cases the relocation should be treated as output section
1314      relative, as when linking ELF DWARF into PE COFF.  Many ELF
1315      targets lack section relative relocations and instead use
1316      ordinary absolute relocations for references between DWARF
1317      sections.  That is arguably a bug in those targets but it happens
1318      to work for the usual case of linking to non-loaded ELF debug
1319      sections with VMAs forced to zero.  PE COFF on the other hand
1320      doesn't allow a section VMA of zero.  */
1321   if (output_bfd == NULL
1322       && !reloc_entry->howto->pc_relative
1323       && (symbol->section->flags & SEC_DEBUGGING) != 0
1324       && (input_section->flags & SEC_DEBUGGING) != 0)
1325     reloc_entry->addend -= symbol->section->output_section->vma;
1326 
1327   return bfd_reloc_continue;
1328 }
1329 
1330 /* Returns TRUE if section A matches section B.
1331    Names, addresses and links may be different, but everything else
1332    should be the same.  */
1333 
1334 static bool
section_match(const Elf_Internal_Shdr * a,const Elf_Internal_Shdr * b)1335 section_match (const Elf_Internal_Shdr * a,
1336 	       const Elf_Internal_Shdr * b)
1337 {
1338   if (a->sh_type != b->sh_type
1339       || ((a->sh_flags ^ b->sh_flags) & ~SHF_INFO_LINK) != 0
1340       || a->sh_addralign != b->sh_addralign
1341       || a->sh_entsize != b->sh_entsize)
1342     return false;
1343   if (a->sh_type == SHT_SYMTAB
1344       || a->sh_type == SHT_STRTAB)
1345     return true;
1346   return a->sh_size == b->sh_size;
1347 }
1348 
1349 /* Find a section in OBFD that has the same characteristics
1350    as IHEADER.  Return the index of this section or SHN_UNDEF if
1351    none can be found.  Check's section HINT first, as this is likely
1352    to be the correct section.  */
1353 
1354 static unsigned int
find_link(const bfd * obfd,const Elf_Internal_Shdr * iheader,const unsigned int hint)1355 find_link (const bfd *obfd, const Elf_Internal_Shdr *iheader,
1356 	   const unsigned int hint)
1357 {
1358   Elf_Internal_Shdr ** oheaders = elf_elfsections (obfd);
1359   unsigned int i;
1360 
1361   BFD_ASSERT (iheader != NULL);
1362 
1363   /* See PR 20922 for a reproducer of the NULL test.  */
1364   if (hint < elf_numsections (obfd)
1365       && oheaders[hint] != NULL
1366       && section_match (oheaders[hint], iheader))
1367     return hint;
1368 
1369   for (i = 1; i < elf_numsections (obfd); i++)
1370     {
1371       Elf_Internal_Shdr * oheader = oheaders[i];
1372 
1373       if (oheader == NULL)
1374 	continue;
1375       if (section_match (oheader, iheader))
1376 	/* FIXME: Do we care if there is a potential for
1377 	   multiple matches ?  */
1378 	return i;
1379     }
1380 
1381   return SHN_UNDEF;
1382 }
1383 
1384 /* PR 19938: Attempt to set the ELF section header fields of an OS or
1385    Processor specific section, based upon a matching input section.
1386    Returns TRUE upon success, FALSE otherwise.  */
1387 
1388 static bool
copy_special_section_fields(const bfd * ibfd,bfd * obfd,const Elf_Internal_Shdr * iheader,Elf_Internal_Shdr * oheader,const unsigned int secnum)1389 copy_special_section_fields (const bfd *ibfd,
1390 			     bfd *obfd,
1391 			     const Elf_Internal_Shdr *iheader,
1392 			     Elf_Internal_Shdr *oheader,
1393 			     const unsigned int secnum)
1394 {
1395   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
1396   const Elf_Internal_Shdr **iheaders
1397     = (const Elf_Internal_Shdr **) elf_elfsections (ibfd);
1398   bool changed = false;
1399   unsigned int sh_link;
1400 
1401   if (oheader->sh_type == SHT_NOBITS)
1402     {
1403       /* This is a feature for objcopy --only-keep-debug:
1404 	 When a section's type is changed to NOBITS, we preserve
1405 	 the sh_link and sh_info fields so that they can be
1406 	 matched up with the original.
1407 
1408 	 Note: Strictly speaking these assignments are wrong.
1409 	 The sh_link and sh_info fields should point to the
1410 	 relevent sections in the output BFD, which may not be in
1411 	 the same location as they were in the input BFD.  But
1412 	 the whole point of this action is to preserve the
1413 	 original values of the sh_link and sh_info fields, so
1414 	 that they can be matched up with the section headers in
1415 	 the original file.  So strictly speaking we may be
1416 	 creating an invalid ELF file, but it is only for a file
1417 	 that just contains debug info and only for sections
1418 	 without any contents.  */
1419       if (oheader->sh_link == 0)
1420 	oheader->sh_link = iheader->sh_link;
1421       if (oheader->sh_info == 0)
1422 	oheader->sh_info = iheader->sh_info;
1423       return true;
1424     }
1425 
1426   /* Allow the target a chance to decide how these fields should be set.  */
1427   if (bed->elf_backend_copy_special_section_fields (ibfd, obfd,
1428 						    iheader, oheader))
1429     return true;
1430 
1431   /* We have an iheader which might match oheader, and which has non-zero
1432      sh_info and/or sh_link fields.  Attempt to follow those links and find
1433      the section in the output bfd which corresponds to the linked section
1434      in the input bfd.  */
1435   if (iheader->sh_link != SHN_UNDEF)
1436     {
1437       /* See PR 20931 for a reproducer.  */
1438       if (iheader->sh_link >= elf_numsections (ibfd))
1439 	{
1440 	  _bfd_error_handler
1441 	    /* xgettext:c-format */
1442 	    (_("%pB: invalid sh_link field (%d) in section number %d"),
1443 	     ibfd, iheader->sh_link, secnum);
1444 	  return false;
1445 	}
1446 
1447       sh_link = find_link (obfd, iheaders[iheader->sh_link], iheader->sh_link);
1448       if (sh_link != SHN_UNDEF)
1449 	{
1450 	  oheader->sh_link = sh_link;
1451 	  changed = true;
1452 	}
1453       else
1454 	/* FIXME: Should we install iheader->sh_link
1455 	   if we could not find a match ?  */
1456 	_bfd_error_handler
1457 	  /* xgettext:c-format */
1458 	  (_("%pB: failed to find link section for section %d"), obfd, secnum);
1459     }
1460 
1461   if (iheader->sh_info)
1462     {
1463       /* The sh_info field can hold arbitrary information, but if the
1464 	 SHF_LINK_INFO flag is set then it should be interpreted as a
1465 	 section index.  */
1466       if (iheader->sh_flags & SHF_INFO_LINK)
1467 	{
1468 	  sh_link = find_link (obfd, iheaders[iheader->sh_info],
1469 			       iheader->sh_info);
1470 	  if (sh_link != SHN_UNDEF)
1471 	    oheader->sh_flags |= SHF_INFO_LINK;
1472 	}
1473       else
1474 	/* No idea what it means - just copy it.  */
1475 	sh_link = iheader->sh_info;
1476 
1477       if (sh_link != SHN_UNDEF)
1478 	{
1479 	  oheader->sh_info = sh_link;
1480 	  changed = true;
1481 	}
1482       else
1483 	_bfd_error_handler
1484 	  /* xgettext:c-format */
1485 	  (_("%pB: failed to find info section for section %d"), obfd, secnum);
1486     }
1487 
1488   return changed;
1489 }
1490 
1491 /* Copy the program header and other data from one object module to
1492    another.  */
1493 
1494 bool
_bfd_elf_copy_private_bfd_data(bfd * ibfd,bfd * obfd)1495 _bfd_elf_copy_private_bfd_data (bfd *ibfd, bfd *obfd)
1496 {
1497   const Elf_Internal_Shdr **iheaders
1498     = (const Elf_Internal_Shdr **) elf_elfsections (ibfd);
1499   Elf_Internal_Shdr **oheaders = elf_elfsections (obfd);
1500   const struct elf_backend_data *bed;
1501   unsigned int i;
1502 
1503   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
1504     || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
1505     return true;
1506 
1507   if (!elf_flags_init (obfd))
1508     {
1509       elf_elfheader (obfd)->e_flags = elf_elfheader (ibfd)->e_flags;
1510       elf_flags_init (obfd) = true;
1511     }
1512 
1513   elf_gp (obfd) = elf_gp (ibfd);
1514 
1515   /* Also copy the EI_OSABI field.  */
1516   elf_elfheader (obfd)->e_ident[EI_OSABI] =
1517     elf_elfheader (ibfd)->e_ident[EI_OSABI];
1518 
1519   /* If set, copy the EI_ABIVERSION field.  */
1520   if (elf_elfheader (ibfd)->e_ident[EI_ABIVERSION])
1521     elf_elfheader (obfd)->e_ident[EI_ABIVERSION]
1522       = elf_elfheader (ibfd)->e_ident[EI_ABIVERSION];
1523 
1524   /* Copy object attributes.  */
1525   _bfd_elf_copy_obj_attributes (ibfd, obfd);
1526 
1527   if (iheaders == NULL || oheaders == NULL)
1528     return true;
1529 
1530   bed = get_elf_backend_data (obfd);
1531 
1532   /* Possibly copy other fields in the section header.  */
1533   for (i = 1; i < elf_numsections (obfd); i++)
1534     {
1535       unsigned int j;
1536       Elf_Internal_Shdr * oheader = oheaders[i];
1537 
1538       /* Ignore ordinary sections.  SHT_NOBITS sections are considered however
1539 	 because of a special case need for generating separate debug info
1540 	 files.  See below for more details.  */
1541       if (oheader == NULL
1542 	  || (oheader->sh_type != SHT_NOBITS
1543 	      && oheader->sh_type < SHT_LOOS))
1544 	continue;
1545 
1546       /* Ignore empty sections, and sections whose
1547 	 fields have already been initialised.  */
1548       if (oheader->sh_size == 0
1549 	  || (oheader->sh_info != 0 && oheader->sh_link != 0))
1550 	continue;
1551 
1552       /* Scan for the matching section in the input bfd.
1553 	 First we try for a direct mapping between the input and
1554 	 output sections.  */
1555       for (j = 1; j < elf_numsections (ibfd); j++)
1556 	{
1557 	  const Elf_Internal_Shdr * iheader = iheaders[j];
1558 
1559 	  if (iheader == NULL)
1560 	    continue;
1561 
1562 	  if (oheader->bfd_section != NULL
1563 	      && iheader->bfd_section != NULL
1564 	      && iheader->bfd_section->output_section != NULL
1565 	      && iheader->bfd_section->output_section == oheader->bfd_section)
1566 	    {
1567 	      /* We have found a connection from the input section to
1568 		 the output section.  Attempt to copy the header fields.
1569 		 If this fails then do not try any further sections -
1570 		 there should only be a one-to-one mapping between
1571 		 input and output.  */
1572 	      if (!copy_special_section_fields (ibfd, obfd,
1573 						iheader, oheader, i))
1574 		j = elf_numsections (ibfd);
1575 	      break;
1576 	    }
1577 	}
1578 
1579       if (j < elf_numsections (ibfd))
1580 	continue;
1581 
1582       /* That failed.  So try to deduce the corresponding input section.
1583 	 Unfortunately we cannot compare names as the output string table
1584 	 is empty, so instead we check size, address and type.  */
1585       for (j = 1; j < elf_numsections (ibfd); j++)
1586 	{
1587 	  const Elf_Internal_Shdr * iheader = iheaders[j];
1588 
1589 	  if (iheader == NULL)
1590 	    continue;
1591 
1592 	  /* Try matching fields in the input section's header.
1593 	     Since --only-keep-debug turns all non-debug sections into
1594 	     SHT_NOBITS sections, the output SHT_NOBITS type matches any
1595 	     input type.  */
1596 	  if ((oheader->sh_type == SHT_NOBITS
1597 	       || iheader->sh_type == oheader->sh_type)
1598 	      && (iheader->sh_flags & ~ SHF_INFO_LINK)
1599 	      == (oheader->sh_flags & ~ SHF_INFO_LINK)
1600 	      && iheader->sh_addralign == oheader->sh_addralign
1601 	      && iheader->sh_entsize == oheader->sh_entsize
1602 	      && iheader->sh_size == oheader->sh_size
1603 	      && iheader->sh_addr == oheader->sh_addr
1604 	      && (iheader->sh_info != oheader->sh_info
1605 		  || iheader->sh_link != oheader->sh_link))
1606 	    {
1607 	      if (copy_special_section_fields (ibfd, obfd, iheader, oheader, i))
1608 		break;
1609 	    }
1610 	}
1611 
1612       if (j == elf_numsections (ibfd) && oheader->sh_type >= SHT_LOOS)
1613 	{
1614 	  /* Final attempt.  Call the backend copy function
1615 	     with a NULL input section.  */
1616 	  (void) bed->elf_backend_copy_special_section_fields (ibfd, obfd,
1617 							       NULL, oheader);
1618 	}
1619     }
1620 
1621   return true;
1622 }
1623 
1624 static const char *
get_segment_type(unsigned int p_type)1625 get_segment_type (unsigned int p_type)
1626 {
1627   const char *pt;
1628   switch (p_type)
1629     {
1630     case PT_NULL: pt = "NULL"; break;
1631     case PT_LOAD: pt = "LOAD"; break;
1632     case PT_DYNAMIC: pt = "DYNAMIC"; break;
1633     case PT_INTERP: pt = "INTERP"; break;
1634     case PT_NOTE: pt = "NOTE"; break;
1635     case PT_SHLIB: pt = "SHLIB"; break;
1636     case PT_PHDR: pt = "PHDR"; break;
1637     case PT_TLS: pt = "TLS"; break;
1638     case PT_GNU_EH_FRAME: pt = "EH_FRAME"; break;
1639     case PT_GNU_STACK: pt = "STACK"; break;
1640     case PT_GNU_RELRO: pt = "RELRO"; break;
1641     case PT_GNU_SFRAME: pt = "SFRAME"; break;
1642     default: pt = NULL; break;
1643     }
1644   return pt;
1645 }
1646 
1647 /* Print out the program headers.  */
1648 
1649 bool
_bfd_elf_print_private_bfd_data(bfd * abfd,void * farg)1650 _bfd_elf_print_private_bfd_data (bfd *abfd, void *farg)
1651 {
1652   FILE *f = (FILE *) farg;
1653   Elf_Internal_Phdr *p;
1654   asection *s;
1655   bfd_byte *dynbuf = NULL;
1656 
1657   p = elf_tdata (abfd)->phdr;
1658   if (p != NULL)
1659     {
1660       unsigned int i, c;
1661 
1662       fprintf (f, _("\nProgram Header:\n"));
1663       c = elf_elfheader (abfd)->e_phnum;
1664       for (i = 0; i < c; i++, p++)
1665 	{
1666 	  const char *pt = get_segment_type (p->p_type);
1667 	  char buf[20];
1668 
1669 	  if (pt == NULL)
1670 	    {
1671 	      sprintf (buf, "0x%lx", p->p_type);
1672 	      pt = buf;
1673 	    }
1674 	  fprintf (f, "%8s off    0x", pt);
1675 	  bfd_fprintf_vma (abfd, f, p->p_offset);
1676 	  fprintf (f, " vaddr 0x");
1677 	  bfd_fprintf_vma (abfd, f, p->p_vaddr);
1678 	  fprintf (f, " paddr 0x");
1679 	  bfd_fprintf_vma (abfd, f, p->p_paddr);
1680 	  fprintf (f, " align 2**%u\n", bfd_log2 (p->p_align));
1681 	  fprintf (f, "         filesz 0x");
1682 	  bfd_fprintf_vma (abfd, f, p->p_filesz);
1683 	  fprintf (f, " memsz 0x");
1684 	  bfd_fprintf_vma (abfd, f, p->p_memsz);
1685 	  fprintf (f, " flags %c%c%c",
1686 		   (p->p_flags & PF_R) != 0 ? 'r' : '-',
1687 		   (p->p_flags & PF_W) != 0 ? 'w' : '-',
1688 		   (p->p_flags & PF_X) != 0 ? 'x' : '-');
1689 	  if ((p->p_flags &~ (unsigned) (PF_R | PF_W | PF_X)) != 0)
1690 	    fprintf (f, " %lx", p->p_flags &~ (unsigned) (PF_R | PF_W | PF_X));
1691 	  fprintf (f, "\n");
1692 	}
1693     }
1694 
1695   s = bfd_get_section_by_name (abfd, ".dynamic");
1696   if (s != NULL && (s->flags & SEC_HAS_CONTENTS) != 0)
1697     {
1698       unsigned int elfsec;
1699       unsigned long shlink;
1700       bfd_byte *extdyn, *extdynend;
1701       size_t extdynsize;
1702       void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
1703 
1704       fprintf (f, _("\nDynamic Section:\n"));
1705 
1706       if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
1707 	goto error_return;
1708 
1709       elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
1710       if (elfsec == SHN_BAD)
1711 	goto error_return;
1712       shlink = elf_elfsections (abfd)[elfsec]->sh_link;
1713 
1714       extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
1715       swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
1716 
1717       for (extdyn = dynbuf, extdynend = dynbuf + s->size;
1718 	   (size_t) (extdynend - extdyn) >= extdynsize;
1719 	   extdyn += extdynsize)
1720 	{
1721 	  Elf_Internal_Dyn dyn;
1722 	  const char *name = "";
1723 	  char ab[20];
1724 	  bool stringp;
1725 	  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
1726 
1727 	  (*swap_dyn_in) (abfd, extdyn, &dyn);
1728 
1729 	  if (dyn.d_tag == DT_NULL)
1730 	    break;
1731 
1732 	  stringp = false;
1733 	  switch (dyn.d_tag)
1734 	    {
1735 	    default:
1736 	      if (bed->elf_backend_get_target_dtag)
1737 		name = (*bed->elf_backend_get_target_dtag) (dyn.d_tag);
1738 
1739 	      if (!strcmp (name, ""))
1740 		{
1741 		  sprintf (ab, "%#" PRIx64, (uint64_t) dyn.d_tag);
1742 		  name = ab;
1743 		}
1744 	      break;
1745 
1746 	    case DT_NEEDED: name = "NEEDED"; stringp = true; break;
1747 	    case DT_PLTRELSZ: name = "PLTRELSZ"; break;
1748 	    case DT_PLTGOT: name = "PLTGOT"; break;
1749 	    case DT_HASH: name = "HASH"; break;
1750 	    case DT_STRTAB: name = "STRTAB"; break;
1751 	    case DT_SYMTAB: name = "SYMTAB"; break;
1752 	    case DT_RELA: name = "RELA"; break;
1753 	    case DT_RELASZ: name = "RELASZ"; break;
1754 	    case DT_RELAENT: name = "RELAENT"; break;
1755 	    case DT_STRSZ: name = "STRSZ"; break;
1756 	    case DT_SYMENT: name = "SYMENT"; break;
1757 	    case DT_INIT: name = "INIT"; break;
1758 	    case DT_FINI: name = "FINI"; break;
1759 	    case DT_SONAME: name = "SONAME"; stringp = true; break;
1760 	    case DT_RPATH: name = "RPATH"; stringp = true; break;
1761 	    case DT_SYMBOLIC: name = "SYMBOLIC"; break;
1762 	    case DT_REL: name = "REL"; break;
1763 	    case DT_RELSZ: name = "RELSZ"; break;
1764 	    case DT_RELENT: name = "RELENT"; break;
1765 	    case DT_RELR: name = "RELR"; break;
1766 	    case DT_RELRSZ: name = "RELRSZ"; break;
1767 	    case DT_RELRENT: name = "RELRENT"; break;
1768 	    case DT_PLTREL: name = "PLTREL"; break;
1769 	    case DT_DEBUG: name = "DEBUG"; break;
1770 	    case DT_TEXTREL: name = "TEXTREL"; break;
1771 	    case DT_JMPREL: name = "JMPREL"; break;
1772 	    case DT_BIND_NOW: name = "BIND_NOW"; break;
1773 	    case DT_INIT_ARRAY: name = "INIT_ARRAY"; break;
1774 	    case DT_FINI_ARRAY: name = "FINI_ARRAY"; break;
1775 	    case DT_INIT_ARRAYSZ: name = "INIT_ARRAYSZ"; break;
1776 	    case DT_FINI_ARRAYSZ: name = "FINI_ARRAYSZ"; break;
1777 	    case DT_RUNPATH: name = "RUNPATH"; stringp = true; break;
1778 	    case DT_FLAGS: name = "FLAGS"; break;
1779 	    case DT_PREINIT_ARRAY: name = "PREINIT_ARRAY"; break;
1780 	    case DT_PREINIT_ARRAYSZ: name = "PREINIT_ARRAYSZ"; break;
1781 	    case DT_CHECKSUM: name = "CHECKSUM"; break;
1782 	    case DT_PLTPADSZ: name = "PLTPADSZ"; break;
1783 	    case DT_MOVEENT: name = "MOVEENT"; break;
1784 	    case DT_MOVESZ: name = "MOVESZ"; break;
1785 	    case DT_FEATURE: name = "FEATURE"; break;
1786 	    case DT_POSFLAG_1: name = "POSFLAG_1"; break;
1787 	    case DT_SYMINSZ: name = "SYMINSZ"; break;
1788 	    case DT_SYMINENT: name = "SYMINENT"; break;
1789 	    case DT_CONFIG: name = "CONFIG"; stringp = true; break;
1790 	    case DT_DEPAUDIT: name = "DEPAUDIT"; stringp = true; break;
1791 	    case DT_AUDIT: name = "AUDIT"; stringp = true; break;
1792 	    case DT_PLTPAD: name = "PLTPAD"; break;
1793 	    case DT_MOVETAB: name = "MOVETAB"; break;
1794 	    case DT_SYMINFO: name = "SYMINFO"; break;
1795 	    case DT_RELACOUNT: name = "RELACOUNT"; break;
1796 	    case DT_RELCOUNT: name = "RELCOUNT"; break;
1797 	    case DT_FLAGS_1: name = "FLAGS_1"; break;
1798 	    case DT_VERSYM: name = "VERSYM"; break;
1799 	    case DT_VERDEF: name = "VERDEF"; break;
1800 	    case DT_VERDEFNUM: name = "VERDEFNUM"; break;
1801 	    case DT_VERNEED: name = "VERNEED"; break;
1802 	    case DT_VERNEEDNUM: name = "VERNEEDNUM"; break;
1803 	    case DT_AUXILIARY: name = "AUXILIARY"; stringp = true; break;
1804 	    case DT_USED: name = "USED"; break;
1805 	    case DT_FILTER: name = "FILTER"; stringp = true; break;
1806 	    case DT_GNU_HASH: name = "GNU_HASH"; break;
1807 	    }
1808 
1809 	  fprintf (f, "  %-20s ", name);
1810 	  if (! stringp)
1811 	    {
1812 	      fprintf (f, "0x");
1813 	      bfd_fprintf_vma (abfd, f, dyn.d_un.d_val);
1814 	    }
1815 	  else
1816 	    {
1817 	      const char *string;
1818 	      unsigned int tagv = dyn.d_un.d_val;
1819 
1820 	      string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
1821 	      if (string == NULL)
1822 		goto error_return;
1823 	      fprintf (f, "%s", string);
1824 	    }
1825 	  fprintf (f, "\n");
1826 	}
1827 
1828       free (dynbuf);
1829       dynbuf = NULL;
1830     }
1831 
1832   if ((elf_dynverdef (abfd) != 0 && elf_tdata (abfd)->verdef == NULL)
1833       || (elf_dynverref (abfd) != 0 && elf_tdata (abfd)->verref == NULL))
1834     {
1835       if (! _bfd_elf_slurp_version_tables (abfd, false))
1836 	return false;
1837     }
1838 
1839   if (elf_dynverdef (abfd) != 0)
1840     {
1841       Elf_Internal_Verdef *t;
1842 
1843       fprintf (f, _("\nVersion definitions:\n"));
1844       for (t = elf_tdata (abfd)->verdef; t != NULL; t = t->vd_nextdef)
1845 	{
1846 	  fprintf (f, "%d 0x%2.2x 0x%8.8lx %s\n", t->vd_ndx,
1847 		   t->vd_flags, t->vd_hash,
1848 		   t->vd_nodename ? t->vd_nodename : "<corrupt>");
1849 	  if (t->vd_auxptr != NULL && t->vd_auxptr->vda_nextptr != NULL)
1850 	    {
1851 	      Elf_Internal_Verdaux *a;
1852 
1853 	      fprintf (f, "\t");
1854 	      for (a = t->vd_auxptr->vda_nextptr;
1855 		   a != NULL;
1856 		   a = a->vda_nextptr)
1857 		fprintf (f, "%s ",
1858 			 a->vda_nodename ? a->vda_nodename : "<corrupt>");
1859 	      fprintf (f, "\n");
1860 	    }
1861 	}
1862     }
1863 
1864   if (elf_dynverref (abfd) != 0)
1865     {
1866       Elf_Internal_Verneed *t;
1867 
1868       fprintf (f, _("\nVersion References:\n"));
1869       for (t = elf_tdata (abfd)->verref; t != NULL; t = t->vn_nextref)
1870 	{
1871 	  Elf_Internal_Vernaux *a;
1872 
1873 	  fprintf (f, _("  required from %s:\n"),
1874 		   t->vn_filename ? t->vn_filename : "<corrupt>");
1875 	  for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
1876 	    fprintf (f, "    0x%8.8lx 0x%2.2x %2.2d %s\n", a->vna_hash,
1877 		     a->vna_flags, a->vna_other,
1878 		     a->vna_nodename ? a->vna_nodename : "<corrupt>");
1879 	}
1880     }
1881 
1882   return true;
1883 
1884  error_return:
1885   free (dynbuf);
1886   return false;
1887 }
1888 
1889 /* Find the file offset corresponding to VMA by using the program
1890    headers.  */
1891 
1892 static file_ptr
offset_from_vma(Elf_Internal_Phdr * phdrs,size_t phnum,bfd_vma vma,size_t size,size_t * max_size_p)1893 offset_from_vma (Elf_Internal_Phdr *phdrs, size_t phnum, bfd_vma vma,
1894 		 size_t size, size_t *max_size_p)
1895 {
1896   Elf_Internal_Phdr *seg;
1897   size_t i;
1898 
1899   for (seg = phdrs, i = 0; i < phnum; ++seg, ++i)
1900     if (seg->p_type == PT_LOAD
1901 	&& vma >= (seg->p_vaddr & -seg->p_align)
1902 	&& vma + size <= seg->p_vaddr + seg->p_filesz)
1903       {
1904 	if (max_size_p)
1905 	  *max_size_p = seg->p_vaddr + seg->p_filesz - vma;
1906 	return vma - seg->p_vaddr + seg->p_offset;
1907       }
1908 
1909   if (max_size_p)
1910     *max_size_p = 0;
1911   bfd_set_error (bfd_error_invalid_operation);
1912   return (file_ptr) -1;
1913 }
1914 
1915 /* Convert hash table to internal form.  */
1916 
1917 static bfd_vma *
get_hash_table_data(bfd * abfd,bfd_size_type number,unsigned int ent_size,bfd_size_type filesize)1918 get_hash_table_data (bfd *abfd, bfd_size_type number,
1919 		     unsigned int ent_size, bfd_size_type filesize)
1920 {
1921   unsigned char *e_data = NULL;
1922   bfd_vma *i_data = NULL;
1923   bfd_size_type size;
1924 
1925   if (ent_size != 4 && ent_size != 8)
1926     return NULL;
1927 
1928   if ((size_t) number != number)
1929     {
1930       bfd_set_error (bfd_error_file_too_big);
1931       return NULL;
1932     }
1933 
1934   size = ent_size * number;
1935   /* Be kind to memory checkers (eg valgrind, address sanitizer) by not
1936      attempting to allocate memory when the read is bound to fail.  */
1937   if (size > filesize
1938       || number >= ~(size_t) 0 / ent_size
1939       || number >= ~(size_t) 0 / sizeof (*i_data))
1940     {
1941       bfd_set_error (bfd_error_file_too_big);
1942       return NULL;
1943     }
1944 
1945   e_data = _bfd_malloc_and_read (abfd, size, size);
1946   if (e_data == NULL)
1947     return NULL;
1948 
1949   i_data = (bfd_vma *) bfd_malloc (number * sizeof (*i_data));
1950   if (i_data == NULL)
1951     {
1952       free (e_data);
1953       return NULL;
1954     }
1955 
1956   if (ent_size == 4)
1957     while (number--)
1958       i_data[number] = bfd_get_32 (abfd, e_data + number * ent_size);
1959   else
1960     while (number--)
1961       i_data[number] = bfd_get_64 (abfd, e_data + number * ent_size);
1962 
1963   free (e_data);
1964   return i_data;
1965 }
1966 
1967 /* Address of .MIPS.xhash section.  FIXME: What is the best way to
1968    support DT_MIPS_XHASH?  */
1969 #define DT_MIPS_XHASH	       0x70000036
1970 
1971 /* Reconstruct dynamic symbol table from PT_DYNAMIC segment.  */
1972 
1973 bool
_bfd_elf_get_dynamic_symbols(bfd * abfd,Elf_Internal_Phdr * phdr,Elf_Internal_Phdr * phdrs,size_t phnum,bfd_size_type filesize)1974 _bfd_elf_get_dynamic_symbols (bfd *abfd, Elf_Internal_Phdr *phdr,
1975 			      Elf_Internal_Phdr *phdrs, size_t phnum,
1976 			      bfd_size_type filesize)
1977 {
1978   bfd_byte *extdyn, *extdynend;
1979   size_t extdynsize;
1980   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
1981   bool (*swap_symbol_in) (bfd *, const void *, const void *,
1982 			  Elf_Internal_Sym *);
1983   Elf_Internal_Dyn dyn;
1984   bfd_vma dt_hash = 0;
1985   bfd_vma dt_gnu_hash = 0;
1986   bfd_vma dt_mips_xhash = 0;
1987   bfd_vma dt_strtab = 0;
1988   bfd_vma dt_symtab = 0;
1989   size_t dt_strsz = 0;
1990   bfd_vma dt_versym = 0;
1991   bfd_vma dt_verdef = 0;
1992   bfd_vma dt_verneed = 0;
1993   bfd_byte *dynbuf = NULL;
1994   char *strbuf = NULL;
1995   bfd_vma *gnubuckets = NULL;
1996   bfd_vma *gnuchains = NULL;
1997   bfd_vma *mipsxlat = NULL;
1998   file_ptr saved_filepos, filepos;
1999   bool res = false;
2000   size_t amt;
2001   bfd_byte *esymbuf = NULL, *esym;
2002   bfd_size_type symcount;
2003   Elf_Internal_Sym *isymbuf = NULL;
2004   Elf_Internal_Sym *isym, *isymend;
2005   bfd_byte *versym = NULL;
2006   bfd_byte *verdef = NULL;
2007   bfd_byte *verneed = NULL;
2008   size_t verdef_size = 0;
2009   size_t verneed_size = 0;
2010   size_t extsym_size;
2011   const struct elf_backend_data *bed;
2012 
2013   /* Return TRUE if symbol table is bad.  */
2014   if (elf_bad_symtab (abfd))
2015     return true;
2016 
2017   /* Return TRUE if DT_HASH/DT_GNU_HASH have bee processed before.  */
2018   if (elf_tdata (abfd)->dt_strtab != NULL)
2019     return true;
2020 
2021   bed = get_elf_backend_data (abfd);
2022 
2023   /* Save file position for elf_object_p.  */
2024   saved_filepos = bfd_tell (abfd);
2025 
2026   if (bfd_seek (abfd, phdr->p_offset, SEEK_SET) != 0)
2027     goto error_return;
2028 
2029   dynbuf = _bfd_malloc_and_read (abfd, phdr->p_filesz, phdr->p_filesz);
2030   if (dynbuf == NULL)
2031     goto error_return;
2032 
2033   extsym_size = bed->s->sizeof_sym;
2034   extdynsize = bed->s->sizeof_dyn;
2035   swap_dyn_in = bed->s->swap_dyn_in;
2036 
2037   extdyn = dynbuf;
2038   if (phdr->p_filesz < extdynsize)
2039     goto error_return;
2040   extdynend = extdyn + phdr->p_filesz;
2041   for (; extdyn <= (extdynend - extdynsize); extdyn += extdynsize)
2042     {
2043       swap_dyn_in (abfd, extdyn, &dyn);
2044 
2045       if (dyn.d_tag == DT_NULL)
2046 	break;
2047 
2048       switch (dyn.d_tag)
2049 	{
2050 	case DT_HASH:
2051 	  dt_hash = dyn.d_un.d_val;
2052 	  break;
2053 	case DT_GNU_HASH:
2054 	  if (bed->elf_machine_code != EM_MIPS
2055 	      && bed->elf_machine_code != EM_MIPS_RS3_LE)
2056 	    dt_gnu_hash = dyn.d_un.d_val;
2057 	  break;
2058 	case DT_STRTAB:
2059 	  dt_strtab = dyn.d_un.d_val;
2060 	  break;
2061 	case DT_SYMTAB:
2062 	  dt_symtab = dyn.d_un.d_val;
2063 	  break;
2064 	case DT_STRSZ:
2065 	  dt_strsz = dyn.d_un.d_val;
2066 	  break;
2067 	case DT_SYMENT:
2068 	  if (dyn.d_un.d_val != extsym_size)
2069 	    goto error_return;
2070 	  break;
2071 	case DT_VERSYM:
2072 	  dt_versym = dyn.d_un.d_val;
2073 	  break;
2074 	case DT_VERDEF:
2075 	  dt_verdef = dyn.d_un.d_val;
2076 	  break;
2077 	case DT_VERNEED:
2078 	  dt_verneed = dyn.d_un.d_val;
2079 	  break;
2080 	default:
2081 	  if (dyn.d_tag == DT_MIPS_XHASH
2082 	      && (bed->elf_machine_code == EM_MIPS
2083 		  || bed->elf_machine_code == EM_MIPS_RS3_LE))
2084 	    {
2085 	      dt_gnu_hash = dyn.d_un.d_val;
2086 	      dt_mips_xhash = dyn.d_un.d_val;
2087 	    }
2088 	  break;
2089 	}
2090     }
2091 
2092   /* Check if we can reconstruct dynamic symbol table from PT_DYNAMIC
2093      segment.  */
2094   if ((!dt_hash && !dt_gnu_hash)
2095       || !dt_strtab
2096       || !dt_symtab
2097       || !dt_strsz)
2098     goto error_return;
2099 
2100   /* Get dynamic string table.  */
2101   filepos = offset_from_vma (phdrs, phnum, dt_strtab, dt_strsz, NULL);
2102   if (filepos == (file_ptr) -1
2103       || bfd_seek (abfd, filepos, SEEK_SET) != 0)
2104     goto error_return;
2105 
2106   /* Dynamic string table must be valid until ABFD is closed.  */
2107   strbuf = (char *) _bfd_alloc_and_read (abfd, dt_strsz + 1, dt_strsz);
2108   if (strbuf == NULL)
2109     goto error_return;
2110   /* Since this is a string table, make sure that it is terminated.  */
2111   strbuf[dt_strsz] = 0;
2112 
2113   /* Get the real symbol count from DT_HASH or DT_GNU_HASH.  Prefer
2114      DT_HASH since it is simpler than DT_GNU_HASH.  */
2115   if (dt_hash)
2116     {
2117       unsigned char nb[16];
2118       unsigned int hash_ent_size;
2119 
2120       switch (bed->elf_machine_code)
2121 	{
2122 	case EM_ALPHA:
2123 	case EM_S390:
2124 	case EM_S390_OLD:
2125 	  if (bed->s->elfclass == ELFCLASS64)
2126 	    {
2127 	      hash_ent_size = 8;
2128 	      break;
2129 	    }
2130 	  /* FALLTHROUGH */
2131 	default:
2132 	  hash_ent_size = 4;
2133 	  break;
2134 	}
2135 
2136       filepos = offset_from_vma (phdrs, phnum, dt_hash, sizeof (nb),
2137 				 NULL);
2138       if (filepos == (file_ptr) -1
2139 	  || bfd_seek (abfd, filepos, SEEK_SET) != 0
2140 	  || bfd_read (nb, 2 * hash_ent_size, abfd) != 2 * hash_ent_size)
2141 	goto error_return;
2142 
2143       /* The number of dynamic symbol table entries equals the number
2144 	 of chains.  */
2145       if (hash_ent_size == 8)
2146 	symcount = bfd_get_64 (abfd, nb + hash_ent_size);
2147       else
2148 	symcount = bfd_get_32 (abfd, nb + hash_ent_size);
2149     }
2150   else
2151     {
2152       /* For DT_GNU_HASH, only defined symbols with non-STB_LOCAL
2153 	 bindings are in hash table.  Since in dynamic symbol table,
2154 	 all symbols with STB_LOCAL binding are placed before symbols
2155 	 with other bindings and all undefined symbols are placed
2156 	 before defined ones, the highest symbol index in DT_GNU_HASH
2157 	 is the highest dynamic symbol table index.  */
2158       unsigned char nb[16];
2159       bfd_vma ngnubuckets;
2160       bfd_vma gnusymidx;
2161       size_t i, ngnuchains;
2162       bfd_vma maxchain = 0xffffffff, bitmaskwords;
2163       bfd_vma buckets_vma;
2164 
2165       filepos = offset_from_vma (phdrs, phnum, dt_gnu_hash,
2166 				 sizeof (nb), NULL);
2167       if (filepos == (file_ptr) -1
2168 	  || bfd_seek (abfd, filepos, SEEK_SET) != 0
2169 	  || bfd_read (nb, sizeof (nb), abfd) != sizeof (nb))
2170 	goto error_return;
2171 
2172       ngnubuckets = bfd_get_32 (abfd, nb);
2173       gnusymidx = bfd_get_32 (abfd, nb + 4);
2174       bitmaskwords = bfd_get_32 (abfd, nb + 8);
2175       buckets_vma = dt_gnu_hash + 16;
2176       if (bed->s->elfclass == ELFCLASS32)
2177 	buckets_vma += bitmaskwords * 4;
2178       else
2179 	buckets_vma += bitmaskwords * 8;
2180       filepos = offset_from_vma (phdrs, phnum, buckets_vma, 4, NULL);
2181       if (filepos == (file_ptr) -1
2182 	  || bfd_seek (abfd, filepos, SEEK_SET) != 0)
2183 	goto error_return;
2184 
2185       gnubuckets = get_hash_table_data (abfd, ngnubuckets, 4, filesize);
2186       if (gnubuckets == NULL)
2187 	goto error_return;
2188 
2189       for (i = 0; i < ngnubuckets; i++)
2190 	if (gnubuckets[i] != 0)
2191 	  {
2192 	    if (gnubuckets[i] < gnusymidx)
2193 	      goto error_return;
2194 
2195 	    if (maxchain == 0xffffffff || gnubuckets[i] > maxchain)
2196 	      maxchain = gnubuckets[i];
2197 	  }
2198 
2199       if (maxchain == 0xffffffff)
2200 	{
2201 	  symcount = 0;
2202 	  goto empty_gnu_hash;
2203 	}
2204 
2205       maxchain -= gnusymidx;
2206       filepos = offset_from_vma (phdrs, phnum,
2207 				 (buckets_vma +
2208 				  4 * (ngnubuckets + maxchain)),
2209 				 4, NULL);
2210       if (filepos == (file_ptr) -1
2211 	  || bfd_seek (abfd, filepos, SEEK_SET) != 0)
2212 	goto error_return;
2213 
2214       do
2215 	{
2216 	  if (bfd_read (nb, 4, abfd) != 4)
2217 	    goto error_return;
2218 	  ++maxchain;
2219 	  if (maxchain == 0)
2220 	    goto error_return;
2221 	}
2222       while ((bfd_get_32 (abfd, nb) & 1) == 0);
2223 
2224       filepos = offset_from_vma (phdrs, phnum,
2225 				 (buckets_vma + 4 * ngnubuckets),
2226 				 4, NULL);
2227       if (filepos == (file_ptr) -1
2228 	  || bfd_seek (abfd, filepos, SEEK_SET) != 0)
2229 	goto error_return;
2230 
2231       gnuchains = get_hash_table_data (abfd, maxchain, 4, filesize);
2232       if (gnuchains == NULL)
2233 	goto error_return;
2234       ngnuchains = maxchain;
2235 
2236       if (dt_mips_xhash)
2237 	{
2238 	  filepos = offset_from_vma (phdrs, phnum,
2239 				     (buckets_vma
2240 				      + 4 * (ngnubuckets + maxchain)),
2241 				     4, NULL);
2242 	  if (filepos == (file_ptr) -1
2243 	      || bfd_seek (abfd, filepos, SEEK_SET) != 0)
2244 	    goto error_return;
2245 
2246 	  mipsxlat = get_hash_table_data (abfd, maxchain, 4, filesize);
2247 	  if (mipsxlat == NULL)
2248 	    goto error_return;
2249 	}
2250 
2251       symcount = 0;
2252       for (i = 0; i < ngnubuckets; ++i)
2253 	if (gnubuckets[i] != 0)
2254 	  {
2255 	    bfd_vma si = gnubuckets[i];
2256 	    bfd_vma off = si - gnusymidx;
2257 	    do
2258 	      {
2259 		if (mipsxlat)
2260 		  {
2261 		    if (mipsxlat[off] >= symcount)
2262 		      symcount = mipsxlat[off] + 1;
2263 		  }
2264 		else
2265 		  {
2266 		    if (si >= symcount)
2267 		      symcount = si + 1;
2268 		  }
2269 		si++;
2270 	      }
2271 	    while (off < ngnuchains && (gnuchains[off++] & 1) == 0);
2272 	  }
2273     }
2274 
2275   /* Swap in dynamic symbol table.  */
2276   if (_bfd_mul_overflow (symcount, extsym_size, &amt))
2277     {
2278       bfd_set_error (bfd_error_file_too_big);
2279       goto error_return;
2280     }
2281 
2282   filepos = offset_from_vma (phdrs, phnum, dt_symtab, amt, NULL);
2283   if (filepos == (file_ptr) -1
2284       || bfd_seek (abfd, filepos, SEEK_SET) != 0)
2285     goto error_return;
2286   esymbuf = _bfd_malloc_and_read (abfd, amt, amt);
2287   if (esymbuf == NULL)
2288     goto error_return;
2289 
2290   if (_bfd_mul_overflow (symcount, sizeof (Elf_Internal_Sym), &amt))
2291     {
2292       bfd_set_error (bfd_error_file_too_big);
2293       goto error_return;
2294     }
2295 
2296   /* Dynamic symbol table must be valid until ABFD is closed.  */
2297   isymbuf = (Elf_Internal_Sym *) bfd_alloc (abfd, amt);
2298   if (isymbuf == NULL)
2299     goto error_return;
2300 
2301   swap_symbol_in = bed->s->swap_symbol_in;
2302 
2303   /* Convert the symbols to internal form.  */
2304   isymend = isymbuf + symcount;
2305   for (esym = esymbuf, isym = isymbuf;
2306        isym < isymend;
2307        esym += extsym_size, isym++)
2308     if (!swap_symbol_in (abfd, esym, NULL, isym)
2309 	|| isym->st_name >= dt_strsz)
2310       {
2311 	bfd_set_error (bfd_error_invalid_operation);
2312 	goto error_return;
2313       }
2314 
2315   if (dt_versym)
2316     {
2317       /* Swap in DT_VERSYM.  */
2318       if (_bfd_mul_overflow (symcount, 2, &amt))
2319 	{
2320 	  bfd_set_error (bfd_error_file_too_big);
2321 	  goto error_return;
2322 	}
2323 
2324       filepos = offset_from_vma (phdrs, phnum, dt_versym, amt, NULL);
2325       if (filepos == (file_ptr) -1
2326 	  || bfd_seek (abfd, filepos, SEEK_SET) != 0)
2327 	goto error_return;
2328 
2329       /* DT_VERSYM info must be valid until ABFD is closed.  */
2330       versym = _bfd_alloc_and_read (abfd, amt, amt);
2331 
2332       if (dt_verdef)
2333 	{
2334 	  /* Read in DT_VERDEF.  */
2335 	  filepos = offset_from_vma (phdrs, phnum, dt_verdef,
2336 				     0, &verdef_size);
2337 	  if (filepos == (file_ptr) -1
2338 	      || bfd_seek (abfd, filepos, SEEK_SET) != 0)
2339 	    goto error_return;
2340 
2341 	  /* DT_VERDEF info must be valid until ABFD is closed.  */
2342 	  verdef = _bfd_alloc_and_read (abfd, verdef_size,
2343 					verdef_size);
2344 	}
2345 
2346       if (dt_verneed)
2347 	{
2348 	  /* Read in DT_VERNEED.  */
2349 	  filepos = offset_from_vma (phdrs, phnum, dt_verneed,
2350 				     0, &verneed_size);
2351 	  if (filepos == (file_ptr) -1
2352 	      || bfd_seek (abfd, filepos, SEEK_SET) != 0)
2353 	    goto error_return;
2354 
2355 	  /* DT_VERNEED info must be valid until ABFD is closed.  */
2356 	  verneed = _bfd_alloc_and_read (abfd, verneed_size,
2357 					 verneed_size);
2358 	}
2359     }
2360 
2361  empty_gnu_hash:
2362   elf_tdata (abfd)->dt_strtab = strbuf;
2363   elf_tdata (abfd)->dt_strsz = dt_strsz;
2364   elf_tdata (abfd)->dt_symtab = isymbuf;
2365   elf_tdata (abfd)->dt_symtab_count = symcount;
2366   elf_tdata (abfd)->dt_versym = versym;
2367   elf_tdata (abfd)->dt_verdef = verdef;
2368   elf_tdata (abfd)->dt_verneed = verneed;
2369   elf_tdata (abfd)->dt_verdef_count
2370     = verdef_size / sizeof (Elf_External_Verdef);
2371   elf_tdata (abfd)->dt_verneed_count
2372     = verneed_size / sizeof (Elf_External_Verneed);
2373 
2374   res = true;
2375 
2376  error_return:
2377   /* Restore file position for elf_object_p.  */
2378   if (bfd_seek (abfd, saved_filepos, SEEK_SET) != 0)
2379     res = false;
2380   free (dynbuf);
2381   free (esymbuf);
2382   free (gnubuckets);
2383   free (gnuchains);
2384   free (mipsxlat);
2385   return res;
2386 }
2387 
2388 /* Reconstruct section from dynamic symbol.  */
2389 
2390 asection *
_bfd_elf_get_section_from_dynamic_symbol(bfd * abfd,Elf_Internal_Sym * isym)2391 _bfd_elf_get_section_from_dynamic_symbol (bfd *abfd,
2392 					  Elf_Internal_Sym *isym)
2393 {
2394   asection *sec;
2395   flagword flags;
2396 
2397   if (!elf_use_dt_symtab_p (abfd))
2398     return NULL;
2399 
2400   flags = SEC_ALLOC | SEC_LOAD;
2401   switch (ELF_ST_TYPE (isym->st_info))
2402     {
2403     case STT_FUNC:
2404     case STT_GNU_IFUNC:
2405       sec = bfd_get_section_by_name (abfd, ".text");
2406       if (sec == NULL)
2407 	sec = bfd_make_section_with_flags (abfd,
2408 					   ".text",
2409 					   flags | SEC_CODE);
2410       break;
2411     case STT_COMMON:
2412       sec = bfd_com_section_ptr;
2413       break;
2414     case STT_OBJECT:
2415       sec = bfd_get_section_by_name (abfd, ".data");
2416       if (sec == NULL)
2417 	sec = bfd_make_section_with_flags (abfd,
2418 					   ".data",
2419 					   flags | SEC_DATA);
2420       break;
2421     case STT_TLS:
2422       sec = bfd_get_section_by_name (abfd, ".tdata");
2423       if (sec == NULL)
2424 	sec = bfd_make_section_with_flags (abfd,
2425 					   ".tdata",
2426 					   (flags
2427 					    | SEC_DATA
2428 					    | SEC_THREAD_LOCAL));
2429       break;
2430     default:
2431       sec = bfd_abs_section_ptr;
2432       break;
2433     }
2434 
2435   return sec;
2436 }
2437 
2438 /* Get version name.  If BASE_P is TRUE, return "Base" for VER_FLG_BASE
2439    and return symbol version for symbol version itself.   */
2440 
2441 const char *
_bfd_elf_get_symbol_version_string(bfd * abfd,asymbol * symbol,bool base_p,bool * hidden)2442 _bfd_elf_get_symbol_version_string (bfd *abfd, asymbol *symbol,
2443 				    bool base_p,
2444 				    bool *hidden)
2445 {
2446   const char *version_string = NULL;
2447   if ((elf_dynversym (abfd) != 0
2448        && (elf_dynverdef (abfd) != 0 || elf_dynverref (abfd) != 0))
2449       || (elf_tdata (abfd)->dt_versym != NULL
2450 	  && (elf_tdata (abfd)->dt_verdef != NULL
2451 	      || elf_tdata (abfd)->dt_verneed != NULL)))
2452     {
2453       unsigned int vernum = ((elf_symbol_type *) symbol)->version;
2454 
2455       *hidden = (vernum & VERSYM_HIDDEN) != 0;
2456       vernum &= VERSYM_VERSION;
2457 
2458       if (vernum == 0)
2459 	version_string = "";
2460       else if (vernum == 1
2461 	       && (vernum > elf_tdata (abfd)->cverdefs
2462 		   || (elf_tdata (abfd)->verdef[0].vd_flags
2463 		       == VER_FLG_BASE)))
2464 	version_string = base_p ? "Base" : "";
2465       else if (vernum <= elf_tdata (abfd)->cverdefs)
2466 	{
2467 	  const char *nodename
2468 	    = elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
2469 	  version_string = "";
2470 	  if (base_p
2471 	      || nodename == NULL
2472 	      || symbol->name == NULL
2473 	      || strcmp (symbol->name, nodename) != 0)
2474 	    version_string = nodename;
2475 	}
2476       else
2477 	{
2478 	  Elf_Internal_Verneed *t;
2479 
2480 	  version_string = _("<corrupt>");
2481 	  for (t = elf_tdata (abfd)->verref;
2482 	       t != NULL;
2483 	       t = t->vn_nextref)
2484 	    {
2485 	      Elf_Internal_Vernaux *a;
2486 
2487 	      for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2488 		{
2489 		  if (a->vna_other == vernum)
2490 		    {
2491 		      *hidden = true;
2492 		      version_string = a->vna_nodename;
2493 		      break;
2494 		    }
2495 		}
2496 	    }
2497 	}
2498     }
2499   return version_string;
2500 }
2501 
2502 /* Display ELF-specific fields of a symbol.  */
2503 
2504 void
bfd_elf_print_symbol(bfd * abfd,void * filep,asymbol * symbol,bfd_print_symbol_type how)2505 bfd_elf_print_symbol (bfd *abfd,
2506 		      void *filep,
2507 		      asymbol *symbol,
2508 		      bfd_print_symbol_type how)
2509 {
2510   FILE *file = (FILE *) filep;
2511   switch (how)
2512     {
2513     case bfd_print_symbol_name:
2514       fprintf (file, "%s", symbol->name);
2515       break;
2516     case bfd_print_symbol_more:
2517       fprintf (file, "elf ");
2518       bfd_fprintf_vma (abfd, file, symbol->value);
2519       fprintf (file, " %x", symbol->flags);
2520       break;
2521     case bfd_print_symbol_all:
2522       {
2523 	const char *section_name;
2524 	const char *name = NULL;
2525 	const struct elf_backend_data *bed;
2526 	unsigned char st_other;
2527 	bfd_vma val;
2528 	const char *version_string;
2529 	bool hidden;
2530 
2531 	section_name = symbol->section ? symbol->section->name : "(*none*)";
2532 
2533 	bed = get_elf_backend_data (abfd);
2534 	if (bed->elf_backend_print_symbol_all)
2535 	  name = (*bed->elf_backend_print_symbol_all) (abfd, filep, symbol);
2536 
2537 	if (name == NULL)
2538 	  {
2539 	    name = symbol->name;
2540 	    bfd_print_symbol_vandf (abfd, file, symbol);
2541 	  }
2542 
2543 	fprintf (file, " %s\t", section_name);
2544 	/* Print the "other" value for a symbol.  For common symbols,
2545 	   we've already printed the size; now print the alignment.
2546 	   For other symbols, we have no specified alignment, and
2547 	   we've printed the address; now print the size.  */
2548 	if (symbol->section && bfd_is_com_section (symbol->section))
2549 	  val = ((elf_symbol_type *) symbol)->internal_elf_sym.st_value;
2550 	else
2551 	  val = ((elf_symbol_type *) symbol)->internal_elf_sym.st_size;
2552 	bfd_fprintf_vma (abfd, file, val);
2553 
2554 	/* If we have version information, print it.  */
2555 	version_string = _bfd_elf_get_symbol_version_string (abfd,
2556 							     symbol,
2557 							     true,
2558 							     &hidden);
2559 	if (version_string)
2560 	  {
2561 	    if (!hidden)
2562 	      fprintf (file, "  %-11s", version_string);
2563 	    else
2564 	      {
2565 		int i;
2566 
2567 		fprintf (file, " (%s)", version_string);
2568 		for (i = 10 - strlen (version_string); i > 0; --i)
2569 		  putc (' ', file);
2570 	      }
2571 	  }
2572 
2573 	/* If the st_other field is not zero, print it.  */
2574 	st_other = ((elf_symbol_type *) symbol)->internal_elf_sym.st_other;
2575 
2576 	switch (st_other)
2577 	  {
2578 	  case 0: break;
2579 	  case STV_INTERNAL:  fprintf (file, " .internal");  break;
2580 	  case STV_HIDDEN:    fprintf (file, " .hidden");    break;
2581 	  case STV_PROTECTED: fprintf (file, " .protected"); break;
2582 	  default:
2583 	    /* Some other non-defined flags are also present, so print
2584 	       everything hex.  */
2585 	    fprintf (file, " 0x%02x", (unsigned int) st_other);
2586 	  }
2587 
2588 	fprintf (file, " %s", name);
2589       }
2590       break;
2591     }
2592 }
2593 
2594 /* ELF .o/exec file reading */
2595 
2596 /* Create a new bfd section from an ELF section header.  */
2597 
2598 bool
bfd_section_from_shdr(bfd * abfd,unsigned int shindex)2599 bfd_section_from_shdr (bfd *abfd, unsigned int shindex)
2600 {
2601   Elf_Internal_Shdr *hdr;
2602   Elf_Internal_Ehdr *ehdr;
2603   const struct elf_backend_data *bed;
2604   const char *name;
2605   bool ret = true;
2606 
2607   if (shindex >= elf_numsections (abfd))
2608     return false;
2609 
2610   /* PR17512: A corrupt ELF binary might contain a loop of sections via
2611      sh_link or sh_info.  Detect this here, by refusing to load a
2612      section that we are already in the process of loading.  */
2613   if (elf_tdata (abfd)->being_created[shindex])
2614     {
2615       _bfd_error_handler
2616 	(_("%pB: warning: loop in section dependencies detected"), abfd);
2617       return false;
2618     }
2619   elf_tdata (abfd)->being_created[shindex] = true;
2620 
2621   hdr = elf_elfsections (abfd)[shindex];
2622   ehdr = elf_elfheader (abfd);
2623   name = bfd_elf_string_from_elf_section (abfd, ehdr->e_shstrndx,
2624 					  hdr->sh_name);
2625   if (name == NULL)
2626     goto fail;
2627 
2628   bed = get_elf_backend_data (abfd);
2629   switch (hdr->sh_type)
2630     {
2631     case SHT_NULL:
2632       /* Inactive section. Throw it away.  */
2633       goto success;
2634 
2635     case SHT_PROGBITS:		/* Normal section with contents.  */
2636     case SHT_NOBITS:		/* .bss section.  */
2637     case SHT_HASH:		/* .hash section.  */
2638     case SHT_NOTE:		/* .note section.  */
2639     case SHT_INIT_ARRAY:	/* .init_array section.  */
2640     case SHT_FINI_ARRAY:	/* .fini_array section.  */
2641     case SHT_PREINIT_ARRAY:	/* .preinit_array section.  */
2642     case SHT_GNU_LIBLIST:	/* .gnu.liblist section.  */
2643     case SHT_GNU_HASH:		/* .gnu.hash section.  */
2644       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
2645       goto success;
2646 
2647     case SHT_DYNAMIC:	/* Dynamic linking information.  */
2648       if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
2649 	goto fail;
2650 
2651       if (hdr->sh_link > elf_numsections (abfd))
2652 	{
2653 	  /* PR 10478: Accept Solaris binaries with a sh_link field
2654 	     set to SHN_BEFORE (LORESERVE) or SHN_AFTER (LORESERVE+1).  */
2655 	  switch (bfd_get_arch (abfd))
2656 	    {
2657 	    case bfd_arch_i386:
2658 	    case bfd_arch_sparc:
2659 	      if (hdr->sh_link == (SHN_LORESERVE & 0xffff)
2660 		  || hdr->sh_link == ((SHN_LORESERVE + 1) & 0xffff))
2661 		break;
2662 	      /* Otherwise fall through.  */
2663 	    default:
2664 	      goto fail;
2665 	    }
2666 	}
2667       else if (elf_elfsections (abfd)[hdr->sh_link] == NULL)
2668 	goto fail;
2669       else if (elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_STRTAB)
2670 	{
2671 	  Elf_Internal_Shdr *dynsymhdr;
2672 
2673 	  /* The shared libraries distributed with hpux11 have a bogus
2674 	     sh_link field for the ".dynamic" section.  Find the
2675 	     string table for the ".dynsym" section instead.  */
2676 	  if (elf_dynsymtab (abfd) != 0)
2677 	    {
2678 	      dynsymhdr = elf_elfsections (abfd)[elf_dynsymtab (abfd)];
2679 	      hdr->sh_link = dynsymhdr->sh_link;
2680 	    }
2681 	  else
2682 	    {
2683 	      unsigned int i, num_sec;
2684 
2685 	      num_sec = elf_numsections (abfd);
2686 	      for (i = 1; i < num_sec; i++)
2687 		{
2688 		  dynsymhdr = elf_elfsections (abfd)[i];
2689 		  if (dynsymhdr->sh_type == SHT_DYNSYM)
2690 		    {
2691 		      hdr->sh_link = dynsymhdr->sh_link;
2692 		      break;
2693 		    }
2694 		}
2695 	    }
2696 	}
2697       goto success;
2698 
2699     case SHT_SYMTAB:		/* A symbol table.  */
2700       if (elf_onesymtab (abfd) == shindex)
2701 	goto success;
2702 
2703       if (hdr->sh_entsize != bed->s->sizeof_sym)
2704 	goto fail;
2705 
2706       if (hdr->sh_info * hdr->sh_entsize > hdr->sh_size)
2707 	{
2708 	  if (hdr->sh_size != 0)
2709 	    goto fail;
2710 	  /* Some assemblers erroneously set sh_info to one with a
2711 	     zero sh_size.  ld sees this as a global symbol count
2712 	     of (unsigned) -1.  Fix it here.  */
2713 	  hdr->sh_info = 0;
2714 	  goto success;
2715 	}
2716 
2717       /* PR 18854: A binary might contain more than one symbol table.
2718 	 Unusual, but possible.  Warn, but continue.  */
2719       if (elf_onesymtab (abfd) != 0)
2720 	{
2721 	  _bfd_error_handler
2722 	    /* xgettext:c-format */
2723 	    (_("%pB: warning: multiple symbol tables detected"
2724 	       " - ignoring the table in section %u"),
2725 	     abfd, shindex);
2726 	  goto success;
2727 	}
2728       elf_onesymtab (abfd) = shindex;
2729       elf_symtab_hdr (abfd) = *hdr;
2730       elf_elfsections (abfd)[shindex] = hdr = & elf_symtab_hdr (abfd);
2731       abfd->flags |= HAS_SYMS;
2732 
2733       /* Sometimes a shared object will map in the symbol table.  If
2734 	 SHF_ALLOC is set, and this is a shared object, then we also
2735 	 treat this section as a BFD section.  We can not base the
2736 	 decision purely on SHF_ALLOC, because that flag is sometimes
2737 	 set in a relocatable object file, which would confuse the
2738 	 linker.  */
2739       if ((hdr->sh_flags & SHF_ALLOC) != 0
2740 	  && (abfd->flags & DYNAMIC) != 0
2741 	  && ! _bfd_elf_make_section_from_shdr (abfd, hdr, name,
2742 						shindex))
2743 	goto fail;
2744 
2745       /* Go looking for SHT_SYMTAB_SHNDX too, since if there is one we
2746 	 can't read symbols without that section loaded as well.  It
2747 	 is most likely specified by the next section header.  */
2748       {
2749 	elf_section_list * entry;
2750 	unsigned int i, num_sec;
2751 
2752 	for (entry = elf_symtab_shndx_list (abfd); entry; entry = entry->next)
2753 	  if (entry->hdr.sh_link == shindex)
2754 	    goto success;
2755 
2756 	num_sec = elf_numsections (abfd);
2757 	for (i = shindex + 1; i < num_sec; i++)
2758 	  {
2759 	    Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
2760 
2761 	    if (hdr2->sh_type == SHT_SYMTAB_SHNDX
2762 		&& hdr2->sh_link == shindex)
2763 	      break;
2764 	  }
2765 
2766 	if (i == num_sec)
2767 	  for (i = 1; i < shindex; i++)
2768 	    {
2769 	      Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
2770 
2771 	      if (hdr2->sh_type == SHT_SYMTAB_SHNDX
2772 		  && hdr2->sh_link == shindex)
2773 		break;
2774 	    }
2775 
2776 	if (i != shindex)
2777 	  ret = bfd_section_from_shdr (abfd, i);
2778 	/* else FIXME: we have failed to find the symbol table.
2779 	   Should we issue an error?  */
2780 	goto success;
2781       }
2782 
2783     case SHT_DYNSYM:		/* A dynamic symbol table.  */
2784       if (elf_dynsymtab (abfd) == shindex)
2785 	goto success;
2786 
2787       if (hdr->sh_entsize != bed->s->sizeof_sym)
2788 	goto fail;
2789 
2790       if (hdr->sh_info * hdr->sh_entsize > hdr->sh_size)
2791 	{
2792 	  if (hdr->sh_size != 0)
2793 	    goto fail;
2794 
2795 	  /* Some linkers erroneously set sh_info to one with a
2796 	     zero sh_size.  ld sees this as a global symbol count
2797 	     of (unsigned) -1.  Fix it here.  */
2798 	  hdr->sh_info = 0;
2799 	  goto success;
2800 	}
2801 
2802       /* PR 18854: A binary might contain more than one dynamic symbol table.
2803 	 Unusual, but possible.  Warn, but continue.  */
2804       if (elf_dynsymtab (abfd) != 0)
2805 	{
2806 	  _bfd_error_handler
2807 	    /* xgettext:c-format */
2808 	    (_("%pB: warning: multiple dynamic symbol tables detected"
2809 	       " - ignoring the table in section %u"),
2810 	     abfd, shindex);
2811 	  goto success;
2812 	}
2813       elf_dynsymtab (abfd) = shindex;
2814       elf_tdata (abfd)->dynsymtab_hdr = *hdr;
2815       elf_elfsections (abfd)[shindex] = hdr = &elf_tdata (abfd)->dynsymtab_hdr;
2816       abfd->flags |= HAS_SYMS;
2817 
2818       /* Besides being a symbol table, we also treat this as a regular
2819 	 section, so that objcopy can handle it.  */
2820       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
2821       goto success;
2822 
2823     case SHT_SYMTAB_SHNDX: /* Symbol section indices when >64k sections.  */
2824       {
2825 	elf_section_list * entry;
2826 
2827 	for (entry = elf_symtab_shndx_list (abfd); entry; entry = entry->next)
2828 	  if (entry->ndx == shindex)
2829 	    goto success;
2830 
2831 	entry = bfd_alloc (abfd, sizeof (*entry));
2832 	if (entry == NULL)
2833 	  goto fail;
2834 	entry->ndx = shindex;
2835 	entry->hdr = * hdr;
2836 	entry->next = elf_symtab_shndx_list (abfd);
2837 	elf_symtab_shndx_list (abfd) = entry;
2838 	elf_elfsections (abfd)[shindex] = & entry->hdr;
2839 	goto success;
2840       }
2841 
2842     case SHT_STRTAB:		/* A string table.  */
2843       if (hdr->bfd_section != NULL)
2844 	goto success;
2845 
2846       if (ehdr->e_shstrndx == shindex)
2847 	{
2848 	  elf_tdata (abfd)->shstrtab_hdr = *hdr;
2849 	  elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->shstrtab_hdr;
2850 	  goto success;
2851 	}
2852 
2853       if (elf_elfsections (abfd)[elf_onesymtab (abfd)]->sh_link == shindex)
2854 	{
2855 	symtab_strtab:
2856 	  elf_tdata (abfd)->strtab_hdr = *hdr;
2857 	  elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->strtab_hdr;
2858 	  goto success;
2859 	}
2860 
2861       if (elf_elfsections (abfd)[elf_dynsymtab (abfd)]->sh_link == shindex)
2862 	{
2863 	dynsymtab_strtab:
2864 	  elf_tdata (abfd)->dynstrtab_hdr = *hdr;
2865 	  hdr = &elf_tdata (abfd)->dynstrtab_hdr;
2866 	  elf_elfsections (abfd)[shindex] = hdr;
2867 	  /* We also treat this as a regular section, so that objcopy
2868 	     can handle it.  */
2869 	  ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name,
2870 						 shindex);
2871 	  goto success;
2872 	}
2873 
2874       /* If the string table isn't one of the above, then treat it as a
2875 	 regular section.  We need to scan all the headers to be sure,
2876 	 just in case this strtab section appeared before the above.  */
2877       if (elf_onesymtab (abfd) == 0 || elf_dynsymtab (abfd) == 0)
2878 	{
2879 	  unsigned int i, num_sec;
2880 
2881 	  num_sec = elf_numsections (abfd);
2882 	  for (i = 1; i < num_sec; i++)
2883 	    {
2884 	      Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
2885 	      if (hdr2->sh_link == shindex)
2886 		{
2887 		  /* Prevent endless recursion on broken objects.  */
2888 		  if (i == shindex)
2889 		    goto fail;
2890 		  if (! bfd_section_from_shdr (abfd, i))
2891 		    goto fail;
2892 		  if (elf_onesymtab (abfd) == i)
2893 		    goto symtab_strtab;
2894 		  if (elf_dynsymtab (abfd) == i)
2895 		    goto dynsymtab_strtab;
2896 		}
2897 	    }
2898 	}
2899       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
2900       goto success;
2901 
2902     case SHT_REL:
2903     case SHT_RELA:
2904     case SHT_RELR:
2905       /* *These* do a lot of work -- but build no sections!  */
2906       {
2907 	asection *target_sect;
2908 	Elf_Internal_Shdr *hdr2, **p_hdr;
2909 	unsigned int num_sec = elf_numsections (abfd);
2910 	struct bfd_elf_section_data *esdt;
2911 	bfd_size_type size;
2912 
2913 	if (hdr->sh_type == SHT_REL)
2914 	  size = bed->s->sizeof_rel;
2915 	else if (hdr->sh_type == SHT_RELA)
2916 	  size = bed->s->sizeof_rela;
2917 	else
2918 	  size = bed->s->arch_size / 8;
2919 	if (hdr->sh_entsize != size)
2920 	  goto fail;
2921 
2922 	/* Check for a bogus link to avoid crashing.  */
2923 	if (hdr->sh_link >= num_sec)
2924 	  {
2925 	    _bfd_error_handler
2926 	      /* xgettext:c-format */
2927 	      (_("%pB: invalid link %u for reloc section %s (index %u)"),
2928 	       abfd, hdr->sh_link, name, shindex);
2929 	    ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
2930 	    goto success;
2931 	  }
2932 
2933 	/* Get the symbol table.  */
2934 	if ((elf_elfsections (abfd)[hdr->sh_link]->sh_type == SHT_SYMTAB
2935 	     || elf_elfsections (abfd)[hdr->sh_link]->sh_type == SHT_DYNSYM)
2936 	    && ! bfd_section_from_shdr (abfd, hdr->sh_link))
2937 	  goto fail;
2938 
2939 	/* If this is an alloc section in an executable or shared
2940 	   library, or the reloc section does not use the main symbol
2941 	   table we don't treat it as a reloc section.  BFD can't
2942 	   adequately represent such a section, so at least for now,
2943 	   we don't try.  We just present it as a normal section.  We
2944 	   also can't use it as a reloc section if it points to the
2945 	   null section, an invalid section, another reloc section, or
2946 	   its sh_link points to the null section.  */
2947 	if (((abfd->flags & (DYNAMIC | EXEC_P)) != 0
2948 	     && (hdr->sh_flags & SHF_ALLOC) != 0)
2949 	    || (hdr->sh_flags & SHF_COMPRESSED) != 0
2950 	    || hdr->sh_type == SHT_RELR
2951 	    || hdr->sh_link == SHN_UNDEF
2952 	    || hdr->sh_link != elf_onesymtab (abfd)
2953 	    || hdr->sh_info == SHN_UNDEF
2954 	    || hdr->sh_info >= num_sec
2955 	    || elf_elfsections (abfd)[hdr->sh_info]->sh_type == SHT_REL
2956 	    || elf_elfsections (abfd)[hdr->sh_info]->sh_type == SHT_RELA)
2957 	  {
2958 	    ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
2959 	    goto success;
2960 	  }
2961 
2962 	if (! bfd_section_from_shdr (abfd, hdr->sh_info))
2963 	  goto fail;
2964 
2965 	target_sect = bfd_section_from_elf_index (abfd, hdr->sh_info);
2966 	if (target_sect == NULL)
2967 	  goto fail;
2968 
2969 	esdt = elf_section_data (target_sect);
2970 	if (hdr->sh_type == SHT_RELA)
2971 	  p_hdr = &esdt->rela.hdr;
2972 	else
2973 	  p_hdr = &esdt->rel.hdr;
2974 
2975 	/* PR 17512: file: 0b4f81b7.
2976 	   Also see PR 24456, for a file which deliberately has two reloc
2977 	   sections.  */
2978 	if (*p_hdr != NULL)
2979 	  {
2980 	    if (!bed->init_secondary_reloc_section (abfd, hdr, name, shindex))
2981 	      {
2982 		_bfd_error_handler
2983 		  /* xgettext:c-format */
2984 		  (_("%pB: warning: secondary relocation section '%s' "
2985 		     "for section %pA found - ignoring"),
2986 		   abfd, name, target_sect);
2987 	      }
2988 	    else
2989 	      esdt->has_secondary_relocs = true;
2990 	    goto success;
2991 	  }
2992 
2993 	hdr2 = (Elf_Internal_Shdr *) bfd_alloc (abfd, sizeof (*hdr2));
2994 	if (hdr2 == NULL)
2995 	  goto fail;
2996 	*hdr2 = *hdr;
2997 	*p_hdr = hdr2;
2998 	elf_elfsections (abfd)[shindex] = hdr2;
2999 	target_sect->reloc_count += (NUM_SHDR_ENTRIES (hdr)
3000 				     * bed->s->int_rels_per_ext_rel);
3001 	target_sect->flags |= SEC_RELOC;
3002 	target_sect->relocation = NULL;
3003 	target_sect->rel_filepos = hdr->sh_offset;
3004 	/* In the section to which the relocations apply, mark whether
3005 	   its relocations are of the REL or RELA variety.  */
3006 	if (hdr->sh_size != 0)
3007 	  {
3008 	    if (hdr->sh_type == SHT_RELA)
3009 	      target_sect->use_rela_p = 1;
3010 	  }
3011 	abfd->flags |= HAS_RELOC;
3012 	goto success;
3013       }
3014 
3015     case SHT_GNU_verdef:
3016       if (hdr->sh_info != 0)
3017 	elf_dynverdef (abfd) = shindex;
3018       elf_tdata (abfd)->dynverdef_hdr = *hdr;
3019       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
3020       goto success;
3021 
3022     case SHT_GNU_versym:
3023       if (hdr->sh_entsize != sizeof (Elf_External_Versym))
3024 	goto fail;
3025 
3026       elf_dynversym (abfd) = shindex;
3027       elf_tdata (abfd)->dynversym_hdr = *hdr;
3028       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
3029       goto success;
3030 
3031     case SHT_GNU_verneed:
3032       if (hdr->sh_info != 0)
3033 	elf_dynverref (abfd) = shindex;
3034       elf_tdata (abfd)->dynverref_hdr = *hdr;
3035       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
3036       goto success;
3037 
3038     case SHT_SHLIB:
3039       goto success;
3040 
3041     case SHT_GROUP:
3042       if (! IS_VALID_GROUP_SECTION_HEADER (hdr, GRP_ENTRY_SIZE))
3043 	goto fail;
3044 
3045       if (!_bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
3046 	goto fail;
3047 
3048       goto success;
3049 
3050     default:
3051       /* Possibly an attributes section.  */
3052       if (hdr->sh_type == SHT_GNU_ATTRIBUTES
3053 	  || hdr->sh_type == bed->obj_attrs_section_type)
3054 	{
3055 	  if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
3056 	    goto fail;
3057 	  _bfd_elf_parse_attributes (abfd, hdr);
3058 	  goto success;
3059 	}
3060 
3061       /* Check for any processor-specific section types.  */
3062       if (bed->elf_backend_section_from_shdr (abfd, hdr, name, shindex))
3063 	goto success;
3064 
3065       if (hdr->sh_type >= SHT_LOUSER && hdr->sh_type <= SHT_HIUSER)
3066 	{
3067 	  if ((hdr->sh_flags & SHF_ALLOC) != 0)
3068 	    /* FIXME: How to properly handle allocated section reserved
3069 	       for applications?  */
3070 	    _bfd_error_handler
3071 	      /* xgettext:c-format */
3072 	      (_("%pB: unknown type [%#x] section `%s'"),
3073 	       abfd, hdr->sh_type, name);
3074 	  else
3075 	    {
3076 	      /* Allow sections reserved for applications.  */
3077 	      ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
3078 	      goto success;
3079 	    }
3080 	}
3081       else if (hdr->sh_type >= SHT_LOPROC
3082 	       && hdr->sh_type <= SHT_HIPROC)
3083 	/* FIXME: We should handle this section.  */
3084 	_bfd_error_handler
3085 	  /* xgettext:c-format */
3086 	  (_("%pB: unknown type [%#x] section `%s'"),
3087 	   abfd, hdr->sh_type, name);
3088       else if (hdr->sh_type >= SHT_LOOS && hdr->sh_type <= SHT_HIOS)
3089 	{
3090 	  /* Unrecognised OS-specific sections.  */
3091 	  if ((hdr->sh_flags & SHF_OS_NONCONFORMING) != 0)
3092 	    /* SHF_OS_NONCONFORMING indicates that special knowledge is
3093 	       required to correctly process the section and the file should
3094 	       be rejected with an error message.  */
3095 	    _bfd_error_handler
3096 	      /* xgettext:c-format */
3097 	      (_("%pB: unknown type [%#x] section `%s'"),
3098 	       abfd, hdr->sh_type, name);
3099 	  else
3100 	    {
3101 	      /* Otherwise it should be processed.  */
3102 	      ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
3103 	      goto success;
3104 	    }
3105 	}
3106       else
3107 	/* FIXME: We should handle this section.  */
3108 	_bfd_error_handler
3109 	  /* xgettext:c-format */
3110 	  (_("%pB: unknown type [%#x] section `%s'"),
3111 	   abfd, hdr->sh_type, name);
3112 
3113       goto fail;
3114     }
3115 
3116  fail:
3117   ret = false;
3118  success:
3119   elf_tdata (abfd)->being_created[shindex] = false;
3120   return ret;
3121 }
3122 
3123 /* Return the local symbol specified by ABFD, R_SYMNDX.  */
3124 
3125 Elf_Internal_Sym *
bfd_sym_from_r_symndx(struct sym_cache * cache,bfd * abfd,unsigned long r_symndx)3126 bfd_sym_from_r_symndx (struct sym_cache *cache,
3127 		       bfd *abfd,
3128 		       unsigned long r_symndx)
3129 {
3130   unsigned int ent = r_symndx % LOCAL_SYM_CACHE_SIZE;
3131 
3132   if (cache->abfd != abfd || cache->indx[ent] != r_symndx)
3133     {
3134       Elf_Internal_Shdr *symtab_hdr;
3135       unsigned char esym[sizeof (Elf64_External_Sym)];
3136       Elf_External_Sym_Shndx eshndx;
3137 
3138       symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
3139       if (bfd_elf_get_elf_syms (abfd, symtab_hdr, 1, r_symndx,
3140 				&cache->sym[ent], esym, &eshndx) == NULL)
3141 	return NULL;
3142 
3143       if (cache->abfd != abfd)
3144 	{
3145 	  memset (cache->indx, -1, sizeof (cache->indx));
3146 	  cache->abfd = abfd;
3147 	}
3148       cache->indx[ent] = r_symndx;
3149     }
3150 
3151   return &cache->sym[ent];
3152 }
3153 
3154 /* Given an ELF section number, retrieve the corresponding BFD
3155    section.  */
3156 
3157 asection *
bfd_section_from_elf_index(bfd * abfd,unsigned int sec_index)3158 bfd_section_from_elf_index (bfd *abfd, unsigned int sec_index)
3159 {
3160   if (sec_index >= elf_numsections (abfd))
3161     return NULL;
3162   return elf_elfsections (abfd)[sec_index]->bfd_section;
3163 }
3164 
3165 static const struct bfd_elf_special_section special_sections_b[] =
3166 {
3167   { STRING_COMMA_LEN (".bss"), -2, SHT_NOBITS,   SHF_ALLOC + SHF_WRITE },
3168   { NULL,		    0,	0, 0,		 0 }
3169 };
3170 
3171 static const struct bfd_elf_special_section special_sections_c[] =
3172 {
3173   { STRING_COMMA_LEN (".comment"), 0, SHT_PROGBITS, 0 },
3174   { STRING_COMMA_LEN (".ctf"),	0, SHT_PROGBITS,    0 },
3175   { NULL,			0, 0, 0,	    0 }
3176 };
3177 
3178 static const struct bfd_elf_special_section special_sections_d[] =
3179 {
3180   { STRING_COMMA_LEN (".data"),		-2, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE },
3181   { STRING_COMMA_LEN (".data1"),	 0, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE },
3182   /* There are more DWARF sections than these, but they needn't be added here
3183      unless you have to cope with broken compilers that don't emit section
3184      attributes or you want to help the user writing assembler.  */
3185   { STRING_COMMA_LEN (".debug"),	 0, SHT_PROGBITS, 0 },
3186   { STRING_COMMA_LEN (".debug_line"),	 0, SHT_PROGBITS, 0 },
3187   { STRING_COMMA_LEN (".debug_info"),	 0, SHT_PROGBITS, 0 },
3188   { STRING_COMMA_LEN (".debug_abbrev"),	 0, SHT_PROGBITS, 0 },
3189   { STRING_COMMA_LEN (".debug_aranges"), 0, SHT_PROGBITS, 0 },
3190   { STRING_COMMA_LEN (".dynamic"),	 0, SHT_DYNAMIC,  SHF_ALLOC },
3191   { STRING_COMMA_LEN (".dynstr"),	 0, SHT_STRTAB,	  SHF_ALLOC },
3192   { STRING_COMMA_LEN (".dynsym"),	 0, SHT_DYNSYM,	  SHF_ALLOC },
3193   { NULL,		       0,	 0, 0,		  0 }
3194 };
3195 
3196 static const struct bfd_elf_special_section special_sections_f[] =
3197 {
3198   { STRING_COMMA_LEN (".fini"),	       0, SHT_PROGBITS,	  SHF_ALLOC + SHF_EXECINSTR },
3199   { STRING_COMMA_LEN (".fini_array"), -2, SHT_FINI_ARRAY, SHF_ALLOC + SHF_WRITE },
3200   { NULL,			   0 , 0, 0,		  0 }
3201 };
3202 
3203 static const struct bfd_elf_special_section special_sections_g[] =
3204 {
3205   { STRING_COMMA_LEN (".gnu.linkonce.b"), -2, SHT_NOBITS,      SHF_ALLOC + SHF_WRITE },
3206   { STRING_COMMA_LEN (".gnu.linkonce.n"), -2, SHT_NOBITS,      SHF_ALLOC + SHF_WRITE },
3207   { STRING_COMMA_LEN (".gnu.linkonce.p"), -2, SHT_PROGBITS,    SHF_ALLOC + SHF_WRITE },
3208   { STRING_COMMA_LEN (".gnu.lto_"),	  -1, SHT_PROGBITS,    SHF_EXCLUDE },
3209   { STRING_COMMA_LEN (".got"),		   0, SHT_PROGBITS,    SHF_ALLOC + SHF_WRITE },
3210   { STRING_COMMA_LEN (".gnu.version"),	   0, SHT_GNU_versym,  0 },
3211   { STRING_COMMA_LEN (".gnu.version_d"),   0, SHT_GNU_verdef,  0 },
3212   { STRING_COMMA_LEN (".gnu.version_r"),   0, SHT_GNU_verneed, 0 },
3213   { STRING_COMMA_LEN (".gnu.liblist"),	   0, SHT_GNU_LIBLIST, SHF_ALLOC },
3214   { STRING_COMMA_LEN (".gnu.conflict"),	   0, SHT_RELA,	       SHF_ALLOC },
3215   { STRING_COMMA_LEN (".gnu.hash"),	   0, SHT_GNU_HASH,    SHF_ALLOC },
3216   { NULL,			 0,	   0, 0,	       0 }
3217 };
3218 
3219 static const struct bfd_elf_special_section special_sections_h[] =
3220 {
3221   { STRING_COMMA_LEN (".hash"), 0, SHT_HASH,	 SHF_ALLOC },
3222   { NULL,		     0, 0, 0,		 0 }
3223 };
3224 
3225 static const struct bfd_elf_special_section special_sections_i[] =
3226 {
3227   { STRING_COMMA_LEN (".init"),	       0, SHT_PROGBITS,	  SHF_ALLOC + SHF_EXECINSTR },
3228   { STRING_COMMA_LEN (".init_array"), -2, SHT_INIT_ARRAY, SHF_ALLOC + SHF_WRITE },
3229   { STRING_COMMA_LEN (".interp"),      0, SHT_PROGBITS,	  0 },
3230   { NULL,		       0,      0, 0,		  0 }
3231 };
3232 
3233 static const struct bfd_elf_special_section special_sections_l[] =
3234 {
3235   { STRING_COMMA_LEN (".line"), 0, SHT_PROGBITS, 0 },
3236   { NULL,		     0, 0, 0,		 0 }
3237 };
3238 
3239 static const struct bfd_elf_special_section special_sections_n[] =
3240 {
3241   { STRING_COMMA_LEN (".noinit"),	 -2, SHT_NOBITS,   SHF_ALLOC + SHF_WRITE },
3242   { STRING_COMMA_LEN (".note.GNU-stack"), 0, SHT_PROGBITS, 0 },
3243   { STRING_COMMA_LEN (".note"),		 -1, SHT_NOTE,	   0 },
3244   { NULL,		     0,		  0, 0,		   0 }
3245 };
3246 
3247 static const struct bfd_elf_special_section special_sections_p[] =
3248 {
3249   { STRING_COMMA_LEN (".persistent.bss"), 0, SHT_NOBITS,	SHF_ALLOC + SHF_WRITE },
3250   { STRING_COMMA_LEN (".persistent"),	 -2, SHT_PROGBITS,	SHF_ALLOC + SHF_WRITE },
3251   { STRING_COMMA_LEN (".preinit_array"), -2, SHT_PREINIT_ARRAY, SHF_ALLOC + SHF_WRITE },
3252   { STRING_COMMA_LEN (".plt"),		  0, SHT_PROGBITS,	SHF_ALLOC + SHF_EXECINSTR },
3253   { NULL,		    0,		  0, 0,			0 }
3254 };
3255 
3256 static const struct bfd_elf_special_section special_sections_r[] =
3257 {
3258   { STRING_COMMA_LEN (".rodata"), -2, SHT_PROGBITS, SHF_ALLOC },
3259   { STRING_COMMA_LEN (".rodata1"), 0, SHT_PROGBITS, SHF_ALLOC },
3260   { STRING_COMMA_LEN (".relr.dyn"), 0, SHT_RELR, SHF_ALLOC },
3261   { STRING_COMMA_LEN (".rela"),	  -1, SHT_RELA,	    0 },
3262   { STRING_COMMA_LEN (".rel"),	  -1, SHT_REL,	    0 },
3263   { NULL,		    0,	   0, 0,	    0 }
3264 };
3265 
3266 static const struct bfd_elf_special_section special_sections_s[] =
3267 {
3268   { STRING_COMMA_LEN (".shstrtab"), 0, SHT_STRTAB, 0 },
3269   { STRING_COMMA_LEN (".strtab"),   0, SHT_STRTAB, 0 },
3270   { STRING_COMMA_LEN (".symtab"),   0, SHT_SYMTAB, 0 },
3271   /* See struct bfd_elf_special_section declaration for the semantics of
3272      this special case where .prefix_length != strlen (.prefix).  */
3273   { ".stabstr",			5,  3, SHT_STRTAB, 0 },
3274   { NULL,			0,  0, 0,	   0 }
3275 };
3276 
3277 static const struct bfd_elf_special_section special_sections_t[] =
3278 {
3279   { STRING_COMMA_LEN (".text"),	 -2, SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR },
3280   { STRING_COMMA_LEN (".tbss"),	 -2, SHT_NOBITS,   SHF_ALLOC + SHF_WRITE + SHF_TLS },
3281   { STRING_COMMA_LEN (".tdata"), -2, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE + SHF_TLS },
3282   { NULL,		      0,  0, 0,		   0 }
3283 };
3284 
3285 static const struct bfd_elf_special_section special_sections_z[] =
3286 {
3287   { STRING_COMMA_LEN (".zdebug_line"),	  0, SHT_PROGBITS, 0 },
3288   { STRING_COMMA_LEN (".zdebug_info"),	  0, SHT_PROGBITS, 0 },
3289   { STRING_COMMA_LEN (".zdebug_abbrev"),  0, SHT_PROGBITS, 0 },
3290   { STRING_COMMA_LEN (".zdebug_aranges"), 0, SHT_PROGBITS, 0 },
3291   { NULL,		      0,  0, 0,		   0 }
3292 };
3293 
3294 static const struct bfd_elf_special_section * const special_sections[] =
3295 {
3296   special_sections_b,		/* 'b' */
3297   special_sections_c,		/* 'c' */
3298   special_sections_d,		/* 'd' */
3299   NULL,				/* 'e' */
3300   special_sections_f,		/* 'f' */
3301   special_sections_g,		/* 'g' */
3302   special_sections_h,		/* 'h' */
3303   special_sections_i,		/* 'i' */
3304   NULL,				/* 'j' */
3305   NULL,				/* 'k' */
3306   special_sections_l,		/* 'l' */
3307   NULL,				/* 'm' */
3308   special_sections_n,		/* 'n' */
3309   NULL,				/* 'o' */
3310   special_sections_p,		/* 'p' */
3311   NULL,				/* 'q' */
3312   special_sections_r,		/* 'r' */
3313   special_sections_s,		/* 's' */
3314   special_sections_t,		/* 't' */
3315   NULL,				/* 'u' */
3316   NULL,				/* 'v' */
3317   NULL,				/* 'w' */
3318   NULL,				/* 'x' */
3319   NULL,				/* 'y' */
3320   special_sections_z		/* 'z' */
3321 };
3322 
3323 const struct bfd_elf_special_section *
_bfd_elf_get_special_section(const char * name,const struct bfd_elf_special_section * spec,unsigned int rela)3324 _bfd_elf_get_special_section (const char *name,
3325 			      const struct bfd_elf_special_section *spec,
3326 			      unsigned int rela)
3327 {
3328   int i;
3329   int len;
3330 
3331   len = strlen (name);
3332 
3333   for (i = 0; spec[i].prefix != NULL; i++)
3334     {
3335       int suffix_len;
3336       int prefix_len = spec[i].prefix_length;
3337 
3338       if (len < prefix_len)
3339 	continue;
3340       if (memcmp (name, spec[i].prefix, prefix_len) != 0)
3341 	continue;
3342 
3343       suffix_len = spec[i].suffix_length;
3344       if (suffix_len <= 0)
3345 	{
3346 	  if (name[prefix_len] != 0)
3347 	    {
3348 	      if (suffix_len == 0)
3349 		continue;
3350 	      if (name[prefix_len] != '.'
3351 		  && (suffix_len == -2
3352 		      || (rela && spec[i].type == SHT_REL)))
3353 		continue;
3354 	    }
3355 	}
3356       else
3357 	{
3358 	  if (len < prefix_len + suffix_len)
3359 	    continue;
3360 	  if (memcmp (name + len - suffix_len,
3361 		      spec[i].prefix + prefix_len,
3362 		      suffix_len) != 0)
3363 	    continue;
3364 	}
3365       return &spec[i];
3366     }
3367 
3368   return NULL;
3369 }
3370 
3371 const struct bfd_elf_special_section *
_bfd_elf_get_sec_type_attr(bfd * abfd,asection * sec)3372 _bfd_elf_get_sec_type_attr (bfd *abfd, asection *sec)
3373 {
3374   int i;
3375   const struct bfd_elf_special_section *spec;
3376   const struct elf_backend_data *bed;
3377 
3378   /* See if this is one of the special sections.  */
3379   if (sec->name == NULL)
3380     return NULL;
3381 
3382   bed = get_elf_backend_data (abfd);
3383   spec = bed->special_sections;
3384   if (spec)
3385     {
3386       spec = _bfd_elf_get_special_section (sec->name,
3387 					   bed->special_sections,
3388 					   sec->use_rela_p);
3389       if (spec != NULL)
3390 	return spec;
3391     }
3392 
3393   if (sec->name[0] != '.')
3394     return NULL;
3395 
3396   i = sec->name[1] - 'b';
3397   if (i < 0 || i > 'z' - 'b')
3398     return NULL;
3399 
3400   spec = special_sections[i];
3401 
3402   if (spec == NULL)
3403     return NULL;
3404 
3405   return _bfd_elf_get_special_section (sec->name, spec, sec->use_rela_p);
3406 }
3407 
3408 bool
_bfd_elf_new_section_hook(bfd * abfd,asection * sec)3409 _bfd_elf_new_section_hook (bfd *abfd, asection *sec)
3410 {
3411   struct bfd_elf_section_data *sdata;
3412   const struct elf_backend_data *bed;
3413   const struct bfd_elf_special_section *ssect;
3414 
3415   sdata = (struct bfd_elf_section_data *) sec->used_by_bfd;
3416   if (sdata == NULL)
3417     {
3418       sdata = (struct bfd_elf_section_data *) bfd_zalloc (abfd,
3419 							  sizeof (*sdata));
3420       if (sdata == NULL)
3421 	return false;
3422       sec->used_by_bfd = sdata;
3423     }
3424 
3425   /* Indicate whether or not this section should use RELA relocations.  */
3426   bed = get_elf_backend_data (abfd);
3427   sec->use_rela_p = bed->default_use_rela_p;
3428 
3429   /* Set up ELF section type and flags for newly created sections, if
3430      there is an ABI mandated section.  */
3431   ssect = (*bed->get_sec_type_attr) (abfd, sec);
3432   if (ssect != NULL)
3433     {
3434       elf_section_type (sec) = ssect->type;
3435       elf_section_flags (sec) = ssect->attr;
3436     }
3437 
3438   return _bfd_generic_new_section_hook (abfd, sec);
3439 }
3440 
3441 /* Create a new bfd section from an ELF program header.
3442 
3443    Since program segments have no names, we generate a synthetic name
3444    of the form segment<NUM>, where NUM is generally the index in the
3445    program header table.  For segments that are split (see below) we
3446    generate the names segment<NUM>a and segment<NUM>b.
3447 
3448    Note that some program segments may have a file size that is different than
3449    (less than) the memory size.  All this means is that at execution the
3450    system must allocate the amount of memory specified by the memory size,
3451    but only initialize it with the first "file size" bytes read from the
3452    file.  This would occur for example, with program segments consisting
3453    of combined data+bss.
3454 
3455    To handle the above situation, this routine generates TWO bfd sections
3456    for the single program segment.  The first has the length specified by
3457    the file size of the segment, and the second has the length specified
3458    by the difference between the two sizes.  In effect, the segment is split
3459    into its initialized and uninitialized parts.  */
3460 
3461 bool
_bfd_elf_make_section_from_phdr(bfd * abfd,Elf_Internal_Phdr * hdr,int hdr_index,const char * type_name)3462 _bfd_elf_make_section_from_phdr (bfd *abfd,
3463 				 Elf_Internal_Phdr *hdr,
3464 				 int hdr_index,
3465 				 const char *type_name)
3466 {
3467   asection *newsect;
3468   char *name;
3469   char namebuf[64];
3470   size_t len;
3471   int split;
3472   unsigned int opb = bfd_octets_per_byte (abfd, NULL);
3473 
3474   split = ((hdr->p_memsz > 0)
3475 	    && (hdr->p_filesz > 0)
3476 	    && (hdr->p_memsz > hdr->p_filesz));
3477 
3478   if (hdr->p_filesz > 0)
3479     {
3480       sprintf (namebuf, "%s%d%s", type_name, hdr_index, split ? "a" : "");
3481       len = strlen (namebuf) + 1;
3482       name = (char *) bfd_alloc (abfd, len);
3483       if (!name)
3484 	return false;
3485       memcpy (name, namebuf, len);
3486       newsect = bfd_make_section (abfd, name);
3487       if (newsect == NULL)
3488 	return false;
3489       newsect->vma = hdr->p_vaddr / opb;
3490       newsect->lma = hdr->p_paddr / opb;
3491       newsect->size = hdr->p_filesz;
3492       newsect->filepos = hdr->p_offset;
3493       newsect->flags |= SEC_HAS_CONTENTS;
3494       newsect->alignment_power = bfd_log2 (hdr->p_align);
3495       if (hdr->p_type == PT_LOAD)
3496 	{
3497 	  newsect->flags |= SEC_ALLOC;
3498 	  newsect->flags |= SEC_LOAD;
3499 	  if (hdr->p_flags & PF_X)
3500 	    {
3501 	      /* FIXME: all we known is that it has execute PERMISSION,
3502 		 may be data.  */
3503 	      newsect->flags |= SEC_CODE;
3504 	    }
3505 	}
3506       if (!(hdr->p_flags & PF_W))
3507 	{
3508 	  newsect->flags |= SEC_READONLY;
3509 	}
3510     }
3511 
3512   if (hdr->p_memsz > hdr->p_filesz)
3513     {
3514       bfd_vma align;
3515 
3516       sprintf (namebuf, "%s%d%s", type_name, hdr_index, split ? "b" : "");
3517       len = strlen (namebuf) + 1;
3518       name = (char *) bfd_alloc (abfd, len);
3519       if (!name)
3520 	return false;
3521       memcpy (name, namebuf, len);
3522       newsect = bfd_make_section (abfd, name);
3523       if (newsect == NULL)
3524 	return false;
3525       newsect->vma = (hdr->p_vaddr + hdr->p_filesz) / opb;
3526       newsect->lma = (hdr->p_paddr + hdr->p_filesz) / opb;
3527       newsect->size = hdr->p_memsz - hdr->p_filesz;
3528       newsect->filepos = hdr->p_offset + hdr->p_filesz;
3529       align = newsect->vma & -newsect->vma;
3530       if (align == 0 || align > hdr->p_align)
3531 	align = hdr->p_align;
3532       newsect->alignment_power = bfd_log2 (align);
3533       if (hdr->p_type == PT_LOAD)
3534 	{
3535 	  newsect->flags |= SEC_ALLOC;
3536 	  if (hdr->p_flags & PF_X)
3537 	    newsect->flags |= SEC_CODE;
3538 	}
3539       if (!(hdr->p_flags & PF_W))
3540 	newsect->flags |= SEC_READONLY;
3541     }
3542 
3543   return true;
3544 }
3545 
3546 static bool
_bfd_elf_core_find_build_id(bfd * templ,bfd_vma offset)3547 _bfd_elf_core_find_build_id (bfd *templ, bfd_vma offset)
3548 {
3549   /* The return value is ignored.  Build-ids are considered optional.  */
3550   if (templ->xvec->flavour == bfd_target_elf_flavour)
3551     return (*get_elf_backend_data (templ)->elf_backend_core_find_build_id)
3552       (templ, offset);
3553   return false;
3554 }
3555 
3556 bool
bfd_section_from_phdr(bfd * abfd,Elf_Internal_Phdr * hdr,int hdr_index)3557 bfd_section_from_phdr (bfd *abfd, Elf_Internal_Phdr *hdr, int hdr_index)
3558 {
3559   const struct elf_backend_data *bed;
3560 
3561   switch (hdr->p_type)
3562     {
3563     case PT_NULL:
3564       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "null");
3565 
3566     case PT_LOAD:
3567       if (! _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "load"))
3568 	return false;
3569       if (bfd_get_format (abfd) == bfd_core && abfd->build_id == NULL)
3570 	_bfd_elf_core_find_build_id (abfd, hdr->p_offset);
3571       return true;
3572 
3573     case PT_DYNAMIC:
3574       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "dynamic");
3575 
3576     case PT_INTERP:
3577       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "interp");
3578 
3579     case PT_NOTE:
3580       if (! _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "note"))
3581 	return false;
3582       if (! elf_read_notes (abfd, hdr->p_offset, hdr->p_filesz,
3583 			    hdr->p_align))
3584 	return false;
3585       return true;
3586 
3587     case PT_SHLIB:
3588       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "shlib");
3589 
3590     case PT_PHDR:
3591       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "phdr");
3592 
3593     case PT_GNU_EH_FRAME:
3594       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index,
3595 					      "eh_frame_hdr");
3596 
3597     case PT_GNU_STACK:
3598       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "stack");
3599 
3600     case PT_GNU_RELRO:
3601       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "relro");
3602 
3603     case PT_GNU_SFRAME:
3604       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index,
3605 					      "sframe");
3606 
3607     default:
3608       /* Check for any processor-specific program segment types.  */
3609       bed = get_elf_backend_data (abfd);
3610       return bed->elf_backend_section_from_phdr (abfd, hdr, hdr_index, "proc");
3611     }
3612 }
3613 
3614 /* Return the REL_HDR for SEC, assuming there is only a single one, either
3615    REL or RELA.  */
3616 
3617 Elf_Internal_Shdr *
_bfd_elf_single_rel_hdr(asection * sec)3618 _bfd_elf_single_rel_hdr (asection *sec)
3619 {
3620   if (elf_section_data (sec)->rel.hdr)
3621     {
3622       BFD_ASSERT (elf_section_data (sec)->rela.hdr == NULL);
3623       return elf_section_data (sec)->rel.hdr;
3624     }
3625   else
3626     return elf_section_data (sec)->rela.hdr;
3627 }
3628 
3629 static bool
_bfd_elf_set_reloc_sh_name(bfd * abfd,Elf_Internal_Shdr * rel_hdr,const char * sec_name,bool use_rela_p)3630 _bfd_elf_set_reloc_sh_name (bfd *abfd,
3631 			    Elf_Internal_Shdr *rel_hdr,
3632 			    const char *sec_name,
3633 			    bool use_rela_p)
3634 {
3635   char *name = (char *) bfd_alloc (abfd,
3636 				   sizeof ".rela" + strlen (sec_name));
3637   if (name == NULL)
3638     return false;
3639 
3640   sprintf (name, "%s%s", use_rela_p ? ".rela" : ".rel", sec_name);
3641   rel_hdr->sh_name =
3642     (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd), name,
3643 					false);
3644   if (rel_hdr->sh_name == (unsigned int) -1)
3645     return false;
3646 
3647   return true;
3648 }
3649 
3650 /* Allocate and initialize a section-header for a new reloc section,
3651    containing relocations against ASECT.  It is stored in RELDATA.  If
3652    USE_RELA_P is TRUE, we use RELA relocations; otherwise, we use REL
3653    relocations.  */
3654 
3655 static bool
_bfd_elf_init_reloc_shdr(bfd * abfd,struct bfd_elf_section_reloc_data * reldata,const char * sec_name,bool use_rela_p,bool delay_st_name_p)3656 _bfd_elf_init_reloc_shdr (bfd *abfd,
3657 			  struct bfd_elf_section_reloc_data *reldata,
3658 			  const char *sec_name,
3659 			  bool use_rela_p,
3660 			  bool delay_st_name_p)
3661 {
3662   Elf_Internal_Shdr *rel_hdr;
3663   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3664 
3665   BFD_ASSERT (reldata->hdr == NULL);
3666   rel_hdr = bfd_zalloc (abfd, sizeof (*rel_hdr));
3667   if (rel_hdr == NULL)
3668     return false;
3669   reldata->hdr = rel_hdr;
3670 
3671   if (delay_st_name_p)
3672     rel_hdr->sh_name = (unsigned int) -1;
3673   else if (!_bfd_elf_set_reloc_sh_name (abfd, rel_hdr, sec_name,
3674 					use_rela_p))
3675     return false;
3676   rel_hdr->sh_type = use_rela_p ? SHT_RELA : SHT_REL;
3677   rel_hdr->sh_entsize = (use_rela_p
3678 			 ? bed->s->sizeof_rela
3679 			 : bed->s->sizeof_rel);
3680   rel_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
3681   rel_hdr->sh_flags = 0;
3682   rel_hdr->sh_addr = 0;
3683   rel_hdr->sh_size = 0;
3684   rel_hdr->sh_offset = 0;
3685 
3686   return true;
3687 }
3688 
3689 /* Return the default section type based on the passed in section flags.  */
3690 
3691 int
bfd_elf_get_default_section_type(flagword flags)3692 bfd_elf_get_default_section_type (flagword flags)
3693 {
3694   if ((flags & (SEC_ALLOC | SEC_IS_COMMON)) != 0
3695       && (flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
3696     return SHT_NOBITS;
3697   return SHT_PROGBITS;
3698 }
3699 
3700 struct fake_section_arg
3701 {
3702   struct bfd_link_info *link_info;
3703   bool failed;
3704 };
3705 
3706 /* Set up an ELF internal section header for a section.  */
3707 
3708 static void
elf_fake_sections(bfd * abfd,asection * asect,void * fsarg)3709 elf_fake_sections (bfd *abfd, asection *asect, void *fsarg)
3710 {
3711   struct fake_section_arg *arg = (struct fake_section_arg *)fsarg;
3712   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3713   struct bfd_elf_section_data *esd = elf_section_data (asect);
3714   Elf_Internal_Shdr *this_hdr;
3715   unsigned int sh_type;
3716   const char *name = asect->name;
3717   bool delay_st_name_p = false;
3718   bfd_vma mask;
3719 
3720   if (arg->failed)
3721     {
3722       /* We already failed; just get out of the bfd_map_over_sections
3723 	 loop.  */
3724       return;
3725     }
3726 
3727   this_hdr = &esd->this_hdr;
3728 
3729   /* ld: compress DWARF debug sections with names: .debug_*.  */
3730   if (arg->link_info
3731       && (abfd->flags & BFD_COMPRESS) != 0
3732       && (asect->flags & SEC_DEBUGGING) != 0
3733       && name[1] == 'd'
3734       && name[6] == '_')
3735     {
3736       /* If this section will be compressed, delay adding section
3737 	 name to section name section after it is compressed in
3738 	 _bfd_elf_assign_file_positions_for_non_load.  */
3739       delay_st_name_p = true;
3740     }
3741 
3742   if (delay_st_name_p)
3743     this_hdr->sh_name = (unsigned int) -1;
3744   else
3745     {
3746       this_hdr->sh_name
3747 	= (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd),
3748 					      name, false);
3749       if (this_hdr->sh_name == (unsigned int) -1)
3750 	{
3751 	  arg->failed = true;
3752 	  return;
3753 	}
3754     }
3755 
3756   /* Don't clear sh_flags. Assembler may set additional bits.  */
3757 
3758   if ((asect->flags & SEC_ALLOC) != 0
3759       || asect->user_set_vma)
3760     this_hdr->sh_addr = asect->vma * bfd_octets_per_byte (abfd, asect);
3761   else
3762     this_hdr->sh_addr = 0;
3763 
3764   this_hdr->sh_offset = 0;
3765   this_hdr->sh_size = asect->size;
3766   this_hdr->sh_link = 0;
3767   /* PR 17512: file: 0eb809fe, 8b0535ee.  */
3768   if (asect->alignment_power >= (sizeof (bfd_vma) * 8) - 1)
3769     {
3770       _bfd_error_handler
3771 	/* xgettext:c-format */
3772 	(_("%pB: error: alignment power %d of section `%pA' is too big"),
3773 	 abfd, asect->alignment_power, asect);
3774       arg->failed = true;
3775       return;
3776     }
3777   /* Set sh_addralign to the highest power of two given by alignment
3778      consistent with the section VMA.  Linker scripts can force VMA.  */
3779   mask = ((bfd_vma) 1 << asect->alignment_power) | this_hdr->sh_addr;
3780   this_hdr->sh_addralign = mask & -mask;
3781   /* The sh_entsize and sh_info fields may have been set already by
3782      copy_private_section_data.  */
3783 
3784   this_hdr->bfd_section = asect;
3785   this_hdr->contents = NULL;
3786 
3787   /* If the section type is unspecified, we set it based on
3788      asect->flags.  */
3789   if (asect->type != 0)
3790     sh_type = asect->type;
3791   else if ((asect->flags & SEC_GROUP) != 0)
3792     sh_type = SHT_GROUP;
3793   else
3794     sh_type = bfd_elf_get_default_section_type (asect->flags);
3795 
3796   if (this_hdr->sh_type == SHT_NULL)
3797     this_hdr->sh_type = sh_type;
3798   else if (this_hdr->sh_type == SHT_NOBITS
3799 	   && sh_type == SHT_PROGBITS
3800 	   && (asect->flags & SEC_ALLOC) != 0)
3801     {
3802       /* Warn if we are changing a NOBITS section to PROGBITS, but
3803 	 allow the link to proceed.  This can happen when users link
3804 	 non-bss input sections to bss output sections, or emit data
3805 	 to a bss output section via a linker script.  */
3806       _bfd_error_handler
3807 	(_("warning: section `%pA' type changed to PROGBITS"), asect);
3808       this_hdr->sh_type = sh_type;
3809     }
3810 
3811   switch (this_hdr->sh_type)
3812     {
3813     default:
3814       break;
3815 
3816     case SHT_STRTAB:
3817     case SHT_NOTE:
3818     case SHT_NOBITS:
3819     case SHT_PROGBITS:
3820       break;
3821 
3822     case SHT_INIT_ARRAY:
3823     case SHT_FINI_ARRAY:
3824     case SHT_PREINIT_ARRAY:
3825       this_hdr->sh_entsize = bed->s->arch_size / 8;
3826       break;
3827 
3828     case SHT_HASH:
3829       this_hdr->sh_entsize = bed->s->sizeof_hash_entry;
3830       break;
3831 
3832     case SHT_DYNSYM:
3833       this_hdr->sh_entsize = bed->s->sizeof_sym;
3834       break;
3835 
3836     case SHT_DYNAMIC:
3837       this_hdr->sh_entsize = bed->s->sizeof_dyn;
3838       break;
3839 
3840     case SHT_RELA:
3841       if (get_elf_backend_data (abfd)->may_use_rela_p)
3842 	this_hdr->sh_entsize = bed->s->sizeof_rela;
3843       break;
3844 
3845      case SHT_REL:
3846       if (get_elf_backend_data (abfd)->may_use_rel_p)
3847 	this_hdr->sh_entsize = bed->s->sizeof_rel;
3848       break;
3849 
3850      case SHT_GNU_versym:
3851       this_hdr->sh_entsize = sizeof (Elf_External_Versym);
3852       break;
3853 
3854      case SHT_GNU_verdef:
3855       this_hdr->sh_entsize = 0;
3856       /* objcopy or strip will copy over sh_info, but may not set
3857 	 cverdefs.  The linker will set cverdefs, but sh_info will be
3858 	 zero.  */
3859       if (this_hdr->sh_info == 0)
3860 	this_hdr->sh_info = elf_tdata (abfd)->cverdefs;
3861       else
3862 	BFD_ASSERT (elf_tdata (abfd)->cverdefs == 0
3863 		    || this_hdr->sh_info == elf_tdata (abfd)->cverdefs);
3864       break;
3865 
3866     case SHT_GNU_verneed:
3867       this_hdr->sh_entsize = 0;
3868       /* objcopy or strip will copy over sh_info, but may not set
3869 	 cverrefs.  The linker will set cverrefs, but sh_info will be
3870 	 zero.  */
3871       if (this_hdr->sh_info == 0)
3872 	this_hdr->sh_info = elf_tdata (abfd)->cverrefs;
3873       else
3874 	BFD_ASSERT (elf_tdata (abfd)->cverrefs == 0
3875 		    || this_hdr->sh_info == elf_tdata (abfd)->cverrefs);
3876       break;
3877 
3878     case SHT_GROUP:
3879       this_hdr->sh_entsize = GRP_ENTRY_SIZE;
3880       break;
3881 
3882     case SHT_GNU_HASH:
3883       this_hdr->sh_entsize = bed->s->arch_size == 64 ? 0 : 4;
3884       break;
3885     }
3886 
3887   if ((asect->flags & SEC_ALLOC) != 0)
3888     this_hdr->sh_flags |= SHF_ALLOC;
3889   if ((asect->flags & SEC_READONLY) == 0)
3890     this_hdr->sh_flags |= SHF_WRITE;
3891   if ((asect->flags & SEC_CODE) != 0)
3892     this_hdr->sh_flags |= SHF_EXECINSTR;
3893   if ((asect->flags & SEC_MERGE) != 0)
3894     {
3895       this_hdr->sh_flags |= SHF_MERGE;
3896       this_hdr->sh_entsize = asect->entsize;
3897     }
3898   if ((asect->flags & SEC_STRINGS) != 0)
3899     this_hdr->sh_flags |= SHF_STRINGS;
3900   if ((asect->flags & SEC_GROUP) == 0 && elf_group_name (asect) != NULL)
3901     this_hdr->sh_flags |= SHF_GROUP;
3902   if ((asect->flags & SEC_THREAD_LOCAL) != 0)
3903     {
3904       this_hdr->sh_flags |= SHF_TLS;
3905       if (asect->size == 0
3906 	  && (asect->flags & SEC_HAS_CONTENTS) == 0)
3907 	{
3908 	  struct bfd_link_order *o = asect->map_tail.link_order;
3909 
3910 	  this_hdr->sh_size = 0;
3911 	  if (o != NULL)
3912 	    {
3913 	      this_hdr->sh_size = o->offset + o->size;
3914 	      if (this_hdr->sh_size != 0)
3915 		this_hdr->sh_type = SHT_NOBITS;
3916 	    }
3917 	}
3918     }
3919   if ((asect->flags & (SEC_GROUP | SEC_EXCLUDE)) == SEC_EXCLUDE)
3920     this_hdr->sh_flags |= SHF_EXCLUDE;
3921 
3922   /* If the section has relocs, set up a section header for the
3923      SHT_REL[A] section.  If two relocation sections are required for
3924      this section, it is up to the processor-specific back-end to
3925      create the other.  */
3926   if ((asect->flags & SEC_RELOC) != 0)
3927     {
3928       /* When doing a relocatable link, create both REL and RELA sections if
3929 	 needed.  */
3930       if (arg->link_info
3931 	  /* Do the normal setup if we wouldn't create any sections here.  */
3932 	  && esd->rel.count + esd->rela.count > 0
3933 	  && (bfd_link_relocatable (arg->link_info)
3934 	      || arg->link_info->emitrelocations))
3935 	{
3936 	  if (esd->rel.count && esd->rel.hdr == NULL
3937 	      && !_bfd_elf_init_reloc_shdr (abfd, &esd->rel, name,
3938 					    false, delay_st_name_p))
3939 	    {
3940 	      arg->failed = true;
3941 	      return;
3942 	    }
3943 	  if (esd->rela.count && esd->rela.hdr == NULL
3944 	      && !_bfd_elf_init_reloc_shdr (abfd, &esd->rela, name,
3945 					    true, delay_st_name_p))
3946 	    {
3947 	      arg->failed = true;
3948 	      return;
3949 	    }
3950 	}
3951       else if (!_bfd_elf_init_reloc_shdr (abfd,
3952 					  (asect->use_rela_p
3953 					   ? &esd->rela : &esd->rel),
3954 					  name,
3955 					  asect->use_rela_p,
3956 					  delay_st_name_p))
3957 	{
3958 	  arg->failed = true;
3959 	  return;
3960 	}
3961     }
3962 
3963   /* Check for processor-specific section types.  */
3964   sh_type = this_hdr->sh_type;
3965   if (bed->elf_backend_fake_sections
3966       && !(*bed->elf_backend_fake_sections) (abfd, this_hdr, asect))
3967     {
3968       arg->failed = true;
3969       return;
3970     }
3971 
3972   if (sh_type == SHT_NOBITS && asect->size != 0)
3973     {
3974       /* Don't change the header type from NOBITS if we are being
3975 	 called for objcopy --only-keep-debug.  */
3976       this_hdr->sh_type = sh_type;
3977     }
3978 }
3979 
3980 /* Fill in the contents of a SHT_GROUP section.  Called from
3981    _bfd_elf_compute_section_file_positions for gas, objcopy, and
3982    when ELF targets use the generic linker, ld.  Called for ld -r
3983    from bfd_elf_final_link.  */
3984 
3985 void
bfd_elf_set_group_contents(bfd * abfd,asection * sec,void * failedptrarg)3986 bfd_elf_set_group_contents (bfd *abfd, asection *sec, void *failedptrarg)
3987 {
3988   bool *failedptr = (bool *) failedptrarg;
3989   asection *elt, *first;
3990   unsigned char *loc;
3991   bool gas;
3992 
3993   /* Ignore linker created group section.  See elfNN_ia64_object_p in
3994      elfxx-ia64.c.  */
3995   if ((sec->flags & (SEC_GROUP | SEC_LINKER_CREATED)) != SEC_GROUP
3996       || sec->size == 0
3997       || *failedptr)
3998     return;
3999 
4000   if (elf_section_data (sec)->this_hdr.sh_info == 0)
4001     {
4002       unsigned long symindx = 0;
4003 
4004       /* elf_group_id will have been set up by objcopy and the
4005 	 generic linker.  */
4006       if (elf_group_id (sec) != NULL)
4007 	symindx = elf_group_id (sec)->udata.i;
4008 
4009       if (symindx == 0)
4010 	{
4011 	  /* If called from the assembler, swap_out_syms will have set up
4012 	     elf_section_syms.
4013 	     PR 25699: A corrupt input file could contain bogus group info.  */
4014 	  if (sec->index >= elf_num_section_syms (abfd)
4015 	      || elf_section_syms (abfd)[sec->index] == NULL)
4016 	    {
4017 	      *failedptr = true;
4018 	      return;
4019 	    }
4020 	  symindx = elf_section_syms (abfd)[sec->index]->udata.i;
4021 	}
4022       elf_section_data (sec)->this_hdr.sh_info = symindx;
4023     }
4024   else if (elf_section_data (sec)->this_hdr.sh_info == (unsigned int) -2)
4025     {
4026       /* The ELF backend linker sets sh_info to -2 when the group
4027 	 signature symbol is global, and thus the index can't be
4028 	 set until all local symbols are output.  */
4029       asection *igroup;
4030       struct bfd_elf_section_data *sec_data;
4031       unsigned long symndx;
4032       unsigned long extsymoff;
4033       struct elf_link_hash_entry *h;
4034 
4035       /* The point of this little dance to the first SHF_GROUP section
4036 	 then back to the SHT_GROUP section is that this gets us to
4037 	 the SHT_GROUP in the input object.  */
4038       igroup = elf_sec_group (elf_next_in_group (sec));
4039       sec_data = elf_section_data (igroup);
4040       symndx = sec_data->this_hdr.sh_info;
4041       extsymoff = 0;
4042       if (!elf_bad_symtab (igroup->owner))
4043 	{
4044 	  Elf_Internal_Shdr *symtab_hdr;
4045 
4046 	  symtab_hdr = &elf_tdata (igroup->owner)->symtab_hdr;
4047 	  extsymoff = symtab_hdr->sh_info;
4048 	}
4049       h = elf_sym_hashes (igroup->owner)[symndx - extsymoff];
4050       while (h->root.type == bfd_link_hash_indirect
4051 	     || h->root.type == bfd_link_hash_warning)
4052 	h = (struct elf_link_hash_entry *) h->root.u.i.link;
4053 
4054       elf_section_data (sec)->this_hdr.sh_info = h->indx;
4055     }
4056 
4057   /* The contents won't be allocated for "ld -r" or objcopy.  */
4058   gas = true;
4059   if (sec->contents == NULL)
4060     {
4061       gas = false;
4062       sec->contents = (unsigned char *) bfd_alloc (abfd, sec->size);
4063 
4064       /* Arrange for the section to be written out.  */
4065       elf_section_data (sec)->this_hdr.contents = sec->contents;
4066       if (sec->contents == NULL)
4067 	{
4068 	  *failedptr = true;
4069 	  return;
4070 	}
4071     }
4072 
4073   loc = sec->contents + sec->size;
4074 
4075   /* Get the pointer to the first section in the group that gas
4076      squirreled away here.  objcopy arranges for this to be set to the
4077      start of the input section group.  */
4078   first = elt = elf_next_in_group (sec);
4079 
4080   /* First element is a flag word.  Rest of section is elf section
4081      indices for all the sections of the group.  Write them backwards
4082      just to keep the group in the same order as given in .section
4083      directives, not that it matters.  */
4084   while (elt != NULL)
4085     {
4086       asection *s;
4087 
4088       s = elt;
4089       if (!gas)
4090 	s = s->output_section;
4091       if (s != NULL
4092 	  && !bfd_is_abs_section (s))
4093 	{
4094 	  struct bfd_elf_section_data *elf_sec = elf_section_data (s);
4095 	  struct bfd_elf_section_data *input_elf_sec = elf_section_data (elt);
4096 
4097 	  if (elf_sec->rel.hdr != NULL
4098 	      && (gas
4099 		  || (input_elf_sec->rel.hdr != NULL
4100 		      && input_elf_sec->rel.hdr->sh_flags & SHF_GROUP) != 0))
4101 	    {
4102 	      elf_sec->rel.hdr->sh_flags |= SHF_GROUP;
4103 	      loc -= 4;
4104 	      if (loc == sec->contents)
4105 		break;
4106 	      H_PUT_32 (abfd, elf_sec->rel.idx, loc);
4107 	    }
4108 	  if (elf_sec->rela.hdr != NULL
4109 	      && (gas
4110 		  || (input_elf_sec->rela.hdr != NULL
4111 		      && input_elf_sec->rela.hdr->sh_flags & SHF_GROUP) != 0))
4112 	    {
4113 	      elf_sec->rela.hdr->sh_flags |= SHF_GROUP;
4114 	      loc -= 4;
4115 	      if (loc == sec->contents)
4116 		break;
4117 	      H_PUT_32 (abfd, elf_sec->rela.idx, loc);
4118 	    }
4119 	  loc -= 4;
4120 	  if (loc == sec->contents)
4121 	    break;
4122 	  H_PUT_32 (abfd, elf_sec->this_idx, loc);
4123 	}
4124       elt = elf_next_in_group (elt);
4125       if (elt == first)
4126 	break;
4127     }
4128 
4129   /* We should always get here with loc == sec->contents + 4, but it is
4130      possible to craft bogus SHT_GROUP sections that will cause segfaults
4131      in objcopy without checking loc here and in the loop above.  */
4132   if (loc == sec->contents)
4133     BFD_ASSERT (0);
4134   else
4135     {
4136       loc -= 4;
4137       if (loc != sec->contents)
4138 	{
4139 	  BFD_ASSERT (0);
4140 	  memset (sec->contents + 4, 0, loc - sec->contents);
4141 	  loc = sec->contents;
4142 	}
4143     }
4144 
4145   H_PUT_32 (abfd, sec->flags & SEC_LINK_ONCE ? GRP_COMDAT : 0, loc);
4146 }
4147 
4148 /* Given NAME, the name of a relocation section stripped of its
4149    .rel/.rela prefix, return the section in ABFD to which the
4150    relocations apply.  */
4151 
4152 asection *
_bfd_elf_plt_get_reloc_section(bfd * abfd,const char * name)4153 _bfd_elf_plt_get_reloc_section (bfd *abfd, const char *name)
4154 {
4155   /* If a target needs .got.plt section, relocations in rela.plt/rel.plt
4156      section likely apply to .got.plt or .got section.  */
4157   if (get_elf_backend_data (abfd)->want_got_plt
4158       && strcmp (name, ".plt") == 0)
4159     {
4160       asection *sec;
4161 
4162       name = ".got.plt";
4163       sec = bfd_get_section_by_name (abfd, name);
4164       if (sec != NULL)
4165 	return sec;
4166       name = ".got";
4167     }
4168 
4169   return bfd_get_section_by_name (abfd, name);
4170 }
4171 
4172 /* Return the section to which RELOC_SEC applies.  */
4173 
4174 static asection *
elf_get_reloc_section(asection * reloc_sec)4175 elf_get_reloc_section (asection *reloc_sec)
4176 {
4177   const char *name;
4178   unsigned int type;
4179   bfd *abfd;
4180   const struct elf_backend_data *bed;
4181 
4182   type = elf_section_data (reloc_sec)->this_hdr.sh_type;
4183   if (type != SHT_REL && type != SHT_RELA)
4184     return NULL;
4185 
4186   /* We look up the section the relocs apply to by name.  */
4187   name = reloc_sec->name;
4188   if (!startswith (name, ".rel"))
4189     return NULL;
4190   name += 4;
4191   if (type == SHT_RELA && *name++ != 'a')
4192     return NULL;
4193 
4194   abfd = reloc_sec->owner;
4195   bed = get_elf_backend_data (abfd);
4196   return bed->get_reloc_section (abfd, name);
4197 }
4198 
4199 /* Assign all ELF section numbers.  The dummy first section is handled here
4200    too.  The link/info pointers for the standard section types are filled
4201    in here too, while we're at it.  LINK_INFO will be 0 when arriving
4202    here for gas, objcopy, and when using the generic ELF linker.  */
4203 
4204 static bool
assign_section_numbers(bfd * abfd,struct bfd_link_info * link_info)4205 assign_section_numbers (bfd *abfd, struct bfd_link_info *link_info)
4206 {
4207   struct elf_obj_tdata *t = elf_tdata (abfd);
4208   asection *sec;
4209   unsigned int section_number;
4210   Elf_Internal_Shdr **i_shdrp;
4211   struct bfd_elf_section_data *d;
4212   bool need_symtab;
4213   size_t amt;
4214 
4215   section_number = 1;
4216 
4217   _bfd_elf_strtab_clear_all_refs (elf_shstrtab (abfd));
4218 
4219   /* SHT_GROUP sections are in relocatable files only.  */
4220   if (link_info == NULL || !link_info->resolve_section_groups)
4221     {
4222       size_t reloc_count = 0;
4223 
4224       /* Put SHT_GROUP sections first.  */
4225       for (sec = abfd->sections; sec != NULL; sec = sec->next)
4226 	{
4227 	  d = elf_section_data (sec);
4228 
4229 	  if (d->this_hdr.sh_type == SHT_GROUP)
4230 	    {
4231 	      if (sec->flags & SEC_LINKER_CREATED)
4232 		{
4233 		  /* Remove the linker created SHT_GROUP sections.  */
4234 		  bfd_section_list_remove (abfd, sec);
4235 		  abfd->section_count--;
4236 		}
4237 	      else
4238 		d->this_idx = section_number++;
4239 	    }
4240 
4241 	  /* Count relocations.  */
4242 	  reloc_count += sec->reloc_count;
4243 	}
4244 
4245       /* Set/clear HAS_RELOC depending on whether there are relocations.  */
4246       if (reloc_count == 0)
4247 	abfd->flags &= ~HAS_RELOC;
4248       else
4249 	abfd->flags |= HAS_RELOC;
4250     }
4251 
4252   for (sec = abfd->sections; sec; sec = sec->next)
4253     {
4254       d = elf_section_data (sec);
4255 
4256       if (d->this_hdr.sh_type != SHT_GROUP)
4257 	d->this_idx = section_number++;
4258       if (d->this_hdr.sh_name != (unsigned int) -1)
4259 	_bfd_elf_strtab_addref (elf_shstrtab (abfd), d->this_hdr.sh_name);
4260       if (d->rel.hdr)
4261 	{
4262 	  d->rel.idx = section_number++;
4263 	  if (d->rel.hdr->sh_name != (unsigned int) -1)
4264 	    _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->rel.hdr->sh_name);
4265 	}
4266       else
4267 	d->rel.idx = 0;
4268 
4269       if (d->rela.hdr)
4270 	{
4271 	  d->rela.idx = section_number++;
4272 	  if (d->rela.hdr->sh_name != (unsigned int) -1)
4273 	    _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->rela.hdr->sh_name);
4274 	}
4275       else
4276 	d->rela.idx = 0;
4277     }
4278 
4279   need_symtab = (bfd_get_symcount (abfd) > 0
4280 		 || (link_info == NULL
4281 		     && ((abfd->flags & (EXEC_P | DYNAMIC | HAS_RELOC))
4282 			 == HAS_RELOC)));
4283   if (need_symtab)
4284     {
4285       elf_onesymtab (abfd) = section_number++;
4286       _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->symtab_hdr.sh_name);
4287       if (section_number > ((SHN_LORESERVE - 2) & 0xFFFF))
4288 	{
4289 	  elf_section_list *entry;
4290 
4291 	  BFD_ASSERT (elf_symtab_shndx_list (abfd) == NULL);
4292 
4293 	  entry = bfd_zalloc (abfd, sizeof (*entry));
4294 	  entry->ndx = section_number++;
4295 	  elf_symtab_shndx_list (abfd) = entry;
4296 	  entry->hdr.sh_name
4297 	    = (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd),
4298 						  ".symtab_shndx", false);
4299 	  if (entry->hdr.sh_name == (unsigned int) -1)
4300 	    return false;
4301 	}
4302       elf_strtab_sec (abfd) = section_number++;
4303       _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->strtab_hdr.sh_name);
4304     }
4305 
4306   elf_shstrtab_sec (abfd) = section_number++;
4307   _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->shstrtab_hdr.sh_name);
4308   elf_elfheader (abfd)->e_shstrndx = elf_shstrtab_sec (abfd);
4309 
4310   if (section_number >= SHN_LORESERVE)
4311     {
4312       /* xgettext:c-format */
4313       _bfd_error_handler (_("%pB: too many sections: %u"),
4314 			  abfd, section_number);
4315       return false;
4316     }
4317 
4318   elf_numsections (abfd) = section_number;
4319   elf_elfheader (abfd)->e_shnum = section_number;
4320 
4321   /* Set up the list of section header pointers, in agreement with the
4322      indices.  */
4323   amt = section_number * sizeof (Elf_Internal_Shdr *);
4324   i_shdrp = (Elf_Internal_Shdr **) bfd_zalloc (abfd, amt);
4325   if (i_shdrp == NULL)
4326     return false;
4327 
4328   i_shdrp[0] = (Elf_Internal_Shdr *) bfd_zalloc (abfd,
4329 						 sizeof (Elf_Internal_Shdr));
4330   if (i_shdrp[0] == NULL)
4331     {
4332       bfd_release (abfd, i_shdrp);
4333       return false;
4334     }
4335 
4336   elf_elfsections (abfd) = i_shdrp;
4337 
4338   i_shdrp[elf_shstrtab_sec (abfd)] = &t->shstrtab_hdr;
4339   if (need_symtab)
4340     {
4341       i_shdrp[elf_onesymtab (abfd)] = &t->symtab_hdr;
4342       if (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF))
4343 	{
4344 	  elf_section_list * entry = elf_symtab_shndx_list (abfd);
4345 	  BFD_ASSERT (entry != NULL);
4346 	  i_shdrp[entry->ndx] = & entry->hdr;
4347 	  entry->hdr.sh_link = elf_onesymtab (abfd);
4348 	}
4349       i_shdrp[elf_strtab_sec (abfd)] = &t->strtab_hdr;
4350       t->symtab_hdr.sh_link = elf_strtab_sec (abfd);
4351     }
4352 
4353   for (sec = abfd->sections; sec; sec = sec->next)
4354     {
4355       asection *s;
4356 
4357       d = elf_section_data (sec);
4358 
4359       i_shdrp[d->this_idx] = &d->this_hdr;
4360       if (d->rel.idx != 0)
4361 	i_shdrp[d->rel.idx] = d->rel.hdr;
4362       if (d->rela.idx != 0)
4363 	i_shdrp[d->rela.idx] = d->rela.hdr;
4364 
4365       /* Fill in the sh_link and sh_info fields while we're at it.  */
4366 
4367       /* sh_link of a reloc section is the section index of the symbol
4368 	 table.  sh_info is the section index of the section to which
4369 	 the relocation entries apply.  */
4370       if (d->rel.idx != 0)
4371 	{
4372 	  d->rel.hdr->sh_link = elf_onesymtab (abfd);
4373 	  d->rel.hdr->sh_info = d->this_idx;
4374 	  d->rel.hdr->sh_flags |= SHF_INFO_LINK;
4375 	}
4376       if (d->rela.idx != 0)
4377 	{
4378 	  d->rela.hdr->sh_link = elf_onesymtab (abfd);
4379 	  d->rela.hdr->sh_info = d->this_idx;
4380 	  d->rela.hdr->sh_flags |= SHF_INFO_LINK;
4381 	}
4382 
4383       /* We need to set up sh_link for SHF_LINK_ORDER.  */
4384       if ((d->this_hdr.sh_flags & SHF_LINK_ORDER) != 0)
4385 	{
4386 	  s = elf_linked_to_section (sec);
4387 	  /* We can now have a NULL linked section pointer.
4388 	     This happens when the sh_link field is 0, which is done
4389 	     when a linked to section is discarded but the linking
4390 	     section has been retained for some reason.  */
4391 	  if (s)
4392 	    {
4393 	      /* Check discarded linkonce section.  */
4394 	      if (discarded_section (s))
4395 		{
4396 		  asection *kept;
4397 		  _bfd_error_handler
4398 		    /* xgettext:c-format */
4399 		    (_("%pB: sh_link of section `%pA' points to"
4400 		       " discarded section `%pA' of `%pB'"),
4401 		     abfd, d->this_hdr.bfd_section, s, s->owner);
4402 		  /* Point to the kept section if it has the same
4403 		     size as the discarded one.  */
4404 		  kept = _bfd_elf_check_kept_section (s, link_info);
4405 		  if (kept == NULL)
4406 		    {
4407 		      bfd_set_error (bfd_error_bad_value);
4408 		      return false;
4409 		    }
4410 		  s = kept;
4411 		}
4412 	      /* Handle objcopy. */
4413 	      else if (s->output_section == NULL)
4414 		{
4415 		  _bfd_error_handler
4416 		    /* xgettext:c-format */
4417 		    (_("%pB: sh_link of section `%pA' points to"
4418 		       " removed section `%pA' of `%pB'"),
4419 		     abfd, d->this_hdr.bfd_section, s, s->owner);
4420 		  bfd_set_error (bfd_error_bad_value);
4421 		  return false;
4422 		}
4423 	      s = s->output_section;
4424 	      d->this_hdr.sh_link = elf_section_data (s)->this_idx;
4425 	    }
4426 	}
4427 
4428       switch (d->this_hdr.sh_type)
4429 	{
4430 	case SHT_REL:
4431 	case SHT_RELA:
4432 	  /* sh_link is the section index of the symbol table.
4433 	     sh_info is the section index of the section to which the
4434 	     relocation entries apply.  */
4435 	  if (d->this_hdr.sh_link == 0)
4436 	    {
4437 	      /* FIXME maybe: If this is a reloc section which we are
4438 		 treating as a normal section then we likely should
4439 		 not be assuming its sh_link is .dynsym or .symtab.  */
4440 	      if ((sec->flags & SEC_ALLOC) != 0)
4441 		{
4442 		  s = bfd_get_section_by_name (abfd, ".dynsym");
4443 		  if (s != NULL)
4444 		    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
4445 		}
4446 	      else
4447 		d->this_hdr.sh_link = elf_onesymtab (abfd);
4448 	    }
4449 
4450 	  s = elf_get_reloc_section (sec);
4451 	  if (s != NULL)
4452 	    {
4453 	      d->this_hdr.sh_info = elf_section_data (s)->this_idx;
4454 	      d->this_hdr.sh_flags |= SHF_INFO_LINK;
4455 	    }
4456 	  break;
4457 
4458 	case SHT_STRTAB:
4459 	  /* We assume that a section named .stab*str is a stabs
4460 	     string section.  We look for a section with the same name
4461 	     but without the trailing ``str'', and set its sh_link
4462 	     field to point to this section.  */
4463 	  if (startswith (sec->name, ".stab")
4464 	      && strcmp (sec->name + strlen (sec->name) - 3, "str") == 0)
4465 	    {
4466 	      size_t len;
4467 	      char *alc;
4468 
4469 	      len = strlen (sec->name);
4470 	      alc = (char *) bfd_malloc (len - 2);
4471 	      if (alc == NULL)
4472 		return false;
4473 	      memcpy (alc, sec->name, len - 3);
4474 	      alc[len - 3] = '\0';
4475 	      s = bfd_get_section_by_name (abfd, alc);
4476 	      free (alc);
4477 	      if (s != NULL)
4478 		{
4479 		  elf_section_data (s)->this_hdr.sh_link = d->this_idx;
4480 
4481 		  /* This is a .stab section.  */
4482 		  elf_section_data (s)->this_hdr.sh_entsize = 12;
4483 		}
4484 	    }
4485 	  break;
4486 
4487 	case SHT_DYNAMIC:
4488 	case SHT_DYNSYM:
4489 	case SHT_GNU_verneed:
4490 	case SHT_GNU_verdef:
4491 	  /* sh_link is the section header index of the string table
4492 	     used for the dynamic entries, or the symbol table, or the
4493 	     version strings.  */
4494 	  s = bfd_get_section_by_name (abfd, ".dynstr");
4495 	  if (s != NULL)
4496 	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
4497 	  break;
4498 
4499 	case SHT_GNU_LIBLIST:
4500 	  /* sh_link is the section header index of the prelink library
4501 	     list used for the dynamic entries, or the symbol table, or
4502 	     the version strings.  */
4503 	  s = bfd_get_section_by_name (abfd, ((sec->flags & SEC_ALLOC)
4504 					      ? ".dynstr" : ".gnu.libstr"));
4505 	  if (s != NULL)
4506 	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
4507 	  break;
4508 
4509 	case SHT_HASH:
4510 	case SHT_GNU_HASH:
4511 	case SHT_GNU_versym:
4512 	  /* sh_link is the section header index of the symbol table
4513 	     this hash table or version table is for.  */
4514 	  s = bfd_get_section_by_name (abfd, ".dynsym");
4515 	  if (s != NULL)
4516 	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
4517 	  break;
4518 
4519 	case SHT_GROUP:
4520 	  d->this_hdr.sh_link = elf_onesymtab (abfd);
4521 	}
4522     }
4523 
4524   /* Delay setting sh_name to _bfd_elf_write_object_contents so that
4525      _bfd_elf_assign_file_positions_for_non_load can convert DWARF
4526      debug section name from .debug_* to .zdebug_* if needed.  */
4527 
4528   return true;
4529 }
4530 
4531 static bool
sym_is_global(bfd * abfd,asymbol * sym)4532 sym_is_global (bfd *abfd, asymbol *sym)
4533 {
4534   /* If the backend has a special mapping, use it.  */
4535   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4536   if (bed->elf_backend_sym_is_global)
4537     return (*bed->elf_backend_sym_is_global) (abfd, sym);
4538 
4539   return ((sym->flags & (BSF_GLOBAL | BSF_WEAK | BSF_GNU_UNIQUE)) != 0
4540 	  || bfd_is_und_section (bfd_asymbol_section (sym))
4541 	  || bfd_is_com_section (bfd_asymbol_section (sym)));
4542 }
4543 
4544 /* Filter global symbols of ABFD to include in the import library.  All
4545    SYMCOUNT symbols of ABFD can be examined from their pointers in
4546    SYMS.  Pointers of symbols to keep should be stored contiguously at
4547    the beginning of that array.
4548 
4549    Returns the number of symbols to keep.  */
4550 
4551 unsigned int
_bfd_elf_filter_global_symbols(bfd * abfd,struct bfd_link_info * info,asymbol ** syms,long symcount)4552 _bfd_elf_filter_global_symbols (bfd *abfd, struct bfd_link_info *info,
4553 				asymbol **syms, long symcount)
4554 {
4555   long src_count, dst_count = 0;
4556 
4557   for (src_count = 0; src_count < symcount; src_count++)
4558     {
4559       asymbol *sym = syms[src_count];
4560       char *name = (char *) bfd_asymbol_name (sym);
4561       struct bfd_link_hash_entry *h;
4562 
4563       if (!sym_is_global (abfd, sym))
4564 	continue;
4565 
4566       h = bfd_link_hash_lookup (info->hash, name, false, false, false);
4567       if (h == NULL)
4568 	continue;
4569       if (h->type != bfd_link_hash_defined && h->type != bfd_link_hash_defweak)
4570 	continue;
4571       if (h->linker_def || h->ldscript_def)
4572 	continue;
4573 
4574       syms[dst_count++] = sym;
4575     }
4576 
4577   syms[dst_count] = NULL;
4578 
4579   return dst_count;
4580 }
4581 
4582 /* Don't output section symbols for sections that are not going to be
4583    output, that are duplicates or there is no BFD section.  */
4584 
4585 static bool
ignore_section_sym(bfd * abfd,asymbol * sym)4586 ignore_section_sym (bfd *abfd, asymbol *sym)
4587 {
4588   elf_symbol_type *type_ptr;
4589 
4590   if (sym == NULL)
4591     return false;
4592 
4593   if ((sym->flags & BSF_SECTION_SYM) == 0)
4594     return false;
4595 
4596   /* Ignore the section symbol if it isn't used.  */
4597   if ((sym->flags & BSF_SECTION_SYM_USED) == 0)
4598     return true;
4599 
4600   if (sym->section == NULL)
4601     return true;
4602 
4603   type_ptr = elf_symbol_from (sym);
4604   return ((type_ptr != NULL
4605 	   && type_ptr->internal_elf_sym.st_shndx != 0
4606 	   && bfd_is_abs_section (sym->section))
4607 	  || !(sym->section->owner == abfd
4608 	       || (sym->section->output_section != NULL
4609 		   && sym->section->output_section->owner == abfd
4610 		   && sym->section->output_offset == 0)
4611 	       || bfd_is_abs_section (sym->section)));
4612 }
4613 
4614 /* Map symbol from it's internal number to the external number, moving
4615    all local symbols to be at the head of the list.  */
4616 
4617 static bool
elf_map_symbols(bfd * abfd,unsigned int * pnum_locals)4618 elf_map_symbols (bfd *abfd, unsigned int *pnum_locals)
4619 {
4620   unsigned int symcount = bfd_get_symcount (abfd);
4621   asymbol **syms = bfd_get_outsymbols (abfd);
4622   asymbol **sect_syms;
4623   unsigned int num_locals = 0;
4624   unsigned int num_globals = 0;
4625   unsigned int num_locals2 = 0;
4626   unsigned int num_globals2 = 0;
4627   unsigned int max_index = 0;
4628   unsigned int idx;
4629   asection *asect;
4630   asymbol **new_syms;
4631   size_t amt;
4632 
4633 #ifdef DEBUG
4634   fprintf (stderr, "elf_map_symbols\n");
4635   fflush (stderr);
4636 #endif
4637 
4638   for (asect = abfd->sections; asect; asect = asect->next)
4639     {
4640       if (max_index < asect->index)
4641 	max_index = asect->index;
4642     }
4643 
4644   max_index++;
4645   amt = max_index * sizeof (asymbol *);
4646   sect_syms = (asymbol **) bfd_zalloc (abfd, amt);
4647   if (sect_syms == NULL)
4648     return false;
4649   elf_section_syms (abfd) = sect_syms;
4650   elf_num_section_syms (abfd) = max_index;
4651 
4652   /* Init sect_syms entries for any section symbols we have already
4653      decided to output.  */
4654   for (idx = 0; idx < symcount; idx++)
4655     {
4656       asymbol *sym = syms[idx];
4657 
4658       if ((sym->flags & BSF_SECTION_SYM) != 0
4659 	  && sym->value == 0
4660 	  && !ignore_section_sym (abfd, sym)
4661 	  && !bfd_is_abs_section (sym->section))
4662 	{
4663 	  asection *sec = sym->section;
4664 
4665 	  if (sec->owner != abfd)
4666 	    sec = sec->output_section;
4667 
4668 	  sect_syms[sec->index] = syms[idx];
4669 	}
4670     }
4671 
4672   /* Classify all of the symbols.  */
4673   for (idx = 0; idx < symcount; idx++)
4674     {
4675       if (sym_is_global (abfd, syms[idx]))
4676 	num_globals++;
4677       else if (!ignore_section_sym (abfd, syms[idx]))
4678 	num_locals++;
4679     }
4680 
4681   /* We will be adding a section symbol for each normal BFD section.  Most
4682      sections will already have a section symbol in outsymbols, but
4683      eg. SHT_GROUP sections will not, and we need the section symbol mapped
4684      at least in that case.  */
4685   for (asect = abfd->sections; asect; asect = asect->next)
4686     {
4687       asymbol *sym = asect->symbol;
4688       /* Don't include ignored section symbols.  */
4689       if (!ignore_section_sym (abfd, sym)
4690 	  && sect_syms[asect->index] == NULL)
4691 	{
4692 	  if (!sym_is_global (abfd, asect->symbol))
4693 	    num_locals++;
4694 	  else
4695 	    num_globals++;
4696 	}
4697     }
4698 
4699   /* Now sort the symbols so the local symbols are first.  */
4700   amt = (num_locals + num_globals) * sizeof (asymbol *);
4701   new_syms = (asymbol **) bfd_alloc (abfd, amt);
4702   if (new_syms == NULL)
4703     return false;
4704 
4705   for (idx = 0; idx < symcount; idx++)
4706     {
4707       asymbol *sym = syms[idx];
4708       unsigned int i;
4709 
4710       if (sym_is_global (abfd, sym))
4711 	i = num_locals + num_globals2++;
4712       /* Don't include ignored section symbols.  */
4713       else if (!ignore_section_sym (abfd, sym))
4714 	i = num_locals2++;
4715       else
4716 	continue;
4717       new_syms[i] = sym;
4718       sym->udata.i = i + 1;
4719     }
4720   for (asect = abfd->sections; asect; asect = asect->next)
4721     {
4722       asymbol *sym = asect->symbol;
4723       if (!ignore_section_sym (abfd, sym)
4724 	  && sect_syms[asect->index] == NULL)
4725 	{
4726 	  unsigned int i;
4727 
4728 	  sect_syms[asect->index] = sym;
4729 	  if (!sym_is_global (abfd, sym))
4730 	    i = num_locals2++;
4731 	  else
4732 	    i = num_locals + num_globals2++;
4733 	  new_syms[i] = sym;
4734 	  sym->udata.i = i + 1;
4735 	}
4736     }
4737 
4738   bfd_set_symtab (abfd, new_syms, num_locals + num_globals);
4739 
4740   *pnum_locals = num_locals;
4741   return true;
4742 }
4743 
4744 /* Align to the maximum file alignment that could be required for any
4745    ELF data structure.  */
4746 
4747 static inline file_ptr
align_file_position(file_ptr off,int align)4748 align_file_position (file_ptr off, int align)
4749 {
4750   return (off + align - 1) & ~(align - 1);
4751 }
4752 
4753 /* Assign a file position to a section, optionally aligning to the
4754    required section alignment.  */
4755 
4756 file_ptr
_bfd_elf_assign_file_position_for_section(Elf_Internal_Shdr * i_shdrp,file_ptr offset,bool align)4757 _bfd_elf_assign_file_position_for_section (Elf_Internal_Shdr *i_shdrp,
4758 					   file_ptr offset,
4759 					   bool align)
4760 {
4761   if (align && i_shdrp->sh_addralign > 1)
4762     offset = BFD_ALIGN (offset, i_shdrp->sh_addralign & -i_shdrp->sh_addralign);
4763   i_shdrp->sh_offset = offset;
4764   if (i_shdrp->bfd_section != NULL)
4765     i_shdrp->bfd_section->filepos = offset;
4766   if (i_shdrp->sh_type != SHT_NOBITS)
4767     offset += i_shdrp->sh_size;
4768   return offset;
4769 }
4770 
4771 /* Compute the file positions we are going to put the sections at, and
4772    otherwise prepare to begin writing out the ELF file.  If LINK_INFO
4773    is not NULL, this is being called by the ELF backend linker.  */
4774 
4775 bool
_bfd_elf_compute_section_file_positions(bfd * abfd,struct bfd_link_info * link_info)4776 _bfd_elf_compute_section_file_positions (bfd *abfd,
4777 					 struct bfd_link_info *link_info)
4778 {
4779   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4780   struct fake_section_arg fsargs;
4781   bool failed;
4782   struct elf_strtab_hash *strtab = NULL;
4783   Elf_Internal_Shdr *shstrtab_hdr;
4784   bool need_symtab;
4785 
4786   if (abfd->output_has_begun)
4787     return true;
4788 
4789   /* Do any elf backend specific processing first.  */
4790   if (bed->elf_backend_begin_write_processing)
4791     (*bed->elf_backend_begin_write_processing) (abfd, link_info);
4792 
4793   if (!(*bed->elf_backend_init_file_header) (abfd, link_info))
4794     return false;
4795 
4796   fsargs.failed = false;
4797   fsargs.link_info = link_info;
4798   bfd_map_over_sections (abfd, elf_fake_sections, &fsargs);
4799   if (fsargs.failed)
4800     return false;
4801 
4802   if (!assign_section_numbers (abfd, link_info))
4803     return false;
4804 
4805   /* The backend linker builds symbol table information itself.  */
4806   need_symtab = (link_info == NULL
4807 		 && (bfd_get_symcount (abfd) > 0
4808 		     || ((abfd->flags & (EXEC_P | DYNAMIC | HAS_RELOC))
4809 			 == HAS_RELOC)));
4810   if (need_symtab)
4811     {
4812       /* Non-zero if doing a relocatable link.  */
4813       int relocatable_p = ! (abfd->flags & (EXEC_P | DYNAMIC));
4814 
4815       if (! swap_out_syms (abfd, &strtab, relocatable_p, link_info))
4816 	return false;
4817     }
4818 
4819   failed = false;
4820   if (link_info == NULL)
4821     {
4822       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
4823       if (failed)
4824 	goto err_free_strtab;
4825     }
4826 
4827   shstrtab_hdr = &elf_tdata (abfd)->shstrtab_hdr;
4828   /* sh_name was set in init_file_header.  */
4829   shstrtab_hdr->sh_type = SHT_STRTAB;
4830   shstrtab_hdr->sh_flags = bed->elf_strtab_flags;
4831   shstrtab_hdr->sh_addr = 0;
4832   /* sh_size is set in _bfd_elf_assign_file_positions_for_non_load.  */
4833   shstrtab_hdr->sh_entsize = 0;
4834   shstrtab_hdr->sh_link = 0;
4835   shstrtab_hdr->sh_info = 0;
4836   /* sh_offset is set in _bfd_elf_assign_file_positions_for_non_load.  */
4837   shstrtab_hdr->sh_addralign = 1;
4838 
4839   if (!assign_file_positions_except_relocs (abfd, link_info))
4840     goto err_free_strtab;
4841 
4842   if (strtab != NULL)
4843     {
4844       file_ptr off;
4845       Elf_Internal_Shdr *hdr;
4846 
4847       off = elf_next_file_pos (abfd);
4848 
4849       hdr = & elf_symtab_hdr (abfd);
4850       off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
4851 
4852       if (elf_symtab_shndx_list (abfd) != NULL)
4853 	{
4854 	  hdr = & elf_symtab_shndx_list (abfd)->hdr;
4855 	  if (hdr->sh_size != 0)
4856 	    off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
4857 	  /* FIXME: What about other symtab_shndx sections in the list ?  */
4858 	}
4859 
4860       hdr = &elf_tdata (abfd)->strtab_hdr;
4861       off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
4862 
4863       elf_next_file_pos (abfd) = off;
4864 
4865       /* Now that we know where the .strtab section goes, write it
4866 	 out.  */
4867       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
4868 	  || ! _bfd_elf_strtab_emit (abfd, strtab))
4869 	goto err_free_strtab;
4870       _bfd_elf_strtab_free (strtab);
4871     }
4872 
4873   abfd->output_has_begun = true;
4874   return true;
4875 
4876  err_free_strtab:
4877   if (strtab != NULL)
4878     _bfd_elf_strtab_free (strtab);
4879   return false;
4880 }
4881 
4882 /* Retrieve .eh_frame_hdr.  Prior to size_dynamic_sections the
4883    function effectively returns whether --eh-frame-hdr is given on the
4884    command line.  After size_dynamic_sections the result reflects
4885    whether .eh_frame_hdr will actually be output (sizing isn't done
4886    until ldemul_after_allocation).  */
4887 
4888 static asection *
elf_eh_frame_hdr(const struct bfd_link_info * info)4889 elf_eh_frame_hdr (const struct bfd_link_info *info)
4890 {
4891   if (info != NULL && is_elf_hash_table (info->hash))
4892     return elf_hash_table (info)->eh_info.hdr_sec;
4893   return NULL;
4894 }
4895 
4896 /* Make an initial estimate of the size of the program header.  If we
4897    get the number wrong here, we'll redo section placement.  */
4898 
4899 static bfd_size_type
get_program_header_size(bfd * abfd,struct bfd_link_info * info)4900 get_program_header_size (bfd *abfd, struct bfd_link_info *info)
4901 {
4902   size_t segs;
4903   asection *s, *s2;
4904   const struct elf_backend_data *bed;
4905 
4906   /* Assume we will need exactly two PT_LOAD segments: one for text
4907      and one for data.  */
4908   segs = 2;
4909 
4910   s = bfd_get_section_by_name (abfd, ".interp");
4911   s2 = bfd_get_section_by_name (abfd, ".dynamic");
4912   if (s != NULL && (s->flags & SEC_LOAD) != 0 && s->size != 0)
4913     {
4914       ++segs;
4915     }
4916 
4917   if (s2 != NULL && (s2->flags & SEC_LOAD) != 0)
4918     {
4919       /* We need a PT_DYNAMIC segment.  */
4920       ++segs;
4921     }
4922 
4923   if ((s != NULL && (s->flags & SEC_LOAD) != 0) ||
4924       (s2 != NULL && (s2->flags & SEC_LOAD) != 0))
4925     {
4926       /*
4927        * If either a PT_INTERP or PT_DYNAMIC segment is created,
4928        * also create a PT_PHDR segment.
4929        */
4930       ++segs;
4931     }
4932 
4933   if (info != NULL && info->relro)
4934     {
4935       /* We need a PT_GNU_RELRO segment.  */
4936       ++segs;
4937     }
4938 
4939   if (elf_eh_frame_hdr (info))
4940     {
4941       /* We need a PT_GNU_EH_FRAME segment.  */
4942       ++segs;
4943     }
4944 
4945   if (elf_stack_flags (abfd))
4946     {
4947       /* We need a PT_GNU_STACK segment.  */
4948       ++segs;
4949     }
4950 
4951   if (elf_sframe (abfd))
4952     {
4953       /* We need a PT_GNU_SFRAME segment.  */
4954       ++segs;
4955     }
4956 
4957   s = bfd_get_section_by_name (abfd,
4958 			       NOTE_GNU_PROPERTY_SECTION_NAME);
4959   if (s != NULL && s->size != 0)
4960     {
4961       /* We need a PT_GNU_PROPERTY segment.  */
4962       ++segs;
4963     }
4964 
4965   for (s = abfd->sections; s != NULL; s = s->next)
4966     {
4967       if ((s->flags & SEC_LOAD) != 0
4968 	  && elf_section_type (s) == SHT_NOTE)
4969 	{
4970 	  unsigned int alignment_power;
4971 	  /* We need a PT_NOTE segment.  */
4972 	  ++segs;
4973 	  /* Try to create just one PT_NOTE segment for all adjacent
4974 	     loadable SHT_NOTE sections.  gABI requires that within a
4975 	     PT_NOTE segment (and also inside of each SHT_NOTE section)
4976 	     each note should have the same alignment.  So we check
4977 	     whether the sections are correctly aligned.  */
4978 	  alignment_power = s->alignment_power;
4979 	  while (s->next != NULL
4980 		 && s->next->alignment_power == alignment_power
4981 		 && (s->next->flags & SEC_LOAD) != 0
4982 		 && elf_section_type (s->next) == SHT_NOTE)
4983 	    s = s->next;
4984 	}
4985     }
4986 
4987   for (s = abfd->sections; s != NULL; s = s->next)
4988     {
4989       if (s->flags & SEC_THREAD_LOCAL)
4990 	{
4991 	  /* We need a PT_TLS segment.  */
4992 	  ++segs;
4993 	  break;
4994 	}
4995     }
4996 
4997   bed = get_elf_backend_data (abfd);
4998 
4999   if ((abfd->flags & D_PAGED) != 0
5000       && (elf_tdata (abfd)->has_gnu_osabi & elf_gnu_osabi_mbind) != 0)
5001     {
5002       /* Add a PT_GNU_MBIND segment for each mbind section.  */
5003       bfd_vma commonpagesize;
5004       unsigned int page_align_power;
5005 
5006       if (info != NULL)
5007 	commonpagesize = info->commonpagesize;
5008       else
5009 	commonpagesize = bed->commonpagesize;
5010       page_align_power = bfd_log2 (commonpagesize);
5011       for (s = abfd->sections; s != NULL; s = s->next)
5012 	if (elf_section_flags (s) & SHF_GNU_MBIND)
5013 	  {
5014 	    if (elf_section_data (s)->this_hdr.sh_info > PT_GNU_MBIND_NUM)
5015 	      {
5016 		_bfd_error_handler
5017 		  /* xgettext:c-format */
5018 		  (_("%pB: GNU_MBIND section `%pA' has invalid "
5019 		     "sh_info field: %d"),
5020 		   abfd, s, elf_section_data (s)->this_hdr.sh_info);
5021 		continue;
5022 	      }
5023 	    /* Align mbind section to page size.  */
5024 	    if (s->alignment_power < page_align_power)
5025 	      s->alignment_power = page_align_power;
5026 	    segs ++;
5027 	  }
5028     }
5029 
5030   /* Let the backend count up any program headers it might need.  */
5031   if (bed->elf_backend_additional_program_headers)
5032     {
5033       int a;
5034 
5035       a = (*bed->elf_backend_additional_program_headers) (abfd, info);
5036       if (a == -1)
5037 	abort ();
5038       segs += a;
5039     }
5040 
5041   return segs * bed->s->sizeof_phdr;
5042 }
5043 
5044 /* Find the segment that contains the output_section of section.  */
5045 
5046 Elf_Internal_Phdr *
_bfd_elf_find_segment_containing_section(bfd * abfd,asection * section)5047 _bfd_elf_find_segment_containing_section (bfd * abfd, asection * section)
5048 {
5049   struct elf_segment_map *m;
5050   Elf_Internal_Phdr *p;
5051 
5052   for (m = elf_seg_map (abfd), p = elf_tdata (abfd)->phdr;
5053        m != NULL;
5054        m = m->next, p++)
5055     {
5056       int i;
5057 
5058       for (i = m->count - 1; i >= 0; i--)
5059 	if (m->sections[i] == section)
5060 	  return p;
5061     }
5062 
5063   return NULL;
5064 }
5065 
5066 /* Create a mapping from a set of sections to a program segment.  */
5067 
5068 static struct elf_segment_map *
make_mapping(bfd * abfd,asection ** sections,unsigned int from,unsigned int to,bool phdr)5069 make_mapping (bfd *abfd,
5070 	      asection **sections,
5071 	      unsigned int from,
5072 	      unsigned int to,
5073 	      bool phdr)
5074 {
5075   struct elf_segment_map *m;
5076   unsigned int i;
5077   asection **hdrpp;
5078   size_t amt;
5079 
5080   amt = sizeof (struct elf_segment_map) - sizeof (asection *);
5081   amt += (to - from) * sizeof (asection *);
5082   m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
5083   if (m == NULL)
5084     return NULL;
5085   m->next = NULL;
5086   m->p_type = PT_LOAD;
5087   for (i = from, hdrpp = sections + from; i < to; i++, hdrpp++)
5088     m->sections[i - from] = *hdrpp;
5089   m->count = to - from;
5090 
5091   if (from == 0 && phdr)
5092     {
5093       /* Include the headers in the first PT_LOAD segment.  */
5094       m->includes_filehdr = 1;
5095       m->includes_phdrs = 1;
5096     }
5097 
5098   return m;
5099 }
5100 
5101 /* Create the PT_DYNAMIC segment, which includes DYNSEC.  Returns NULL
5102    on failure.  */
5103 
5104 struct elf_segment_map *
_bfd_elf_make_dynamic_segment(bfd * abfd,asection * dynsec)5105 _bfd_elf_make_dynamic_segment (bfd *abfd, asection *dynsec)
5106 {
5107   struct elf_segment_map *m;
5108 
5109   m = (struct elf_segment_map *) bfd_zalloc (abfd,
5110 					     sizeof (struct elf_segment_map));
5111   if (m == NULL)
5112     return NULL;
5113   m->next = NULL;
5114   m->p_type = PT_DYNAMIC;
5115   m->count = 1;
5116   m->sections[0] = dynsec;
5117 
5118   return m;
5119 }
5120 
5121 /* Possibly add or remove segments from the segment map.  */
5122 
5123 static bool
elf_modify_segment_map(bfd * abfd,struct bfd_link_info * info,bool remove_empty_load)5124 elf_modify_segment_map (bfd *abfd,
5125 			struct bfd_link_info *info,
5126 			bool remove_empty_load)
5127 {
5128   struct elf_segment_map **m;
5129   const struct elf_backend_data *bed;
5130 
5131   /* The placement algorithm assumes that non allocated sections are
5132      not in PT_LOAD segments.  We ensure this here by removing such
5133      sections from the segment map.  We also remove excluded
5134      sections.  Finally, any PT_LOAD segment without sections is
5135      removed.  */
5136   m = &elf_seg_map (abfd);
5137   while (*m)
5138     {
5139       unsigned int i, new_count;
5140 
5141       for (new_count = 0, i = 0; i < (*m)->count; i++)
5142 	{
5143 	  if (((*m)->sections[i]->flags & SEC_EXCLUDE) == 0
5144 	      && (((*m)->sections[i]->flags & SEC_ALLOC) != 0
5145 		  || (*m)->p_type != PT_LOAD))
5146 	    {
5147 	      (*m)->sections[new_count] = (*m)->sections[i];
5148 	      new_count++;
5149 	    }
5150 	}
5151       (*m)->count = new_count;
5152 
5153       if (remove_empty_load
5154 	  && (*m)->p_type == PT_LOAD
5155 	  && (*m)->count == 0
5156 	  && !(*m)->includes_phdrs)
5157 	*m = (*m)->next;
5158       else
5159 	m = &(*m)->next;
5160     }
5161 
5162   bed = get_elf_backend_data (abfd);
5163   if (bed->elf_backend_modify_segment_map != NULL)
5164     {
5165       if (!(*bed->elf_backend_modify_segment_map) (abfd, info))
5166 	return false;
5167     }
5168 
5169   return true;
5170 }
5171 
5172 #define IS_TBSS(s) \
5173   ((s->flags & (SEC_THREAD_LOCAL | SEC_LOAD)) == SEC_THREAD_LOCAL)
5174 
5175 /* Set up a mapping from BFD sections to program segments.  Update
5176    NEED_LAYOUT if the section layout is changed.  */
5177 
5178 bool
_bfd_elf_map_sections_to_segments(bfd * abfd,struct bfd_link_info * info,bool * need_layout)5179 _bfd_elf_map_sections_to_segments (bfd *abfd,
5180 				   struct bfd_link_info *info,
5181 				   bool *need_layout)
5182 {
5183   unsigned int count;
5184   struct elf_segment_map *m;
5185   asection **sections = NULL;
5186   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5187   bool no_user_phdrs;
5188 
5189   no_user_phdrs = elf_seg_map (abfd) == NULL;
5190 
5191   if (info != NULL)
5192     {
5193       info->user_phdrs = !no_user_phdrs;
5194 
5195       /* Size the relative relocations if DT_RELR is enabled.  */
5196       if (info->enable_dt_relr
5197 	  && need_layout != NULL
5198 	  && bed->size_relative_relocs
5199 	  && !bed->size_relative_relocs (info, need_layout))
5200 	info->callbacks->einfo
5201 	  (_("%F%P: failed to size relative relocations\n"));
5202     }
5203 
5204   if (no_user_phdrs && bfd_count_sections (abfd) != 0)
5205     {
5206       asection *s;
5207       unsigned int i;
5208       struct elf_segment_map *mfirst;
5209       struct elf_segment_map **pm;
5210       asection *last_hdr;
5211       bfd_vma last_size;
5212       unsigned int hdr_index;
5213       bfd_vma maxpagesize;
5214       asection **hdrpp;
5215       bool phdr_in_segment;
5216       bool writable;
5217       bool executable;
5218       unsigned int tls_count = 0;
5219       asection *first_tls = NULL;
5220       asection *first_mbind = NULL;
5221       asection *dynsec, *eh_frame_hdr;
5222       asection *sframe;
5223       size_t amt;
5224       bfd_vma addr_mask, wrap_to = 0;  /* Bytes.  */
5225       bfd_size_type phdr_size;  /* Octets/bytes.  */
5226       unsigned int opb = bfd_octets_per_byte (abfd, NULL);
5227 
5228       /* Select the allocated sections, and sort them.  */
5229 
5230       amt = bfd_count_sections (abfd) * sizeof (asection *);
5231       sections = (asection **) bfd_malloc (amt);
5232       if (sections == NULL)
5233 	goto error_return;
5234 
5235       /* Calculate top address, avoiding undefined behaviour of shift
5236 	 left operator when shift count is equal to size of type
5237 	 being shifted.  */
5238       addr_mask = ((bfd_vma) 1 << (bfd_arch_bits_per_address (abfd) - 1)) - 1;
5239       addr_mask = (addr_mask << 1) + 1;
5240 
5241       i = 0;
5242       for (s = abfd->sections; s != NULL; s = s->next)
5243 	{
5244 	  if ((s->flags & SEC_ALLOC) != 0)
5245 	    {
5246 	      /* target_index is unused until bfd_elf_final_link
5247 		 starts output of section symbols.  Use it to make
5248 		 qsort stable.  */
5249 	      s->target_index = i;
5250 	      sections[i] = s;
5251 	      ++i;
5252 	      /* A wrapping section potentially clashes with header.  */
5253 	      if (((s->lma + s->size / opb) & addr_mask) < (s->lma & addr_mask))
5254 		wrap_to = (s->lma + s->size / opb) & addr_mask;
5255 	    }
5256 	}
5257       BFD_ASSERT (i <= bfd_count_sections (abfd));
5258       count = i;
5259 
5260       qsort (sections, (size_t) count, sizeof (asection *), elf_sort_sections);
5261 
5262       phdr_size = elf_program_header_size (abfd);
5263       if (phdr_size == (bfd_size_type) -1)
5264 	phdr_size = get_program_header_size (abfd, info);
5265       phdr_size += bed->s->sizeof_ehdr;
5266       /* phdr_size is compared to LMA values which are in bytes.  */
5267       phdr_size /= opb;
5268       if (info != NULL)
5269 	maxpagesize = info->maxpagesize;
5270       else
5271 	maxpagesize = bed->maxpagesize;
5272       if (maxpagesize == 0)
5273 	maxpagesize = 1;
5274       phdr_in_segment = info != NULL && info->load_phdrs;
5275       if (count != 0
5276 	  && (((sections[0]->lma & addr_mask) & (maxpagesize - 1))
5277 	      >= (phdr_size & (maxpagesize - 1))))
5278 	/* For compatibility with old scripts that may not be using
5279 	   SIZEOF_HEADERS, add headers when it looks like space has
5280 	   been left for them.  */
5281 	phdr_in_segment = true;
5282 
5283       /* Build the mapping.  */
5284       mfirst = NULL;
5285       pm = &mfirst;
5286 
5287       /* If we have a .interp section, then create a PT_PHDR segment for
5288 	 the program headers and a PT_INTERP segment for the .interp
5289 	 section.  */
5290       s = bfd_get_section_by_name (abfd, ".interp");
5291       if (s != NULL && (s->flags & SEC_LOAD) == 0)
5292       if (s != NULL && (s->flags & SEC_LOAD) != 0 && s->size != 0)
5293 	s = NULL;
5294       dynsec = bfd_get_section_by_name (abfd, ".dynamic");
5295       if (dynsec != NULL && (dynsec->flags & SEC_LOAD) == 0)
5296 	dynsec = NULL;
5297 
5298       if (s != NULL || dynsec != NULL)
5299 	{
5300 	  amt = sizeof (struct elf_segment_map);
5301 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
5302 	  if (m == NULL)
5303 	    goto error_return;
5304 	  m->next = NULL;
5305 	  m->p_type = PT_PHDR;
5306 	  m->p_flags = PF_R;
5307 	  m->p_flags_valid = 1;
5308 	  m->includes_phdrs = 1;
5309 	  phdr_in_segment = true;
5310 	  *pm = m;
5311 	  pm = &m->next;
5312 	}
5313 
5314       if (s != NULL)
5315 	{
5316 	  amt = sizeof (struct elf_segment_map);
5317 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
5318 	  if (m == NULL)
5319 	    goto error_return;
5320 	  m->next = NULL;
5321 	  m->p_type = PT_INTERP;
5322 	  m->count = 1;
5323 	  m->sections[0] = s;
5324 
5325 	  *pm = m;
5326 	  pm = &m->next;
5327 	}
5328 
5329       /* Look through the sections.  We put sections in the same program
5330 	 segment when the start of the second section can be placed within
5331 	 a few bytes of the end of the first section.  */
5332       last_hdr = NULL;
5333       last_size = 0;
5334       hdr_index = 0;
5335       writable = false;
5336       executable = false;
5337 
5338       if ((abfd->flags & D_PAGED) == 0)
5339 	phdr_in_segment = false;
5340 
5341       /* Deal with -Ttext or something similar such that the first section
5342 	 is not adjacent to the program headers.  This is an
5343 	 approximation, since at this point we don't know exactly how many
5344 	 program headers we will need.  */
5345       if (phdr_in_segment && count > 0)
5346 	{
5347 	  bfd_vma phdr_lma;  /* Bytes.  */
5348 	  bool separate_phdr = false;
5349 
5350 	  phdr_lma = (sections[0]->lma - phdr_size) & addr_mask & -maxpagesize;
5351 	  if (info != NULL
5352 	      && info->separate_code
5353 	      && (sections[0]->flags & SEC_CODE) != 0)
5354 	    {
5355 	      /* If data sections should be separate from code and
5356 		 thus not executable, and the first section is
5357 		 executable then put the file and program headers in
5358 		 their own PT_LOAD.  */
5359 	      separate_phdr = true;
5360 	      if ((((phdr_lma + phdr_size - 1) & addr_mask & -maxpagesize)
5361 		   == (sections[0]->lma & addr_mask & -maxpagesize)))
5362 		{
5363 		  /* The file and program headers are currently on the
5364 		     same page as the first section.  Put them on the
5365 		     previous page if we can.  */
5366 		  if (phdr_lma >= maxpagesize)
5367 		    phdr_lma -= maxpagesize;
5368 		  else
5369 		    separate_phdr = false;
5370 		}
5371 	    }
5372 	  if ((sections[0]->lma & addr_mask) < phdr_lma
5373 	      || (sections[0]->lma & addr_mask) < phdr_size)
5374 	    /* If file and program headers would be placed at the end
5375 	       of memory then it's probably better to omit them.  */
5376 	    phdr_in_segment = false;
5377 	  else if (phdr_lma < wrap_to)
5378 	    /* If a section wraps around to where we'll be placing
5379 	       file and program headers, then the headers will be
5380 	       overwritten.  */
5381 	    phdr_in_segment = false;
5382 	  else if (separate_phdr)
5383 	    {
5384 	      m = make_mapping (abfd, sections, 0, 0, phdr_in_segment);
5385 	      if (m == NULL)
5386 		goto error_return;
5387 	      m->p_paddr = phdr_lma * opb;
5388 	      m->p_vaddr_offset
5389 		= (sections[0]->vma - phdr_size) & addr_mask & -maxpagesize;
5390 	      m->p_paddr_valid = 1;
5391 	      *pm = m;
5392 	      pm = &m->next;
5393 	      phdr_in_segment = false;
5394 	    }
5395 	}
5396 
5397       for (i = 0, hdrpp = sections; i < count; i++, hdrpp++)
5398 	{
5399 	  asection *hdr;
5400 	  bool new_segment;
5401 
5402 	  hdr = *hdrpp;
5403 
5404 	  /* See if this section and the last one will fit in the same
5405 	     segment.  */
5406 
5407 	  if (last_hdr == NULL)
5408 	    {
5409 	      /* If we don't have a segment yet, then we don't need a new
5410 		 one (we build the last one after this loop).  */
5411 	      new_segment = false;
5412 	    }
5413 	  else if (last_hdr->lma - last_hdr->vma != hdr->lma - hdr->vma)
5414 	    {
5415 	      /* If this section has a different relation between the
5416 		 virtual address and the load address, then we need a new
5417 		 segment.  */
5418 	      new_segment = true;
5419 	    }
5420 	  else if (hdr->lma < last_hdr->lma + last_size
5421 		   || last_hdr->lma + last_size < last_hdr->lma)
5422 	    {
5423 	      /* If this section has a load address that makes it overlap
5424 		 the previous section, then we need a new segment.  */
5425 	      new_segment = true;
5426 	    }
5427 	  else if ((abfd->flags & D_PAGED) != 0
5428 		   && (((last_hdr->lma + last_size - 1) & -maxpagesize)
5429 		       == (hdr->lma & -maxpagesize)))
5430 	    {
5431 	      /* If we are demand paged then we can't map two disk
5432 		 pages onto the same memory page.  */
5433 	      new_segment = false;
5434 	    }
5435 	  /* In the next test we have to be careful when last_hdr->lma is close
5436 	     to the end of the address space.  If the aligned address wraps
5437 	     around to the start of the address space, then there are no more
5438 	     pages left in memory and it is OK to assume that the current
5439 	     section can be included in the current segment.  */
5440 	  else if ((BFD_ALIGN (last_hdr->lma + last_size, maxpagesize)
5441 		    + maxpagesize > last_hdr->lma)
5442 		   && (BFD_ALIGN (last_hdr->lma + last_size, maxpagesize)
5443 		       + maxpagesize <= hdr->lma))
5444 	    {
5445 	      /* If putting this section in this segment would force us to
5446 		 skip a page in the segment, then we need a new segment.  */
5447 	      new_segment = true;
5448 	    }
5449 	  else if ((last_hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0
5450 		   && (hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) != 0)
5451 	    {
5452 	      /* We don't want to put a loaded section after a
5453 		 nonloaded (ie. bss style) section in the same segment
5454 		 as that will force the non-loaded section to be loaded.
5455 		 Consider .tbss sections as loaded for this purpose.  */
5456 	      new_segment = true;
5457 	    }
5458 	  else if ((abfd->flags & D_PAGED) == 0)
5459 	    {
5460 	      /* If the file is not demand paged, which means that we
5461 		 don't require the sections to be correctly aligned in the
5462 		 file, then there is no other reason for a new segment.  */
5463 	      new_segment = false;
5464 	    }
5465 	  else if (info != NULL
5466 		   && info->separate_code
5467 		   && executable != ((hdr->flags & SEC_CODE) != 0))
5468 	    {
5469 	      new_segment = true;
5470 	    }
5471 	  else if (! writable
5472 		   && (hdr->flags & SEC_READONLY) == 0)
5473 	    {
5474 	      /* We don't want to put a writable section in a read only
5475 		 segment.  */
5476 	      new_segment = true;
5477 	    }
5478 	  else
5479 	    {
5480 	      /* Otherwise, we can use the same segment.  */
5481 	      new_segment = false;
5482 	    }
5483 
5484 	  /* Allow interested parties a chance to override our decision.  */
5485 	  if (last_hdr != NULL
5486 	      && info != NULL
5487 	      && info->callbacks->override_segment_assignment != NULL)
5488 	    new_segment
5489 	      = info->callbacks->override_segment_assignment (info, abfd, hdr,
5490 							      last_hdr,
5491 							      new_segment);
5492 
5493 	  if (! new_segment)
5494 	    {
5495 	      if ((hdr->flags & SEC_READONLY) == 0)
5496 		writable = true;
5497 	      if ((hdr->flags & SEC_CODE) != 0)
5498 		executable = true;
5499 	      last_hdr = hdr;
5500 	      /* .tbss sections effectively have zero size.  */
5501 	      last_size = (!IS_TBSS (hdr) ? hdr->size : 0) / opb;
5502 	      continue;
5503 	    }
5504 
5505 	  /* We need a new program segment.  We must create a new program
5506 	     header holding all the sections from hdr_index until hdr.  */
5507 
5508 	  m = make_mapping (abfd, sections, hdr_index, i, phdr_in_segment);
5509 	  if (m == NULL)
5510 	    goto error_return;
5511 
5512 	  *pm = m;
5513 	  pm = &m->next;
5514 
5515 	  if ((hdr->flags & SEC_READONLY) == 0)
5516 	    writable = true;
5517 	  else
5518 	    writable = false;
5519 
5520 	  if ((hdr->flags & SEC_CODE) == 0)
5521 	    executable = false;
5522 	  else
5523 	    executable = true;
5524 
5525 	  last_hdr = hdr;
5526 	  /* .tbss sections effectively have zero size.  */
5527 	  last_size = (!IS_TBSS (hdr) ? hdr->size : 0) / opb;
5528 	  hdr_index = i;
5529 	  phdr_in_segment = false;
5530 	}
5531 
5532       /* Create a final PT_LOAD program segment, but not if it's just
5533 	 for .tbss.  */
5534       if (last_hdr != NULL
5535 	  && (i - hdr_index != 1
5536 	      || !IS_TBSS (last_hdr)))
5537 	{
5538 	  m = make_mapping (abfd, sections, hdr_index, i, phdr_in_segment);
5539 	  if (m == NULL)
5540 	    goto error_return;
5541 
5542 	  *pm = m;
5543 	  pm = &m->next;
5544 	}
5545 
5546       /* If there is a .dynamic section, throw in a PT_DYNAMIC segment.  */
5547       if (dynsec != NULL)
5548 	{
5549 	  m = _bfd_elf_make_dynamic_segment (abfd, dynsec);
5550 	  if (m == NULL)
5551 	    goto error_return;
5552 	  *pm = m;
5553 	  pm = &m->next;
5554 	}
5555 
5556       /* For each batch of consecutive loadable SHT_NOTE  sections,
5557 	 add a PT_NOTE segment.  We don't use bfd_get_section_by_name,
5558 	 because if we link together nonloadable .note sections and
5559 	 loadable .note sections, we will generate two .note sections
5560 	 in the output file.  */
5561       for (s = abfd->sections; s != NULL; s = s->next)
5562 	{
5563 	  if ((s->flags & SEC_LOAD) != 0
5564 	      && elf_section_type (s) == SHT_NOTE)
5565 	    {
5566 	      asection *s2;
5567 	      unsigned int alignment_power = s->alignment_power;
5568 
5569 	      count = 1;
5570 	      for (s2 = s; s2->next != NULL; s2 = s2->next)
5571 		{
5572 		  if (s2->next->alignment_power == alignment_power
5573 		      && (s2->next->flags & SEC_LOAD) != 0
5574 		      && elf_section_type (s2->next) == SHT_NOTE
5575 		      && align_power (s2->lma + s2->size / opb,
5576 				      alignment_power)
5577 		      == s2->next->lma)
5578 		    count++;
5579 		  else
5580 		    break;
5581 		}
5582 	      amt = sizeof (struct elf_segment_map) - sizeof (asection *);
5583 	      amt += count * sizeof (asection *);
5584 	      m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
5585 	      if (m == NULL)
5586 		goto error_return;
5587 	      m->next = NULL;
5588 	      m->p_type = PT_NOTE;
5589 	      m->count = count;
5590 	      while (count > 1)
5591 		{
5592 		  m->sections[m->count - count--] = s;
5593 		  BFD_ASSERT ((s->flags & SEC_THREAD_LOCAL) == 0);
5594 		  s = s->next;
5595 		}
5596 	      m->sections[m->count - 1] = s;
5597 	      BFD_ASSERT ((s->flags & SEC_THREAD_LOCAL) == 0);
5598 	      *pm = m;
5599 	      pm = &m->next;
5600 	    }
5601 	  if (s->flags & SEC_THREAD_LOCAL)
5602 	    {
5603 	      if (! tls_count)
5604 		first_tls = s;
5605 	      tls_count++;
5606 	    }
5607 	  if (first_mbind == NULL
5608 	      && (elf_section_flags (s) & SHF_GNU_MBIND) != 0)
5609 	    first_mbind = s;
5610 	}
5611 
5612       /* If there are any SHF_TLS output sections, add PT_TLS segment.  */
5613       if (tls_count > 0)
5614 	{
5615 	  amt = sizeof (struct elf_segment_map) - sizeof (asection *);
5616 	  amt += tls_count * sizeof (asection *);
5617 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
5618 	  if (m == NULL)
5619 	    goto error_return;
5620 	  m->next = NULL;
5621 	  m->p_type = PT_TLS;
5622 	  m->count = tls_count;
5623 	  /* Mandated PF_R.  */
5624 	  m->p_flags = PF_R;
5625 	  m->p_flags_valid = 1;
5626 	  s = first_tls;
5627 	  for (i = 0; i < tls_count; ++i)
5628 	    {
5629 	      if ((s->flags & SEC_THREAD_LOCAL) == 0)
5630 		{
5631 		  _bfd_error_handler
5632 		    (_("%pB: TLS sections are not adjacent:"), abfd);
5633 		  s = first_tls;
5634 		  i = 0;
5635 		  while (i < tls_count)
5636 		    {
5637 		      if ((s->flags & SEC_THREAD_LOCAL) != 0)
5638 			{
5639 			  _bfd_error_handler (_("	    TLS: %pA"), s);
5640 			  i++;
5641 			}
5642 		      else
5643 			_bfd_error_handler (_("	non-TLS: %pA"), s);
5644 		      s = s->next;
5645 		    }
5646 		  bfd_set_error (bfd_error_bad_value);
5647 		  goto error_return;
5648 		}
5649 	      m->sections[i] = s;
5650 	      s = s->next;
5651 	    }
5652 
5653 	  *pm = m;
5654 	  pm = &m->next;
5655 	}
5656 
5657       if (first_mbind
5658 	  && (abfd->flags & D_PAGED) != 0
5659 	  && (elf_tdata (abfd)->has_gnu_osabi & elf_gnu_osabi_mbind) != 0)
5660 	for (s = first_mbind; s != NULL; s = s->next)
5661 	  if ((elf_section_flags (s) & SHF_GNU_MBIND) != 0
5662 	      && elf_section_data (s)->this_hdr.sh_info <= PT_GNU_MBIND_NUM)
5663 	    {
5664 	      /* Mandated PF_R.  */
5665 	      unsigned long p_flags = PF_R;
5666 	      if ((s->flags & SEC_READONLY) == 0)
5667 		p_flags |= PF_W;
5668 	      if ((s->flags & SEC_CODE) != 0)
5669 		p_flags |= PF_X;
5670 
5671 	      amt = sizeof (struct elf_segment_map) + sizeof (asection *);
5672 	      m = bfd_zalloc (abfd, amt);
5673 	      if (m == NULL)
5674 		goto error_return;
5675 	      m->next = NULL;
5676 	      m->p_type = (PT_GNU_MBIND_LO
5677 			   + elf_section_data (s)->this_hdr.sh_info);
5678 	      m->count = 1;
5679 	      m->p_flags_valid = 1;
5680 	      m->sections[0] = s;
5681 	      m->p_flags = p_flags;
5682 
5683 	      *pm = m;
5684 	      pm = &m->next;
5685 	    }
5686 
5687       s = bfd_get_section_by_name (abfd,
5688 				   NOTE_GNU_PROPERTY_SECTION_NAME);
5689       if (s != NULL && s->size != 0)
5690 	{
5691 	  amt = sizeof (struct elf_segment_map) + sizeof (asection *);
5692 	  m = bfd_zalloc (abfd, amt);
5693 	  if (m == NULL)
5694 	    goto error_return;
5695 	  m->next = NULL;
5696 	  m->p_type = PT_GNU_PROPERTY;
5697 	  m->count = 1;
5698 	  m->p_flags_valid = 1;
5699 	  m->sections[0] = s;
5700 	  m->p_flags = PF_R;
5701 	  *pm = m;
5702 	  pm = &m->next;
5703 	}
5704 
5705       /* If there is a .eh_frame_hdr section, throw in a PT_GNU_EH_FRAME
5706 	 segment.  */
5707       eh_frame_hdr = elf_eh_frame_hdr (info);
5708       if (eh_frame_hdr != NULL
5709 	  && (eh_frame_hdr->output_section->flags & SEC_LOAD) != 0)
5710 	{
5711 	  amt = sizeof (struct elf_segment_map);
5712 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
5713 	  if (m == NULL)
5714 	    goto error_return;
5715 	  m->next = NULL;
5716 	  m->p_type = PT_GNU_EH_FRAME;
5717 	  m->count = 1;
5718 	  m->sections[0] = eh_frame_hdr->output_section;
5719 
5720 	  *pm = m;
5721 	  pm = &m->next;
5722 	}
5723 
5724       /* If there is a .sframe section, throw in a PT_GNU_SFRAME
5725 	 segment.  */
5726       sframe = elf_sframe (abfd);
5727       if (sframe != NULL
5728 	  && (sframe->output_section->flags & SEC_LOAD) != 0
5729 	  && sframe->size != 0)
5730 	{
5731 	  amt = sizeof (struct elf_segment_map);
5732 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
5733 	  if (m == NULL)
5734 	    goto error_return;
5735 	  m->next = NULL;
5736 	  m->p_type = PT_GNU_SFRAME;
5737 	  m->count = 1;
5738 	  m->sections[0] = sframe->output_section;
5739 
5740 	  *pm = m;
5741 	  pm = &m->next;
5742 	}
5743 
5744       if (elf_stack_flags (abfd))
5745 	{
5746 	  amt = sizeof (struct elf_segment_map);
5747 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
5748 	  if (m == NULL)
5749 	    goto error_return;
5750 	  m->next = NULL;
5751 	  m->p_type = PT_GNU_STACK;
5752 	  m->p_flags = elf_stack_flags (abfd);
5753 	  m->p_align = bed->stack_align;
5754 	  m->p_flags_valid = 1;
5755 	  m->p_align_valid = m->p_align != 0;
5756 	  if (info->stacksize > 0)
5757 	    {
5758 	      m->p_size = info->stacksize;
5759 	      m->p_size_valid = 1;
5760 	    }
5761 
5762 	  *pm = m;
5763 	  pm = &m->next;
5764 	}
5765 
5766       if (info != NULL && info->relro)
5767 	{
5768 	  for (m = mfirst; m != NULL; m = m->next)
5769 	    {
5770 	      if (m->p_type == PT_LOAD
5771 		  && m->count != 0
5772 		  && m->sections[0]->vma >= info->relro_start
5773 		  && m->sections[0]->vma < info->relro_end)
5774 		{
5775 		  i = m->count;
5776 		  while (--i != (unsigned) -1)
5777 		    {
5778 		      if (m->sections[i]->size > 0
5779 			  && (m->sections[i]->flags & SEC_LOAD) != 0
5780 			  && (m->sections[i]->flags & SEC_HAS_CONTENTS) != 0)
5781 			break;
5782 		    }
5783 
5784 		  if (i != (unsigned) -1)
5785 		    break;
5786 		}
5787 	    }
5788 
5789 	  /* Make a PT_GNU_RELRO segment only when it isn't empty.  */
5790 	  if (m != NULL)
5791 	    {
5792 	      amt = sizeof (struct elf_segment_map);
5793 	      m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
5794 	      if (m == NULL)
5795 		goto error_return;
5796 	      m->next = NULL;
5797 	      m->p_type = PT_GNU_RELRO;
5798 	      *pm = m;
5799 	      pm = &m->next;
5800 	    }
5801 	}
5802 
5803       free (sections);
5804       elf_seg_map (abfd) = mfirst;
5805     }
5806 
5807   if (!elf_modify_segment_map (abfd, info, no_user_phdrs))
5808     return false;
5809 
5810   for (count = 0, m = elf_seg_map (abfd); m != NULL; m = m->next)
5811     ++count;
5812   elf_program_header_size (abfd) = count * bed->s->sizeof_phdr;
5813 
5814   return true;
5815 
5816  error_return:
5817   free (sections);
5818   return false;
5819 }
5820 
5821 /* Sort sections by address.  */
5822 
5823 static int
elf_sort_sections(const void * arg1,const void * arg2)5824 elf_sort_sections (const void *arg1, const void *arg2)
5825 {
5826   const asection *sec1 = *(const asection **) arg1;
5827   const asection *sec2 = *(const asection **) arg2;
5828   bfd_size_type size1, size2;
5829 
5830   /* Sort by LMA first, since this is the address used to
5831      place the section into a segment.  */
5832   if (sec1->lma < sec2->lma)
5833     return -1;
5834   else if (sec1->lma > sec2->lma)
5835     return 1;
5836 
5837   /* Then sort by VMA.  Normally the LMA and the VMA will be
5838      the same, and this will do nothing.  */
5839   if (sec1->vma < sec2->vma)
5840     return -1;
5841   else if (sec1->vma > sec2->vma)
5842     return 1;
5843 
5844   /* Put !SEC_LOAD sections after SEC_LOAD ones.  */
5845 
5846 #define TOEND(x) (((x)->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0 \
5847 		  && (x)->size != 0)
5848 
5849   if (TOEND (sec1))
5850     {
5851       if (!TOEND (sec2))
5852 	return 1;
5853     }
5854   else if (TOEND (sec2))
5855     return -1;
5856 
5857 #undef TOEND
5858 
5859   /* Sort by size, to put zero sized sections
5860      before others at the same address.  */
5861 
5862   size1 = (sec1->flags & SEC_LOAD) ? sec1->size : 0;
5863   size2 = (sec2->flags & SEC_LOAD) ? sec2->size : 0;
5864 
5865   if (size1 < size2)
5866     return -1;
5867   if (size1 > size2)
5868     return 1;
5869 
5870   return sec1->target_index - sec2->target_index;
5871 }
5872 
5873 /* This qsort comparison functions sorts PT_LOAD segments first and
5874    by p_paddr, for assign_file_positions_for_load_sections.  */
5875 
5876 static int
elf_sort_segments(const void * arg1,const void * arg2)5877 elf_sort_segments (const void *arg1, const void *arg2)
5878 {
5879   const struct elf_segment_map *m1 = *(const struct elf_segment_map **) arg1;
5880   const struct elf_segment_map *m2 = *(const struct elf_segment_map **) arg2;
5881 
5882   if (m1->p_type != m2->p_type)
5883     {
5884       if (m1->p_type == PT_NULL)
5885 	return 1;
5886       if (m2->p_type == PT_NULL)
5887 	return -1;
5888       return m1->p_type < m2->p_type ? -1 : 1;
5889     }
5890   if (m1->includes_filehdr != m2->includes_filehdr)
5891     return m1->includes_filehdr ? -1 : 1;
5892   if (m1->no_sort_lma != m2->no_sort_lma)
5893     return m1->no_sort_lma ? -1 : 1;
5894   if (m1->p_type == PT_LOAD && !m1->no_sort_lma)
5895     {
5896       bfd_vma lma1, lma2;  /* Octets.  */
5897       lma1 = 0;
5898       if (m1->p_paddr_valid)
5899 	lma1 = m1->p_paddr;
5900       else if (m1->count != 0)
5901 	{
5902 	  unsigned int opb = bfd_octets_per_byte (m1->sections[0]->owner,
5903 						  m1->sections[0]);
5904 	  lma1 = (m1->sections[0]->lma + m1->p_vaddr_offset) * opb;
5905 	}
5906       lma2 = 0;
5907       if (m2->p_paddr_valid)
5908 	lma2 = m2->p_paddr;
5909       else if (m2->count != 0)
5910 	{
5911 	  unsigned int opb = bfd_octets_per_byte (m2->sections[0]->owner,
5912 						  m2->sections[0]);
5913 	  lma2 = (m2->sections[0]->lma + m2->p_vaddr_offset) * opb;
5914 	}
5915       if (lma1 != lma2)
5916 	return lma1 < lma2 ? -1 : 1;
5917     }
5918   if (m1->idx != m2->idx)
5919     return m1->idx < m2->idx ? -1 : 1;
5920   return 0;
5921 }
5922 
5923 /* Ian Lance Taylor writes:
5924 
5925    We shouldn't be using % with a negative signed number.  That's just
5926    not good.  We have to make sure either that the number is not
5927    negative, or that the number has an unsigned type.  When the types
5928    are all the same size they wind up as unsigned.  When file_ptr is a
5929    larger signed type, the arithmetic winds up as signed long long,
5930    which is wrong.
5931 
5932    What we're trying to say here is something like ``increase OFF by
5933    the least amount that will cause it to be equal to the VMA modulo
5934    the page size.''  */
5935 /* In other words, something like:
5936 
5937    vma_offset = m->sections[0]->vma % bed->maxpagesize;
5938    off_offset = off % bed->maxpagesize;
5939    if (vma_offset < off_offset)
5940      adjustment = vma_offset + bed->maxpagesize - off_offset;
5941    else
5942      adjustment = vma_offset - off_offset;
5943 
5944    which can be collapsed into the expression below.  */
5945 
5946 static file_ptr
vma_page_aligned_bias(bfd_vma vma,ufile_ptr off,bfd_vma maxpagesize)5947 vma_page_aligned_bias (bfd_vma vma, ufile_ptr off, bfd_vma maxpagesize)
5948 {
5949   /* PR binutils/16199: Handle an alignment of zero.  */
5950   if (maxpagesize == 0)
5951     maxpagesize = 1;
5952   return ((vma - off) % maxpagesize);
5953 }
5954 
5955 static void
print_segment_map(const struct elf_segment_map * m)5956 print_segment_map (const struct elf_segment_map *m)
5957 {
5958   unsigned int j;
5959   const char *pt = get_segment_type (m->p_type);
5960   char buf[32];
5961 
5962   if (pt == NULL)
5963     {
5964       if (m->p_type >= PT_LOPROC && m->p_type <= PT_HIPROC)
5965 	sprintf (buf, "LOPROC+%7.7x",
5966 		 (unsigned int) (m->p_type - PT_LOPROC));
5967       else if (m->p_type >= PT_LOOS && m->p_type <= PT_HIOS)
5968 	sprintf (buf, "LOOS+%7.7x",
5969 		 (unsigned int) (m->p_type - PT_LOOS));
5970       else
5971 	snprintf (buf, sizeof (buf), "%8.8x",
5972 		  (unsigned int) m->p_type);
5973       pt = buf;
5974     }
5975   fflush (stdout);
5976   fprintf (stderr, "%s:", pt);
5977   for (j = 0; j < m->count; j++)
5978     fprintf (stderr, " %s", m->sections [j]->name);
5979   putc ('\n',stderr);
5980   fflush (stderr);
5981 }
5982 
5983 /* Assign file positions to the sections based on the mapping from
5984    sections to segments.  This function also sets up some fields in
5985    the file header.  */
5986 
5987 static bool
assign_file_positions_for_load_sections(bfd * abfd,struct bfd_link_info * link_info)5988 assign_file_positions_for_load_sections (bfd *abfd,
5989 					 struct bfd_link_info *link_info)
5990 {
5991   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5992   struct elf_segment_map *m;
5993   struct elf_segment_map *phdr_load_seg;
5994   Elf_Internal_Phdr *phdrs;
5995   Elf_Internal_Phdr *p;
5996   file_ptr off;  /* Octets.  */
5997   bfd_size_type maxpagesize;
5998   unsigned int alloc, actual;
5999   unsigned int i, j;
6000   struct elf_segment_map **sorted_seg_map;
6001   unsigned int opb = bfd_octets_per_byte (abfd, NULL);
6002 
6003   if (link_info == NULL
6004       && !_bfd_elf_map_sections_to_segments (abfd, link_info, NULL))
6005     return false;
6006 
6007   alloc = 0;
6008   for (m = elf_seg_map (abfd); m != NULL; m = m->next)
6009     m->idx = alloc++;
6010 
6011   if (alloc)
6012     {
6013       elf_elfheader (abfd)->e_phoff = bed->s->sizeof_ehdr;
6014       elf_elfheader (abfd)->e_phentsize = bed->s->sizeof_phdr;
6015     }
6016   else
6017     {
6018       /* PR binutils/12467.  */
6019       elf_elfheader (abfd)->e_phoff = 0;
6020       elf_elfheader (abfd)->e_phentsize = 0;
6021     }
6022 
6023   elf_elfheader (abfd)->e_phnum = alloc;
6024 
6025   if (elf_program_header_size (abfd) == (bfd_size_type) -1)
6026     {
6027       actual = alloc;
6028       elf_program_header_size (abfd) = alloc * bed->s->sizeof_phdr;
6029     }
6030   else
6031     {
6032       actual = elf_program_header_size (abfd) / bed->s->sizeof_phdr;
6033       BFD_ASSERT (elf_program_header_size (abfd)
6034 		  == actual * bed->s->sizeof_phdr);
6035       BFD_ASSERT (actual >= alloc);
6036     }
6037 
6038   if (alloc == 0)
6039     {
6040       elf_next_file_pos (abfd) = bed->s->sizeof_ehdr;
6041       return true;
6042     }
6043 
6044   /* We're writing the size in elf_program_header_size (abfd),
6045      see assign_file_positions_except_relocs, so make sure we have
6046      that amount allocated, with trailing space cleared.
6047      The variable alloc contains the computed need, while
6048      elf_program_header_size (abfd) contains the size used for the
6049      layout.
6050      See ld/emultempl/elf-generic.em:gld${EMULATION_NAME}_map_segments
6051      where the layout is forced to according to a larger size in the
6052      last iterations for the testcase ld-elf/header.  */
6053   phdrs = bfd_zalloc (abfd, (actual * sizeof (*phdrs)
6054 			     + alloc * sizeof (*sorted_seg_map)));
6055   sorted_seg_map = (struct elf_segment_map **) (phdrs + actual);
6056   elf_tdata (abfd)->phdr = phdrs;
6057   if (phdrs == NULL)
6058     return false;
6059 
6060   for (m = elf_seg_map (abfd), j = 0; m != NULL; m = m->next, j++)
6061     {
6062       sorted_seg_map[j] = m;
6063       /* If elf_segment_map is not from map_sections_to_segments, the
6064 	 sections may not be correctly ordered.  NOTE: sorting should
6065 	 not be done to the PT_NOTE section of a corefile, which may
6066 	 contain several pseudo-sections artificially created by bfd.
6067 	 Sorting these pseudo-sections breaks things badly.  */
6068       if (m->count > 1
6069 	  && !(elf_elfheader (abfd)->e_type == ET_CORE
6070 	       && m->p_type == PT_NOTE))
6071 	{
6072 	  for (i = 0; i < m->count; i++)
6073 	    m->sections[i]->target_index = i;
6074 	  qsort (m->sections, (size_t) m->count, sizeof (asection *),
6075 		 elf_sort_sections);
6076 	}
6077     }
6078   if (alloc > 1)
6079     qsort (sorted_seg_map, alloc, sizeof (*sorted_seg_map),
6080 	   elf_sort_segments);
6081 
6082   maxpagesize = 1;
6083   if ((abfd->flags & D_PAGED) != 0)
6084     {
6085       if (link_info != NULL)
6086 	maxpagesize = link_info->maxpagesize;
6087       else
6088 	maxpagesize = bed->maxpagesize;
6089     }
6090 
6091   /* Sections must map to file offsets past the ELF file header.  */
6092   off = bed->s->sizeof_ehdr;
6093   /* And if one of the PT_LOAD headers doesn't include the program
6094      headers then we'll be mapping program headers in the usual
6095      position after the ELF file header.  */
6096   phdr_load_seg = NULL;
6097   for (j = 0; j < alloc; j++)
6098     {
6099       m = sorted_seg_map[j];
6100       if (m->p_type != PT_LOAD)
6101 	break;
6102       if (m->includes_phdrs)
6103 	{
6104 	  phdr_load_seg = m;
6105 	  break;
6106 	}
6107     }
6108   if (phdr_load_seg == NULL)
6109     off += actual * bed->s->sizeof_phdr;
6110 
6111   for (j = 0; j < alloc; j++)
6112     {
6113       asection **secpp;
6114       bfd_vma off_adjust;  /* Octets.  */
6115       bool no_contents;
6116       bfd_size_type p_align;
6117       bool p_align_p;
6118 
6119       /* An ELF segment (described by Elf_Internal_Phdr) may contain a
6120 	 number of sections with contents contributing to both p_filesz
6121 	 and p_memsz, followed by a number of sections with no contents
6122 	 that just contribute to p_memsz.  In this loop, OFF tracks next
6123 	 available file offset for PT_LOAD and PT_NOTE segments.  */
6124       m = sorted_seg_map[j];
6125       p = phdrs + m->idx;
6126       p->p_type = m->p_type;
6127       p->p_flags = m->p_flags;
6128       p_align = bed->p_align;
6129       p_align_p = false;
6130 
6131       if (m->count == 0)
6132 	p->p_vaddr = m->p_vaddr_offset * opb;
6133       else
6134 	p->p_vaddr = (m->sections[0]->vma + m->p_vaddr_offset) * opb;
6135 
6136       if (m->p_paddr_valid)
6137 	p->p_paddr = m->p_paddr;
6138       else if (m->count == 0)
6139 	p->p_paddr = 0;
6140       else
6141 	p->p_paddr = (m->sections[0]->lma + m->p_vaddr_offset) * opb;
6142 
6143       if (p->p_type == PT_LOAD
6144 	  && (abfd->flags & D_PAGED) != 0)
6145 	{
6146 	  /* p_align in demand paged PT_LOAD segments effectively stores
6147 	     the maximum page size.  When copying an executable with
6148 	     objcopy, we set m->p_align from the input file.  Use this
6149 	     value for maxpagesize rather than bed->maxpagesize, which
6150 	     may be different.  Note that we use maxpagesize for PT_TLS
6151 	     segment alignment later in this function, so we are relying
6152 	     on at least one PT_LOAD segment appearing before a PT_TLS
6153 	     segment.  */
6154 	  if (m->p_align_valid)
6155 	    maxpagesize = m->p_align;
6156 	  else if (p_align != 0
6157 		   && (link_info == NULL
6158 		       || !link_info->maxpagesize_is_set))
6159 	    /* Set p_align to the default p_align value while laying
6160 	       out segments aligning to the maximum page size or the
6161 	       largest section alignment.  The run-time loader can
6162 	       align segments to the default p_align value or the
6163 	       maximum page size, depending on system page size.  */
6164 	    p_align_p = true;
6165 
6166 	  p->p_align = maxpagesize;
6167 	}
6168       else if (m->p_align_valid)
6169 	p->p_align = m->p_align;
6170       else if (m->count == 0)
6171 	p->p_align = 1 << bed->s->log_file_align;
6172 
6173       if (m == phdr_load_seg)
6174 	{
6175 	  if (!m->includes_filehdr)
6176 	    p->p_offset = off;
6177 	  off += actual * bed->s->sizeof_phdr;
6178 	}
6179 
6180       no_contents = false;
6181       off_adjust = 0;
6182       if (p->p_type == PT_LOAD
6183 	  && m->count > 0)
6184 	{
6185 	  bfd_size_type align;  /* Bytes.  */
6186 	  unsigned int align_power = 0;
6187 
6188 	  if (m->p_align_valid)
6189 	    align = p->p_align;
6190 	  else
6191 	    {
6192 	      for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
6193 		{
6194 		  unsigned int secalign;
6195 
6196 		  secalign = bfd_section_alignment (*secpp);
6197 		  if (secalign > align_power)
6198 		    align_power = secalign;
6199 		}
6200 	      align = (bfd_size_type) 1 << align_power;
6201 	      if (align < maxpagesize)
6202 		{
6203 		  /* If a section requires alignment higher than the
6204 		     default p_align value, don't set p_align to the
6205 		     default p_align value.  */
6206 		  if (align > p_align)
6207 		    p_align_p = false;
6208 		  align = maxpagesize;
6209 		}
6210 	      else
6211 		{
6212 		  /* If a section requires alignment higher than the
6213 		     maximum page size, set p_align to the section
6214 		     alignment.  */
6215 		  p_align_p = true;
6216 		  p_align = align;
6217 		}
6218 	    }
6219 
6220 	  for (i = 0; i < m->count; i++)
6221 	    if ((m->sections[i]->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
6222 	      /* If we aren't making room for this section, then
6223 		 it must be SHT_NOBITS regardless of what we've
6224 		 set via struct bfd_elf_special_section.  */
6225 	      elf_section_type (m->sections[i]) = SHT_NOBITS;
6226 
6227 	  /* Find out whether this segment contains any loadable
6228 	     sections.  */
6229 	  no_contents = true;
6230 	  for (i = 0; i < m->count; i++)
6231 	    if (elf_section_type (m->sections[i]) != SHT_NOBITS)
6232 	      {
6233 		no_contents = false;
6234 		break;
6235 	      }
6236 
6237 	  off_adjust = vma_page_aligned_bias (p->p_vaddr, off, align * opb);
6238 
6239 	  /* Broken hardware and/or kernel require that files do not
6240 	     map the same page with different permissions on some hppa
6241 	     processors.  */
6242 	  if (j != 0
6243 	      && (abfd->flags & D_PAGED) != 0
6244 	      && bed->no_page_alias
6245 	      && (off & (maxpagesize - 1)) != 0
6246 	      && ((off & -maxpagesize)
6247 		  == ((off + off_adjust) & -maxpagesize)))
6248 	    off_adjust += maxpagesize;
6249 	  off += off_adjust;
6250 	  if (no_contents)
6251 	    {
6252 	      /* We shouldn't need to align the segment on disk since
6253 		 the segment doesn't need file space, but the gABI
6254 		 arguably requires the alignment and glibc ld.so
6255 		 checks it.  So to comply with the alignment
6256 		 requirement but not waste file space, we adjust
6257 		 p_offset for just this segment.  (OFF_ADJUST is
6258 		 subtracted from OFF later.)  This may put p_offset
6259 		 past the end of file, but that shouldn't matter.  */
6260 	    }
6261 	  else
6262 	    off_adjust = 0;
6263 	}
6264       /* Make sure the .dynamic section is the first section in the
6265 	 PT_DYNAMIC segment.  */
6266       else if (p->p_type == PT_DYNAMIC
6267 	       && m->count > 1
6268 	       && strcmp (m->sections[0]->name, ".dynamic") != 0)
6269 	{
6270 	  _bfd_error_handler
6271 	    (_("%pB: The first section in the PT_DYNAMIC segment"
6272 	       " is not the .dynamic section"),
6273 	     abfd);
6274 	  bfd_set_error (bfd_error_bad_value);
6275 	  return false;
6276 	}
6277       /* Set the note section type to SHT_NOTE.  */
6278       else if (p->p_type == PT_NOTE)
6279 	for (i = 0; i < m->count; i++)
6280 	  elf_section_type (m->sections[i]) = SHT_NOTE;
6281 
6282       if (m->includes_filehdr)
6283 	{
6284 	  if (!m->p_flags_valid)
6285 	    p->p_flags |= PF_R;
6286 	  p->p_filesz = bed->s->sizeof_ehdr;
6287 	  p->p_memsz = bed->s->sizeof_ehdr;
6288 	  if (p->p_type == PT_LOAD)
6289 	    {
6290 	      if (m->count > 0)
6291 		{
6292 		  if (p->p_vaddr < (bfd_vma) off
6293 		      || (!m->p_paddr_valid
6294 			  && p->p_paddr < (bfd_vma) off))
6295 		    {
6296 		      _bfd_error_handler
6297 			(_("%pB: not enough room for program headers,"
6298 			   " try linking with -N"),
6299 			 abfd);
6300 		      bfd_set_error (bfd_error_bad_value);
6301 		      return false;
6302 		    }
6303 		  p->p_vaddr -= off;
6304 		  if (!m->p_paddr_valid)
6305 		    p->p_paddr -= off;
6306 		}
6307 	    }
6308 	  else if (sorted_seg_map[0]->includes_filehdr)
6309 	    {
6310 	      Elf_Internal_Phdr *filehdr = phdrs + sorted_seg_map[0]->idx;
6311 	      p->p_vaddr = filehdr->p_vaddr;
6312 	      if (!m->p_paddr_valid)
6313 		p->p_paddr = filehdr->p_paddr;
6314 	    }
6315 	}
6316 
6317       if (m->includes_phdrs)
6318 	{
6319 	  if (!m->p_flags_valid)
6320 	    p->p_flags |= PF_R;
6321 	  p->p_filesz += actual * bed->s->sizeof_phdr;
6322 	  p->p_memsz += actual * bed->s->sizeof_phdr;
6323 	  if (!m->includes_filehdr)
6324 	    {
6325 	      if (p->p_type == PT_LOAD)
6326 		{
6327 		  elf_elfheader (abfd)->e_phoff = p->p_offset;
6328 		  if (m->count > 0)
6329 		    {
6330 		      p->p_vaddr -= off - p->p_offset;
6331 		      if (!m->p_paddr_valid)
6332 			p->p_paddr -= off - p->p_offset;
6333 		    }
6334 		}
6335 	      else if (phdr_load_seg != NULL)
6336 		{
6337 		  Elf_Internal_Phdr *phdr = phdrs + phdr_load_seg->idx;
6338 		  bfd_vma phdr_off = 0;  /* Octets.  */
6339 		  if (phdr_load_seg->includes_filehdr)
6340 		    phdr_off = bed->s->sizeof_ehdr;
6341 		  p->p_vaddr = phdr->p_vaddr + phdr_off;
6342 		  if (!m->p_paddr_valid)
6343 		    p->p_paddr = phdr->p_paddr + phdr_off;
6344 		  p->p_offset = phdr->p_offset + phdr_off;
6345 		}
6346 	      else
6347 		p->p_offset = bed->s->sizeof_ehdr;
6348 	    }
6349 	}
6350 
6351       if (p->p_type == PT_LOAD
6352 	  || (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core))
6353 	{
6354 	  if (!m->includes_filehdr && !m->includes_phdrs)
6355 	    {
6356 	      p->p_offset = off;
6357 	      if (no_contents)
6358 		{
6359 		  /* Put meaningless p_offset for PT_LOAD segments
6360 		     without file contents somewhere within the first
6361 		     page, in an attempt to not point past EOF.  */
6362 		  bfd_size_type align = maxpagesize;
6363 		  if (align < p->p_align)
6364 		    align = p->p_align;
6365 		  if (align < 1)
6366 		    align = 1;
6367 		  p->p_offset = off % align;
6368 		}
6369 	    }
6370 	  else
6371 	    {
6372 	      file_ptr adjust;  /* Octets.  */
6373 
6374 	      adjust = off - (p->p_offset + p->p_filesz);
6375 	      if (!no_contents)
6376 		p->p_filesz += adjust;
6377 	      p->p_memsz += adjust;
6378 	    }
6379 	}
6380 
6381       /* Set up p_filesz, p_memsz, p_align and p_flags from the section
6382 	 maps.  Set filepos for sections in PT_LOAD segments, and in
6383 	 core files, for sections in PT_NOTE segments.
6384 	 assign_file_positions_for_non_load_sections will set filepos
6385 	 for other sections and update p_filesz for other segments.  */
6386       for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
6387 	{
6388 	  asection *sec;
6389 	  bfd_size_type align;
6390 	  Elf_Internal_Shdr *this_hdr;
6391 
6392 	  sec = *secpp;
6393 	  this_hdr = &elf_section_data (sec)->this_hdr;
6394 	  align = (bfd_size_type) 1 << bfd_section_alignment (sec);
6395 
6396 	  if ((p->p_type == PT_LOAD
6397 	       || p->p_type == PT_TLS)
6398 	      && (this_hdr->sh_type != SHT_NOBITS
6399 		  || ((this_hdr->sh_flags & SHF_ALLOC) != 0
6400 		      && ((this_hdr->sh_flags & SHF_TLS) == 0
6401 			  || p->p_type == PT_TLS))))
6402 	    {
6403 	      bfd_vma p_start = p->p_paddr;		/* Octets.  */
6404 	      bfd_vma p_end = p_start + p->p_memsz;	/* Octets.  */
6405 	      bfd_vma s_start = sec->lma * opb;		/* Octets.  */
6406 	      bfd_vma adjust = s_start - p_end;		/* Octets.  */
6407 
6408 	      if (adjust != 0
6409 		  && (s_start < p_end
6410 		      || p_end < p_start))
6411 		{
6412 		  _bfd_error_handler
6413 		    /* xgettext:c-format */
6414 		    (_("%pB: section %pA lma %#" PRIx64
6415 		       " adjusted to %#" PRIx64),
6416 		     abfd, sec, (uint64_t) s_start / opb,
6417 		     (uint64_t) p_end / opb);
6418 		  adjust = 0;
6419 		  sec->lma = p_end / opb;
6420 		}
6421 	      p->p_memsz += adjust;
6422 
6423 	      if (p->p_type == PT_LOAD)
6424 		{
6425 		  if (this_hdr->sh_type != SHT_NOBITS)
6426 		    {
6427 		      off_adjust = 0;
6428 		      if (p->p_filesz + adjust < p->p_memsz)
6429 			{
6430 			  /* We have a PROGBITS section following NOBITS ones.
6431 			     Allocate file space for the NOBITS section(s).
6432 			     We don't need to write out the zeros, posix
6433 			     fseek past the end of data already written
6434 			     followed by a write at that location is
6435 			     guaranteed to result in zeros being read
6436 			     from the gap.  */
6437 			  adjust = p->p_memsz - p->p_filesz;
6438 			}
6439 		    }
6440 		  /* We only adjust sh_offset in SHT_NOBITS sections
6441 		     as would seem proper for their address when the
6442 		     section is first in the segment.  sh_offset
6443 		     doesn't really have any significance for
6444 		     SHT_NOBITS anyway, apart from a notional position
6445 		     relative to other sections.  Historically we
6446 		     didn't bother with adjusting sh_offset and some
6447 		     programs depend on it not being adjusted.  See
6448 		     pr12921 and pr25662.  */
6449 		  if (this_hdr->sh_type != SHT_NOBITS || i == 0)
6450 		    {
6451 		      off += adjust;
6452 		      if (this_hdr->sh_type == SHT_NOBITS)
6453 			off_adjust += adjust;
6454 		    }
6455 		}
6456 	      if (this_hdr->sh_type != SHT_NOBITS)
6457 		p->p_filesz += adjust;
6458 	    }
6459 
6460 	  if (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core)
6461 	    {
6462 	      /* The section at i == 0 is the one that actually contains
6463 		 everything.  */
6464 	      if (i == 0)
6465 		{
6466 		  this_hdr->sh_offset = sec->filepos = off;
6467 		  off += this_hdr->sh_size;
6468 		  p->p_filesz = this_hdr->sh_size;
6469 		  p->p_memsz = 0;
6470 		  p->p_align = 1;
6471 		}
6472 	      else
6473 		{
6474 		  /* The rest are fake sections that shouldn't be written.  */
6475 		  sec->filepos = 0;
6476 		  sec->size = 0;
6477 		  sec->flags = 0;
6478 		  continue;
6479 		}
6480 	    }
6481 	  else
6482 	    {
6483 	      if (p->p_type == PT_LOAD)
6484 		{
6485 		  this_hdr->sh_offset = sec->filepos = off;
6486 		  if (this_hdr->sh_type != SHT_NOBITS)
6487 		    off += this_hdr->sh_size;
6488 		}
6489 	      else if (this_hdr->sh_type == SHT_NOBITS
6490 		       && (this_hdr->sh_flags & SHF_TLS) != 0
6491 		       && this_hdr->sh_offset == 0)
6492 		{
6493 		  /* This is a .tbss section that didn't get a PT_LOAD.
6494 		     (See _bfd_elf_map_sections_to_segments "Create a
6495 		     final PT_LOAD".)  Set sh_offset to the value it
6496 		     would have if we had created a zero p_filesz and
6497 		     p_memsz PT_LOAD header for the section.  This
6498 		     also makes the PT_TLS header have the same
6499 		     p_offset value.  */
6500 		  bfd_vma adjust = vma_page_aligned_bias (this_hdr->sh_addr,
6501 							  off, align);
6502 		  this_hdr->sh_offset = sec->filepos = off + adjust;
6503 		}
6504 
6505 	      if (this_hdr->sh_type != SHT_NOBITS)
6506 		{
6507 		  p->p_filesz += this_hdr->sh_size;
6508 		  /* A load section without SHF_ALLOC is something like
6509 		     a note section in a PT_NOTE segment.  These take
6510 		     file space but are not loaded into memory.  */
6511 		  if ((this_hdr->sh_flags & SHF_ALLOC) != 0)
6512 		    p->p_memsz += this_hdr->sh_size;
6513 		}
6514 	      else if ((this_hdr->sh_flags & SHF_ALLOC) != 0)
6515 		{
6516 		  if (p->p_type == PT_TLS)
6517 		    p->p_memsz += this_hdr->sh_size;
6518 
6519 		  /* .tbss is special.  It doesn't contribute to p_memsz of
6520 		     normal segments.  */
6521 		  else if ((this_hdr->sh_flags & SHF_TLS) == 0)
6522 		    p->p_memsz += this_hdr->sh_size;
6523 		}
6524 
6525 	      if (align > p->p_align
6526 		  && !m->p_align_valid
6527 		  && (p->p_type != PT_LOAD
6528 		      || (abfd->flags & D_PAGED) == 0))
6529 		p->p_align = align;
6530 	    }
6531 
6532 	  if (!m->p_flags_valid)
6533 	    {
6534 	      p->p_flags |= PF_R;
6535 	      if ((this_hdr->sh_flags & SHF_EXECINSTR) != 0)
6536 		p->p_flags |= PF_X;
6537 	      if ((this_hdr->sh_flags & SHF_WRITE) != 0)
6538 		p->p_flags |= PF_W;
6539 	    }
6540 	}
6541 
6542       off -= off_adjust;
6543 
6544       /* PR ld/20815 - Check that the program header segment, if
6545 	 present, will be loaded into memory.  */
6546       if (p->p_type == PT_PHDR
6547 	  && phdr_load_seg == NULL
6548 	  && !(bed->elf_backend_allow_non_load_phdr != NULL
6549 	       && bed->elf_backend_allow_non_load_phdr (abfd, phdrs, alloc)))
6550 	{
6551 	  /* The fix for this error is usually to edit the linker script being
6552 	     used and set up the program headers manually.  Either that or
6553 	     leave room for the headers at the start of the SECTIONS.  */
6554 	  _bfd_error_handler (_("%pB: error: PHDR segment not covered"
6555 				" by LOAD segment"),
6556 			      abfd);
6557 	  if (link_info == NULL)
6558 	    return false;
6559 	  /* Arrange for the linker to exit with an error, deleting
6560 	     the output file unless --noinhibit-exec is given.  */
6561 	  link_info->callbacks->info ("%X");
6562 	}
6563 
6564       /* Check that all sections are in a PT_LOAD segment.
6565 	 Don't check funky gdb generated core files.  */
6566       if (p->p_type == PT_LOAD && bfd_get_format (abfd) != bfd_core)
6567 	{
6568 	  bool check_vma = true;
6569 
6570 	  for (i = 1; i < m->count; i++)
6571 	    if (m->sections[i]->vma == m->sections[i - 1]->vma
6572 		&& ELF_SECTION_SIZE (&(elf_section_data (m->sections[i])
6573 				       ->this_hdr), p) != 0
6574 		&& ELF_SECTION_SIZE (&(elf_section_data (m->sections[i - 1])
6575 				       ->this_hdr), p) != 0)
6576 	      {
6577 		/* Looks like we have overlays packed into the segment.  */
6578 		check_vma = false;
6579 		break;
6580 	      }
6581 
6582 	  for (i = 0; i < m->count; i++)
6583 	    {
6584 	      Elf_Internal_Shdr *this_hdr;
6585 	      asection *sec;
6586 
6587 	      sec = m->sections[i];
6588 	      this_hdr = &(elf_section_data(sec)->this_hdr);
6589 	      if (!ELF_SECTION_IN_SEGMENT_1 (this_hdr, p, check_vma, 0)
6590 		  && !ELF_TBSS_SPECIAL (this_hdr, p))
6591 		{
6592 		  _bfd_error_handler
6593 		    /* xgettext:c-format */
6594 		    (_("%pB: section `%pA' can't be allocated in segment %d"),
6595 		     abfd, sec, j);
6596 		  print_segment_map (m);
6597 		}
6598 	    }
6599 
6600 	  if (p_align_p)
6601 	    p->p_align = p_align;
6602 	}
6603     }
6604 
6605   elf_next_file_pos (abfd) = off;
6606 
6607   if (link_info != NULL
6608       && phdr_load_seg != NULL
6609       && phdr_load_seg->includes_filehdr)
6610     {
6611       /* There is a segment that contains both the file headers and the
6612 	 program headers, so provide a symbol __ehdr_start pointing there.
6613 	 A program can use this to examine itself robustly.  */
6614 
6615       struct elf_link_hash_entry *hash
6616 	= elf_link_hash_lookup (elf_hash_table (link_info), "__ehdr_start",
6617 				false, false, true);
6618       /* If the symbol was referenced and not defined, define it.  */
6619       if (hash != NULL
6620 	  && (hash->root.type == bfd_link_hash_new
6621 	      || hash->root.type == bfd_link_hash_undefined
6622 	      || hash->root.type == bfd_link_hash_undefweak
6623 	      || hash->root.type == bfd_link_hash_common))
6624 	{
6625 	  asection *s = NULL;
6626 	  bfd_vma filehdr_vaddr = phdrs[phdr_load_seg->idx].p_vaddr / opb;
6627 
6628 	  if (phdr_load_seg->count != 0)
6629 	    /* The segment contains sections, so use the first one.  */
6630 	    s = phdr_load_seg->sections[0];
6631 	  else
6632 	    /* Use the first (i.e. lowest-addressed) section in any segment.  */
6633 	    for (m = elf_seg_map (abfd); m != NULL; m = m->next)
6634 	      if (m->p_type == PT_LOAD && m->count != 0)
6635 		{
6636 		  s = m->sections[0];
6637 		  break;
6638 		}
6639 
6640 	  if (s != NULL)
6641 	    {
6642 	      hash->root.u.def.value = filehdr_vaddr - s->vma;
6643 	      hash->root.u.def.section = s;
6644 	    }
6645 	  else
6646 	    {
6647 	      hash->root.u.def.value = filehdr_vaddr;
6648 	      hash->root.u.def.section = bfd_abs_section_ptr;
6649 	    }
6650 
6651 	  hash->root.type = bfd_link_hash_defined;
6652 	  hash->def_regular = 1;
6653 	  hash->non_elf = 0;
6654 	}
6655     }
6656 
6657   return true;
6658 }
6659 
6660 /* Determine if a bfd is a debuginfo file.  Unfortunately there
6661    is no defined method for detecting such files, so we have to
6662    use heuristics instead.  */
6663 
6664 bool
is_debuginfo_file(bfd * abfd)6665 is_debuginfo_file (bfd *abfd)
6666 {
6667   if (abfd == NULL || bfd_get_flavour (abfd) != bfd_target_elf_flavour)
6668     return false;
6669 
6670   Elf_Internal_Shdr **start_headers = elf_elfsections (abfd);
6671   Elf_Internal_Shdr **end_headers = start_headers + elf_numsections (abfd);
6672   Elf_Internal_Shdr **headerp;
6673 
6674   for (headerp = start_headers; headerp < end_headers; headerp ++)
6675     {
6676       Elf_Internal_Shdr *header = * headerp;
6677 
6678       /* Debuginfo files do not have any allocated SHT_PROGBITS sections.
6679 	 The only allocated sections are SHT_NOBITS or SHT_NOTES.  */
6680       if ((header->sh_flags & SHF_ALLOC) == SHF_ALLOC
6681 	  && header->sh_type != SHT_NOBITS
6682 	  && header->sh_type != SHT_NOTE)
6683 	return false;
6684     }
6685 
6686   return true;
6687 }
6688 
6689 /* Assign file positions for other sections, except for compressed debug
6690    and sections assigned in _bfd_elf_assign_file_positions_for_non_load.  */
6691 
6692 static bool
assign_file_positions_for_non_load_sections(bfd * abfd,struct bfd_link_info * link_info)6693 assign_file_positions_for_non_load_sections (bfd *abfd,
6694 					     struct bfd_link_info *link_info)
6695 {
6696   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
6697   Elf_Internal_Shdr **i_shdrpp;
6698   Elf_Internal_Shdr **hdrpp, **end_hdrpp;
6699   Elf_Internal_Phdr *phdrs;
6700   Elf_Internal_Phdr *p;
6701   struct elf_segment_map *m;
6702   file_ptr off;
6703   unsigned int opb = bfd_octets_per_byte (abfd, NULL);
6704   bfd_vma maxpagesize;
6705 
6706   if (link_info != NULL)
6707     maxpagesize = link_info->maxpagesize;
6708   else
6709     maxpagesize = bed->maxpagesize;
6710   i_shdrpp = elf_elfsections (abfd);
6711   end_hdrpp = i_shdrpp + elf_numsections (abfd);
6712   off = elf_next_file_pos (abfd);
6713   for (hdrpp = i_shdrpp + 1; hdrpp < end_hdrpp; hdrpp++)
6714     {
6715       Elf_Internal_Shdr *hdr;
6716       bfd_vma align;
6717 
6718       hdr = *hdrpp;
6719       if (hdr->bfd_section != NULL
6720 	  && (hdr->bfd_section->filepos != 0
6721 	      || (hdr->sh_type == SHT_NOBITS
6722 		  && hdr->contents == NULL)))
6723 	BFD_ASSERT (hdr->sh_offset == hdr->bfd_section->filepos);
6724       else if ((hdr->sh_flags & SHF_ALLOC) != 0)
6725 	{
6726 	  if (hdr->sh_size != 0
6727 	      /* PR 24717 - debuginfo files are known to be not strictly
6728 		 compliant with the ELF standard.  In particular they often
6729 		 have .note.gnu.property sections that are outside of any
6730 		 loadable segment.  This is not a problem for such files,
6731 		 so do not warn about them.  */
6732 	      && ! is_debuginfo_file (abfd))
6733 	    _bfd_error_handler
6734 	      /* xgettext:c-format */
6735 	      (_("%pB: warning: allocated section `%s' not in segment"),
6736 	       abfd,
6737 	       (hdr->bfd_section == NULL
6738 		? "*unknown*"
6739 		: hdr->bfd_section->name));
6740 	  /* We don't need to page align empty sections.  */
6741 	  if ((abfd->flags & D_PAGED) != 0 && hdr->sh_size != 0)
6742 	    align = maxpagesize;
6743 	  else
6744 	    align = hdr->sh_addralign & -hdr->sh_addralign;
6745 	  off += vma_page_aligned_bias (hdr->sh_addr, off, align);
6746 	  off = _bfd_elf_assign_file_position_for_section (hdr, off,
6747 							   false);
6748 	}
6749       else if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
6750 		&& hdr->bfd_section == NULL)
6751 	       /* We don't know the offset of these sections yet:
6752 		  their size has not been decided.  */
6753 	       || (abfd->is_linker_output
6754 		   && hdr->bfd_section != NULL
6755 		   && (hdr->sh_name == -1u
6756 		       || bfd_section_is_ctf (hdr->bfd_section)))
6757 	       || hdr == i_shdrpp[elf_onesymtab (abfd)]
6758 	       || (elf_symtab_shndx_list (abfd) != NULL
6759 		   && hdr == i_shdrpp[elf_symtab_shndx_list (abfd)->ndx])
6760 	       || hdr == i_shdrpp[elf_strtab_sec (abfd)]
6761 	       || hdr == i_shdrpp[elf_shstrtab_sec (abfd)])
6762 	hdr->sh_offset = -1;
6763       else
6764 	off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
6765     }
6766   elf_next_file_pos (abfd) = off;
6767 
6768   /* Now that we have set the section file positions, we can set up
6769      the file positions for the non PT_LOAD segments.  */
6770   phdrs = elf_tdata (abfd)->phdr;
6771   for (m = elf_seg_map (abfd), p = phdrs; m != NULL; m = m->next, p++)
6772     {
6773       if (p->p_type == PT_GNU_RELRO)
6774 	{
6775 	  bfd_vma start, end;  /* Bytes.  */
6776 	  bool ok;
6777 
6778 	  if (link_info != NULL)
6779 	    {
6780 	      /* During linking the range of the RELRO segment is passed
6781 		 in link_info.  Note that there may be padding between
6782 		 relro_start and the first RELRO section.  */
6783 	      start = link_info->relro_start;
6784 	      end = link_info->relro_end;
6785 	    }
6786 	  else if (m->count != 0)
6787 	    {
6788 	      if (!m->p_size_valid)
6789 		abort ();
6790 	      start = m->sections[0]->vma;
6791 	      end = start + m->p_size / opb;
6792 	    }
6793 	  else
6794 	    {
6795 	      start = 0;
6796 	      end = 0;
6797 	    }
6798 
6799 	  ok = false;
6800 	  if (start < end)
6801 	    {
6802 	      struct elf_segment_map *lm;
6803 	      const Elf_Internal_Phdr *lp;
6804 	      unsigned int i;
6805 
6806 	      /* Find a LOAD segment containing a section in the RELRO
6807 		 segment.  */
6808 	      for (lm = elf_seg_map (abfd), lp = phdrs;
6809 		   lm != NULL;
6810 		   lm = lm->next, lp++)
6811 		{
6812 		  if (lp->p_type == PT_LOAD
6813 		      && lm->count != 0
6814 		      && (lm->sections[lm->count - 1]->vma
6815 			  + (!IS_TBSS (lm->sections[lm->count - 1])
6816 			     ? lm->sections[lm->count - 1]->size / opb
6817 			     : 0)) > start
6818 		      && lm->sections[0]->vma < end)
6819 		    break;
6820 		}
6821 
6822 	      if (lm != NULL)
6823 		{
6824 		  /* Find the section starting the RELRO segment.  */
6825 		  for (i = 0; i < lm->count; i++)
6826 		    {
6827 		      asection *s = lm->sections[i];
6828 		      if (s->vma >= start
6829 			  && s->vma < end
6830 			  && s->size != 0)
6831 			break;
6832 		    }
6833 
6834 		  if (i < lm->count)
6835 		    {
6836 		      p->p_vaddr = lm->sections[i]->vma * opb;
6837 		      p->p_paddr = lm->sections[i]->lma * opb;
6838 		      p->p_offset = lm->sections[i]->filepos;
6839 		      p->p_memsz = end * opb - p->p_vaddr;
6840 		      p->p_filesz = p->p_memsz;
6841 
6842 		      /* The RELRO segment typically ends a few bytes
6843 			 into .got.plt but other layouts are possible.
6844 			 In cases where the end does not match any
6845 			 loaded section (for instance is in file
6846 			 padding), trim p_filesz back to correspond to
6847 			 the end of loaded section contents.  */
6848 		      if (p->p_filesz > lp->p_vaddr + lp->p_filesz - p->p_vaddr)
6849 			p->p_filesz = lp->p_vaddr + lp->p_filesz - p->p_vaddr;
6850 
6851 		      /* Preserve the alignment and flags if they are
6852 			 valid.  The gold linker generates RW/4 for
6853 			 the PT_GNU_RELRO section.  It is better for
6854 			 objcopy/strip to honor these attributes
6855 			 otherwise gdb will choke when using separate
6856 			 debug files.  */
6857 		      if (!m->p_align_valid)
6858 			p->p_align = 1;
6859 		      if (!m->p_flags_valid)
6860 			p->p_flags = PF_R;
6861 		      ok = true;
6862 		    }
6863 		}
6864 	    }
6865 
6866 	  if (!ok)
6867 	    {
6868 	      if (link_info != NULL)
6869 		_bfd_error_handler
6870 		  (_("%pB: warning: unable to allocate any sections"
6871 		     " to PT_GNU_RELRO segment"),
6872 		   abfd);
6873 	      memset (p, 0, sizeof *p);
6874 	    }
6875 	}
6876       else if (p->p_type == PT_GNU_STACK)
6877 	{
6878 	  if (m->p_size_valid)
6879 	    p->p_memsz = m->p_size;
6880 	}
6881       else if (m->count != 0)
6882 	{
6883 	  unsigned int i;
6884 
6885 	  if (p->p_type != PT_LOAD
6886 	      && (p->p_type != PT_NOTE
6887 		  || bfd_get_format (abfd) != bfd_core))
6888 	    {
6889 	      /* A user specified segment layout may include a PHDR
6890 		 segment that overlaps with a LOAD segment...  */
6891 	      if (p->p_type == PT_PHDR)
6892 		{
6893 		  m->count = 0;
6894 		  continue;
6895 		}
6896 
6897 	      if (m->includes_filehdr || m->includes_phdrs)
6898 		{
6899 		  /* PR 17512: file: 2195325e.  */
6900 		  _bfd_error_handler
6901 		    (_("%pB: error: non-load segment %d includes file header "
6902 		       "and/or program header"),
6903 		     abfd, (int) (p - phdrs));
6904 		  return false;
6905 		}
6906 
6907 	      p->p_filesz = 0;
6908 	      p->p_offset = m->sections[0]->filepos;
6909 	      for (i = m->count; i-- != 0;)
6910 		{
6911 		  asection *sect = m->sections[i];
6912 		  Elf_Internal_Shdr *hdr = &elf_section_data (sect)->this_hdr;
6913 		  if (hdr->sh_type != SHT_NOBITS)
6914 		    {
6915 		      p->p_filesz = sect->filepos - p->p_offset + hdr->sh_size;
6916 		      /* NB: p_memsz of the loadable PT_NOTE segment
6917 			 should be the same as p_filesz.  */
6918 		      if (p->p_type == PT_NOTE
6919 			  && (hdr->sh_flags & SHF_ALLOC) != 0)
6920 			p->p_memsz = p->p_filesz;
6921 		      break;
6922 		    }
6923 		}
6924 	    }
6925 	}
6926     }
6927 
6928   return true;
6929 }
6930 
6931 static elf_section_list *
find_section_in_list(unsigned int i,elf_section_list * list)6932 find_section_in_list (unsigned int i, elf_section_list * list)
6933 {
6934   for (;list != NULL; list = list->next)
6935     if (list->ndx == i)
6936       break;
6937   return list;
6938 }
6939 
6940 /* Work out the file positions of all the sections.  This is called by
6941    _bfd_elf_compute_section_file_positions.  All the section sizes and
6942    VMAs must be known before this is called.
6943 
6944    Reloc sections come in two flavours: Those processed specially as
6945    "side-channel" data attached to a section to which they apply, and
6946    those that bfd doesn't process as relocations.  The latter sort are
6947    stored in a normal bfd section by bfd_section_from_shdr.  We don't
6948    consider the former sort here, unless they form part of the loadable
6949    image.  Reloc sections not assigned here (and compressed debugging
6950    sections and CTF sections which nothing else in the file can rely
6951    upon) will be handled later by assign_file_positions_for_relocs.
6952 
6953    We also don't set the positions of the .symtab and .strtab here.  */
6954 
6955 static bool
assign_file_positions_except_relocs(bfd * abfd,struct bfd_link_info * link_info)6956 assign_file_positions_except_relocs (bfd *abfd,
6957 				     struct bfd_link_info *link_info)
6958 {
6959   struct elf_obj_tdata *tdata = elf_tdata (abfd);
6960   Elf_Internal_Ehdr *i_ehdrp = elf_elfheader (abfd);
6961   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
6962   unsigned int alloc;
6963 
6964   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
6965       && bfd_get_format (abfd) != bfd_core)
6966     {
6967       Elf_Internal_Shdr ** const i_shdrpp = elf_elfsections (abfd);
6968       unsigned int num_sec = elf_numsections (abfd);
6969       Elf_Internal_Shdr **hdrpp;
6970       unsigned int i;
6971       file_ptr off;
6972 
6973       /* Start after the ELF header.  */
6974       off = i_ehdrp->e_ehsize;
6975 
6976       /* We are not creating an executable, which means that we are
6977 	 not creating a program header, and that the actual order of
6978 	 the sections in the file is unimportant.  */
6979       for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
6980 	{
6981 	  Elf_Internal_Shdr *hdr;
6982 
6983 	  hdr = *hdrpp;
6984 	  if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
6985 	       && hdr->bfd_section == NULL)
6986 	      /* Do not assign offsets for these sections yet: we don't know
6987 		 their sizes.  */
6988 	      || (abfd->is_linker_output
6989 		  && hdr->bfd_section != NULL
6990 		  && (hdr->sh_name == -1u
6991 		      || bfd_section_is_ctf (hdr->bfd_section)))
6992 	      || i == elf_onesymtab (abfd)
6993 	      || (elf_symtab_shndx_list (abfd) != NULL
6994 		  && hdr == i_shdrpp[elf_symtab_shndx_list (abfd)->ndx])
6995 	      || i == elf_strtab_sec (abfd)
6996 	      || i == elf_shstrtab_sec (abfd))
6997 	    {
6998 	      hdr->sh_offset = -1;
6999 	    }
7000 	  else
7001 	    off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
7002 	}
7003 
7004       elf_next_file_pos (abfd) = off;
7005       elf_program_header_size (abfd) = 0;
7006     }
7007   else
7008     {
7009       /* Assign file positions for the loaded sections based on the
7010 	 assignment of sections to segments.  */
7011       if (!assign_file_positions_for_load_sections (abfd, link_info))
7012 	return false;
7013 
7014       /* And for non-load sections.  */
7015       if (!assign_file_positions_for_non_load_sections (abfd, link_info))
7016 	return false;
7017     }
7018 
7019   if (!(*bed->elf_backend_modify_headers) (abfd, link_info))
7020     return false;
7021 
7022   /* Write out the program headers.  */
7023   alloc = i_ehdrp->e_phnum;
7024   if (alloc != 0)
7025     {
7026       if (link_info != NULL && ! link_info->no_warn_rwx_segments)
7027 	{
7028 	  bool warned_tls = false;
7029 	  bool warned_rwx = false;
7030 
7031 	  /* Memory resident segments with non-zero size and RWX
7032 	     permissions are a security risk, so we generate a warning
7033 	     here if we are creating any.  */
7034 	  unsigned int i;
7035 
7036 	  for (i = 0; i < alloc; i++)
7037 	    {
7038 	      const Elf_Internal_Phdr * phdr = tdata->phdr + i;
7039 
7040 	      if (phdr->p_memsz == 0)
7041 		continue;
7042 
7043 	      if (! warned_tls
7044 		  && phdr->p_type == PT_TLS
7045 		  && (phdr->p_flags & PF_X))
7046 		{
7047 		  if (link_info->warn_is_error_for_rwx_segments)
7048 		    {
7049 		      _bfd_error_handler (_("\
7050 error: %pB has a TLS segment with execute permission"),
7051 					  abfd);
7052 		      return false;
7053 		    }
7054 
7055 		  _bfd_error_handler (_("\
7056 warning: %pB has a TLS segment with execute permission"),
7057 				      abfd);
7058 		  if (warned_rwx)
7059 		    break;
7060 
7061 		  warned_tls = true;
7062 		}
7063 	      else if (! warned_rwx
7064 		       && phdr->p_type == PT_LOAD
7065 		       && ((phdr->p_flags & (PF_R | PF_W | PF_X))
7066 			   == (PF_R | PF_W | PF_X)))
7067 		{
7068 		  if (link_info->warn_is_error_for_rwx_segments)
7069 		    {
7070 		      _bfd_error_handler (_("\
7071 error: %pB has a LOAD segment with RWX permissions"),
7072 					  abfd);
7073 		      return false;
7074 		    }
7075 
7076 		  _bfd_error_handler (_("\
7077 warning: %pB has a LOAD segment with RWX permissions"),
7078 				      abfd);
7079 		  if (warned_tls)
7080 		    break;
7081 
7082 		  warned_rwx = true;
7083 		}
7084 	    }
7085 	}
7086 
7087       if (bfd_seek (abfd, i_ehdrp->e_phoff, SEEK_SET) != 0
7088 	  || bed->s->write_out_phdrs (abfd, tdata->phdr, alloc) != 0)
7089 	return false;
7090     }
7091 
7092   return true;
7093 }
7094 
7095 bool
_bfd_elf_init_file_header(bfd * abfd,struct bfd_link_info * info ATTRIBUTE_UNUSED)7096 _bfd_elf_init_file_header (bfd *abfd,
7097 			   struct bfd_link_info *info ATTRIBUTE_UNUSED)
7098 {
7099   Elf_Internal_Ehdr *i_ehdrp;	/* Elf file header, internal form.  */
7100   struct elf_strtab_hash *shstrtab;
7101   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7102 
7103   i_ehdrp = elf_elfheader (abfd);
7104 
7105   shstrtab = _bfd_elf_strtab_init ();
7106   if (shstrtab == NULL)
7107     return false;
7108 
7109   elf_shstrtab (abfd) = shstrtab;
7110 
7111   i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
7112   i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
7113   i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
7114   i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
7115 
7116   i_ehdrp->e_ident[EI_CLASS] = bed->s->elfclass;
7117   i_ehdrp->e_ident[EI_DATA] =
7118     bfd_big_endian (abfd) ? ELFDATA2MSB : ELFDATA2LSB;
7119   i_ehdrp->e_ident[EI_VERSION] = bed->s->ev_current;
7120 
7121   if ((abfd->flags & DYNAMIC) != 0)
7122     i_ehdrp->e_type = ET_DYN;
7123   else if ((abfd->flags & EXEC_P) != 0)
7124     i_ehdrp->e_type = ET_EXEC;
7125   else if (bfd_get_format (abfd) == bfd_core)
7126     i_ehdrp->e_type = ET_CORE;
7127   else
7128     i_ehdrp->e_type = ET_REL;
7129 
7130   switch (bfd_get_arch (abfd))
7131     {
7132     case bfd_arch_unknown:
7133       i_ehdrp->e_machine = EM_NONE;
7134       break;
7135 
7136       /* There used to be a long list of cases here, each one setting
7137 	 e_machine to the same EM_* macro #defined as ELF_MACHINE_CODE
7138 	 in the corresponding bfd definition.  To avoid duplication,
7139 	 the switch was removed.  Machines that need special handling
7140 	 can generally do it in elf_backend_final_write_processing(),
7141 	 unless they need the information earlier than the final write.
7142 	 Such need can generally be supplied by replacing the tests for
7143 	 e_machine with the conditions used to determine it.  */
7144     default:
7145       i_ehdrp->e_machine = bed->elf_machine_code;
7146     }
7147 
7148   i_ehdrp->e_version = bed->s->ev_current;
7149   i_ehdrp->e_ehsize = bed->s->sizeof_ehdr;
7150 
7151   /* No program header, for now.  */
7152   i_ehdrp->e_phoff = 0;
7153   i_ehdrp->e_phentsize = 0;
7154   i_ehdrp->e_phnum = 0;
7155 
7156   /* Each bfd section is section header entry.  */
7157   i_ehdrp->e_entry = bfd_get_start_address (abfd);
7158   i_ehdrp->e_shentsize = bed->s->sizeof_shdr;
7159 
7160   elf_tdata (abfd)->symtab_hdr.sh_name =
7161     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".symtab", false);
7162   elf_tdata (abfd)->strtab_hdr.sh_name =
7163     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".strtab", false);
7164   elf_tdata (abfd)->shstrtab_hdr.sh_name =
7165     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".shstrtab", false);
7166   if (elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
7167       || elf_tdata (abfd)->strtab_hdr.sh_name == (unsigned int) -1
7168       || elf_tdata (abfd)->shstrtab_hdr.sh_name == (unsigned int) -1)
7169     return false;
7170 
7171   return true;
7172 }
7173 
7174 /* Set e_type in ELF header to ET_EXEC for -pie -Ttext-segment=.
7175 
7176    FIXME: We used to have code here to sort the PT_LOAD segments into
7177    ascending order, as per the ELF spec.  But this breaks some programs,
7178    including the Linux kernel.  But really either the spec should be
7179    changed or the programs updated.  */
7180 
7181 bool
_bfd_elf_modify_headers(bfd * obfd,struct bfd_link_info * link_info)7182 _bfd_elf_modify_headers (bfd *obfd, struct bfd_link_info *link_info)
7183 {
7184   if (link_info != NULL && bfd_link_pie (link_info))
7185     {
7186       Elf_Internal_Ehdr *i_ehdrp = elf_elfheader (obfd);
7187       unsigned int num_segments = i_ehdrp->e_phnum;
7188       struct elf_obj_tdata *tdata = elf_tdata (obfd);
7189       Elf_Internal_Phdr *segment = tdata->phdr;
7190       Elf_Internal_Phdr *end_segment = &segment[num_segments];
7191 
7192       /* Find the lowest p_vaddr in PT_LOAD segments.  */
7193       bfd_vma p_vaddr = (bfd_vma) -1;
7194       for (; segment < end_segment; segment++)
7195 	if (segment->p_type == PT_LOAD && p_vaddr > segment->p_vaddr)
7196 	  p_vaddr = segment->p_vaddr;
7197 
7198       /* Set e_type to ET_EXEC if the lowest p_vaddr in PT_LOAD
7199 	 segments is non-zero.  */
7200       if (p_vaddr)
7201 	i_ehdrp->e_type = ET_EXEC;
7202     }
7203   return true;
7204 }
7205 
7206 /* Assign file positions for all the reloc sections which are not part
7207    of the loadable file image, and the file position of section headers.  */
7208 
7209 static bool
_bfd_elf_assign_file_positions_for_non_load(bfd * abfd)7210 _bfd_elf_assign_file_positions_for_non_load (bfd *abfd)
7211 {
7212   file_ptr off;
7213   Elf_Internal_Shdr **shdrpp, **end_shdrpp;
7214   Elf_Internal_Shdr *shdrp;
7215   Elf_Internal_Ehdr *i_ehdrp;
7216   const struct elf_backend_data *bed;
7217 
7218   /* Skip non-load sections without section header.  */
7219   if ((abfd->flags & BFD_NO_SECTION_HEADER) != 0)
7220     return true;
7221 
7222   off = elf_next_file_pos (abfd);
7223 
7224   shdrpp = elf_elfsections (abfd);
7225   end_shdrpp = shdrpp + elf_numsections (abfd);
7226   for (shdrpp++; shdrpp < end_shdrpp; shdrpp++)
7227     {
7228       shdrp = *shdrpp;
7229       if (shdrp->sh_offset == -1)
7230 	{
7231 	  asection *sec = shdrp->bfd_section;
7232 	  if (sec == NULL
7233 	      || shdrp->sh_type == SHT_REL
7234 	      || shdrp->sh_type == SHT_RELA)
7235 	    ;
7236 	  else if (bfd_section_is_ctf (sec))
7237 	    {
7238 	      /* Update section size and contents.	*/
7239 	      shdrp->sh_size = sec->size;
7240 	      shdrp->contents = sec->contents;
7241 	    }
7242 	  else if (shdrp->sh_name == -1u)
7243 	    {
7244 	      const char *name = sec->name;
7245 	      struct bfd_elf_section_data *d;
7246 
7247 	      /* Compress DWARF debug sections.  */
7248 	      if (!bfd_compress_section (abfd, sec, shdrp->contents))
7249 		return false;
7250 
7251 	      if (sec->compress_status == COMPRESS_SECTION_DONE
7252 		  && (abfd->flags & BFD_COMPRESS_GABI) == 0
7253 		  && name[1] == 'd')
7254 		{
7255 		  /* If section is compressed with zlib-gnu, convert
7256 		     section name from .debug_* to .zdebug_*.  */
7257 		  char *new_name = bfd_debug_name_to_zdebug (abfd, name);
7258 		  if (new_name == NULL)
7259 		    return false;
7260 		  name = new_name;
7261 		}
7262 	      /* Add section name to section name section.  */
7263 	      shdrp->sh_name
7264 		= (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd),
7265 						      name, false);
7266 	      d = elf_section_data (sec);
7267 
7268 	      /* Add reloc section name to section name section.  */
7269 	      if (d->rel.hdr
7270 		  && !_bfd_elf_set_reloc_sh_name (abfd, d->rel.hdr,
7271 						  name, false))
7272 		return false;
7273 	      if (d->rela.hdr
7274 		  && !_bfd_elf_set_reloc_sh_name (abfd, d->rela.hdr,
7275 						  name, true))
7276 		return false;
7277 
7278 	      /* Update section size and contents.  */
7279 	      shdrp->sh_size = sec->size;
7280 	      shdrp->contents = sec->contents;
7281 	      sec->contents = NULL;
7282 	    }
7283 
7284 	  off = _bfd_elf_assign_file_position_for_section (shdrp, off, true);
7285 	}
7286     }
7287 
7288   /* Place section name section after DWARF debug sections have been
7289      compressed.  */
7290   _bfd_elf_strtab_finalize (elf_shstrtab (abfd));
7291   shdrp = &elf_tdata (abfd)->shstrtab_hdr;
7292   shdrp->sh_size = _bfd_elf_strtab_size (elf_shstrtab (abfd));
7293   off = _bfd_elf_assign_file_position_for_section (shdrp, off, true);
7294 
7295   /* Place the section headers.  */
7296   i_ehdrp = elf_elfheader (abfd);
7297   bed = get_elf_backend_data (abfd);
7298   off = align_file_position (off, 1 << bed->s->log_file_align);
7299   i_ehdrp->e_shoff = off;
7300   off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
7301   elf_next_file_pos (abfd) = off;
7302 
7303   return true;
7304 }
7305 
7306 bool
_bfd_elf_write_object_contents(bfd * abfd)7307 _bfd_elf_write_object_contents (bfd *abfd)
7308 {
7309   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7310   Elf_Internal_Shdr **i_shdrp;
7311   bool failed;
7312   unsigned int count, num_sec;
7313   struct elf_obj_tdata *t;
7314 
7315   if (! abfd->output_has_begun
7316       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
7317     return false;
7318   /* Do not rewrite ELF data when the BFD has been opened for update.
7319      abfd->output_has_begun was set to TRUE on opening, so creation of
7320      new sections, and modification of existing section sizes was
7321      restricted.  This means the ELF header, program headers and
7322      section headers can't have changed.  If the contents of any
7323      sections has been modified, then those changes have already been
7324      written to the BFD.  */
7325   else if (abfd->direction == both_direction)
7326     {
7327       BFD_ASSERT (abfd->output_has_begun);
7328       return true;
7329     }
7330 
7331   i_shdrp = elf_elfsections (abfd);
7332 
7333   failed = false;
7334   bfd_map_over_sections (abfd, bed->s->write_relocs, &failed);
7335   if (failed)
7336     return false;
7337 
7338   if (!_bfd_elf_assign_file_positions_for_non_load (abfd))
7339     return false;
7340 
7341   /* After writing the headers, we need to write the sections too...  */
7342   num_sec = elf_numsections (abfd);
7343   for (count = 1; count < num_sec; count++)
7344     {
7345       /* Don't set the sh_name field without section header.  */
7346       if ((abfd->flags & BFD_NO_SECTION_HEADER) == 0)
7347 	i_shdrp[count]->sh_name
7348 	  = _bfd_elf_strtab_offset (elf_shstrtab (abfd),
7349 				    i_shdrp[count]->sh_name);
7350       if (bed->elf_backend_section_processing)
7351 	if (!(*bed->elf_backend_section_processing) (abfd, i_shdrp[count]))
7352 	  return false;
7353       if (i_shdrp[count]->contents)
7354 	{
7355 	  bfd_size_type amt = i_shdrp[count]->sh_size;
7356 
7357 	  if (bfd_seek (abfd, i_shdrp[count]->sh_offset, SEEK_SET) != 0
7358 	      || bfd_write (i_shdrp[count]->contents, amt, abfd) != amt)
7359 	    return false;
7360 	}
7361     }
7362 
7363   /* Write out the section header names.  */
7364   t = elf_tdata (abfd);
7365   if (elf_shstrtab (abfd) != NULL
7366       && t->shstrtab_hdr.sh_offset != -1
7367       && (bfd_seek (abfd, t->shstrtab_hdr.sh_offset, SEEK_SET) != 0
7368 	  || !_bfd_elf_strtab_emit (abfd, elf_shstrtab (abfd))))
7369     return false;
7370 
7371   if (!(*bed->elf_backend_final_write_processing) (abfd))
7372     return false;
7373 
7374   if (!bed->s->write_shdrs_and_ehdr (abfd))
7375     return false;
7376 
7377   /* This is last since write_shdrs_and_ehdr can touch i_shdrp[0].  */
7378   if (t->o->build_id.after_write_object_contents != NULL
7379       && !(*t->o->build_id.after_write_object_contents) (abfd))
7380     return false;
7381   if (t->o->package_metadata.after_write_object_contents != NULL
7382       && !(*t->o->package_metadata.after_write_object_contents) (abfd))
7383     return false;
7384 
7385   return true;
7386 }
7387 
7388 bool
_bfd_elf_write_corefile_contents(bfd * abfd)7389 _bfd_elf_write_corefile_contents (bfd *abfd)
7390 {
7391   /* Hopefully this can be done just like an object file.  */
7392   return _bfd_elf_write_object_contents (abfd);
7393 }
7394 
7395 /* Given a section, search the header to find them.  */
7396 
7397 unsigned int
_bfd_elf_section_from_bfd_section(bfd * abfd,struct bfd_section * asect)7398 _bfd_elf_section_from_bfd_section (bfd *abfd, struct bfd_section *asect)
7399 {
7400   const struct elf_backend_data *bed;
7401   unsigned int sec_index;
7402 
7403   if (elf_section_data (asect) != NULL
7404       && elf_section_data (asect)->this_idx != 0)
7405     return elf_section_data (asect)->this_idx;
7406 
7407   if (bfd_is_abs_section (asect))
7408     sec_index = SHN_ABS;
7409   else if (bfd_is_com_section (asect))
7410     sec_index = SHN_COMMON;
7411   else if (bfd_is_und_section (asect))
7412     sec_index = SHN_UNDEF;
7413   else
7414     sec_index = SHN_BAD;
7415 
7416   bed = get_elf_backend_data (abfd);
7417   if (bed->elf_backend_section_from_bfd_section)
7418     {
7419       int retval = sec_index;
7420 
7421       if ((*bed->elf_backend_section_from_bfd_section) (abfd, asect, &retval))
7422 	return retval;
7423     }
7424 
7425   if (sec_index == SHN_BAD)
7426     bfd_set_error (bfd_error_nonrepresentable_section);
7427 
7428   return sec_index;
7429 }
7430 
7431 /* Given a BFD symbol, return the index in the ELF symbol table, or -1
7432    on error.  */
7433 
7434 int
_bfd_elf_symbol_from_bfd_symbol(bfd * abfd,asymbol ** asym_ptr_ptr)7435 _bfd_elf_symbol_from_bfd_symbol (bfd *abfd, asymbol **asym_ptr_ptr)
7436 {
7437   asymbol *asym_ptr = *asym_ptr_ptr;
7438   int idx;
7439   flagword flags = asym_ptr->flags;
7440 
7441   /* When gas creates relocations against local labels, it creates its
7442      own symbol for the section, but does put the symbol into the
7443      symbol chain, so udata is 0.  When the linker is generating
7444      relocatable output, this section symbol may be for one of the
7445      input sections rather than the output section.  */
7446   if (asym_ptr->udata.i == 0
7447       && (flags & BSF_SECTION_SYM)
7448       && asym_ptr->section)
7449     {
7450       asection *sec;
7451 
7452       sec = asym_ptr->section;
7453       if (sec->owner != abfd && sec->output_section != NULL)
7454 	sec = sec->output_section;
7455       if (sec->owner == abfd
7456 	  && sec->index < elf_num_section_syms (abfd)
7457 	  && elf_section_syms (abfd)[sec->index] != NULL)
7458 	asym_ptr->udata.i = elf_section_syms (abfd)[sec->index]->udata.i;
7459     }
7460 
7461   idx = asym_ptr->udata.i;
7462 
7463   if (idx == 0)
7464     {
7465       /* This case can occur when using --strip-symbol on a symbol
7466 	 which is used in a relocation entry.  */
7467       _bfd_error_handler
7468 	/* xgettext:c-format */
7469 	(_("%pB: symbol `%s' required but not present"),
7470 	 abfd, bfd_asymbol_name (asym_ptr));
7471       bfd_set_error (bfd_error_no_symbols);
7472       return -1;
7473     }
7474 
7475 #if DEBUG & 4
7476   {
7477     fprintf (stderr,
7478 	     "elf_symbol_from_bfd_symbol 0x%.8lx, name = %s, sym num = %d,"
7479 	     " flags = 0x%.8x\n",
7480 	     (long) asym_ptr, asym_ptr->name, idx, flags);
7481     fflush (stderr);
7482   }
7483 #endif
7484 
7485   return idx;
7486 }
7487 
7488 static inline bfd_vma
segment_size(Elf_Internal_Phdr * segment)7489 segment_size (Elf_Internal_Phdr *segment)
7490 {
7491   return (segment->p_memsz > segment->p_filesz
7492 	  ? segment->p_memsz : segment->p_filesz);
7493 }
7494 
7495 
7496 /* Returns the end address of the segment + 1.  */
7497 static inline bfd_vma
segment_end(Elf_Internal_Phdr * segment,bfd_vma start)7498 segment_end (Elf_Internal_Phdr *segment, bfd_vma start)
7499 {
7500   return start + segment_size (segment);
7501 }
7502 
7503 static inline bfd_size_type
section_size(asection * section,Elf_Internal_Phdr * segment)7504 section_size (asection *section, Elf_Internal_Phdr *segment)
7505 {
7506   if ((section->flags & SEC_HAS_CONTENTS) != 0
7507       || (section->flags & SEC_THREAD_LOCAL) == 0
7508       || segment->p_type == PT_TLS)
7509     return section->size;
7510   return 0;
7511 }
7512 
7513 /* Returns TRUE if the given section is contained within the given
7514    segment.  LMA addresses are compared against PADDR when
7515    USE_VADDR is false, VMA against VADDR when true.  */
7516 static bool
is_contained_by(asection * section,Elf_Internal_Phdr * segment,bfd_vma paddr,bfd_vma vaddr,unsigned int opb,bool use_vaddr)7517 is_contained_by (asection *section, Elf_Internal_Phdr *segment,
7518 		 bfd_vma paddr, bfd_vma vaddr, unsigned int opb,
7519 		 bool use_vaddr)
7520 {
7521   bfd_vma seg_addr = !use_vaddr ? paddr : vaddr;
7522   bfd_vma addr = !use_vaddr ? section->lma : section->vma;
7523   bfd_vma octet;
7524   if (_bfd_mul_overflow (addr, opb, &octet))
7525     return false;
7526   /* The third and fourth lines below are testing that the section end
7527      address is within the segment.  It's written this way to avoid
7528      overflow.  Add seg_addr + section_size to both sides of the
7529      inequality to make it obvious.  */
7530   return (octet >= seg_addr
7531 	  && segment_size (segment) >= section_size (section, segment)
7532 	  && (octet - seg_addr
7533 	      <= segment_size (segment) - section_size (section, segment)));
7534 }
7535 
7536 /* Handle PT_NOTE segment.  */
7537 static bool
is_note(asection * s,Elf_Internal_Phdr * p)7538 is_note (asection *s, Elf_Internal_Phdr *p)
7539 {
7540   return (p->p_type == PT_NOTE
7541 	  && elf_section_type (s) == SHT_NOTE
7542 	  && (ufile_ptr) s->filepos >= p->p_offset
7543 	  && p->p_filesz >= s->size
7544 	  && (ufile_ptr) s->filepos - p->p_offset <= p->p_filesz - s->size);
7545 }
7546 
7547 /* Rewrite program header information.  */
7548 
7549 static bool
rewrite_elf_program_header(bfd * ibfd,bfd * obfd,bfd_vma maxpagesize)7550 rewrite_elf_program_header (bfd *ibfd, bfd *obfd, bfd_vma maxpagesize)
7551 {
7552   Elf_Internal_Ehdr *iehdr;
7553   struct elf_segment_map *map;
7554   struct elf_segment_map *map_first;
7555   struct elf_segment_map **pointer_to_map;
7556   Elf_Internal_Phdr *segment;
7557   asection *section;
7558   unsigned int i;
7559   unsigned int num_segments;
7560   bool phdr_included = false;
7561   bool p_paddr_valid;
7562   struct elf_segment_map *phdr_adjust_seg = NULL;
7563   unsigned int phdr_adjust_num = 0;
7564   const struct elf_backend_data *bed;
7565   unsigned int opb = bfd_octets_per_byte (ibfd, NULL);
7566 
7567   bed = get_elf_backend_data (ibfd);
7568   iehdr = elf_elfheader (ibfd);
7569 
7570   map_first = NULL;
7571   pointer_to_map = &map_first;
7572 
7573   num_segments = elf_elfheader (ibfd)->e_phnum;
7574 
7575   /* The complicated case when p_vaddr is 0 is to handle the Solaris
7576      linker, which generates a PT_INTERP section with p_vaddr and
7577      p_memsz set to 0.  */
7578 #define IS_SOLARIS_PT_INTERP(p, s)					\
7579   (p->p_vaddr == 0							\
7580    && p->p_paddr == 0							\
7581    && p->p_memsz == 0							\
7582    && p->p_filesz > 0							\
7583    && (s->flags & SEC_HAS_CONTENTS) != 0				\
7584    && s->size > 0							\
7585    && (bfd_vma) s->filepos >= p->p_offset				\
7586    && ((bfd_vma) s->filepos + s->size					\
7587        <= p->p_offset + p->p_filesz))
7588 
7589   /* Decide if the given section should be included in the given segment.
7590      A section will be included if:
7591        1. It is within the address space of the segment -- we use the LMA
7592 	  if that is set for the segment and the VMA otherwise,
7593        2. It is an allocated section or a NOTE section in a PT_NOTE
7594 	  segment.
7595        3. There is an output section associated with it,
7596        4. The section has not already been allocated to a previous segment.
7597        5. PT_GNU_STACK segments do not include any sections.
7598        6. PT_TLS segment includes only SHF_TLS sections.
7599        7. SHF_TLS sections are only in PT_TLS or PT_LOAD segments.
7600        8. PT_DYNAMIC should not contain empty sections at the beginning
7601 	  (with the possible exception of .dynamic).  */
7602 #define IS_SECTION_IN_INPUT_SEGMENT(section, segment, bed, opb)		\
7603   (((is_contained_by (section, segment, segment->p_paddr,		\
7604 		      segment->p_vaddr, opb,				\
7605 		      bed->want_p_paddr_set_to_zero)			\
7606      && (section->flags & SEC_ALLOC) != 0)				\
7607     || is_note (section, segment))					\
7608    && segment->p_type != PT_GNU_STACK					\
7609    && (segment->p_type != PT_TLS					\
7610        || (section->flags & SEC_THREAD_LOCAL))				\
7611    && (segment->p_type == PT_LOAD					\
7612        || segment->p_type == PT_TLS					\
7613        || (section->flags & SEC_THREAD_LOCAL) == 0)			\
7614    && (segment->p_type != PT_DYNAMIC					\
7615        || section_size (section, segment) > 0				\
7616        || (segment->p_paddr						\
7617 	   ? segment->p_paddr != section->lma * (opb)			\
7618 	   : segment->p_vaddr != section->vma * (opb))			\
7619        || (strcmp (bfd_section_name (section), ".dynamic") == 0))	\
7620    && (segment->p_type != PT_LOAD || !section->segment_mark))
7621 
7622 /* If the output section of a section in the input segment is NULL,
7623    it is removed from the corresponding output segment.   */
7624 #define INCLUDE_SECTION_IN_SEGMENT(section, segment, bed, opb)		\
7625   (IS_SECTION_IN_INPUT_SEGMENT (section, segment, bed, opb)		\
7626    && section->output_section != NULL)
7627 
7628   /* Returns TRUE iff seg1 starts after the end of seg2.  */
7629 #define SEGMENT_AFTER_SEGMENT(seg1, seg2, field)			\
7630   (seg1->field >= segment_end (seg2, seg2->field))
7631 
7632   /* Returns TRUE iff seg1 and seg2 overlap. Segments overlap iff both
7633      their VMA address ranges and their LMA address ranges overlap.
7634      It is possible to have overlapping VMA ranges without overlapping LMA
7635      ranges.  RedBoot images for example can have both .data and .bss mapped
7636      to the same VMA range, but with the .data section mapped to a different
7637      LMA.  */
7638 #define SEGMENT_OVERLAPS(seg1, seg2)					\
7639   (   !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_vaddr)			\
7640 	|| SEGMENT_AFTER_SEGMENT (seg2, seg1, p_vaddr))			\
7641    && !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_paddr)			\
7642 	|| SEGMENT_AFTER_SEGMENT (seg2, seg1, p_paddr)))
7643 
7644   /* Initialise the segment mark field, and discard stupid alignment.  */
7645   for (section = ibfd->sections; section != NULL; section = section->next)
7646     {
7647       asection *o = section->output_section;
7648       if (o != NULL && o->alignment_power >= (sizeof (bfd_vma) * 8) - 1)
7649 	o->alignment_power = 0;
7650       section->segment_mark = false;
7651     }
7652 
7653   /* The Solaris linker creates program headers in which all the
7654      p_paddr fields are zero.  When we try to objcopy or strip such a
7655      file, we get confused.  Check for this case, and if we find it
7656      don't set the p_paddr_valid fields.  */
7657   p_paddr_valid = false;
7658   for (i = 0, segment = elf_tdata (ibfd)->phdr;
7659        i < num_segments;
7660        i++, segment++)
7661     if (segment->p_paddr != 0)
7662       {
7663 	p_paddr_valid = true;
7664 	break;
7665       }
7666 
7667   /* Scan through the segments specified in the program header
7668      of the input BFD.  For this first scan we look for overlaps
7669      in the loadable segments.  These can be created by weird
7670      parameters to objcopy.  Also, fix some solaris weirdness.  */
7671   for (i = 0, segment = elf_tdata (ibfd)->phdr;
7672        i < num_segments;
7673        i++, segment++)
7674     {
7675       unsigned int j;
7676       Elf_Internal_Phdr *segment2;
7677 
7678       if (segment->p_type == PT_INTERP)
7679 	for (section = ibfd->sections; section; section = section->next)
7680 	  if (IS_SOLARIS_PT_INTERP (segment, section))
7681 	    {
7682 	      /* Mininal change so that the normal section to segment
7683 		 assignment code will work.  */
7684 	      segment->p_vaddr = section->vma * opb;
7685 	      break;
7686 	    }
7687 
7688       if (segment->p_type != PT_LOAD)
7689 	{
7690 	  /* Remove PT_GNU_RELRO segment.  */
7691 	  if (segment->p_type == PT_GNU_RELRO)
7692 	    segment->p_type = PT_NULL;
7693 	  continue;
7694 	}
7695 
7696       /* Determine if this segment overlaps any previous segments.  */
7697       for (j = 0, segment2 = elf_tdata (ibfd)->phdr; j < i; j++, segment2++)
7698 	{
7699 	  bfd_signed_vma extra_length;
7700 
7701 	  if (segment2->p_type != PT_LOAD
7702 	      || !SEGMENT_OVERLAPS (segment, segment2))
7703 	    continue;
7704 
7705 	  /* Merge the two segments together.  */
7706 	  if (segment2->p_vaddr < segment->p_vaddr)
7707 	    {
7708 	      /* Extend SEGMENT2 to include SEGMENT and then delete
7709 		 SEGMENT.  */
7710 	      extra_length = (segment_end (segment, segment->p_vaddr)
7711 			      - segment_end (segment2, segment2->p_vaddr));
7712 
7713 	      if (extra_length > 0)
7714 		{
7715 		  segment2->p_memsz += extra_length;
7716 		  segment2->p_filesz += extra_length;
7717 		}
7718 
7719 	      segment->p_type = PT_NULL;
7720 
7721 	      /* Since we have deleted P we must restart the outer loop.  */
7722 	      i = 0;
7723 	      segment = elf_tdata (ibfd)->phdr;
7724 	      break;
7725 	    }
7726 	  else
7727 	    {
7728 	      /* Extend SEGMENT to include SEGMENT2 and then delete
7729 		 SEGMENT2.  */
7730 	      extra_length = (segment_end (segment2, segment2->p_vaddr)
7731 			      - segment_end (segment, segment->p_vaddr));
7732 
7733 	      if (extra_length > 0)
7734 		{
7735 		  segment->p_memsz += extra_length;
7736 		  segment->p_filesz += extra_length;
7737 		}
7738 
7739 	      segment2->p_type = PT_NULL;
7740 	    }
7741 	}
7742     }
7743 
7744   /* The second scan attempts to assign sections to segments.  */
7745   for (i = 0, segment = elf_tdata (ibfd)->phdr;
7746        i < num_segments;
7747        i++, segment++)
7748     {
7749       unsigned int section_count;
7750       asection **sections;
7751       asection *output_section;
7752       unsigned int isec;
7753       asection *matching_lma;
7754       asection *suggested_lma;
7755       unsigned int j;
7756       size_t amt;
7757       asection *first_section;
7758 
7759       if (segment->p_type == PT_NULL)
7760 	continue;
7761 
7762       first_section = NULL;
7763       /* Compute how many sections might be placed into this segment.  */
7764       for (section = ibfd->sections, section_count = 0;
7765 	   section != NULL;
7766 	   section = section->next)
7767 	{
7768 	  /* Find the first section in the input segment, which may be
7769 	     removed from the corresponding output segment.   */
7770 	  if (IS_SECTION_IN_INPUT_SEGMENT (section, segment, bed, opb))
7771 	    {
7772 	      if (first_section == NULL)
7773 		first_section = section;
7774 	      if (section->output_section != NULL)
7775 		++section_count;
7776 	    }
7777 	}
7778 
7779       /* Allocate a segment map big enough to contain
7780 	 all of the sections we have selected.  */
7781       amt = sizeof (struct elf_segment_map) - sizeof (asection *);
7782       amt += section_count * sizeof (asection *);
7783       map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
7784       if (map == NULL)
7785 	return false;
7786 
7787       /* Initialise the fields of the segment map.  Default to
7788 	 using the physical address of the segment in the input BFD.  */
7789       map->next = NULL;
7790       map->p_type = segment->p_type;
7791       map->p_flags = segment->p_flags;
7792       map->p_flags_valid = 1;
7793 
7794       if (map->p_type == PT_LOAD
7795 	  && (ibfd->flags & D_PAGED) != 0
7796 	  && maxpagesize > 1
7797 	  && segment->p_align > 1)
7798 	{
7799 	  map->p_align = segment->p_align;
7800 	  if (segment->p_align > maxpagesize)
7801 	    map->p_align = maxpagesize;
7802 	  map->p_align_valid = 1;
7803 	}
7804 
7805       /* If the first section in the input segment is removed, there is
7806 	 no need to preserve segment physical address in the corresponding
7807 	 output segment.  */
7808       if (!first_section || first_section->output_section != NULL)
7809 	{
7810 	  map->p_paddr = segment->p_paddr;
7811 	  map->p_paddr_valid = p_paddr_valid;
7812 	}
7813 
7814       /* Determine if this segment contains the ELF file header
7815 	 and if it contains the program headers themselves.  */
7816       map->includes_filehdr = (segment->p_offset == 0
7817 			       && segment->p_filesz >= iehdr->e_ehsize);
7818       map->includes_phdrs = 0;
7819 
7820       if (!phdr_included || segment->p_type != PT_LOAD)
7821 	{
7822 	  map->includes_phdrs =
7823 	    (segment->p_offset <= (bfd_vma) iehdr->e_phoff
7824 	     && (segment->p_offset + segment->p_filesz
7825 		 >= ((bfd_vma) iehdr->e_phoff
7826 		     + iehdr->e_phnum * iehdr->e_phentsize)));
7827 
7828 	  if (segment->p_type == PT_LOAD && map->includes_phdrs)
7829 	    phdr_included = true;
7830 	}
7831 
7832       if (section_count == 0)
7833 	{
7834 	  /* Special segments, such as the PT_PHDR segment, may contain
7835 	     no sections, but ordinary, loadable segments should contain
7836 	     something.  They are allowed by the ELF spec however, so only
7837 	     a warning is produced.
7838 	     Don't warn if an empty PT_LOAD contains the program headers.
7839 	     There is however the valid use case of embedded systems which
7840 	     have segments with p_filesz of 0 and a p_memsz > 0 to initialize
7841 	     flash memory with zeros.  No warning is shown for that case.  */
7842 	  if (segment->p_type == PT_LOAD
7843 	      && !map->includes_phdrs
7844 	      && (segment->p_filesz > 0 || segment->p_memsz == 0))
7845 	    /* xgettext:c-format */
7846 	    _bfd_error_handler
7847 	      (_("%pB: warning: empty loadable segment detected"
7848 		 " at vaddr=%#" PRIx64 ", is this intentional?"),
7849 	       ibfd, (uint64_t) segment->p_vaddr);
7850 
7851 	  map->p_vaddr_offset = segment->p_vaddr / opb;
7852 	  map->count = 0;
7853 	  *pointer_to_map = map;
7854 	  pointer_to_map = &map->next;
7855 
7856 	  continue;
7857 	}
7858 
7859       /* Now scan the sections in the input BFD again and attempt
7860 	 to add their corresponding output sections to the segment map.
7861 	 The problem here is how to handle an output section which has
7862 	 been moved (ie had its LMA changed).  There are four possibilities:
7863 
7864 	 1. None of the sections have been moved.
7865 	    In this case we can continue to use the segment LMA from the
7866 	    input BFD.
7867 
7868 	 2. All of the sections have been moved by the same amount.
7869 	    In this case we can change the segment's LMA to match the LMA
7870 	    of the first section.
7871 
7872 	 3. Some of the sections have been moved, others have not.
7873 	    In this case those sections which have not been moved can be
7874 	    placed in the current segment which will have to have its size,
7875 	    and possibly its LMA changed, and a new segment or segments will
7876 	    have to be created to contain the other sections.
7877 
7878 	 4. The sections have been moved, but not by the same amount.
7879 	    In this case we can change the segment's LMA to match the LMA
7880 	    of the first section and we will have to create a new segment
7881 	    or segments to contain the other sections.
7882 
7883 	 In order to save time, we allocate an array to hold the section
7884 	 pointers that we are interested in.  As these sections get assigned
7885 	 to a segment, they are removed from this array.  */
7886 
7887       amt = section_count * sizeof (asection *);
7888       sections = (asection **) bfd_malloc (amt);
7889       if (sections == NULL)
7890 	return false;
7891 
7892       /* Step One: Scan for segment vs section LMA conflicts.
7893 	 Also add the sections to the section array allocated above.
7894 	 Also add the sections to the current segment.  In the common
7895 	 case, where the sections have not been moved, this means that
7896 	 we have completely filled the segment, and there is nothing
7897 	 more to do.  */
7898       isec = 0;
7899       matching_lma = NULL;
7900       suggested_lma = NULL;
7901 
7902       for (section = first_section, j = 0;
7903 	   section != NULL;
7904 	   section = section->next)
7905 	{
7906 	  if (INCLUDE_SECTION_IN_SEGMENT (section, segment, bed, opb))
7907 	    {
7908 	      output_section = section->output_section;
7909 
7910 	      sections[j++] = section;
7911 
7912 	      /* The Solaris native linker always sets p_paddr to 0.
7913 		 We try to catch that case here, and set it to the
7914 		 correct value.  Note - some backends require that
7915 		 p_paddr be left as zero.  */
7916 	      if (!p_paddr_valid
7917 		  && segment->p_vaddr != 0
7918 		  && !bed->want_p_paddr_set_to_zero
7919 		  && isec == 0
7920 		  && output_section->lma != 0
7921 		  && (align_power (segment->p_vaddr
7922 				   + (map->includes_filehdr
7923 				      ? iehdr->e_ehsize : 0)
7924 				   + (map->includes_phdrs
7925 				      ? iehdr->e_phnum * iehdr->e_phentsize
7926 				      : 0),
7927 				   output_section->alignment_power * opb)
7928 		      == (output_section->vma * opb)))
7929 		map->p_paddr = segment->p_vaddr;
7930 
7931 	      /* Match up the physical address of the segment with the
7932 		 LMA address of the output section.  */
7933 	      if (is_contained_by (output_section, segment, map->p_paddr,
7934 				   0, opb, false)
7935 		  || is_note (section, segment))
7936 		{
7937 		  if (matching_lma == NULL
7938 		      || output_section->lma < matching_lma->lma)
7939 		    matching_lma = output_section;
7940 
7941 		  /* We assume that if the section fits within the segment
7942 		     then it does not overlap any other section within that
7943 		     segment.  */
7944 		  map->sections[isec++] = output_section;
7945 		}
7946 	      else if (suggested_lma == NULL)
7947 		suggested_lma = output_section;
7948 
7949 	      if (j == section_count)
7950 		break;
7951 	    }
7952 	}
7953 
7954       BFD_ASSERT (j == section_count);
7955 
7956       /* Step Two: Adjust the physical address of the current segment,
7957 	 if necessary.  */
7958       if (isec == section_count)
7959 	{
7960 	  /* All of the sections fitted within the segment as currently
7961 	     specified.  This is the default case.  Add the segment to
7962 	     the list of built segments and carry on to process the next
7963 	     program header in the input BFD.  */
7964 	  map->count = section_count;
7965 	  *pointer_to_map = map;
7966 	  pointer_to_map = &map->next;
7967 
7968 	  if (p_paddr_valid
7969 	      && !bed->want_p_paddr_set_to_zero)
7970 	    {
7971 	      bfd_vma hdr_size = 0;
7972 	      if (map->includes_filehdr)
7973 		hdr_size = iehdr->e_ehsize;
7974 	      if (map->includes_phdrs)
7975 		hdr_size += iehdr->e_phnum * iehdr->e_phentsize;
7976 
7977 	      /* Account for padding before the first section in the
7978 		 segment.  */
7979 	      map->p_vaddr_offset = ((map->p_paddr + hdr_size) / opb
7980 				     - matching_lma->lma);
7981 	    }
7982 
7983 	  free (sections);
7984 	  continue;
7985 	}
7986       else
7987 	{
7988 	  /* Change the current segment's physical address to match
7989 	     the LMA of the first section that fitted, or if no
7990 	     section fitted, the first section.  */
7991 	  if (matching_lma == NULL)
7992 	    matching_lma = suggested_lma;
7993 
7994 	  map->p_paddr = matching_lma->lma * opb;
7995 
7996 	  /* Offset the segment physical address from the lma
7997 	     to allow for space taken up by elf headers.  */
7998 	  if (map->includes_phdrs)
7999 	    {
8000 	      map->p_paddr -= iehdr->e_phnum * iehdr->e_phentsize;
8001 
8002 	      /* iehdr->e_phnum is just an estimate of the number
8003 		 of program headers that we will need.  Make a note
8004 		 here of the number we used and the segment we chose
8005 		 to hold these headers, so that we can adjust the
8006 		 offset when we know the correct value.  */
8007 	      phdr_adjust_num = iehdr->e_phnum;
8008 	      phdr_adjust_seg = map;
8009 	    }
8010 
8011 	  if (map->includes_filehdr)
8012 	    {
8013 	      bfd_vma align = (bfd_vma) 1 << matching_lma->alignment_power;
8014 	      map->p_paddr -= iehdr->e_ehsize;
8015 	      /* We've subtracted off the size of headers from the
8016 		 first section lma, but there may have been some
8017 		 alignment padding before that section too.  Try to
8018 		 account for that by adjusting the segment lma down to
8019 		 the same alignment.  */
8020 	      if (segment->p_align != 0 && segment->p_align < align)
8021 		align = segment->p_align;
8022 	      map->p_paddr &= -(align * opb);
8023 	    }
8024 	}
8025 
8026       /* Step Three: Loop over the sections again, this time assigning
8027 	 those that fit to the current segment and removing them from the
8028 	 sections array; but making sure not to leave large gaps.  Once all
8029 	 possible sections have been assigned to the current segment it is
8030 	 added to the list of built segments and if sections still remain
8031 	 to be assigned, a new segment is constructed before repeating
8032 	 the loop.  */
8033       isec = 0;
8034       do
8035 	{
8036 	  map->count = 0;
8037 	  suggested_lma = NULL;
8038 
8039 	  /* Fill the current segment with sections that fit.  */
8040 	  for (j = 0; j < section_count; j++)
8041 	    {
8042 	      section = sections[j];
8043 
8044 	      if (section == NULL)
8045 		continue;
8046 
8047 	      output_section = section->output_section;
8048 
8049 	      BFD_ASSERT (output_section != NULL);
8050 
8051 	      if (is_contained_by (output_section, segment, map->p_paddr,
8052 				   0, opb, false)
8053 		  || is_note (section, segment))
8054 		{
8055 		  if (map->count == 0)
8056 		    {
8057 		      /* If the first section in a segment does not start at
8058 			 the beginning of the segment, then something is
8059 			 wrong.  */
8060 		      if (align_power (map->p_paddr
8061 				       + (map->includes_filehdr
8062 					  ? iehdr->e_ehsize : 0)
8063 				       + (map->includes_phdrs
8064 					  ? iehdr->e_phnum * iehdr->e_phentsize
8065 					  : 0),
8066 				       output_section->alignment_power * opb)
8067 			  != output_section->lma * opb)
8068 			goto sorry;
8069 		    }
8070 		  else
8071 		    {
8072 		      asection *prev_sec;
8073 
8074 		      prev_sec = map->sections[map->count - 1];
8075 
8076 		      /* If the gap between the end of the previous section
8077 			 and the start of this section is more than
8078 			 maxpagesize then we need to start a new segment.  */
8079 		      if ((BFD_ALIGN (prev_sec->lma + prev_sec->size,
8080 				      maxpagesize)
8081 			   < BFD_ALIGN (output_section->lma, maxpagesize))
8082 			  || (prev_sec->lma + prev_sec->size
8083 			      > output_section->lma))
8084 			{
8085 			  if (suggested_lma == NULL)
8086 			    suggested_lma = output_section;
8087 
8088 			  continue;
8089 			}
8090 		    }
8091 
8092 		  map->sections[map->count++] = output_section;
8093 		  ++isec;
8094 		  sections[j] = NULL;
8095 		  if (segment->p_type == PT_LOAD)
8096 		    section->segment_mark = true;
8097 		}
8098 	      else if (suggested_lma == NULL)
8099 		suggested_lma = output_section;
8100 	    }
8101 
8102 	  /* PR 23932.  A corrupt input file may contain sections that cannot
8103 	     be assigned to any segment - because for example they have a
8104 	     negative size - or segments that do not contain any sections.
8105 	     But there are also valid reasons why a segment can be empty.
8106 	     So allow a count of zero.  */
8107 
8108 	  /* Add the current segment to the list of built segments.  */
8109 	  *pointer_to_map = map;
8110 	  pointer_to_map = &map->next;
8111 
8112 	  if (isec < section_count)
8113 	    {
8114 	      /* We still have not allocated all of the sections to
8115 		 segments.  Create a new segment here, initialise it
8116 		 and carry on looping.  */
8117 	      amt = sizeof (struct elf_segment_map) - sizeof (asection *);
8118 	      amt += section_count * sizeof (asection *);
8119 	      map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
8120 	      if (map == NULL)
8121 		{
8122 		  free (sections);
8123 		  return false;
8124 		}
8125 
8126 	      /* Initialise the fields of the segment map.  Set the physical
8127 		 physical address to the LMA of the first section that has
8128 		 not yet been assigned.  */
8129 	      map->next = NULL;
8130 	      map->p_type = segment->p_type;
8131 	      map->p_flags = segment->p_flags;
8132 	      map->p_flags_valid = 1;
8133 	      map->p_paddr = suggested_lma->lma * opb;
8134 	      map->p_paddr_valid = p_paddr_valid;
8135 	      map->includes_filehdr = 0;
8136 	      map->includes_phdrs = 0;
8137 	    }
8138 
8139 	  continue;
8140 	sorry:
8141 	  bfd_set_error (bfd_error_sorry);
8142 	  free (sections);
8143 	  return false;
8144 	}
8145       while (isec < section_count);
8146 
8147       free (sections);
8148     }
8149 
8150   elf_seg_map (obfd) = map_first;
8151 
8152   /* If we had to estimate the number of program headers that were
8153      going to be needed, then check our estimate now and adjust
8154      the offset if necessary.  */
8155   if (phdr_adjust_seg != NULL)
8156     {
8157       unsigned int count;
8158 
8159       for (count = 0, map = map_first; map != NULL; map = map->next)
8160 	count++;
8161 
8162       if (count > phdr_adjust_num)
8163 	phdr_adjust_seg->p_paddr
8164 	  -= (count - phdr_adjust_num) * iehdr->e_phentsize;
8165 
8166       for (map = map_first; map != NULL; map = map->next)
8167 	if (map->p_type == PT_PHDR)
8168 	  {
8169 	    bfd_vma adjust
8170 	      = phdr_adjust_seg->includes_filehdr ? iehdr->e_ehsize : 0;
8171 	    map->p_paddr = phdr_adjust_seg->p_paddr + adjust;
8172 	    break;
8173 	  }
8174     }
8175 
8176 #undef IS_SOLARIS_PT_INTERP
8177 #undef IS_SECTION_IN_INPUT_SEGMENT
8178 #undef INCLUDE_SECTION_IN_SEGMENT
8179 #undef SEGMENT_AFTER_SEGMENT
8180 #undef SEGMENT_OVERLAPS
8181   return true;
8182 }
8183 
8184 /* Return true if p_align in the ELF program header in ABFD is valid.  */
8185 
8186 static bool
elf_is_p_align_valid(bfd * abfd)8187 elf_is_p_align_valid (bfd *abfd)
8188 {
8189   unsigned int i;
8190   Elf_Internal_Phdr *segment;
8191   unsigned int num_segments;
8192   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8193   bfd_size_type maxpagesize = bed->maxpagesize;
8194   bfd_size_type p_align = bed->p_align;
8195 
8196   /* Return true if the default p_align value isn't set or the maximum
8197      page size is the same as the minimum page size.  */
8198   if (p_align == 0 || maxpagesize == bed->minpagesize)
8199     return true;
8200 
8201   /* When the default p_align value is set, p_align may be set to the
8202      default p_align value while segments are aligned to the maximum
8203      page size.  In this case, the input p_align will be ignored and
8204      the maximum page size will be used to align the output segments.  */
8205   segment = elf_tdata (abfd)->phdr;
8206   num_segments = elf_elfheader (abfd)->e_phnum;
8207   for (i = 0; i < num_segments; i++, segment++)
8208     if (segment->p_type == PT_LOAD
8209 	&& (segment->p_align != p_align
8210 	    || vma_page_aligned_bias (segment->p_vaddr,
8211 				      segment->p_offset,
8212 				      maxpagesize) != 0))
8213       return true;
8214 
8215   return false;
8216 }
8217 
8218 /* Copy ELF program header information.  */
8219 
8220 static bool
copy_elf_program_header(bfd * ibfd,bfd * obfd)8221 copy_elf_program_header (bfd *ibfd, bfd *obfd)
8222 {
8223   Elf_Internal_Ehdr *iehdr;
8224   struct elf_segment_map *map;
8225   struct elf_segment_map *map_first;
8226   struct elf_segment_map **pointer_to_map;
8227   Elf_Internal_Phdr *segment;
8228   unsigned int i;
8229   unsigned int num_segments;
8230   bool phdr_included = false;
8231   bool p_paddr_valid;
8232   bool p_palign_valid;
8233   unsigned int opb = bfd_octets_per_byte (ibfd, NULL);
8234 
8235   iehdr = elf_elfheader (ibfd);
8236 
8237   map_first = NULL;
8238   pointer_to_map = &map_first;
8239 
8240   /* If all the segment p_paddr fields are zero, don't set
8241      map->p_paddr_valid.  */
8242   p_paddr_valid = false;
8243   num_segments = elf_elfheader (ibfd)->e_phnum;
8244   for (i = 0, segment = elf_tdata (ibfd)->phdr;
8245        i < num_segments;
8246        i++, segment++)
8247     if (segment->p_paddr != 0)
8248       {
8249 	p_paddr_valid = true;
8250 	break;
8251       }
8252 
8253   p_palign_valid = elf_is_p_align_valid (ibfd);
8254 
8255   for (i = 0, segment = elf_tdata (ibfd)->phdr;
8256        i < num_segments;
8257        i++, segment++)
8258     {
8259       asection *section;
8260       unsigned int section_count;
8261       size_t amt;
8262       Elf_Internal_Shdr *this_hdr;
8263       asection *first_section = NULL;
8264       asection *lowest_section;
8265 
8266       /* Compute how many sections are in this segment.  */
8267       for (section = ibfd->sections, section_count = 0;
8268 	   section != NULL;
8269 	   section = section->next)
8270 	{
8271 	  this_hdr = &(elf_section_data(section)->this_hdr);
8272 	  if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
8273 	    {
8274 	      if (first_section == NULL)
8275 		first_section = section;
8276 	      section_count++;
8277 	    }
8278 	}
8279 
8280       /* Allocate a segment map big enough to contain
8281 	 all of the sections we have selected.  */
8282       amt = sizeof (struct elf_segment_map) - sizeof (asection *);
8283       amt += section_count * sizeof (asection *);
8284       map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
8285       if (map == NULL)
8286 	return false;
8287 
8288       /* Initialize the fields of the output segment map with the
8289 	 input segment.  */
8290       map->next = NULL;
8291       map->p_type = segment->p_type;
8292       map->p_flags = segment->p_flags;
8293       map->p_flags_valid = 1;
8294       map->p_paddr = segment->p_paddr;
8295       map->p_paddr_valid = p_paddr_valid;
8296       map->p_align = segment->p_align;
8297       /* Keep p_align of PT_GNU_STACK for stack alignment.  */
8298       map->p_align_valid = (map->p_type == PT_GNU_STACK
8299 			    || p_palign_valid);
8300       map->p_vaddr_offset = 0;
8301 
8302       if (map->p_type == PT_GNU_RELRO
8303 	  || map->p_type == PT_GNU_STACK)
8304 	{
8305 	  /* The PT_GNU_RELRO segment may contain the first a few
8306 	     bytes in the .got.plt section even if the whole .got.plt
8307 	     section isn't in the PT_GNU_RELRO segment.  We won't
8308 	     change the size of the PT_GNU_RELRO segment.
8309 	     Similarly, PT_GNU_STACK size is significant on uclinux
8310 	     systems.    */
8311 	  map->p_size = segment->p_memsz;
8312 	  map->p_size_valid = 1;
8313 	}
8314 
8315       /* Determine if this segment contains the ELF file header
8316 	 and if it contains the program headers themselves.  */
8317       map->includes_filehdr = (segment->p_offset == 0
8318 			       && segment->p_filesz >= iehdr->e_ehsize);
8319 
8320       map->includes_phdrs = 0;
8321       if (! phdr_included || segment->p_type != PT_LOAD)
8322 	{
8323 	  map->includes_phdrs =
8324 	    (segment->p_offset <= (bfd_vma) iehdr->e_phoff
8325 	     && (segment->p_offset + segment->p_filesz
8326 		 >= ((bfd_vma) iehdr->e_phoff
8327 		     + iehdr->e_phnum * iehdr->e_phentsize)));
8328 
8329 	  if (segment->p_type == PT_LOAD && map->includes_phdrs)
8330 	    phdr_included = true;
8331 	}
8332 
8333       lowest_section = NULL;
8334       if (section_count != 0)
8335 	{
8336 	  unsigned int isec = 0;
8337 
8338 	  for (section = first_section;
8339 	       section != NULL;
8340 	       section = section->next)
8341 	    {
8342 	      this_hdr = &(elf_section_data(section)->this_hdr);
8343 	      if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
8344 		{
8345 		  map->sections[isec++] = section->output_section;
8346 		  if ((section->flags & SEC_ALLOC) != 0)
8347 		    {
8348 		      bfd_vma seg_off;
8349 
8350 		      if (lowest_section == NULL
8351 			  || section->lma < lowest_section->lma)
8352 			lowest_section = section;
8353 
8354 		      /* Section lmas are set up from PT_LOAD header
8355 			 p_paddr in _bfd_elf_make_section_from_shdr.
8356 			 If this header has a p_paddr that disagrees
8357 			 with the section lma, flag the p_paddr as
8358 			 invalid.  */
8359 		      if ((section->flags & SEC_LOAD) != 0)
8360 			seg_off = this_hdr->sh_offset - segment->p_offset;
8361 		      else
8362 			seg_off = this_hdr->sh_addr - segment->p_vaddr;
8363 		      if (section->lma * opb - segment->p_paddr != seg_off)
8364 			map->p_paddr_valid = false;
8365 		    }
8366 		  if (isec == section_count)
8367 		    break;
8368 		}
8369 	    }
8370 	}
8371 
8372       if (section_count == 0)
8373 	map->p_vaddr_offset = segment->p_vaddr / opb;
8374       else if (map->p_paddr_valid)
8375 	{
8376 	  /* Account for padding before the first section in the segment.  */
8377 	  bfd_vma hdr_size = 0;
8378 	  if (map->includes_filehdr)
8379 	    hdr_size = iehdr->e_ehsize;
8380 	  if (map->includes_phdrs)
8381 	    hdr_size += iehdr->e_phnum * iehdr->e_phentsize;
8382 
8383 	  map->p_vaddr_offset = ((map->p_paddr + hdr_size) / opb
8384 				 - (lowest_section ? lowest_section->lma : 0));
8385 	}
8386 
8387       map->count = section_count;
8388       *pointer_to_map = map;
8389       pointer_to_map = &map->next;
8390     }
8391 
8392   elf_seg_map (obfd) = map_first;
8393   return true;
8394 }
8395 
8396 /* Copy private BFD data.  This copies or rewrites ELF program header
8397    information.  */
8398 
8399 static bool
copy_private_bfd_data(bfd * ibfd,bfd * obfd)8400 copy_private_bfd_data (bfd *ibfd, bfd *obfd)
8401 {
8402   bfd_vma maxpagesize;
8403 
8404   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
8405       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
8406     return true;
8407 
8408   if (elf_tdata (ibfd)->phdr == NULL)
8409     return true;
8410 
8411   if (ibfd->xvec == obfd->xvec)
8412     {
8413       /* Check to see if any sections in the input BFD
8414 	 covered by ELF program header have changed.  */
8415       Elf_Internal_Phdr *segment;
8416       asection *section, *osec;
8417       unsigned int i, num_segments;
8418       Elf_Internal_Shdr *this_hdr;
8419       const struct elf_backend_data *bed;
8420 
8421       bed = get_elf_backend_data (ibfd);
8422 
8423       /* Regenerate the segment map if p_paddr is set to 0.  */
8424       if (bed->want_p_paddr_set_to_zero)
8425 	goto rewrite;
8426 
8427       /* Initialize the segment mark field.  */
8428       for (section = obfd->sections; section != NULL;
8429 	   section = section->next)
8430 	section->segment_mark = false;
8431 
8432       num_segments = elf_elfheader (ibfd)->e_phnum;
8433       for (i = 0, segment = elf_tdata (ibfd)->phdr;
8434 	   i < num_segments;
8435 	   i++, segment++)
8436 	{
8437 	  /* PR binutils/3535.  The Solaris linker always sets the p_paddr
8438 	     and p_memsz fields of special segments (DYNAMIC, INTERP) to 0
8439 	     which severly confuses things, so always regenerate the segment
8440 	     map in this case.  */
8441 	  if (segment->p_paddr == 0
8442 	      && segment->p_memsz == 0
8443 	      && (segment->p_type == PT_INTERP
8444 		  || segment->p_type == PT_DYNAMIC))
8445 	    goto rewrite;
8446 
8447 	  for (section = ibfd->sections;
8448 	       section != NULL; section = section->next)
8449 	    {
8450 	      /* We mark the output section so that we know it comes
8451 		 from the input BFD.  */
8452 	      osec = section->output_section;
8453 	      if (osec)
8454 		osec->segment_mark = true;
8455 
8456 	      /* Check if this section is covered by the segment.  */
8457 	      this_hdr = &(elf_section_data(section)->this_hdr);
8458 	      if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
8459 		{
8460 		  /* FIXME: Check if its output section is changed or
8461 		     removed.  What else do we need to check?  */
8462 		  if (osec == NULL
8463 		      || section->flags != osec->flags
8464 		      || section->lma != osec->lma
8465 		      || section->vma != osec->vma
8466 		      || section->size != osec->size
8467 		      || section->rawsize != osec->rawsize
8468 		      || section->alignment_power != osec->alignment_power)
8469 		    goto rewrite;
8470 		}
8471 	    }
8472 	}
8473 
8474       /* Check to see if any output section do not come from the
8475 	 input BFD.  */
8476       for (section = obfd->sections; section != NULL;
8477 	   section = section->next)
8478 	{
8479 	  if (!section->segment_mark)
8480 	    goto rewrite;
8481 	  else
8482 	    section->segment_mark = false;
8483 	}
8484 
8485       return copy_elf_program_header (ibfd, obfd);
8486     }
8487 
8488  rewrite:
8489   maxpagesize = 0;
8490   if (ibfd->xvec == obfd->xvec)
8491     {
8492       /* When rewriting program header, set the output maxpagesize to
8493 	 the maximum alignment of input PT_LOAD segments.  */
8494       Elf_Internal_Phdr *segment;
8495       unsigned int i;
8496       unsigned int num_segments = elf_elfheader (ibfd)->e_phnum;
8497 
8498       for (i = 0, segment = elf_tdata (ibfd)->phdr;
8499 	   i < num_segments;
8500 	   i++, segment++)
8501 	if (segment->p_type == PT_LOAD
8502 	    && maxpagesize < segment->p_align)
8503 	  {
8504 	    /* PR 17512: file: f17299af.  */
8505 	    if (segment->p_align > (bfd_vma) 1 << ((sizeof (bfd_vma) * 8) - 2))
8506 	      /* xgettext:c-format */
8507 	      _bfd_error_handler (_("%pB: warning: segment alignment of %#"
8508 				    PRIx64 " is too large"),
8509 				  ibfd, (uint64_t) segment->p_align);
8510 	    else
8511 	      maxpagesize = segment->p_align;
8512 	  }
8513     }
8514   if (maxpagesize == 0)
8515     maxpagesize = get_elf_backend_data (obfd)->maxpagesize;
8516 
8517   return rewrite_elf_program_header (ibfd, obfd, maxpagesize);
8518 }
8519 
8520 /* Initialize private output section information from input section.  */
8521 
8522 bool
_bfd_elf_init_private_section_data(bfd * ibfd,asection * isec,bfd * obfd,asection * osec,struct bfd_link_info * link_info)8523 _bfd_elf_init_private_section_data (bfd *ibfd,
8524 				    asection *isec,
8525 				    bfd *obfd,
8526 				    asection *osec,
8527 				    struct bfd_link_info *link_info)
8528 
8529 {
8530   Elf_Internal_Shdr *ihdr, *ohdr;
8531   bool final_link = (link_info != NULL
8532 		     && !bfd_link_relocatable (link_info));
8533 
8534   if (ibfd->xvec->flavour != bfd_target_elf_flavour
8535       || obfd->xvec->flavour != bfd_target_elf_flavour)
8536     return true;
8537 
8538   BFD_ASSERT (elf_section_data (osec) != NULL);
8539 
8540   /* If this is a known ABI section, ELF section type and flags may
8541      have been set up when OSEC was created.  For normal sections we
8542      allow the user to override the type and flags other than
8543      SHF_MASKOS and SHF_MASKPROC.  */
8544   if (elf_section_type (osec) == SHT_PROGBITS
8545       || elf_section_type (osec) == SHT_NOTE
8546       || elf_section_type (osec) == SHT_NOBITS)
8547     elf_section_type (osec) = SHT_NULL;
8548   /* For objcopy and relocatable link, copy the ELF section type from
8549      the input file if the BFD section flags are the same.  (If they
8550      are different the user may be doing something like
8551      "objcopy --set-section-flags .text=alloc,data".)  For a final
8552      link allow some flags that the linker clears to differ.  */
8553   if (elf_section_type (osec) == SHT_NULL
8554       && (osec->flags == isec->flags
8555 	  || (final_link
8556 	      && ((osec->flags ^ isec->flags)
8557 		  & ~(SEC_LINK_ONCE | SEC_LINK_DUPLICATES | SEC_RELOC)) == 0)))
8558     elf_section_type (osec) = elf_section_type (isec);
8559 
8560   /* FIXME: Is this correct for all OS/PROC specific flags?  */
8561   elf_section_flags (osec) = (elf_section_flags (isec)
8562 			      & (SHF_MASKOS | SHF_MASKPROC));
8563 
8564   /* Copy sh_info from input for mbind section.  */
8565   if ((elf_tdata (ibfd)->has_gnu_osabi & elf_gnu_osabi_mbind) != 0
8566       && elf_section_flags (isec) & SHF_GNU_MBIND)
8567     elf_section_data (osec)->this_hdr.sh_info
8568       = elf_section_data (isec)->this_hdr.sh_info;
8569 
8570   /* Set things up for objcopy and relocatable link.  The output
8571      SHT_GROUP section will have its elf_next_in_group pointing back
8572      to the input group members.  Ignore linker created group section.
8573      See elfNN_ia64_object_p in elfxx-ia64.c.  */
8574   if ((link_info == NULL
8575        || !link_info->resolve_section_groups)
8576       && (elf_sec_group (isec) == NULL
8577 	  || (elf_sec_group (isec)->flags & SEC_LINKER_CREATED) == 0))
8578     {
8579       if (elf_section_flags (isec) & SHF_GROUP)
8580 	elf_section_flags (osec) |= SHF_GROUP;
8581       elf_next_in_group (osec) = elf_next_in_group (isec);
8582       elf_section_data (osec)->group = elf_section_data (isec)->group;
8583     }
8584 
8585   /* If not decompress, preserve SHF_COMPRESSED.  */
8586   if (!final_link && (ibfd->flags & BFD_DECOMPRESS) == 0)
8587     elf_section_flags (osec) |= (elf_section_flags (isec)
8588 				 & SHF_COMPRESSED);
8589 
8590   ihdr = &elf_section_data (isec)->this_hdr;
8591 
8592   /* We need to handle elf_linked_to_section for SHF_LINK_ORDER. We
8593      don't use the output section of the linked-to section since it
8594      may be NULL at this point.  */
8595   if ((ihdr->sh_flags & SHF_LINK_ORDER) != 0)
8596     {
8597       ohdr = &elf_section_data (osec)->this_hdr;
8598       ohdr->sh_flags |= SHF_LINK_ORDER;
8599       elf_linked_to_section (osec) = elf_linked_to_section (isec);
8600     }
8601 
8602   osec->use_rela_p = isec->use_rela_p;
8603 
8604   return true;
8605 }
8606 
8607 /* Copy private section information.  This copies over the entsize
8608    field, and sometimes the info field.  */
8609 
8610 bool
_bfd_elf_copy_private_section_data(bfd * ibfd,asection * isec,bfd * obfd,asection * osec)8611 _bfd_elf_copy_private_section_data (bfd *ibfd,
8612 				    asection *isec,
8613 				    bfd *obfd,
8614 				    asection *osec)
8615 {
8616   Elf_Internal_Shdr *ihdr, *ohdr;
8617 
8618   if (ibfd->xvec->flavour != bfd_target_elf_flavour
8619       || obfd->xvec->flavour != bfd_target_elf_flavour)
8620     return true;
8621 
8622   ihdr = &elf_section_data (isec)->this_hdr;
8623   ohdr = &elf_section_data (osec)->this_hdr;
8624 
8625   ohdr->sh_entsize = ihdr->sh_entsize;
8626 
8627   if (ihdr->sh_type == SHT_SYMTAB
8628       || ihdr->sh_type == SHT_DYNSYM
8629       || ihdr->sh_type == SHT_GNU_verneed
8630       || ihdr->sh_type == SHT_GNU_verdef)
8631     ohdr->sh_info = ihdr->sh_info;
8632 
8633   return _bfd_elf_init_private_section_data (ibfd, isec, obfd, osec,
8634 					     NULL);
8635 }
8636 
8637 /* Look at all the SHT_GROUP sections in IBFD, making any adjustments
8638    necessary if we are removing either the SHT_GROUP section or any of
8639    the group member sections.  DISCARDED is the value that a section's
8640    output_section has if the section will be discarded, NULL when this
8641    function is called from objcopy, bfd_abs_section_ptr when called
8642    from the linker.  */
8643 
8644 bool
_bfd_elf_fixup_group_sections(bfd * ibfd,asection * discarded)8645 _bfd_elf_fixup_group_sections (bfd *ibfd, asection *discarded)
8646 {
8647   asection *isec;
8648 
8649   for (isec = ibfd->sections; isec != NULL; isec = isec->next)
8650     if (elf_section_type (isec) == SHT_GROUP)
8651       {
8652 	asection *first = elf_next_in_group (isec);
8653 	asection *s = first;
8654 	bfd_size_type removed = 0;
8655 
8656 	while (s != NULL)
8657 	  {
8658 	    /* If this member section is being output but the
8659 	       SHT_GROUP section is not, then clear the group info
8660 	       set up by _bfd_elf_copy_private_section_data.  */
8661 	    if (s->output_section != discarded
8662 		&& isec->output_section == discarded)
8663 	      {
8664 		elf_section_flags (s->output_section) &= ~SHF_GROUP;
8665 		elf_group_name (s->output_section) = NULL;
8666 	      }
8667 	    else
8668 	      {
8669 		struct bfd_elf_section_data *elf_sec = elf_section_data (s);
8670 		if (s->output_section == discarded
8671 		    && isec->output_section != discarded)
8672 		  {
8673 		    /* Conversely, if the member section is not being
8674 		       output but the SHT_GROUP section is, then adjust
8675 		       its size.  */
8676 		    removed += 4;
8677 		    if (elf_sec->rel.hdr != NULL
8678 			&& (elf_sec->rel.hdr->sh_flags & SHF_GROUP) != 0)
8679 		      removed += 4;
8680 		    if (elf_sec->rela.hdr != NULL
8681 			&& (elf_sec->rela.hdr->sh_flags & SHF_GROUP) != 0)
8682 		      removed += 4;
8683 		  }
8684 		else
8685 		  {
8686 		    /* Also adjust for zero-sized relocation member
8687 		       section.  */
8688 		    if (elf_sec->rel.hdr != NULL
8689 			&& elf_sec->rel.hdr->sh_size == 0)
8690 		      removed += 4;
8691 		    if (elf_sec->rela.hdr != NULL
8692 			&& elf_sec->rela.hdr->sh_size == 0)
8693 		      removed += 4;
8694 		  }
8695 	      }
8696 	    s = elf_next_in_group (s);
8697 	    if (s == first)
8698 	      break;
8699 	  }
8700 	if (removed != 0)
8701 	  {
8702 	    if (discarded != NULL)
8703 	      {
8704 		/* If we've been called for ld -r, then we need to
8705 		   adjust the input section size.  */
8706 		if (isec->rawsize == 0)
8707 		  isec->rawsize = isec->size;
8708 		isec->size = isec->rawsize - removed;
8709 		if (isec->size <= 4)
8710 		  {
8711 		    isec->size = 0;
8712 		    isec->flags |= SEC_EXCLUDE;
8713 		  }
8714 	      }
8715 	    else if (isec->output_section != NULL)
8716 	      {
8717 		/* Adjust the output section size when called from
8718 		   objcopy. */
8719 		isec->output_section->size -= removed;
8720 		if (isec->output_section->size <= 4)
8721 		  {
8722 		    isec->output_section->size = 0;
8723 		    isec->output_section->flags |= SEC_EXCLUDE;
8724 		  }
8725 	      }
8726 	  }
8727       }
8728 
8729   return true;
8730 }
8731 
8732 /* Copy private header information.  */
8733 
8734 bool
_bfd_elf_copy_private_header_data(bfd * ibfd,bfd * obfd)8735 _bfd_elf_copy_private_header_data (bfd *ibfd, bfd *obfd)
8736 {
8737   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
8738       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
8739     return true;
8740 
8741   /* Copy over private BFD data if it has not already been copied.
8742      This must be done here, rather than in the copy_private_bfd_data
8743      entry point, because the latter is called after the section
8744      contents have been set, which means that the program headers have
8745      already been worked out.  */
8746   if (elf_seg_map (obfd) == NULL && elf_tdata (ibfd)->phdr != NULL)
8747     {
8748       if (! copy_private_bfd_data (ibfd, obfd))
8749 	return false;
8750     }
8751 
8752   return _bfd_elf_fixup_group_sections (ibfd, NULL);
8753 }
8754 
8755 /* Copy private symbol information.  If this symbol is in a section
8756    which we did not map into a BFD section, try to map the section
8757    index correctly.  We use special macro definitions for the mapped
8758    section indices; these definitions are interpreted by the
8759    swap_out_syms function.  */
8760 
8761 #define MAP_ONESYMTAB (SHN_HIOS + 1)
8762 #define MAP_DYNSYMTAB (SHN_HIOS + 2)
8763 #define MAP_STRTAB    (SHN_HIOS + 3)
8764 #define MAP_SHSTRTAB  (SHN_HIOS + 4)
8765 #define MAP_SYM_SHNDX (SHN_HIOS + 5)
8766 
8767 bool
_bfd_elf_copy_private_symbol_data(bfd * ibfd,asymbol * isymarg,bfd * obfd,asymbol * osymarg)8768 _bfd_elf_copy_private_symbol_data (bfd *ibfd,
8769 				   asymbol *isymarg,
8770 				   bfd *obfd,
8771 				   asymbol *osymarg)
8772 {
8773   elf_symbol_type *isym, *osym;
8774 
8775   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
8776       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
8777     return true;
8778 
8779   isym = elf_symbol_from (isymarg);
8780   osym = elf_symbol_from (osymarg);
8781 
8782   if (isym != NULL
8783       && isym->internal_elf_sym.st_shndx != 0
8784       && osym != NULL
8785       && bfd_is_abs_section (isym->symbol.section))
8786     {
8787       unsigned int shndx;
8788 
8789       shndx = isym->internal_elf_sym.st_shndx;
8790       if (shndx == elf_onesymtab (ibfd))
8791 	shndx = MAP_ONESYMTAB;
8792       else if (shndx == elf_dynsymtab (ibfd))
8793 	shndx = MAP_DYNSYMTAB;
8794       else if (shndx == elf_strtab_sec (ibfd))
8795 	shndx = MAP_STRTAB;
8796       else if (shndx == elf_shstrtab_sec (ibfd))
8797 	shndx = MAP_SHSTRTAB;
8798       else if (find_section_in_list (shndx, elf_symtab_shndx_list (ibfd)))
8799 	shndx = MAP_SYM_SHNDX;
8800       osym->internal_elf_sym.st_shndx = shndx;
8801     }
8802 
8803   return true;
8804 }
8805 
8806 /* Swap out the symbols.  */
8807 
8808 static bool
swap_out_syms(bfd * abfd,struct elf_strtab_hash ** sttp,int relocatable_p,struct bfd_link_info * info)8809 swap_out_syms (bfd *abfd,
8810 	       struct elf_strtab_hash **sttp,
8811 	       int relocatable_p,
8812 	       struct bfd_link_info *info)
8813 {
8814   const struct elf_backend_data *bed;
8815   unsigned int symcount;
8816   asymbol **syms;
8817   struct elf_strtab_hash *stt;
8818   Elf_Internal_Shdr *symtab_hdr;
8819   Elf_Internal_Shdr *symtab_shndx_hdr;
8820   Elf_Internal_Shdr *symstrtab_hdr;
8821   struct elf_sym_strtab *symstrtab;
8822   bfd_byte *outbound_syms;
8823   bfd_byte *outbound_shndx;
8824   unsigned long outbound_syms_index;
8825   unsigned int idx;
8826   unsigned int num_locals;
8827   size_t amt;
8828   bool name_local_sections;
8829 
8830   if (!elf_map_symbols (abfd, &num_locals))
8831     return false;
8832 
8833   /* Dump out the symtabs.  */
8834   stt = _bfd_elf_strtab_init ();
8835   if (stt == NULL)
8836     return false;
8837 
8838   bed = get_elf_backend_data (abfd);
8839   symcount = bfd_get_symcount (abfd);
8840   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8841   symtab_hdr->sh_type = SHT_SYMTAB;
8842   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
8843   symtab_hdr->sh_size = symtab_hdr->sh_entsize * (symcount + 1);
8844   symtab_hdr->sh_info = num_locals + 1;
8845   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
8846 
8847   symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
8848   symstrtab_hdr->sh_type = SHT_STRTAB;
8849 
8850   /* Allocate buffer to swap out the .strtab section.  */
8851   if (_bfd_mul_overflow (symcount + 1, sizeof (*symstrtab), &amt)
8852       || (symstrtab = (struct elf_sym_strtab *) bfd_malloc (amt)) == NULL)
8853     {
8854       bfd_set_error (bfd_error_no_memory);
8855       _bfd_elf_strtab_free (stt);
8856       return false;
8857     }
8858 
8859   if (_bfd_mul_overflow (symcount + 1, bed->s->sizeof_sym, &amt)
8860       || (outbound_syms = (bfd_byte *) bfd_alloc (abfd, amt)) == NULL)
8861     {
8862     error_no_mem:
8863       bfd_set_error (bfd_error_no_memory);
8864     error_return:
8865       free (symstrtab);
8866       _bfd_elf_strtab_free (stt);
8867       return false;
8868     }
8869   symtab_hdr->contents = outbound_syms;
8870   outbound_syms_index = 0;
8871 
8872   outbound_shndx = NULL;
8873 
8874   if (elf_symtab_shndx_list (abfd))
8875     {
8876       symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
8877       if (symtab_shndx_hdr->sh_name != 0)
8878 	{
8879 	  if (_bfd_mul_overflow (symcount + 1,
8880 				 sizeof (Elf_External_Sym_Shndx), &amt))
8881 	    goto error_no_mem;
8882 	  outbound_shndx =  (bfd_byte *) bfd_zalloc (abfd, amt);
8883 	  if (outbound_shndx == NULL)
8884 	    goto error_return;
8885 
8886 	  symtab_shndx_hdr->contents = outbound_shndx;
8887 	  symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
8888 	  symtab_shndx_hdr->sh_size = amt;
8889 	  symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
8890 	  symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
8891 	}
8892       /* FIXME: What about any other headers in the list ?  */
8893     }
8894 
8895   /* Now generate the data (for "contents").  */
8896   {
8897     /* Fill in zeroth symbol and swap it out.  */
8898     Elf_Internal_Sym sym;
8899     sym.st_name = 0;
8900     sym.st_value = 0;
8901     sym.st_size = 0;
8902     sym.st_info = 0;
8903     sym.st_other = 0;
8904     sym.st_shndx = SHN_UNDEF;
8905     sym.st_target_internal = 0;
8906     symstrtab[0].sym = sym;
8907     symstrtab[0].dest_index = outbound_syms_index;
8908     outbound_syms_index++;
8909   }
8910 
8911   name_local_sections
8912     = (bed->elf_backend_name_local_section_symbols
8913        && bed->elf_backend_name_local_section_symbols (abfd));
8914 
8915   syms = bfd_get_outsymbols (abfd);
8916   for (idx = 0; idx < symcount;)
8917     {
8918       Elf_Internal_Sym sym;
8919       bfd_vma value = syms[idx]->value;
8920       elf_symbol_type *type_ptr;
8921       flagword flags = syms[idx]->flags;
8922       int type;
8923 
8924       if (!name_local_sections
8925 	  && (flags & (BSF_SECTION_SYM | BSF_GLOBAL)) == BSF_SECTION_SYM)
8926 	{
8927 	  /* Local section symbols have no name.  */
8928 	  sym.st_name = (unsigned long) -1;
8929 	}
8930       else
8931 	{
8932 	  /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
8933 	     to get the final offset for st_name.  */
8934 	  sym.st_name
8935 	    = (unsigned long) _bfd_elf_strtab_add (stt, syms[idx]->name,
8936 						   false);
8937 	  if (sym.st_name == (unsigned long) -1)
8938 	    goto error_return;
8939 	}
8940 
8941       type_ptr = elf_symbol_from (syms[idx]);
8942 
8943       if ((flags & BSF_SECTION_SYM) == 0
8944 	  && bfd_is_com_section (syms[idx]->section))
8945 	{
8946 	  /* ELF common symbols put the alignment into the `value' field,
8947 	     and the size into the `size' field.  This is backwards from
8948 	     how BFD handles it, so reverse it here.  */
8949 	  sym.st_size = value;
8950 	  if (type_ptr == NULL
8951 	      || type_ptr->internal_elf_sym.st_value == 0)
8952 	    sym.st_value = value >= 16 ? 16 : (1 << bfd_log2 (value));
8953 	  else
8954 	    sym.st_value = type_ptr->internal_elf_sym.st_value;
8955 	  sym.st_shndx = _bfd_elf_section_from_bfd_section
8956 	    (abfd, syms[idx]->section);
8957 	}
8958       else
8959 	{
8960 	  asection *sec = syms[idx]->section;
8961 	  unsigned int shndx;
8962 
8963 	  if (sec->output_section)
8964 	    {
8965 	      value += sec->output_offset;
8966 	      sec = sec->output_section;
8967 	    }
8968 
8969 	  /* Don't add in the section vma for relocatable output.  */
8970 	  if (! relocatable_p)
8971 	    value += sec->vma;
8972 	  sym.st_value = value;
8973 	  sym.st_size = type_ptr ? type_ptr->internal_elf_sym.st_size : 0;
8974 
8975 	  if (bfd_is_abs_section (sec)
8976 	      && type_ptr != NULL
8977 	      && type_ptr->internal_elf_sym.st_shndx != 0)
8978 	    {
8979 	      /* This symbol is in a real ELF section which we did
8980 		 not create as a BFD section.  Undo the mapping done
8981 		 by copy_private_symbol_data.  */
8982 	      shndx = type_ptr->internal_elf_sym.st_shndx;
8983 	      switch (shndx)
8984 		{
8985 		case MAP_ONESYMTAB:
8986 		  shndx = elf_onesymtab (abfd);
8987 		  break;
8988 		case MAP_DYNSYMTAB:
8989 		  shndx = elf_dynsymtab (abfd);
8990 		  break;
8991 		case MAP_STRTAB:
8992 		  shndx = elf_strtab_sec (abfd);
8993 		  break;
8994 		case MAP_SHSTRTAB:
8995 		  shndx = elf_shstrtab_sec (abfd);
8996 		  break;
8997 		case MAP_SYM_SHNDX:
8998 		  if (elf_symtab_shndx_list (abfd))
8999 		    shndx = elf_symtab_shndx_list (abfd)->ndx;
9000 		  break;
9001 		case SHN_COMMON:
9002 		case SHN_ABS:
9003 		  shndx = SHN_ABS;
9004 		  break;
9005 		default:
9006 		  if (shndx >= SHN_LOPROC && shndx <= SHN_HIOS)
9007 		    {
9008 		      if (bed->symbol_section_index)
9009 			shndx = bed->symbol_section_index (abfd, type_ptr);
9010 		      /* Otherwise just leave the index alone.  */
9011 		    }
9012 		  else
9013 		    {
9014 		      if (shndx > SHN_HIOS && shndx < SHN_HIRESERVE)
9015 			_bfd_error_handler (_("%pB: \
9016 Unable to handle section index %x in ELF symbol.  Using ABS instead."),
9017 					  abfd, shndx);
9018 		      shndx = SHN_ABS;
9019 		    }
9020 		  break;
9021 		}
9022 	    }
9023 	  else
9024 	    {
9025 	      shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
9026 
9027 	      if (shndx == SHN_BAD)
9028 		{
9029 		  asection *sec2;
9030 
9031 		  /* Writing this would be a hell of a lot easier if
9032 		     we had some decent documentation on bfd, and
9033 		     knew what to expect of the library, and what to
9034 		     demand of applications.  For example, it
9035 		     appears that `objcopy' might not set the
9036 		     section of a symbol to be a section that is
9037 		     actually in the output file.  */
9038 		  sec2 = bfd_get_section_by_name (abfd, sec->name);
9039 		  if (sec2 != NULL)
9040 		    shndx = _bfd_elf_section_from_bfd_section (abfd, sec2);
9041 		  if (shndx == SHN_BAD)
9042 		    {
9043 		      /* xgettext:c-format */
9044 		      _bfd_error_handler
9045 			(_("unable to find equivalent output section"
9046 			   " for symbol '%s' from section '%s'"),
9047 			 syms[idx]->name ? syms[idx]->name : "<Local sym>",
9048 			 sec->name);
9049 		      bfd_set_error (bfd_error_invalid_operation);
9050 		      goto error_return;
9051 		    }
9052 		}
9053 	    }
9054 
9055 	  sym.st_shndx = shndx;
9056 	}
9057 
9058       if ((flags & BSF_THREAD_LOCAL) != 0)
9059 	type = STT_TLS;
9060       else if ((flags & BSF_GNU_INDIRECT_FUNCTION) != 0)
9061 	type = STT_GNU_IFUNC;
9062       else if ((flags & BSF_FUNCTION) != 0)
9063 	type = STT_FUNC;
9064       else if ((flags & BSF_OBJECT) != 0)
9065 	type = STT_OBJECT;
9066       else if ((flags & BSF_RELC) != 0)
9067 	type = STT_RELC;
9068       else if ((flags & BSF_SRELC) != 0)
9069 	type = STT_SRELC;
9070       else
9071 	type = STT_NOTYPE;
9072 
9073       if (syms[idx]->section->flags & SEC_THREAD_LOCAL)
9074 	type = STT_TLS;
9075 
9076       /* Processor-specific types.  */
9077       if (type_ptr != NULL
9078 	  && bed->elf_backend_get_symbol_type)
9079 	type = ((*bed->elf_backend_get_symbol_type)
9080 		(&type_ptr->internal_elf_sym, type));
9081 
9082       if (flags & BSF_SECTION_SYM)
9083 	{
9084 	  if (flags & BSF_GLOBAL)
9085 	    sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9086 	  else
9087 	    sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
9088 	}
9089       else if (bfd_is_com_section (syms[idx]->section))
9090 	{
9091 	  if (type != STT_TLS)
9092 	    {
9093 	      if ((abfd->flags & BFD_CONVERT_ELF_COMMON))
9094 		type = ((abfd->flags & BFD_USE_ELF_STT_COMMON)
9095 			? STT_COMMON : STT_OBJECT);
9096 	      else
9097 		type = ((flags & BSF_ELF_COMMON) != 0
9098 			? STT_COMMON : STT_OBJECT);
9099 	    }
9100 	  sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9101 	}
9102       else if (bfd_is_und_section (syms[idx]->section))
9103 	sym.st_info = ELF_ST_INFO (((flags & BSF_WEAK)
9104 				    ? STB_WEAK
9105 				    : STB_GLOBAL),
9106 				   type);
9107       else if (flags & BSF_FILE)
9108 	sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9109       else
9110 	{
9111 	  int bind = STB_LOCAL;
9112 
9113 	  if (flags & BSF_LOCAL)
9114 	    bind = STB_LOCAL;
9115 	  else if (flags & BSF_GNU_UNIQUE)
9116 	    bind = STB_GNU_UNIQUE;
9117 	  else if (flags & BSF_WEAK)
9118 	    bind = STB_WEAK;
9119 	  else if (flags & BSF_GLOBAL)
9120 	    bind = STB_GLOBAL;
9121 
9122 	  sym.st_info = ELF_ST_INFO (bind, type);
9123 	}
9124 
9125       if (type_ptr != NULL)
9126 	{
9127 	  sym.st_other = type_ptr->internal_elf_sym.st_other;
9128 	  sym.st_target_internal
9129 	    = type_ptr->internal_elf_sym.st_target_internal;
9130 	}
9131       else
9132 	{
9133 	  sym.st_other = 0;
9134 	  sym.st_target_internal = 0;
9135 	}
9136 
9137       idx++;
9138       symstrtab[idx].sym = sym;
9139       symstrtab[idx].dest_index = outbound_syms_index;
9140 
9141       outbound_syms_index++;
9142     }
9143 
9144   /* Finalize the .strtab section.  */
9145   _bfd_elf_strtab_finalize (stt);
9146 
9147   /* Swap out the .strtab section.  */
9148   for (idx = 0; idx <= symcount; idx++)
9149     {
9150       struct elf_sym_strtab *elfsym = &symstrtab[idx];
9151       if (elfsym->sym.st_name == (unsigned long) -1)
9152 	elfsym->sym.st_name = 0;
9153       else
9154 	elfsym->sym.st_name = _bfd_elf_strtab_offset (stt,
9155 						      elfsym->sym.st_name);
9156       if (info && info->callbacks->ctf_new_symbol)
9157 	info->callbacks->ctf_new_symbol (elfsym->dest_index,
9158 					 &elfsym->sym);
9159 
9160       /* Inform the linker of the addition of this symbol.  */
9161 
9162       bed->s->swap_symbol_out (abfd, &elfsym->sym,
9163 			       (outbound_syms
9164 				+ (elfsym->dest_index
9165 				   * bed->s->sizeof_sym)),
9166 			       NPTR_ADD (outbound_shndx,
9167 					 (elfsym->dest_index
9168 					  * sizeof (Elf_External_Sym_Shndx))));
9169     }
9170   free (symstrtab);
9171 
9172   *sttp = stt;
9173   symstrtab_hdr->sh_size = _bfd_elf_strtab_size (stt);
9174   symstrtab_hdr->sh_type = SHT_STRTAB;
9175   symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
9176   symstrtab_hdr->sh_addr = 0;
9177   symstrtab_hdr->sh_entsize = 0;
9178   symstrtab_hdr->sh_link = 0;
9179   symstrtab_hdr->sh_info = 0;
9180   symstrtab_hdr->sh_addralign = 1;
9181 
9182   return true;
9183 }
9184 
9185 /* Return the number of bytes required to hold the symtab vector.
9186 
9187    Note that we base it on the count plus 1, since we will null terminate
9188    the vector allocated based on this size.  However, the ELF symbol table
9189    always has a dummy entry as symbol #0, so it ends up even.  */
9190 
9191 long
_bfd_elf_get_symtab_upper_bound(bfd * abfd)9192 _bfd_elf_get_symtab_upper_bound (bfd *abfd)
9193 {
9194   bfd_size_type symcount;
9195   long symtab_size;
9196   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->symtab_hdr;
9197 
9198   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
9199   if (symcount > LONG_MAX / sizeof (asymbol *))
9200     {
9201       bfd_set_error (bfd_error_file_too_big);
9202       return -1;
9203     }
9204   symtab_size = symcount * (sizeof (asymbol *));
9205   if (symcount == 0)
9206     symtab_size = sizeof (asymbol *);
9207   else if (!bfd_write_p (abfd))
9208     {
9209       ufile_ptr filesize = bfd_get_file_size (abfd);
9210 
9211       if (filesize != 0 && (unsigned long) symtab_size > filesize)
9212 	{
9213 	  bfd_set_error (bfd_error_file_truncated);
9214 	  return -1;
9215 	}
9216     }
9217 
9218   return symtab_size;
9219 }
9220 
9221 long
_bfd_elf_get_dynamic_symtab_upper_bound(bfd * abfd)9222 _bfd_elf_get_dynamic_symtab_upper_bound (bfd *abfd)
9223 {
9224   bfd_size_type symcount;
9225   long symtab_size;
9226   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->dynsymtab_hdr;
9227 
9228   if (elf_dynsymtab (abfd) == 0)
9229     {
9230       /* Check if there is dynamic symbol table.  */
9231       symcount = elf_tdata (abfd)->dt_symtab_count;
9232       if (symcount)
9233 	goto compute_symtab_size;
9234 
9235       bfd_set_error (bfd_error_invalid_operation);
9236       return -1;
9237     }
9238 
9239   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
9240   if (symcount > LONG_MAX / sizeof (asymbol *))
9241     {
9242       bfd_set_error (bfd_error_file_too_big);
9243       return -1;
9244     }
9245 
9246  compute_symtab_size:
9247   symtab_size = symcount * (sizeof (asymbol *));
9248   if (symcount == 0)
9249     symtab_size = sizeof (asymbol *);
9250   else if (!bfd_write_p (abfd))
9251     {
9252       ufile_ptr filesize = bfd_get_file_size (abfd);
9253 
9254       if (filesize != 0 && (unsigned long) symtab_size > filesize)
9255 	{
9256 	  bfd_set_error (bfd_error_file_truncated);
9257 	  return -1;
9258 	}
9259     }
9260 
9261   return symtab_size;
9262 }
9263 
9264 long
_bfd_elf_get_reloc_upper_bound(bfd * abfd,sec_ptr asect)9265 _bfd_elf_get_reloc_upper_bound (bfd *abfd, sec_ptr asect)
9266 {
9267   if (asect->reloc_count != 0 && !bfd_write_p (abfd))
9268     {
9269       /* Sanity check reloc section size.  */
9270       ufile_ptr filesize = bfd_get_file_size (abfd);
9271 
9272       if (filesize != 0)
9273 	{
9274 	  struct bfd_elf_section_data *d = elf_section_data (asect);
9275 	  bfd_size_type rel_size = d->rel.hdr ? d->rel.hdr->sh_size : 0;
9276 	  bfd_size_type rela_size = d->rela.hdr ? d->rela.hdr->sh_size : 0;
9277 
9278 	  if (rel_size + rela_size > filesize
9279 	      || rel_size + rela_size < rel_size)
9280 	    {
9281 	      bfd_set_error (bfd_error_file_truncated);
9282 	      return -1;
9283 	    }
9284 	}
9285     }
9286 
9287 #if SIZEOF_LONG == SIZEOF_INT
9288   if (asect->reloc_count >= LONG_MAX / sizeof (arelent *))
9289     {
9290       bfd_set_error (bfd_error_file_too_big);
9291       return -1;
9292     }
9293 #endif
9294   return (asect->reloc_count + 1L) * sizeof (arelent *);
9295 }
9296 
9297 /* Canonicalize the relocs.  */
9298 
9299 long
_bfd_elf_canonicalize_reloc(bfd * abfd,sec_ptr section,arelent ** relptr,asymbol ** symbols)9300 _bfd_elf_canonicalize_reloc (bfd *abfd,
9301 			     sec_ptr section,
9302 			     arelent **relptr,
9303 			     asymbol **symbols)
9304 {
9305   arelent *tblptr;
9306   unsigned int i;
9307   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9308 
9309   if (! bed->s->slurp_reloc_table (abfd, section, symbols, false))
9310     return -1;
9311 
9312   tblptr = section->relocation;
9313   for (i = 0; i < section->reloc_count; i++)
9314     *relptr++ = tblptr++;
9315 
9316   *relptr = NULL;
9317 
9318   return section->reloc_count;
9319 }
9320 
9321 long
_bfd_elf_canonicalize_symtab(bfd * abfd,asymbol ** allocation)9322 _bfd_elf_canonicalize_symtab (bfd *abfd, asymbol **allocation)
9323 {
9324   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9325   long symcount = bed->s->slurp_symbol_table (abfd, allocation, false);
9326 
9327   if (symcount >= 0)
9328     abfd->symcount = symcount;
9329   return symcount;
9330 }
9331 
9332 long
_bfd_elf_canonicalize_dynamic_symtab(bfd * abfd,asymbol ** allocation)9333 _bfd_elf_canonicalize_dynamic_symtab (bfd *abfd,
9334 				      asymbol **allocation)
9335 {
9336   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9337   long symcount = bed->s->slurp_symbol_table (abfd, allocation, true);
9338 
9339   if (symcount >= 0)
9340     abfd->dynsymcount = symcount;
9341   return symcount;
9342 }
9343 
9344 /* Return the size required for the dynamic reloc entries.  Any loadable
9345    section that was actually installed in the BFD, and has type SHT_REL
9346    or SHT_RELA, and uses the dynamic symbol table, is considered to be a
9347    dynamic reloc section.  */
9348 
9349 long
_bfd_elf_get_dynamic_reloc_upper_bound(bfd * abfd)9350 _bfd_elf_get_dynamic_reloc_upper_bound (bfd *abfd)
9351 {
9352   bfd_size_type count, ext_rel_size;
9353   asection *s;
9354 
9355   if (elf_dynsymtab (abfd) == 0)
9356     {
9357       bfd_set_error (bfd_error_invalid_operation);
9358       return -1;
9359     }
9360 
9361   count = 1;
9362   ext_rel_size = 0;
9363   for (s = abfd->sections; s != NULL; s = s->next)
9364     if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
9365 	&& (elf_section_data (s)->this_hdr.sh_type == SHT_REL
9366 	    || elf_section_data (s)->this_hdr.sh_type == SHT_RELA)
9367 	&& (elf_section_data (s)->this_hdr.sh_flags & SHF_COMPRESSED) == 0)
9368       {
9369 	ext_rel_size += elf_section_data (s)->this_hdr.sh_size;
9370 	if (ext_rel_size < elf_section_data (s)->this_hdr.sh_size)
9371 	  {
9372 	    bfd_set_error (bfd_error_file_truncated);
9373 	    return -1;
9374 	  }
9375 	count += NUM_SHDR_ENTRIES (&elf_section_data (s)->this_hdr);
9376 	if (count > LONG_MAX / sizeof (arelent *))
9377 	  {
9378 	    bfd_set_error (bfd_error_file_too_big);
9379 	    return -1;
9380 	  }
9381       }
9382   if (count > 1 && !bfd_write_p (abfd))
9383     {
9384       /* Sanity check reloc section sizes.  */
9385       ufile_ptr filesize = bfd_get_file_size (abfd);
9386       if (filesize != 0 && ext_rel_size > filesize)
9387 	{
9388 	  bfd_set_error (bfd_error_file_truncated);
9389 	  return -1;
9390 	}
9391     }
9392   return count * sizeof (arelent *);
9393 }
9394 
9395 /* Canonicalize the dynamic relocation entries.  Note that we return the
9396    dynamic relocations as a single block, although they are actually
9397    associated with particular sections; the interface, which was
9398    designed for SunOS style shared libraries, expects that there is only
9399    one set of dynamic relocs.  Any loadable section that was actually
9400    installed in the BFD, and has type SHT_REL or SHT_RELA, and uses the
9401    dynamic symbol table, is considered to be a dynamic reloc section.  */
9402 
9403 long
_bfd_elf_canonicalize_dynamic_reloc(bfd * abfd,arelent ** storage,asymbol ** syms)9404 _bfd_elf_canonicalize_dynamic_reloc (bfd *abfd,
9405 				     arelent **storage,
9406 				     asymbol **syms)
9407 {
9408   bool (*slurp_relocs) (bfd *, asection *, asymbol **, bool);
9409   asection *s;
9410   long ret;
9411 
9412   if (elf_dynsymtab (abfd) == 0)
9413     {
9414       bfd_set_error (bfd_error_invalid_operation);
9415       return -1;
9416     }
9417 
9418   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
9419   ret = 0;
9420   for (s = abfd->sections; s != NULL; s = s->next)
9421     {
9422       if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
9423 	  && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
9424 	      || elf_section_data (s)->this_hdr.sh_type == SHT_RELA)
9425 	  && (elf_section_data (s)->this_hdr.sh_flags & SHF_COMPRESSED) == 0)
9426 	{
9427 	  arelent *p;
9428 	  long count, i;
9429 
9430 	  if (! (*slurp_relocs) (abfd, s, syms, true))
9431 	    return -1;
9432 	  count = NUM_SHDR_ENTRIES (&elf_section_data (s)->this_hdr);
9433 	  p = s->relocation;
9434 	  for (i = 0; i < count; i++)
9435 	    *storage++ = p++;
9436 	  ret += count;
9437 	}
9438     }
9439 
9440   *storage = NULL;
9441 
9442   return ret;
9443 }
9444 
9445 /* Read in the version information.  */
9446 
9447 bool
_bfd_elf_slurp_version_tables(bfd * abfd,bool default_imported_symver)9448 _bfd_elf_slurp_version_tables (bfd *abfd, bool default_imported_symver)
9449 {
9450   bfd_byte *contents = NULL;
9451   unsigned int freeidx = 0;
9452   size_t amt;
9453 
9454   if (elf_dynverref (abfd) != 0 || elf_tdata (abfd)->dt_verneed != NULL)
9455     {
9456       Elf_Internal_Shdr *hdr;
9457       Elf_External_Verneed *everneed;
9458       Elf_Internal_Verneed *iverneed;
9459       unsigned int i;
9460       bfd_byte *contents_end;
9461       size_t verneed_count;
9462       size_t verneed_size;
9463 
9464       if (elf_tdata (abfd)->dt_verneed != NULL)
9465 	{
9466 	  hdr = NULL;
9467 	  contents = elf_tdata (abfd)->dt_verneed;
9468 	  verneed_count = elf_tdata (abfd)->dt_verneed_count;
9469 	  verneed_size = verneed_count * sizeof (Elf_External_Verneed);
9470 	}
9471       else
9472 	{
9473 	  hdr = &elf_tdata (abfd)->dynverref_hdr;
9474 
9475 	  if (hdr->sh_info > hdr->sh_size / sizeof (Elf_External_Verneed))
9476 	    {
9477 	    error_return_bad_verref:
9478 	      _bfd_error_handler
9479 		(_("%pB: .gnu.version_r invalid entry"), abfd);
9480 	      bfd_set_error (bfd_error_bad_value);
9481 	    error_return_verref:
9482 	      elf_tdata (abfd)->verref = NULL;
9483 	      elf_tdata (abfd)->cverrefs = 0;
9484 	      goto error_return;
9485 	    }
9486 
9487 	  if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0)
9488 	    goto error_return_verref;
9489 	  contents = _bfd_malloc_and_read (abfd, hdr->sh_size, hdr->sh_size);
9490 	  if (contents == NULL)
9491 	    goto error_return_verref;
9492 
9493 	  verneed_size = hdr->sh_size;
9494 	  verneed_count = hdr->sh_info;
9495 	}
9496 
9497       if (_bfd_mul_overflow (verneed_count,
9498 			     sizeof (Elf_Internal_Verneed), &amt))
9499 	{
9500 	  bfd_set_error (bfd_error_file_too_big);
9501 	  goto error_return_verref;
9502 	}
9503       if (amt == 0)
9504 	goto error_return_verref;
9505       elf_tdata (abfd)->verref = (Elf_Internal_Verneed *) bfd_zalloc (abfd, amt);
9506       if (elf_tdata (abfd)->verref == NULL)
9507 	goto error_return_verref;
9508 
9509       BFD_ASSERT (sizeof (Elf_External_Verneed)
9510 		  == sizeof (Elf_External_Vernaux));
9511       contents_end = (contents + verneed_size
9512 		      - sizeof (Elf_External_Verneed));
9513       everneed = (Elf_External_Verneed *) contents;
9514       iverneed = elf_tdata (abfd)->verref;
9515       for (i = 0; i < verneed_count; i++, iverneed++)
9516 	{
9517 	  Elf_External_Vernaux *evernaux;
9518 	  Elf_Internal_Vernaux *ivernaux;
9519 	  unsigned int j;
9520 
9521 	  _bfd_elf_swap_verneed_in (abfd, everneed, iverneed);
9522 
9523 	  iverneed->vn_bfd = abfd;
9524 
9525 	  if (elf_use_dt_symtab_p (abfd))
9526 	    {
9527 	      if (iverneed->vn_file < elf_tdata (abfd)->dt_strsz)
9528 		iverneed->vn_filename
9529 		  = elf_tdata (abfd)->dt_strtab + iverneed->vn_file;
9530 	      else
9531 		iverneed->vn_filename = NULL;
9532 	    }
9533 	  else if (hdr == NULL)
9534 	    goto error_return_bad_verref;
9535 	  else
9536 	    iverneed->vn_filename
9537 	      = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
9538 						 iverneed->vn_file);
9539 	  if (iverneed->vn_filename == NULL)
9540 	    goto error_return_bad_verref;
9541 
9542 	  if (iverneed->vn_cnt == 0)
9543 	    iverneed->vn_auxptr = NULL;
9544 	  else
9545 	    {
9546 	      if (_bfd_mul_overflow (iverneed->vn_cnt,
9547 				     sizeof (Elf_Internal_Vernaux), &amt))
9548 		{
9549 		  bfd_set_error (bfd_error_file_too_big);
9550 		  goto error_return_verref;
9551 		}
9552 	      iverneed->vn_auxptr = (struct elf_internal_vernaux *)
9553 		bfd_alloc (abfd, amt);
9554 	      if (iverneed->vn_auxptr == NULL)
9555 		goto error_return_verref;
9556 	    }
9557 
9558 	  if (iverneed->vn_aux
9559 	      > (size_t) (contents_end - (bfd_byte *) everneed))
9560 	    goto error_return_bad_verref;
9561 
9562 	  evernaux = ((Elf_External_Vernaux *)
9563 		      ((bfd_byte *) everneed + iverneed->vn_aux));
9564 	  ivernaux = iverneed->vn_auxptr;
9565 	  for (j = 0; j < iverneed->vn_cnt; j++, ivernaux++)
9566 	    {
9567 	      _bfd_elf_swap_vernaux_in (abfd, evernaux, ivernaux);
9568 
9569 	      if (elf_use_dt_symtab_p (abfd))
9570 		{
9571 		  if (ivernaux->vna_name < elf_tdata (abfd)->dt_strsz)
9572 		    ivernaux->vna_nodename
9573 		      = elf_tdata (abfd)->dt_strtab + ivernaux->vna_name;
9574 		  else
9575 		    ivernaux->vna_nodename = NULL;
9576 		}
9577 	      else if (hdr == NULL)
9578 		goto error_return_bad_verref;
9579 	      else
9580 		ivernaux->vna_nodename
9581 		  = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
9582 						     ivernaux->vna_name);
9583 	      if (ivernaux->vna_nodename == NULL)
9584 		goto error_return_bad_verref;
9585 
9586 	      if (ivernaux->vna_other > freeidx)
9587 		freeidx = ivernaux->vna_other;
9588 
9589 	      ivernaux->vna_nextptr = NULL;
9590 	      if (ivernaux->vna_next == 0)
9591 		{
9592 		  iverneed->vn_cnt = j + 1;
9593 		  break;
9594 		}
9595 	      if (j + 1 < iverneed->vn_cnt)
9596 		ivernaux->vna_nextptr = ivernaux + 1;
9597 
9598 	      if (ivernaux->vna_next
9599 		  > (size_t) (contents_end - (bfd_byte *) evernaux))
9600 		goto error_return_bad_verref;
9601 
9602 	      evernaux = ((Elf_External_Vernaux *)
9603 			  ((bfd_byte *) evernaux + ivernaux->vna_next));
9604 	    }
9605 
9606 	  iverneed->vn_nextref = NULL;
9607 	  if (iverneed->vn_next == 0)
9608 	    break;
9609 	  if (hdr != NULL && (i + 1 < hdr->sh_info))
9610 	    iverneed->vn_nextref = iverneed + 1;
9611 
9612 	  if (iverneed->vn_next
9613 	      > (size_t) (contents_end - (bfd_byte *) everneed))
9614 	    goto error_return_bad_verref;
9615 
9616 	  everneed = ((Elf_External_Verneed *)
9617 		      ((bfd_byte *) everneed + iverneed->vn_next));
9618 	}
9619       elf_tdata (abfd)->cverrefs = i;
9620 
9621       if (contents != elf_tdata (abfd)->dt_verneed)
9622 	free (contents);
9623       contents = NULL;
9624     }
9625 
9626   if (elf_dynverdef (abfd) != 0 || elf_tdata (abfd)->dt_verdef != NULL)
9627     {
9628       Elf_Internal_Shdr *hdr;
9629       Elf_External_Verdef *everdef;
9630       Elf_Internal_Verdef *iverdef;
9631       Elf_Internal_Verdef *iverdefarr;
9632       Elf_Internal_Verdef iverdefmem;
9633       unsigned int i;
9634       unsigned int maxidx;
9635       bfd_byte *contents_end_def, *contents_end_aux;
9636       size_t verdef_count;
9637       size_t verdef_size;
9638 
9639       if (elf_tdata (abfd)->dt_verdef != NULL)
9640 	{
9641 	  hdr = NULL;
9642 	  contents = elf_tdata (abfd)->dt_verdef;
9643 	  verdef_count = elf_tdata (abfd)->dt_verdef_count;
9644 	  verdef_size = verdef_count * sizeof (Elf_External_Verdef);
9645 	}
9646       else
9647 	{
9648 	  hdr = &elf_tdata (abfd)->dynverdef_hdr;
9649 
9650 	  if (hdr->sh_size < sizeof (Elf_External_Verdef))
9651 	    {
9652 	    error_return_bad_verdef:
9653 	      _bfd_error_handler
9654 		(_("%pB: .gnu.version_d invalid entry"), abfd);
9655 	      bfd_set_error (bfd_error_bad_value);
9656 	    error_return_verdef:
9657 	      elf_tdata (abfd)->verdef = NULL;
9658 	      elf_tdata (abfd)->cverdefs = 0;
9659 	      goto error_return;
9660 	    }
9661 
9662 	  if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0)
9663 	    goto error_return_verdef;
9664 	  contents = _bfd_malloc_and_read (abfd, hdr->sh_size, hdr->sh_size);
9665 	  if (contents == NULL)
9666 	    goto error_return_verdef;
9667 
9668 	  BFD_ASSERT (sizeof (Elf_External_Verdef)
9669 		      >= sizeof (Elf_External_Verdaux));
9670 
9671 	  verdef_count = hdr->sh_info;
9672 	  verdef_size = hdr->sh_size;
9673 	}
9674 
9675       contents_end_def = (contents + verdef_size
9676 			  - sizeof (Elf_External_Verdef));
9677       contents_end_aux = (contents + verdef_size
9678 			  - sizeof (Elf_External_Verdaux));
9679 
9680       /* We know the number of entries in the section but not the maximum
9681 	 index.  Therefore we have to run through all entries and find
9682 	 the maximum.  */
9683       everdef = (Elf_External_Verdef *) contents;
9684       maxidx = 0;
9685       for (i = 0; i < verdef_count; ++i)
9686 	{
9687 	  _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
9688 
9689 	  if ((iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION)) == 0)
9690 	    goto error_return_bad_verdef;
9691 	  if ((iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION)) > maxidx)
9692 	    maxidx = iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION);
9693 
9694 	  if (iverdefmem.vd_next == 0)
9695 	    break;
9696 
9697 	  if (iverdefmem.vd_next
9698 	      > (size_t) (contents_end_def - (bfd_byte *) everdef))
9699 	    goto error_return_bad_verdef;
9700 
9701 	  everdef = ((Elf_External_Verdef *)
9702 		     ((bfd_byte *) everdef + iverdefmem.vd_next));
9703 	}
9704 
9705       if (default_imported_symver)
9706 	{
9707 	  if (freeidx > maxidx)
9708 	    maxidx = ++freeidx;
9709 	  else
9710 	    freeidx = ++maxidx;
9711 	}
9712       if (_bfd_mul_overflow (maxidx, sizeof (Elf_Internal_Verdef), &amt))
9713 	{
9714 	  bfd_set_error (bfd_error_file_too_big);
9715 	  goto error_return_verdef;
9716 	}
9717 
9718       if (amt == 0)
9719 	goto error_return_verdef;
9720       elf_tdata (abfd)->verdef = (Elf_Internal_Verdef *) bfd_zalloc (abfd, amt);
9721       if (elf_tdata (abfd)->verdef == NULL)
9722 	goto error_return_verdef;
9723 
9724       elf_tdata (abfd)->cverdefs = maxidx;
9725 
9726       everdef = (Elf_External_Verdef *) contents;
9727       iverdefarr = elf_tdata (abfd)->verdef;
9728       for (i = 0; i < verdef_count; ++i)
9729 	{
9730 	  Elf_External_Verdaux *everdaux;
9731 	  Elf_Internal_Verdaux *iverdaux;
9732 	  unsigned int j;
9733 
9734 	  _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
9735 
9736 	  if ((iverdefmem.vd_ndx & VERSYM_VERSION) == 0)
9737 	    goto error_return_bad_verdef;
9738 
9739 	  iverdef = &iverdefarr[(iverdefmem.vd_ndx & VERSYM_VERSION) - 1];
9740 	  memcpy (iverdef, &iverdefmem, offsetof (Elf_Internal_Verdef, vd_bfd));
9741 
9742 	  iverdef->vd_bfd = abfd;
9743 
9744 	  if (iverdef->vd_cnt == 0)
9745 	    iverdef->vd_auxptr = NULL;
9746 	  else
9747 	    {
9748 	      if (_bfd_mul_overflow (iverdef->vd_cnt,
9749 				     sizeof (Elf_Internal_Verdaux), &amt))
9750 		{
9751 		  bfd_set_error (bfd_error_file_too_big);
9752 		  goto error_return_verdef;
9753 		}
9754 	      iverdef->vd_auxptr = (struct elf_internal_verdaux *)
9755 		bfd_alloc (abfd, amt);
9756 	      if (iverdef->vd_auxptr == NULL)
9757 		goto error_return_verdef;
9758 	    }
9759 
9760 	  if (iverdef->vd_aux
9761 	      > (size_t) (contents_end_aux - (bfd_byte *) everdef))
9762 	    goto error_return_bad_verdef;
9763 
9764 	  everdaux = ((Elf_External_Verdaux *)
9765 		      ((bfd_byte *) everdef + iverdef->vd_aux));
9766 	  iverdaux = iverdef->vd_auxptr;
9767 	  for (j = 0; j < iverdef->vd_cnt; j++, iverdaux++)
9768 	    {
9769 	      _bfd_elf_swap_verdaux_in (abfd, everdaux, iverdaux);
9770 
9771 	      if (elf_use_dt_symtab_p (abfd))
9772 		{
9773 		  if (iverdaux->vda_name < elf_tdata (abfd)->dt_strsz)
9774 		    iverdaux->vda_nodename
9775 		      = elf_tdata (abfd)->dt_strtab + iverdaux->vda_name;
9776 		  else
9777 		    iverdaux->vda_nodename = NULL;
9778 		}
9779 	      else
9780 		iverdaux->vda_nodename
9781 		  = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
9782 						     iverdaux->vda_name);
9783 	      if (iverdaux->vda_nodename == NULL)
9784 		goto error_return_bad_verdef;
9785 
9786 	      iverdaux->vda_nextptr = NULL;
9787 	      if (iverdaux->vda_next == 0)
9788 		{
9789 		  iverdef->vd_cnt = j + 1;
9790 		  break;
9791 		}
9792 	      if (j + 1 < iverdef->vd_cnt)
9793 		iverdaux->vda_nextptr = iverdaux + 1;
9794 
9795 	      if (iverdaux->vda_next
9796 		  > (size_t) (contents_end_aux - (bfd_byte *) everdaux))
9797 		goto error_return_bad_verdef;
9798 
9799 	      everdaux = ((Elf_External_Verdaux *)
9800 			  ((bfd_byte *) everdaux + iverdaux->vda_next));
9801 	    }
9802 
9803 	  iverdef->vd_nodename = NULL;
9804 	  if (iverdef->vd_cnt)
9805 	    iverdef->vd_nodename = iverdef->vd_auxptr->vda_nodename;
9806 
9807 	  iverdef->vd_nextdef = NULL;
9808 	  if (iverdef->vd_next == 0)
9809 	    break;
9810 	  if ((size_t) (iverdef - iverdefarr) + 1 < maxidx)
9811 	    iverdef->vd_nextdef = iverdef + 1;
9812 
9813 	  everdef = ((Elf_External_Verdef *)
9814 		     ((bfd_byte *) everdef + iverdef->vd_next));
9815 	}
9816 
9817       if (contents != elf_tdata (abfd)->dt_verdef)
9818 	free (contents);
9819       contents = NULL;
9820     }
9821   else if (default_imported_symver)
9822     {
9823       if (freeidx < 3)
9824 	freeidx = 3;
9825       else
9826 	freeidx++;
9827 
9828       if (_bfd_mul_overflow (freeidx, sizeof (Elf_Internal_Verdef), &amt))
9829 	{
9830 	  bfd_set_error (bfd_error_file_too_big);
9831 	  goto error_return;
9832 	}
9833       if (amt == 0)
9834 	goto error_return;
9835       elf_tdata (abfd)->verdef = (Elf_Internal_Verdef *) bfd_zalloc (abfd, amt);
9836       if (elf_tdata (abfd)->verdef == NULL)
9837 	goto error_return;
9838 
9839       elf_tdata (abfd)->cverdefs = freeidx;
9840     }
9841 
9842   /* Create a default version based on the soname.  */
9843   if (default_imported_symver)
9844     {
9845       Elf_Internal_Verdef *iverdef;
9846       Elf_Internal_Verdaux *iverdaux;
9847 
9848       iverdef = &elf_tdata (abfd)->verdef[freeidx - 1];
9849 
9850       iverdef->vd_version = VER_DEF_CURRENT;
9851       iverdef->vd_flags = 0;
9852       iverdef->vd_ndx = freeidx;
9853       iverdef->vd_cnt = 1;
9854 
9855       iverdef->vd_bfd = abfd;
9856 
9857       iverdef->vd_nodename = bfd_elf_get_dt_soname (abfd);
9858       if (iverdef->vd_nodename == NULL)
9859 	goto error_return_verdef;
9860       iverdef->vd_nextdef = NULL;
9861       iverdef->vd_auxptr = ((struct elf_internal_verdaux *)
9862 			    bfd_zalloc (abfd, sizeof (Elf_Internal_Verdaux)));
9863       if (iverdef->vd_auxptr == NULL)
9864 	goto error_return_verdef;
9865 
9866       iverdaux = iverdef->vd_auxptr;
9867       iverdaux->vda_nodename = iverdef->vd_nodename;
9868     }
9869 
9870   return true;
9871 
9872  error_return:
9873   if (contents != elf_tdata (abfd)->dt_verneed
9874       && contents != elf_tdata (abfd)->dt_verdef)
9875     free (contents);
9876   return false;
9877 }
9878 
9879 asymbol *
_bfd_elf_make_empty_symbol(bfd * abfd)9880 _bfd_elf_make_empty_symbol (bfd *abfd)
9881 {
9882   elf_symbol_type *newsym;
9883 
9884   newsym = (elf_symbol_type *) bfd_zalloc (abfd, sizeof (*newsym));
9885   if (!newsym)
9886     return NULL;
9887   newsym->symbol.the_bfd = abfd;
9888   return &newsym->symbol;
9889 }
9890 
9891 void
_bfd_elf_get_symbol_info(bfd * abfd ATTRIBUTE_UNUSED,asymbol * symbol,symbol_info * ret)9892 _bfd_elf_get_symbol_info (bfd *abfd ATTRIBUTE_UNUSED,
9893 			  asymbol *symbol,
9894 			  symbol_info *ret)
9895 {
9896   bfd_symbol_info (symbol, ret);
9897 }
9898 
9899 /* Return whether a symbol name implies a local symbol.  Most targets
9900    use this function for the is_local_label_name entry point, but some
9901    override it.  */
9902 
9903 bool
_bfd_elf_is_local_label_name(bfd * abfd ATTRIBUTE_UNUSED,const char * name)9904 _bfd_elf_is_local_label_name (bfd *abfd ATTRIBUTE_UNUSED,
9905 			      const char *name)
9906 {
9907   /* Normal local symbols start with ``.L''.  */
9908   if (name[0] == '.' && name[1] == 'L')
9909     return true;
9910 
9911   /* At least some SVR4 compilers (e.g., UnixWare 2.1 cc) generate
9912      DWARF debugging symbols starting with ``..''.  */
9913   if (name[0] == '.' && name[1] == '.')
9914     return true;
9915 
9916   /* gcc will sometimes generate symbols beginning with ``_.L_'' when
9917      emitting DWARF debugging output.  I suspect this is actually a
9918      small bug in gcc (it calls ASM_OUTPUT_LABEL when it should call
9919      ASM_GENERATE_INTERNAL_LABEL, and this causes the leading
9920      underscore to be emitted on some ELF targets).  For ease of use,
9921      we treat such symbols as local.  */
9922   if (name[0] == '_' && name[1] == '.' && name[2] == 'L' && name[3] == '_')
9923     return true;
9924 
9925   /* Treat assembler generated fake symbols, dollar local labels and
9926      forward-backward labels (aka local labels) as locals.
9927      These labels have the form:
9928 
9929        L0^A.*				       (fake symbols)
9930 
9931        [.]?L[0123456789]+{^A|^B}[0123456789]*  (local labels)
9932 
9933      Versions which start with .L will have already been matched above,
9934      so we only need to match the rest.  */
9935   if (name[0] == 'L' && ISDIGIT (name[1]))
9936     {
9937       bool ret = false;
9938       const char * p;
9939       char c;
9940 
9941       for (p = name + 2; (c = *p); p++)
9942 	{
9943 	  if (c == 1 || c == 2)
9944 	    {
9945 	      if (c == 1 && p == name + 2)
9946 		/* A fake symbol.  */
9947 		return true;
9948 
9949 	      /* FIXME: We are being paranoid here and treating symbols like
9950 		 L0^Bfoo as if there were non-local, on the grounds that the
9951 		 assembler will never generate them.  But can any symbol
9952 		 containing an ASCII value in the range 1-31 ever be anything
9953 		 other than some kind of local ?  */
9954 	      ret = true;
9955 	    }
9956 
9957 	  if (! ISDIGIT (c))
9958 	    {
9959 	      ret = false;
9960 	      break;
9961 	    }
9962 	}
9963       return ret;
9964     }
9965 
9966   return false;
9967 }
9968 
9969 alent *
_bfd_elf_get_lineno(bfd * abfd ATTRIBUTE_UNUSED,asymbol * symbol ATTRIBUTE_UNUSED)9970 _bfd_elf_get_lineno (bfd *abfd ATTRIBUTE_UNUSED,
9971 		     asymbol *symbol ATTRIBUTE_UNUSED)
9972 {
9973   abort ();
9974   return NULL;
9975 }
9976 
9977 bool
_bfd_elf_set_arch_mach(bfd * abfd,enum bfd_architecture arch,unsigned long machine)9978 _bfd_elf_set_arch_mach (bfd *abfd,
9979 			enum bfd_architecture arch,
9980 			unsigned long machine)
9981 {
9982   /* If this isn't the right architecture for this backend, and this
9983      isn't the generic backend, fail.  */
9984   if (arch != get_elf_backend_data (abfd)->arch
9985       && arch != bfd_arch_unknown
9986       && get_elf_backend_data (abfd)->arch != bfd_arch_unknown)
9987     return false;
9988 
9989   return bfd_default_set_arch_mach (abfd, arch, machine);
9990 }
9991 
9992 /* Find the nearest line to a particular section and offset,
9993    for error reporting.  */
9994 
9995 bool
_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)9996 _bfd_elf_find_nearest_line (bfd *abfd,
9997 			    asymbol **symbols,
9998 			    asection *section,
9999 			    bfd_vma offset,
10000 			    const char **filename_ptr,
10001 			    const char **functionname_ptr,
10002 			    unsigned int *line_ptr,
10003 			    unsigned int *discriminator_ptr)
10004 {
10005   return _bfd_elf_find_nearest_line_with_alt (abfd, NULL, symbols, section,
10006 					      offset, filename_ptr,
10007 					      functionname_ptr, line_ptr,
10008 					      discriminator_ptr);
10009 }
10010 
10011 /* Find the nearest line to a particular section and offset,
10012    for error reporting.  ALT_BFD representing a .gnu_debugaltlink file
10013    can be optionally specified.  */
10014 
10015 bool
_bfd_elf_find_nearest_line_with_alt(bfd * abfd,const char * alt_filename,asymbol ** symbols,asection * section,bfd_vma offset,const char ** filename_ptr,const char ** functionname_ptr,unsigned int * line_ptr,unsigned int * discriminator_ptr)10016 _bfd_elf_find_nearest_line_with_alt (bfd *abfd,
10017 				     const char *alt_filename,
10018 				     asymbol **symbols,
10019 				     asection *section,
10020 				     bfd_vma offset,
10021 				     const char **filename_ptr,
10022 				     const char **functionname_ptr,
10023 				     unsigned int *line_ptr,
10024 				     unsigned int *discriminator_ptr)
10025 {
10026   bool found;
10027 
10028   if (_bfd_dwarf2_find_nearest_line_with_alt (abfd, alt_filename, symbols, NULL,
10029 					      section, offset, filename_ptr,
10030 					      functionname_ptr, line_ptr,
10031 					      discriminator_ptr,
10032 					      dwarf_debug_sections,
10033 					      &elf_tdata (abfd)->dwarf2_find_line_info))
10034     return true;
10035 
10036   if (_bfd_dwarf1_find_nearest_line (abfd, symbols, section, offset,
10037 				     filename_ptr, functionname_ptr, line_ptr))
10038     {
10039       if (!*functionname_ptr)
10040 	_bfd_elf_find_function (abfd, symbols, section, offset,
10041 				*filename_ptr ? NULL : filename_ptr,
10042 				functionname_ptr);
10043       return true;
10044     }
10045 
10046   if (! _bfd_stab_section_find_nearest_line (abfd, symbols, section, offset,
10047 					     &found, filename_ptr,
10048 					     functionname_ptr, line_ptr,
10049 					     &elf_tdata (abfd)->line_info))
10050     return false;
10051   if (found && (*functionname_ptr || *line_ptr))
10052     return true;
10053 
10054   if (symbols == NULL)
10055     return false;
10056 
10057   if (! _bfd_elf_find_function (abfd, symbols, section, offset,
10058 				filename_ptr, functionname_ptr))
10059     return false;
10060 
10061   *line_ptr = 0;
10062   return true;
10063 }
10064 
10065 /* Find the line for a symbol.  */
10066 
10067 bool
_bfd_elf_find_line(bfd * abfd,asymbol ** symbols,asymbol * symbol,const char ** filename_ptr,unsigned int * line_ptr)10068 _bfd_elf_find_line (bfd *abfd, asymbol **symbols, asymbol *symbol,
10069 		    const char **filename_ptr, unsigned int *line_ptr)
10070 {
10071   struct elf_obj_tdata *tdata = elf_tdata (abfd);
10072   return _bfd_dwarf2_find_nearest_line (abfd, symbols, symbol, NULL, 0,
10073 					filename_ptr, NULL, line_ptr, NULL,
10074 					dwarf_debug_sections,
10075 					&tdata->dwarf2_find_line_info);
10076 }
10077 
10078 /* After a call to bfd_find_nearest_line, successive calls to
10079    bfd_find_inliner_info can be used to get source information about
10080    each level of function inlining that terminated at the address
10081    passed to bfd_find_nearest_line.  Currently this is only supported
10082    for DWARF2 with appropriate DWARF3 extensions. */
10083 
10084 bool
_bfd_elf_find_inliner_info(bfd * abfd,const char ** filename_ptr,const char ** functionname_ptr,unsigned int * line_ptr)10085 _bfd_elf_find_inliner_info (bfd *abfd,
10086 			    const char **filename_ptr,
10087 			    const char **functionname_ptr,
10088 			    unsigned int *line_ptr)
10089 {
10090   struct elf_obj_tdata *tdata = elf_tdata (abfd);
10091   return _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
10092 					functionname_ptr, line_ptr,
10093 					&tdata->dwarf2_find_line_info);
10094 }
10095 
10096 int
_bfd_elf_sizeof_headers(bfd * abfd,struct bfd_link_info * info)10097 _bfd_elf_sizeof_headers (bfd *abfd, struct bfd_link_info *info)
10098 {
10099   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10100   int ret = bed->s->sizeof_ehdr;
10101 
10102   if (!bfd_link_relocatable (info))
10103     {
10104       bfd_size_type phdr_size = elf_program_header_size (abfd);
10105 
10106       if (phdr_size == (bfd_size_type) -1)
10107 	{
10108 	  struct elf_segment_map *m;
10109 
10110 	  phdr_size = 0;
10111 	  for (m = elf_seg_map (abfd); m != NULL; m = m->next)
10112 	    phdr_size += bed->s->sizeof_phdr;
10113 
10114 	  if (phdr_size == 0)
10115 	    phdr_size = get_program_header_size (abfd, info);
10116 	}
10117 
10118       elf_program_header_size (abfd) = phdr_size;
10119       ret += phdr_size;
10120     }
10121 
10122   return ret;
10123 }
10124 
10125 bool
_bfd_elf_set_section_contents(bfd * abfd,sec_ptr section,const void * location,file_ptr offset,bfd_size_type count)10126 _bfd_elf_set_section_contents (bfd *abfd,
10127 			       sec_ptr section,
10128 			       const void *location,
10129 			       file_ptr offset,
10130 			       bfd_size_type count)
10131 {
10132   Elf_Internal_Shdr *hdr;
10133 
10134   if (! abfd->output_has_begun
10135       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
10136     return false;
10137 
10138   if (!count)
10139     return true;
10140 
10141   hdr = &elf_section_data (section)->this_hdr;
10142   if (hdr->sh_offset == (file_ptr) -1)
10143     {
10144       unsigned char *contents;
10145 
10146       if (bfd_section_is_ctf (section))
10147 	/* Nothing to do with this section: the contents are generated
10148 	   later.  */
10149 	return true;
10150 
10151       if ((offset + count) > hdr->sh_size)
10152 	{
10153 	  _bfd_error_handler
10154 	    (_("%pB:%pA: error: attempting to write"
10155 	       " over the end of the section"),
10156 	     abfd, section);
10157 
10158 	  bfd_set_error (bfd_error_invalid_operation);
10159 	  return false;
10160 	}
10161 
10162       contents = hdr->contents;
10163       if (contents == NULL)
10164 	{
10165 	  _bfd_error_handler
10166 	    (_("%pB:%pA: error: attempting to write"
10167 	       " section into an empty buffer"),
10168 	     abfd, section);
10169 
10170 	  bfd_set_error (bfd_error_invalid_operation);
10171 	  return false;
10172 	}
10173 
10174       memcpy (contents + offset, location, count);
10175       return true;
10176     }
10177 
10178   return _bfd_generic_set_section_contents (abfd, section,
10179 					    location, offset, count);
10180 }
10181 
10182 bool
_bfd_elf_no_info_to_howto(bfd * abfd ATTRIBUTE_UNUSED,arelent * cache_ptr ATTRIBUTE_UNUSED,Elf_Internal_Rela * dst ATTRIBUTE_UNUSED)10183 _bfd_elf_no_info_to_howto (bfd *abfd ATTRIBUTE_UNUSED,
10184 			   arelent *cache_ptr ATTRIBUTE_UNUSED,
10185 			   Elf_Internal_Rela *dst ATTRIBUTE_UNUSED)
10186 {
10187   abort ();
10188   return false;
10189 }
10190 
10191 /* Try to convert a non-ELF reloc into an ELF one.  */
10192 
10193 bool
_bfd_elf_validate_reloc(bfd * abfd,arelent * areloc)10194 _bfd_elf_validate_reloc (bfd *abfd, arelent *areloc)
10195 {
10196   /* Check whether we really have an ELF howto.  */
10197 
10198   if ((*areloc->sym_ptr_ptr)->the_bfd->xvec != abfd->xvec)
10199     {
10200       bfd_reloc_code_real_type code;
10201       reloc_howto_type *howto;
10202 
10203       /* Alien reloc: Try to determine its type to replace it with an
10204 	 equivalent ELF reloc.  */
10205 
10206       if (areloc->howto->pc_relative)
10207 	{
10208 	  switch (areloc->howto->bitsize)
10209 	    {
10210 	    case 8:
10211 	      code = BFD_RELOC_8_PCREL;
10212 	      break;
10213 	    case 12:
10214 	      code = BFD_RELOC_12_PCREL;
10215 	      break;
10216 	    case 16:
10217 	      code = BFD_RELOC_16_PCREL;
10218 	      break;
10219 	    case 24:
10220 	      code = BFD_RELOC_24_PCREL;
10221 	      break;
10222 	    case 32:
10223 	      code = BFD_RELOC_32_PCREL;
10224 	      break;
10225 	    case 64:
10226 	      code = BFD_RELOC_64_PCREL;
10227 	      break;
10228 	    default:
10229 	      goto fail;
10230 	    }
10231 
10232 	  howto = bfd_reloc_type_lookup (abfd, code);
10233 
10234 	  if (howto && areloc->howto->pcrel_offset != howto->pcrel_offset)
10235 	    {
10236 	      if (howto->pcrel_offset)
10237 		areloc->addend += areloc->address;
10238 	      else
10239 		areloc->addend -= areloc->address; /* addend is unsigned!! */
10240 	    }
10241 	}
10242       else
10243 	{
10244 	  switch (areloc->howto->bitsize)
10245 	    {
10246 	    case 8:
10247 	      code = BFD_RELOC_8;
10248 	      break;
10249 	    case 14:
10250 	      code = BFD_RELOC_14;
10251 	      break;
10252 	    case 16:
10253 	      code = BFD_RELOC_16;
10254 	      break;
10255 	    case 26:
10256 	      code = BFD_RELOC_26;
10257 	      break;
10258 	    case 32:
10259 	      code = BFD_RELOC_32;
10260 	      break;
10261 	    case 64:
10262 	      code = BFD_RELOC_64;
10263 	      break;
10264 	    default:
10265 	      goto fail;
10266 	    }
10267 
10268 	  howto = bfd_reloc_type_lookup (abfd, code);
10269 	}
10270 
10271       if (howto)
10272 	areloc->howto = howto;
10273       else
10274 	goto fail;
10275     }
10276 
10277   return true;
10278 
10279  fail:
10280   /* xgettext:c-format */
10281   _bfd_error_handler (_("%pB: %s unsupported"),
10282 		      abfd, areloc->howto->name);
10283   bfd_set_error (bfd_error_sorry);
10284   return false;
10285 }
10286 
10287 bool
_bfd_elf_free_cached_info(bfd * abfd)10288 _bfd_elf_free_cached_info (bfd *abfd)
10289 {
10290   struct elf_obj_tdata *tdata;
10291 
10292   if ((bfd_get_format (abfd) == bfd_object
10293        || bfd_get_format (abfd) == bfd_core)
10294       && (tdata = elf_tdata (abfd)) != NULL)
10295     {
10296       if (tdata->o != NULL && elf_shstrtab (abfd) != NULL)
10297 	_bfd_elf_strtab_free (elf_shstrtab (abfd));
10298       _bfd_dwarf2_cleanup_debug_info (abfd, &tdata->dwarf2_find_line_info);
10299       _bfd_dwarf1_cleanup_debug_info (abfd, &tdata->dwarf1_find_line_info);
10300       _bfd_stab_cleanup (abfd, &tdata->line_info);
10301     }
10302 
10303   return _bfd_generic_bfd_free_cached_info (abfd);
10304 }
10305 
10306 /* For Rel targets, we encode meaningful data for BFD_RELOC_VTABLE_ENTRY
10307    in the relocation's offset.  Thus we cannot allow any sort of sanity
10308    range-checking to interfere.  There is nothing else to do in processing
10309    this reloc.  */
10310 
10311 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)10312 _bfd_elf_rel_vtable_reloc_fn
10313   (bfd *abfd ATTRIBUTE_UNUSED, arelent *re ATTRIBUTE_UNUSED,
10314    struct bfd_symbol *symbol ATTRIBUTE_UNUSED,
10315    void *data ATTRIBUTE_UNUSED, asection *is ATTRIBUTE_UNUSED,
10316    bfd *obfd ATTRIBUTE_UNUSED, char **errmsg ATTRIBUTE_UNUSED)
10317 {
10318   return bfd_reloc_ok;
10319 }
10320 
10321 /* Elf core file support.  Much of this only works on native
10322    toolchains, since we rely on knowing the
10323    machine-dependent procfs structure in order to pick
10324    out details about the corefile.  */
10325 
10326 #ifdef HAVE_SYS_PROCFS_H
10327 # include <sys/procfs.h>
10328 #endif
10329 
10330 /* Return a PID that identifies a "thread" for threaded cores, or the
10331    PID of the main process for non-threaded cores.  */
10332 
10333 static int
elfcore_make_pid(bfd * abfd)10334 elfcore_make_pid (bfd *abfd)
10335 {
10336   int pid;
10337 
10338   pid = elf_tdata (abfd)->core->lwpid;
10339   if (pid == 0)
10340     pid = elf_tdata (abfd)->core->pid;
10341 
10342   return pid;
10343 }
10344 
10345 /* If there isn't a section called NAME, make one, using data from
10346    SECT.  Note, this function will generate a reference to NAME, so
10347    you shouldn't deallocate or overwrite it.  */
10348 
10349 static bool
elfcore_maybe_make_sect(bfd * abfd,char * name,asection * sect)10350 elfcore_maybe_make_sect (bfd *abfd, char *name, asection *sect)
10351 {
10352   asection *sect2;
10353 
10354   if (bfd_get_section_by_name (abfd, name) != NULL)
10355     return true;
10356 
10357   sect2 = bfd_make_section_with_flags (abfd, name, sect->flags);
10358   if (sect2 == NULL)
10359     return false;
10360 
10361   sect2->size = sect->size;
10362   sect2->filepos = sect->filepos;
10363   sect2->alignment_power = sect->alignment_power;
10364   return true;
10365 }
10366 
10367 /* Create a pseudosection containing SIZE bytes at FILEPOS.  This
10368    actually creates up to two pseudosections:
10369    - For the single-threaded case, a section named NAME, unless
10370      such a section already exists.
10371    - For the multi-threaded case, a section named "NAME/PID", where
10372      PID is elfcore_make_pid (abfd).
10373    Both pseudosections have identical contents.  */
10374 bool
_bfd_elfcore_make_pseudosection(bfd * abfd,char * name,size_t size,ufile_ptr filepos)10375 _bfd_elfcore_make_pseudosection (bfd *abfd,
10376 				 char *name,
10377 				 size_t size,
10378 				 ufile_ptr filepos)
10379 {
10380   char buf[100];
10381   char *threaded_name;
10382   size_t len;
10383   asection *sect;
10384 
10385   /* Build the section name.  */
10386 
10387   sprintf (buf, "%s/%d", name, elfcore_make_pid (abfd));
10388   len = strlen (buf) + 1;
10389   threaded_name = (char *) bfd_alloc (abfd, len);
10390   if (threaded_name == NULL)
10391     return false;
10392   memcpy (threaded_name, buf, len);
10393 
10394   sect = bfd_make_section_anyway_with_flags (abfd, threaded_name,
10395 					     SEC_HAS_CONTENTS);
10396   if (sect == NULL)
10397     return false;
10398   sect->size = size;
10399   sect->filepos = filepos;
10400   sect->alignment_power = 2;
10401 
10402   return elfcore_maybe_make_sect (abfd, name, sect);
10403 }
10404 
10405 static bool
elfcore_make_auxv_note_section(bfd * abfd,Elf_Internal_Note * note,size_t offs)10406 elfcore_make_auxv_note_section (bfd *abfd, Elf_Internal_Note *note,
10407 				size_t offs)
10408 {
10409   asection *sect = bfd_make_section_anyway_with_flags (abfd, ".auxv",
10410 						       SEC_HAS_CONTENTS);
10411 
10412   if (sect == NULL)
10413     return false;
10414 
10415   sect->size = note->descsz - offs;
10416   sect->filepos = note->descpos + offs;
10417   sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
10418 
10419   return true;
10420 }
10421 
10422 /* prstatus_t exists on:
10423      solaris 2.5+
10424      linux 2.[01] + glibc
10425      unixware 4.2
10426 */
10427 
10428 #if defined (HAVE_PRSTATUS_T)
10429 
10430 static bool
elfcore_grok_prstatus(bfd * abfd,Elf_Internal_Note * note)10431 elfcore_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
10432 {
10433   size_t size;
10434   int offset;
10435 
10436   if (note->descsz == sizeof (prstatus_t))
10437     {
10438       prstatus_t prstat;
10439 
10440       size = sizeof (prstat.pr_reg);
10441       offset   = offsetof (prstatus_t, pr_reg);
10442       memcpy (&prstat, note->descdata, sizeof (prstat));
10443 
10444       /* Do not overwrite the core signal if it
10445 	 has already been set by another thread.  */
10446       if (elf_tdata (abfd)->core->signal == 0)
10447 	elf_tdata (abfd)->core->signal = prstat.pr_cursig;
10448       if (elf_tdata (abfd)->core->pid == 0)
10449 	elf_tdata (abfd)->core->pid = prstat.pr_pid;
10450 
10451       /* pr_who exists on:
10452 	 solaris 2.5+
10453 	 unixware 4.2
10454 	 pr_who doesn't exist on:
10455 	 linux 2.[01]
10456 	 */
10457 #if defined (HAVE_PRSTATUS_T_PR_WHO)
10458       elf_tdata (abfd)->core->lwpid = prstat.pr_who;
10459 #else
10460       elf_tdata (abfd)->core->lwpid = prstat.pr_pid;
10461 #endif
10462     }
10463 #if defined (HAVE_PRSTATUS32_T)
10464   else if (note->descsz == sizeof (prstatus32_t))
10465     {
10466       /* 64-bit host, 32-bit corefile */
10467       prstatus32_t prstat;
10468 
10469       size = sizeof (prstat.pr_reg);
10470       offset   = offsetof (prstatus32_t, pr_reg);
10471       memcpy (&prstat, note->descdata, sizeof (prstat));
10472 
10473       /* Do not overwrite the core signal if it
10474 	 has already been set by another thread.  */
10475       if (elf_tdata (abfd)->core->signal == 0)
10476 	elf_tdata (abfd)->core->signal = prstat.pr_cursig;
10477       if (elf_tdata (abfd)->core->pid == 0)
10478 	elf_tdata (abfd)->core->pid = prstat.pr_pid;
10479 
10480       /* pr_who exists on:
10481 	 solaris 2.5+
10482 	 unixware 4.2
10483 	 pr_who doesn't exist on:
10484 	 linux 2.[01]
10485 	 */
10486 #if defined (HAVE_PRSTATUS32_T_PR_WHO)
10487       elf_tdata (abfd)->core->lwpid = prstat.pr_who;
10488 #else
10489       elf_tdata (abfd)->core->lwpid = prstat.pr_pid;
10490 #endif
10491     }
10492 #endif /* HAVE_PRSTATUS32_T */
10493   else
10494     {
10495       /* Fail - we don't know how to handle any other
10496 	 note size (ie. data object type).  */
10497       return true;
10498     }
10499 
10500   /* Make a ".reg/999" section and a ".reg" section.  */
10501   return _bfd_elfcore_make_pseudosection (abfd, ".reg",
10502 					  size, note->descpos + offset);
10503 }
10504 #endif /* defined (HAVE_PRSTATUS_T) */
10505 
10506 /* Create a pseudosection containing the exact contents of NOTE.  */
10507 static bool
elfcore_make_note_pseudosection(bfd * abfd,char * name,Elf_Internal_Note * note)10508 elfcore_make_note_pseudosection (bfd *abfd,
10509 				 char *name,
10510 				 Elf_Internal_Note *note)
10511 {
10512   return _bfd_elfcore_make_pseudosection (abfd, name,
10513 					  note->descsz, note->descpos);
10514 }
10515 
10516 /* There isn't a consistent prfpregset_t across platforms,
10517    but it doesn't matter, because we don't have to pick this
10518    data structure apart.  */
10519 
10520 static bool
elfcore_grok_prfpreg(bfd * abfd,Elf_Internal_Note * note)10521 elfcore_grok_prfpreg (bfd *abfd, Elf_Internal_Note *note)
10522 {
10523   return elfcore_make_note_pseudosection (abfd, ".reg2", note);
10524 }
10525 
10526 /* Linux dumps the Intel SSE regs in a note named "LINUX" with a note
10527    type of NT_PRXFPREG.  Just include the whole note's contents
10528    literally.  */
10529 
10530 static bool
elfcore_grok_prxfpreg(bfd * abfd,Elf_Internal_Note * note)10531 elfcore_grok_prxfpreg (bfd *abfd, Elf_Internal_Note *note)
10532 {
10533   return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
10534 }
10535 
10536 /* Linux dumps the Intel XSAVE extended state in a note named "LINUX"
10537    with a note type of NT_X86_XSTATE.  Just include the whole note's
10538    contents literally.  */
10539 
10540 static bool
elfcore_grok_xstatereg(bfd * abfd,Elf_Internal_Note * note)10541 elfcore_grok_xstatereg (bfd *abfd, Elf_Internal_Note *note)
10542 {
10543   return elfcore_make_note_pseudosection (abfd, ".reg-xstate", note);
10544 }
10545 
10546 static bool
elfcore_grok_ppc_vmx(bfd * abfd,Elf_Internal_Note * note)10547 elfcore_grok_ppc_vmx (bfd *abfd, Elf_Internal_Note *note)
10548 {
10549   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-vmx", note);
10550 }
10551 
10552 static bool
elfcore_grok_ppc_vsx(bfd * abfd,Elf_Internal_Note * note)10553 elfcore_grok_ppc_vsx (bfd *abfd, Elf_Internal_Note *note)
10554 {
10555   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-vsx", note);
10556 }
10557 
10558 static bool
elfcore_grok_ppc_tar(bfd * abfd,Elf_Internal_Note * note)10559 elfcore_grok_ppc_tar (bfd *abfd, Elf_Internal_Note *note)
10560 {
10561   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-tar", note);
10562 }
10563 
10564 static bool
elfcore_grok_ppc_ppr(bfd * abfd,Elf_Internal_Note * note)10565 elfcore_grok_ppc_ppr (bfd *abfd, Elf_Internal_Note *note)
10566 {
10567   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-ppr", note);
10568 }
10569 
10570 static bool
elfcore_grok_ppc_dscr(bfd * abfd,Elf_Internal_Note * note)10571 elfcore_grok_ppc_dscr (bfd *abfd, Elf_Internal_Note *note)
10572 {
10573   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-dscr", note);
10574 }
10575 
10576 static bool
elfcore_grok_ppc_ebb(bfd * abfd,Elf_Internal_Note * note)10577 elfcore_grok_ppc_ebb (bfd *abfd, Elf_Internal_Note *note)
10578 {
10579   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-ebb", note);
10580 }
10581 
10582 static bool
elfcore_grok_ppc_pmu(bfd * abfd,Elf_Internal_Note * note)10583 elfcore_grok_ppc_pmu (bfd *abfd, Elf_Internal_Note *note)
10584 {
10585   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-pmu", note);
10586 }
10587 
10588 static bool
elfcore_grok_ppc_tm_cgpr(bfd * abfd,Elf_Internal_Note * note)10589 elfcore_grok_ppc_tm_cgpr (bfd *abfd, Elf_Internal_Note *note)
10590 {
10591   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-tm-cgpr", note);
10592 }
10593 
10594 static bool
elfcore_grok_ppc_tm_cfpr(bfd * abfd,Elf_Internal_Note * note)10595 elfcore_grok_ppc_tm_cfpr (bfd *abfd, Elf_Internal_Note *note)
10596 {
10597   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-tm-cfpr", note);
10598 }
10599 
10600 static bool
elfcore_grok_ppc_tm_cvmx(bfd * abfd,Elf_Internal_Note * note)10601 elfcore_grok_ppc_tm_cvmx (bfd *abfd, Elf_Internal_Note *note)
10602 {
10603   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-tm-cvmx", note);
10604 }
10605 
10606 static bool
elfcore_grok_ppc_tm_cvsx(bfd * abfd,Elf_Internal_Note * note)10607 elfcore_grok_ppc_tm_cvsx (bfd *abfd, Elf_Internal_Note *note)
10608 {
10609   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-tm-cvsx", note);
10610 }
10611 
10612 static bool
elfcore_grok_ppc_tm_spr(bfd * abfd,Elf_Internal_Note * note)10613 elfcore_grok_ppc_tm_spr (bfd *abfd, Elf_Internal_Note *note)
10614 {
10615   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-tm-spr", note);
10616 }
10617 
10618 static bool
elfcore_grok_ppc_tm_ctar(bfd * abfd,Elf_Internal_Note * note)10619 elfcore_grok_ppc_tm_ctar (bfd *abfd, Elf_Internal_Note *note)
10620 {
10621   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-tm-ctar", note);
10622 }
10623 
10624 static bool
elfcore_grok_ppc_tm_cppr(bfd * abfd,Elf_Internal_Note * note)10625 elfcore_grok_ppc_tm_cppr (bfd *abfd, Elf_Internal_Note *note)
10626 {
10627   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-tm-cppr", note);
10628 }
10629 
10630 static bool
elfcore_grok_ppc_tm_cdscr(bfd * abfd,Elf_Internal_Note * note)10631 elfcore_grok_ppc_tm_cdscr (bfd *abfd, Elf_Internal_Note *note)
10632 {
10633   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-tm-cdscr", note);
10634 }
10635 
10636 static bool
elfcore_grok_s390_high_gprs(bfd * abfd,Elf_Internal_Note * note)10637 elfcore_grok_s390_high_gprs (bfd *abfd, Elf_Internal_Note *note)
10638 {
10639   return elfcore_make_note_pseudosection (abfd, ".reg-s390-high-gprs", note);
10640 }
10641 
10642 static bool
elfcore_grok_s390_timer(bfd * abfd,Elf_Internal_Note * note)10643 elfcore_grok_s390_timer (bfd *abfd, Elf_Internal_Note *note)
10644 {
10645   return elfcore_make_note_pseudosection (abfd, ".reg-s390-timer", note);
10646 }
10647 
10648 static bool
elfcore_grok_s390_todcmp(bfd * abfd,Elf_Internal_Note * note)10649 elfcore_grok_s390_todcmp (bfd *abfd, Elf_Internal_Note *note)
10650 {
10651   return elfcore_make_note_pseudosection (abfd, ".reg-s390-todcmp", note);
10652 }
10653 
10654 static bool
elfcore_grok_s390_todpreg(bfd * abfd,Elf_Internal_Note * note)10655 elfcore_grok_s390_todpreg (bfd *abfd, Elf_Internal_Note *note)
10656 {
10657   return elfcore_make_note_pseudosection (abfd, ".reg-s390-todpreg", note);
10658 }
10659 
10660 static bool
elfcore_grok_s390_ctrs(bfd * abfd,Elf_Internal_Note * note)10661 elfcore_grok_s390_ctrs (bfd *abfd, Elf_Internal_Note *note)
10662 {
10663   return elfcore_make_note_pseudosection (abfd, ".reg-s390-ctrs", note);
10664 }
10665 
10666 static bool
elfcore_grok_s390_prefix(bfd * abfd,Elf_Internal_Note * note)10667 elfcore_grok_s390_prefix (bfd *abfd, Elf_Internal_Note *note)
10668 {
10669   return elfcore_make_note_pseudosection (abfd, ".reg-s390-prefix", note);
10670 }
10671 
10672 static bool
elfcore_grok_s390_last_break(bfd * abfd,Elf_Internal_Note * note)10673 elfcore_grok_s390_last_break (bfd *abfd, Elf_Internal_Note *note)
10674 {
10675   return elfcore_make_note_pseudosection (abfd, ".reg-s390-last-break", note);
10676 }
10677 
10678 static bool
elfcore_grok_s390_system_call(bfd * abfd,Elf_Internal_Note * note)10679 elfcore_grok_s390_system_call (bfd *abfd, Elf_Internal_Note *note)
10680 {
10681   return elfcore_make_note_pseudosection (abfd, ".reg-s390-system-call", note);
10682 }
10683 
10684 static bool
elfcore_grok_s390_tdb(bfd * abfd,Elf_Internal_Note * note)10685 elfcore_grok_s390_tdb (bfd *abfd, Elf_Internal_Note *note)
10686 {
10687   return elfcore_make_note_pseudosection (abfd, ".reg-s390-tdb", note);
10688 }
10689 
10690 static bool
elfcore_grok_s390_vxrs_low(bfd * abfd,Elf_Internal_Note * note)10691 elfcore_grok_s390_vxrs_low (bfd *abfd, Elf_Internal_Note *note)
10692 {
10693   return elfcore_make_note_pseudosection (abfd, ".reg-s390-vxrs-low", note);
10694 }
10695 
10696 static bool
elfcore_grok_s390_vxrs_high(bfd * abfd,Elf_Internal_Note * note)10697 elfcore_grok_s390_vxrs_high (bfd *abfd, Elf_Internal_Note *note)
10698 {
10699   return elfcore_make_note_pseudosection (abfd, ".reg-s390-vxrs-high", note);
10700 }
10701 
10702 static bool
elfcore_grok_s390_gs_cb(bfd * abfd,Elf_Internal_Note * note)10703 elfcore_grok_s390_gs_cb (bfd *abfd, Elf_Internal_Note *note)
10704 {
10705   return elfcore_make_note_pseudosection (abfd, ".reg-s390-gs-cb", note);
10706 }
10707 
10708 static bool
elfcore_grok_s390_gs_bc(bfd * abfd,Elf_Internal_Note * note)10709 elfcore_grok_s390_gs_bc (bfd *abfd, Elf_Internal_Note *note)
10710 {
10711   return elfcore_make_note_pseudosection (abfd, ".reg-s390-gs-bc", note);
10712 }
10713 
10714 static bool
elfcore_grok_arm_vfp(bfd * abfd,Elf_Internal_Note * note)10715 elfcore_grok_arm_vfp (bfd *abfd, Elf_Internal_Note *note)
10716 {
10717   return elfcore_make_note_pseudosection (abfd, ".reg-arm-vfp", note);
10718 }
10719 
10720 static bool
elfcore_grok_aarch_tls(bfd * abfd,Elf_Internal_Note * note)10721 elfcore_grok_aarch_tls (bfd *abfd, Elf_Internal_Note *note)
10722 {
10723   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-tls", note);
10724 }
10725 
10726 static bool
elfcore_grok_aarch_hw_break(bfd * abfd,Elf_Internal_Note * note)10727 elfcore_grok_aarch_hw_break (bfd *abfd, Elf_Internal_Note *note)
10728 {
10729   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-hw-break", note);
10730 }
10731 
10732 static bool
elfcore_grok_aarch_hw_watch(bfd * abfd,Elf_Internal_Note * note)10733 elfcore_grok_aarch_hw_watch (bfd *abfd, Elf_Internal_Note *note)
10734 {
10735   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-hw-watch", note);
10736 }
10737 
10738 static bool
elfcore_grok_aarch_sve(bfd * abfd,Elf_Internal_Note * note)10739 elfcore_grok_aarch_sve (bfd *abfd, Elf_Internal_Note *note)
10740 {
10741   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-sve", note);
10742 }
10743 
10744 static bool
elfcore_grok_aarch_pauth(bfd * abfd,Elf_Internal_Note * note)10745 elfcore_grok_aarch_pauth (bfd *abfd, Elf_Internal_Note *note)
10746 {
10747   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-pauth", note);
10748 }
10749 
10750 static bool
elfcore_grok_aarch_mte(bfd * abfd,Elf_Internal_Note * note)10751 elfcore_grok_aarch_mte (bfd *abfd, Elf_Internal_Note *note)
10752 {
10753   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-mte",
10754 					  note);
10755 }
10756 
10757 static bool
elfcore_grok_aarch_ssve(bfd * abfd,Elf_Internal_Note * note)10758 elfcore_grok_aarch_ssve (bfd *abfd, Elf_Internal_Note *note)
10759 {
10760   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-ssve", note);
10761 }
10762 
10763 static bool
elfcore_grok_aarch_za(bfd * abfd,Elf_Internal_Note * note)10764 elfcore_grok_aarch_za (bfd *abfd, Elf_Internal_Note *note)
10765 {
10766   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-za", note);
10767 }
10768 
10769 /* Convert NOTE into a bfd_section called ".reg-aarch-zt".  Return TRUE if
10770    successful, otherwise return FALSE.  */
10771 
10772 static bool
elfcore_grok_aarch_zt(bfd * abfd,Elf_Internal_Note * note)10773 elfcore_grok_aarch_zt (bfd *abfd, Elf_Internal_Note *note)
10774 {
10775   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-zt", note);
10776 }
10777 
10778 static bool
elfcore_grok_arc_v2(bfd * abfd,Elf_Internal_Note * note)10779 elfcore_grok_arc_v2 (bfd *abfd, Elf_Internal_Note *note)
10780 {
10781   return elfcore_make_note_pseudosection (abfd, ".reg-arc-v2", note);
10782 }
10783 
10784 /* Convert NOTE into a bfd_section called ".reg-riscv-csr".  Return TRUE if
10785    successful otherwise, return FALSE.  */
10786 
10787 static bool
elfcore_grok_riscv_csr(bfd * abfd,Elf_Internal_Note * note)10788 elfcore_grok_riscv_csr (bfd *abfd, Elf_Internal_Note *note)
10789 {
10790   return elfcore_make_note_pseudosection (abfd, ".reg-riscv-csr", note);
10791 }
10792 
10793 /* Convert NOTE into a bfd_section called ".gdb-tdesc".  Return TRUE if
10794    successful otherwise, return FALSE.  */
10795 
10796 static bool
elfcore_grok_gdb_tdesc(bfd * abfd,Elf_Internal_Note * note)10797 elfcore_grok_gdb_tdesc (bfd *abfd, Elf_Internal_Note *note)
10798 {
10799   return elfcore_make_note_pseudosection (abfd, ".gdb-tdesc", note);
10800 }
10801 
10802 static bool
elfcore_grok_loongarch_cpucfg(bfd * abfd,Elf_Internal_Note * note)10803 elfcore_grok_loongarch_cpucfg (bfd *abfd, Elf_Internal_Note *note)
10804 {
10805   return elfcore_make_note_pseudosection (abfd, ".reg-loongarch-cpucfg", note);
10806 }
10807 
10808 static bool
elfcore_grok_loongarch_lbt(bfd * abfd,Elf_Internal_Note * note)10809 elfcore_grok_loongarch_lbt (bfd *abfd, Elf_Internal_Note *note)
10810 {
10811   return elfcore_make_note_pseudosection (abfd, ".reg-loongarch-lbt", note);
10812 }
10813 
10814 static bool
elfcore_grok_loongarch_lsx(bfd * abfd,Elf_Internal_Note * note)10815 elfcore_grok_loongarch_lsx (bfd *abfd, Elf_Internal_Note *note)
10816 {
10817   return elfcore_make_note_pseudosection (abfd, ".reg-loongarch-lsx", note);
10818 }
10819 
10820 static bool
elfcore_grok_loongarch_lasx(bfd * abfd,Elf_Internal_Note * note)10821 elfcore_grok_loongarch_lasx (bfd *abfd, Elf_Internal_Note *note)
10822 {
10823   return elfcore_make_note_pseudosection (abfd, ".reg-loongarch-lasx", note);
10824 }
10825 
10826 #if defined (HAVE_PRPSINFO_T)
10827 typedef prpsinfo_t   elfcore_psinfo_t;
10828 #if defined (HAVE_PRPSINFO32_T)		/* Sparc64 cross Sparc32 */
10829 typedef prpsinfo32_t elfcore_psinfo32_t;
10830 #endif
10831 #endif
10832 
10833 #if defined (HAVE_PSINFO_T)
10834 typedef psinfo_t   elfcore_psinfo_t;
10835 #if defined (HAVE_PSINFO32_T)		/* Sparc64 cross Sparc32 */
10836 typedef psinfo32_t elfcore_psinfo32_t;
10837 #endif
10838 #endif
10839 
10840 /* return a malloc'ed copy of a string at START which is at
10841    most MAX bytes long, possibly without a terminating '\0'.
10842    the copy will always have a terminating '\0'.  */
10843 
10844 char *
_bfd_elfcore_strndup(bfd * abfd,char * start,size_t max)10845 _bfd_elfcore_strndup (bfd *abfd, char *start, size_t max)
10846 {
10847   char *dups;
10848   char *end = (char *) memchr (start, '\0', max);
10849   size_t len;
10850 
10851   if (end == NULL)
10852     len = max;
10853   else
10854     len = end - start;
10855 
10856   dups = (char *) bfd_alloc (abfd, len + 1);
10857   if (dups == NULL)
10858     return NULL;
10859 
10860   memcpy (dups, start, len);
10861   dups[len] = '\0';
10862 
10863   return dups;
10864 }
10865 
10866 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
10867 static bool
elfcore_grok_psinfo(bfd * abfd,Elf_Internal_Note * note)10868 elfcore_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
10869 {
10870   if (note->descsz == sizeof (elfcore_psinfo_t))
10871     {
10872       elfcore_psinfo_t psinfo;
10873 
10874       memcpy (&psinfo, note->descdata, sizeof (psinfo));
10875 
10876 #if defined (HAVE_PSINFO_T_PR_PID) || defined (HAVE_PRPSINFO_T_PR_PID)
10877       elf_tdata (abfd)->core->pid = psinfo.pr_pid;
10878 #endif
10879       elf_tdata (abfd)->core->program
10880 	= _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
10881 				sizeof (psinfo.pr_fname));
10882 
10883       elf_tdata (abfd)->core->command
10884 	= _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
10885 				sizeof (psinfo.pr_psargs));
10886     }
10887 #if defined (HAVE_PRPSINFO32_T) || defined (HAVE_PSINFO32_T)
10888   else if (note->descsz == sizeof (elfcore_psinfo32_t))
10889     {
10890       /* 64-bit host, 32-bit corefile */
10891       elfcore_psinfo32_t psinfo;
10892 
10893       memcpy (&psinfo, note->descdata, sizeof (psinfo));
10894 
10895 #if defined (HAVE_PSINFO32_T_PR_PID) || defined (HAVE_PRPSINFO32_T_PR_PID)
10896       elf_tdata (abfd)->core->pid = psinfo.pr_pid;
10897 #endif
10898       elf_tdata (abfd)->core->program
10899 	= _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
10900 				sizeof (psinfo.pr_fname));
10901 
10902       elf_tdata (abfd)->core->command
10903 	= _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
10904 				sizeof (psinfo.pr_psargs));
10905     }
10906 #endif
10907 
10908   else
10909     {
10910       /* Fail - we don't know how to handle any other
10911 	 note size (ie. data object type).  */
10912       return true;
10913     }
10914 
10915   /* Note that for some reason, a spurious space is tacked
10916      onto the end of the args in some (at least one anyway)
10917      implementations, so strip it off if it exists.  */
10918 
10919   {
10920     char *command = elf_tdata (abfd)->core->command;
10921     int n = strlen (command);
10922 
10923     if (0 < n && command[n - 1] == ' ')
10924       command[n - 1] = '\0';
10925   }
10926 
10927   return true;
10928 }
10929 #endif /* defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T) */
10930 
10931 #if defined (HAVE_PSTATUS_T)
10932 static bool
elfcore_grok_pstatus(bfd * abfd,Elf_Internal_Note * note)10933 elfcore_grok_pstatus (bfd *abfd, Elf_Internal_Note *note)
10934 {
10935   if (note->descsz == sizeof (pstatus_t)
10936 #if defined (HAVE_PXSTATUS_T)
10937       || note->descsz == sizeof (pxstatus_t)
10938 #endif
10939       )
10940     {
10941       pstatus_t pstat;
10942 
10943       memcpy (&pstat, note->descdata, sizeof (pstat));
10944 
10945       elf_tdata (abfd)->core->pid = pstat.pr_pid;
10946     }
10947 #if defined (HAVE_PSTATUS32_T)
10948   else if (note->descsz == sizeof (pstatus32_t))
10949     {
10950       /* 64-bit host, 32-bit corefile */
10951       pstatus32_t pstat;
10952 
10953       memcpy (&pstat, note->descdata, sizeof (pstat));
10954 
10955       elf_tdata (abfd)->core->pid = pstat.pr_pid;
10956     }
10957 #endif
10958   /* Could grab some more details from the "representative"
10959      lwpstatus_t in pstat.pr_lwp, but we'll catch it all in an
10960      NT_LWPSTATUS note, presumably.  */
10961 
10962   return true;
10963 }
10964 #endif /* defined (HAVE_PSTATUS_T) */
10965 
10966 #if defined (HAVE_LWPSTATUS_T)
10967 static bool
elfcore_grok_lwpstatus(bfd * abfd,Elf_Internal_Note * note)10968 elfcore_grok_lwpstatus (bfd *abfd, Elf_Internal_Note *note)
10969 {
10970   lwpstatus_t lwpstat;
10971   char buf[100];
10972   char *name;
10973   size_t len;
10974   asection *sect;
10975 
10976   if (note->descsz != sizeof (lwpstat)
10977 #if defined (HAVE_LWPXSTATUS_T)
10978       && note->descsz != sizeof (lwpxstatus_t)
10979 #endif
10980       )
10981     return true;
10982 
10983   memcpy (&lwpstat, note->descdata, sizeof (lwpstat));
10984 
10985   elf_tdata (abfd)->core->lwpid = lwpstat.pr_lwpid;
10986   /* Do not overwrite the core signal if it has already been set by
10987      another thread.  */
10988   if (elf_tdata (abfd)->core->signal == 0)
10989     elf_tdata (abfd)->core->signal = lwpstat.pr_cursig;
10990 
10991   /* Make a ".reg/999" section.  */
10992 
10993   sprintf (buf, ".reg/%d", elfcore_make_pid (abfd));
10994   len = strlen (buf) + 1;
10995   name = bfd_alloc (abfd, len);
10996   if (name == NULL)
10997     return false;
10998   memcpy (name, buf, len);
10999 
11000   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
11001   if (sect == NULL)
11002     return false;
11003 
11004 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
11005   sect->size = sizeof (lwpstat.pr_context.uc_mcontext.gregs);
11006   sect->filepos = note->descpos
11007     + offsetof (lwpstatus_t, pr_context.uc_mcontext.gregs);
11008 #endif
11009 
11010 #if defined (HAVE_LWPSTATUS_T_PR_REG)
11011   sect->size = sizeof (lwpstat.pr_reg);
11012   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_reg);
11013 #endif
11014 
11015   sect->alignment_power = 2;
11016 
11017   if (!elfcore_maybe_make_sect (abfd, ".reg", sect))
11018     return false;
11019 
11020   /* Make a ".reg2/999" section */
11021 
11022   sprintf (buf, ".reg2/%d", elfcore_make_pid (abfd));
11023   len = strlen (buf) + 1;
11024   name = bfd_alloc (abfd, len);
11025   if (name == NULL)
11026     return false;
11027   memcpy (name, buf, len);
11028 
11029   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
11030   if (sect == NULL)
11031     return false;
11032 
11033 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
11034   sect->size = sizeof (lwpstat.pr_context.uc_mcontext.fpregs);
11035   sect->filepos = note->descpos
11036     + offsetof (lwpstatus_t, pr_context.uc_mcontext.fpregs);
11037 #endif
11038 
11039 #if defined (HAVE_LWPSTATUS_T_PR_FPREG)
11040   sect->size = sizeof (lwpstat.pr_fpreg);
11041   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_fpreg);
11042 #endif
11043 
11044   sect->alignment_power = 2;
11045 
11046   return elfcore_maybe_make_sect (abfd, ".reg2", sect);
11047 }
11048 #endif /* defined (HAVE_LWPSTATUS_T) */
11049 
11050 /* These constants, and the structure offsets used below, are defined by
11051    Cygwin's core_dump.h */
11052 #define NOTE_INFO_PROCESS  1
11053 #define NOTE_INFO_THREAD   2
11054 #define NOTE_INFO_MODULE   3
11055 #define NOTE_INFO_MODULE64 4
11056 
11057 static bool
elfcore_grok_win32pstatus(bfd * abfd,Elf_Internal_Note * note)11058 elfcore_grok_win32pstatus (bfd *abfd, Elf_Internal_Note *note)
11059 {
11060   char buf[30];
11061   char *name;
11062   size_t len;
11063   unsigned int name_size;
11064   asection *sect;
11065   unsigned int type;
11066   int is_active_thread;
11067   bfd_vma base_addr;
11068 
11069   if (note->descsz < 4)
11070     return true;
11071 
11072   if (! startswith (note->namedata, "win32"))
11073     return true;
11074 
11075   type = bfd_get_32 (abfd, note->descdata);
11076 
11077   struct
11078   {
11079     const char *type_name;
11080     unsigned long min_size;
11081   } size_check[] =
11082       {
11083        { "NOTE_INFO_PROCESS", 12 },
11084        { "NOTE_INFO_THREAD", 12 },
11085        { "NOTE_INFO_MODULE", 12 },
11086        { "NOTE_INFO_MODULE64", 16 },
11087       };
11088 
11089   if (type == 0 || type > (sizeof(size_check)/sizeof(size_check[0])))
11090       return true;
11091 
11092   if (note->descsz < size_check[type - 1].min_size)
11093     {
11094       _bfd_error_handler (_("%pB: warning: win32pstatus %s of size %lu bytes"
11095 			    " is too small"),
11096 			  abfd, size_check[type - 1].type_name, note->descsz);
11097       return true;
11098     }
11099 
11100   switch (type)
11101     {
11102     case NOTE_INFO_PROCESS:
11103       /* FIXME: need to add ->core->command.  */
11104       elf_tdata (abfd)->core->pid = bfd_get_32 (abfd, note->descdata + 4);
11105       elf_tdata (abfd)->core->signal = bfd_get_32 (abfd, note->descdata + 8);
11106       break;
11107 
11108     case NOTE_INFO_THREAD:
11109       /* Make a ".reg/<tid>" section containing the Win32 API thread CONTEXT
11110 	 structure. */
11111       /* thread_info.tid */
11112       sprintf (buf, ".reg/%ld", (long) bfd_get_32 (abfd, note->descdata + 4));
11113 
11114       len = strlen (buf) + 1;
11115       name = (char *) bfd_alloc (abfd, len);
11116       if (name == NULL)
11117 	return false;
11118 
11119       memcpy (name, buf, len);
11120 
11121       sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
11122       if (sect == NULL)
11123 	return false;
11124 
11125       /* sizeof (thread_info.thread_context) */
11126       sect->size = note->descsz - 12;
11127       /* offsetof (thread_info.thread_context) */
11128       sect->filepos = note->descpos + 12;
11129       sect->alignment_power = 2;
11130 
11131       /* thread_info.is_active_thread */
11132       is_active_thread = bfd_get_32 (abfd, note->descdata + 8);
11133 
11134       if (is_active_thread)
11135 	if (! elfcore_maybe_make_sect (abfd, ".reg", sect))
11136 	  return false;
11137       break;
11138 
11139     case NOTE_INFO_MODULE:
11140     case NOTE_INFO_MODULE64:
11141       /* Make a ".module/xxxxxxxx" section.  */
11142       if (type == NOTE_INFO_MODULE)
11143 	{
11144 	  /* module_info.base_address */
11145 	  base_addr = bfd_get_32 (abfd, note->descdata + 4);
11146 	  sprintf (buf, ".module/%08lx", (unsigned long) base_addr);
11147 	  /* module_info.module_name_size */
11148 	  name_size = bfd_get_32 (abfd, note->descdata + 8);
11149 	}
11150       else /* NOTE_INFO_MODULE64 */
11151 	{
11152 	  /* module_info.base_address */
11153 	  base_addr = bfd_get_64 (abfd, note->descdata + 4);
11154 	  sprintf (buf, ".module/%016lx", (unsigned long) base_addr);
11155 	  /* module_info.module_name_size */
11156 	  name_size = bfd_get_32 (abfd, note->descdata + 12);
11157 	}
11158 
11159       len = strlen (buf) + 1;
11160       name = (char *) bfd_alloc (abfd, len);
11161       if (name == NULL)
11162 	return false;
11163 
11164       memcpy (name, buf, len);
11165 
11166       sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
11167 
11168       if (sect == NULL)
11169 	return false;
11170 
11171       if (note->descsz < 12 + name_size)
11172 	{
11173 	  _bfd_error_handler (_("%pB: win32pstatus NOTE_INFO_MODULE of size %lu"
11174 				" is too small to contain a name of size %u"),
11175 			      abfd, note->descsz, name_size);
11176 	  return true;
11177 	}
11178 
11179       sect->size = note->descsz;
11180       sect->filepos = note->descpos;
11181       sect->alignment_power = 2;
11182       break;
11183 
11184     default:
11185       return true;
11186     }
11187 
11188   return true;
11189 }
11190 
11191 static bool
elfcore_grok_note(bfd * abfd,Elf_Internal_Note * note)11192 elfcore_grok_note (bfd *abfd, Elf_Internal_Note *note)
11193 {
11194   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11195 
11196   switch (note->type)
11197     {
11198     default:
11199       return true;
11200 
11201     case NT_PRSTATUS:
11202       if (bed->elf_backend_grok_prstatus)
11203 	if ((*bed->elf_backend_grok_prstatus) (abfd, note))
11204 	  return true;
11205 #if defined (HAVE_PRSTATUS_T)
11206       return elfcore_grok_prstatus (abfd, note);
11207 #else
11208       return true;
11209 #endif
11210 
11211 #if defined (HAVE_PSTATUS_T)
11212     case NT_PSTATUS:
11213       return elfcore_grok_pstatus (abfd, note);
11214 #endif
11215 
11216 #if defined (HAVE_LWPSTATUS_T)
11217     case NT_LWPSTATUS:
11218       return elfcore_grok_lwpstatus (abfd, note);
11219 #endif
11220 
11221     case NT_FPREGSET:		/* FIXME: rename to NT_PRFPREG */
11222       return elfcore_grok_prfpreg (abfd, note);
11223 
11224     case NT_WIN32PSTATUS:
11225       return elfcore_grok_win32pstatus (abfd, note);
11226 
11227     case NT_PRXFPREG:		/* Linux SSE extension */
11228       if (note->namesz == 6
11229 	  && strcmp (note->namedata, "LINUX") == 0)
11230 	return elfcore_grok_prxfpreg (abfd, note);
11231       else
11232 	return true;
11233 
11234     case NT_X86_XSTATE:		/* Linux XSAVE extension */
11235       if (note->namesz == 6
11236 	  && strcmp (note->namedata, "LINUX") == 0)
11237 	return elfcore_grok_xstatereg (abfd, note);
11238       else
11239 	return true;
11240 
11241     case NT_PPC_VMX:
11242       if (note->namesz == 6
11243 	  && strcmp (note->namedata, "LINUX") == 0)
11244 	return elfcore_grok_ppc_vmx (abfd, note);
11245       else
11246 	return true;
11247 
11248     case NT_PPC_VSX:
11249       if (note->namesz == 6
11250 	  && strcmp (note->namedata, "LINUX") == 0)
11251 	return elfcore_grok_ppc_vsx (abfd, note);
11252       else
11253 	return true;
11254 
11255     case NT_PPC_TAR:
11256       if (note->namesz == 6
11257 	  && strcmp (note->namedata, "LINUX") == 0)
11258 	return elfcore_grok_ppc_tar (abfd, note);
11259       else
11260 	return true;
11261 
11262     case NT_PPC_PPR:
11263       if (note->namesz == 6
11264 	  && strcmp (note->namedata, "LINUX") == 0)
11265 	return elfcore_grok_ppc_ppr (abfd, note);
11266       else
11267 	return true;
11268 
11269     case NT_PPC_DSCR:
11270       if (note->namesz == 6
11271 	  && strcmp (note->namedata, "LINUX") == 0)
11272 	return elfcore_grok_ppc_dscr (abfd, note);
11273       else
11274 	return true;
11275 
11276     case NT_PPC_EBB:
11277       if (note->namesz == 6
11278 	  && strcmp (note->namedata, "LINUX") == 0)
11279 	return elfcore_grok_ppc_ebb (abfd, note);
11280       else
11281 	return true;
11282 
11283     case NT_PPC_PMU:
11284       if (note->namesz == 6
11285 	  && strcmp (note->namedata, "LINUX") == 0)
11286 	return elfcore_grok_ppc_pmu (abfd, note);
11287       else
11288 	return true;
11289 
11290     case NT_PPC_TM_CGPR:
11291       if (note->namesz == 6
11292 	  && strcmp (note->namedata, "LINUX") == 0)
11293 	return elfcore_grok_ppc_tm_cgpr (abfd, note);
11294       else
11295 	return true;
11296 
11297     case NT_PPC_TM_CFPR:
11298       if (note->namesz == 6
11299 	  && strcmp (note->namedata, "LINUX") == 0)
11300 	return elfcore_grok_ppc_tm_cfpr (abfd, note);
11301       else
11302 	return true;
11303 
11304     case NT_PPC_TM_CVMX:
11305       if (note->namesz == 6
11306 	  && strcmp (note->namedata, "LINUX") == 0)
11307 	return elfcore_grok_ppc_tm_cvmx (abfd, note);
11308       else
11309 	return true;
11310 
11311     case NT_PPC_TM_CVSX:
11312       if (note->namesz == 6
11313 	  && strcmp (note->namedata, "LINUX") == 0)
11314 	return elfcore_grok_ppc_tm_cvsx (abfd, note);
11315       else
11316 	return true;
11317 
11318     case NT_PPC_TM_SPR:
11319       if (note->namesz == 6
11320 	  && strcmp (note->namedata, "LINUX") == 0)
11321 	return elfcore_grok_ppc_tm_spr (abfd, note);
11322       else
11323 	return true;
11324 
11325     case NT_PPC_TM_CTAR:
11326       if (note->namesz == 6
11327 	  && strcmp (note->namedata, "LINUX") == 0)
11328 	return elfcore_grok_ppc_tm_ctar (abfd, note);
11329       else
11330 	return true;
11331 
11332     case NT_PPC_TM_CPPR:
11333       if (note->namesz == 6
11334 	  && strcmp (note->namedata, "LINUX") == 0)
11335 	return elfcore_grok_ppc_tm_cppr (abfd, note);
11336       else
11337 	return true;
11338 
11339     case NT_PPC_TM_CDSCR:
11340       if (note->namesz == 6
11341 	  && strcmp (note->namedata, "LINUX") == 0)
11342 	return elfcore_grok_ppc_tm_cdscr (abfd, note);
11343       else
11344 	return true;
11345 
11346     case NT_S390_HIGH_GPRS:
11347       if (note->namesz == 6
11348 	  && strcmp (note->namedata, "LINUX") == 0)
11349 	return elfcore_grok_s390_high_gprs (abfd, note);
11350       else
11351 	return true;
11352 
11353     case NT_S390_TIMER:
11354       if (note->namesz == 6
11355 	  && strcmp (note->namedata, "LINUX") == 0)
11356 	return elfcore_grok_s390_timer (abfd, note);
11357       else
11358 	return true;
11359 
11360     case NT_S390_TODCMP:
11361       if (note->namesz == 6
11362 	  && strcmp (note->namedata, "LINUX") == 0)
11363 	return elfcore_grok_s390_todcmp (abfd, note);
11364       else
11365 	return true;
11366 
11367     case NT_S390_TODPREG:
11368       if (note->namesz == 6
11369 	  && strcmp (note->namedata, "LINUX") == 0)
11370 	return elfcore_grok_s390_todpreg (abfd, note);
11371       else
11372 	return true;
11373 
11374     case NT_S390_CTRS:
11375       if (note->namesz == 6
11376 	  && strcmp (note->namedata, "LINUX") == 0)
11377 	return elfcore_grok_s390_ctrs (abfd, note);
11378       else
11379 	return true;
11380 
11381     case NT_S390_PREFIX:
11382       if (note->namesz == 6
11383 	  && strcmp (note->namedata, "LINUX") == 0)
11384 	return elfcore_grok_s390_prefix (abfd, note);
11385       else
11386 	return true;
11387 
11388     case NT_S390_LAST_BREAK:
11389       if (note->namesz == 6
11390 	  && strcmp (note->namedata, "LINUX") == 0)
11391 	return elfcore_grok_s390_last_break (abfd, note);
11392       else
11393 	return true;
11394 
11395     case NT_S390_SYSTEM_CALL:
11396       if (note->namesz == 6
11397 	  && strcmp (note->namedata, "LINUX") == 0)
11398 	return elfcore_grok_s390_system_call (abfd, note);
11399       else
11400 	return true;
11401 
11402     case NT_S390_TDB:
11403       if (note->namesz == 6
11404 	  && strcmp (note->namedata, "LINUX") == 0)
11405 	return elfcore_grok_s390_tdb (abfd, note);
11406       else
11407 	return true;
11408 
11409     case NT_S390_VXRS_LOW:
11410       if (note->namesz == 6
11411 	  && strcmp (note->namedata, "LINUX") == 0)
11412 	return elfcore_grok_s390_vxrs_low (abfd, note);
11413       else
11414 	return true;
11415 
11416     case NT_S390_VXRS_HIGH:
11417       if (note->namesz == 6
11418 	  && strcmp (note->namedata, "LINUX") == 0)
11419 	return elfcore_grok_s390_vxrs_high (abfd, note);
11420       else
11421 	return true;
11422 
11423     case NT_S390_GS_CB:
11424       if (note->namesz == 6
11425 	  && strcmp (note->namedata, "LINUX") == 0)
11426 	return elfcore_grok_s390_gs_cb (abfd, note);
11427       else
11428 	return true;
11429 
11430     case NT_S390_GS_BC:
11431       if (note->namesz == 6
11432 	  && strcmp (note->namedata, "LINUX") == 0)
11433 	return elfcore_grok_s390_gs_bc (abfd, note);
11434       else
11435 	return true;
11436 
11437     case NT_ARC_V2:
11438       if (note->namesz == 6
11439 	  && strcmp (note->namedata, "LINUX") == 0)
11440 	return elfcore_grok_arc_v2 (abfd, note);
11441       else
11442 	return true;
11443 
11444     case NT_ARM_VFP:
11445       if (note->namesz == 6
11446 	  && strcmp (note->namedata, "LINUX") == 0)
11447 	return elfcore_grok_arm_vfp (abfd, note);
11448       else
11449 	return true;
11450 
11451     case NT_ARM_TLS:
11452       if (note->namesz == 6
11453 	  && strcmp (note->namedata, "LINUX") == 0)
11454 	return elfcore_grok_aarch_tls (abfd, note);
11455       else
11456 	return true;
11457 
11458     case NT_ARM_HW_BREAK:
11459       if (note->namesz == 6
11460 	  && strcmp (note->namedata, "LINUX") == 0)
11461 	return elfcore_grok_aarch_hw_break (abfd, note);
11462       else
11463 	return true;
11464 
11465     case NT_ARM_HW_WATCH:
11466       if (note->namesz == 6
11467 	  && strcmp (note->namedata, "LINUX") == 0)
11468 	return elfcore_grok_aarch_hw_watch (abfd, note);
11469       else
11470 	return true;
11471 
11472     case NT_ARM_SVE:
11473       if (note->namesz == 6
11474 	  && strcmp (note->namedata, "LINUX") == 0)
11475 	return elfcore_grok_aarch_sve (abfd, note);
11476       else
11477 	return true;
11478 
11479     case NT_ARM_PAC_MASK:
11480       if (note->namesz == 6
11481 	  && strcmp (note->namedata, "LINUX") == 0)
11482 	return elfcore_grok_aarch_pauth (abfd, note);
11483       else
11484 	return true;
11485 
11486     case NT_ARM_TAGGED_ADDR_CTRL:
11487       if (note->namesz == 6
11488 	  && strcmp (note->namedata, "LINUX") == 0)
11489 	return elfcore_grok_aarch_mte (abfd, note);
11490       else
11491 	return true;
11492 
11493     case NT_ARM_SSVE:
11494       if (note->namesz == 6
11495 	  && strcmp (note->namedata, "LINUX") == 0)
11496 	return elfcore_grok_aarch_ssve (abfd, note);
11497       else
11498 	return true;
11499 
11500     case NT_ARM_ZA:
11501       if (note->namesz == 6
11502 	  && strcmp (note->namedata, "LINUX") == 0)
11503 	return elfcore_grok_aarch_za (abfd, note);
11504       else
11505 	return true;
11506 
11507     case NT_ARM_ZT:
11508       if (note->namesz == 6
11509 	  && strcmp (note->namedata, "LINUX") == 0)
11510 	return elfcore_grok_aarch_zt (abfd, note);
11511       else
11512 	return true;
11513 
11514     case NT_GDB_TDESC:
11515       if (note->namesz == 4
11516 	  && strcmp (note->namedata, "GDB") == 0)
11517 	return elfcore_grok_gdb_tdesc (abfd, note);
11518       else
11519 	return true;
11520 
11521     case NT_RISCV_CSR:
11522       if (note->namesz == 4
11523 	  && strcmp (note->namedata, "GDB") == 0)
11524 	return elfcore_grok_riscv_csr (abfd, note);
11525       else
11526 	return true;
11527 
11528     case NT_LARCH_CPUCFG:
11529       if (note->namesz == 6
11530 	  && strcmp (note->namedata, "LINUX") == 0)
11531 	return elfcore_grok_loongarch_cpucfg (abfd, note);
11532       else
11533 	return true;
11534 
11535     case NT_LARCH_LBT:
11536       if (note->namesz == 6
11537 	  && strcmp (note->namedata, "LINUX") == 0)
11538 	return elfcore_grok_loongarch_lbt (abfd, note);
11539       else
11540 	return true;
11541 
11542     case NT_LARCH_LSX:
11543       if (note->namesz == 6
11544 	  && strcmp (note->namedata, "LINUX") == 0)
11545 	return elfcore_grok_loongarch_lsx (abfd, note);
11546       else
11547 	return true;
11548 
11549     case NT_LARCH_LASX:
11550       if (note->namesz == 6
11551 	  && strcmp (note->namedata, "LINUX") == 0)
11552 	return elfcore_grok_loongarch_lasx (abfd, note);
11553       else
11554 	return true;
11555 
11556     case NT_PRPSINFO:
11557     case NT_PSINFO:
11558       if (bed->elf_backend_grok_psinfo)
11559 	if ((*bed->elf_backend_grok_psinfo) (abfd, note))
11560 	  return true;
11561 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
11562       return elfcore_grok_psinfo (abfd, note);
11563 #else
11564       return true;
11565 #endif
11566 
11567     case NT_AUXV:
11568       return elfcore_make_auxv_note_section (abfd, note, 0);
11569 
11570     case NT_FILE:
11571       return elfcore_make_note_pseudosection (abfd, ".note.linuxcore.file",
11572 					      note);
11573 
11574     case NT_SIGINFO:
11575       return elfcore_make_note_pseudosection (abfd, ".note.linuxcore.siginfo",
11576 					      note);
11577 
11578     }
11579 }
11580 
11581 static bool
elfobj_grok_gnu_build_id(bfd * abfd,Elf_Internal_Note * note)11582 elfobj_grok_gnu_build_id (bfd *abfd, Elf_Internal_Note *note)
11583 {
11584   struct bfd_build_id* build_id;
11585 
11586   if (note->descsz == 0)
11587     return false;
11588 
11589   build_id = bfd_alloc (abfd, sizeof (struct bfd_build_id) - 1 + note->descsz);
11590   if (build_id == NULL)
11591     return false;
11592 
11593   build_id->size = note->descsz;
11594   memcpy (build_id->data, note->descdata, note->descsz);
11595   abfd->build_id = build_id;
11596 
11597   return true;
11598 }
11599 
11600 static bool
elfobj_grok_gnu_note(bfd * abfd,Elf_Internal_Note * note)11601 elfobj_grok_gnu_note (bfd *abfd, Elf_Internal_Note *note)
11602 {
11603   switch (note->type)
11604     {
11605     default:
11606       return true;
11607 
11608     case NT_GNU_PROPERTY_TYPE_0:
11609       return _bfd_elf_parse_gnu_properties (abfd, note);
11610 
11611     case NT_GNU_BUILD_ID:
11612       return elfobj_grok_gnu_build_id (abfd, note);
11613     }
11614 }
11615 
11616 static bool
elfobj_grok_stapsdt_note_1(bfd * abfd,Elf_Internal_Note * note)11617 elfobj_grok_stapsdt_note_1 (bfd *abfd, Elf_Internal_Note *note)
11618 {
11619   struct sdt_note *cur =
11620     (struct sdt_note *) bfd_alloc (abfd,
11621 				   sizeof (struct sdt_note) + note->descsz);
11622 
11623   cur->next = (struct sdt_note *) (elf_tdata (abfd))->sdt_note_head;
11624   cur->size = (bfd_size_type) note->descsz;
11625   memcpy (cur->data, note->descdata, note->descsz);
11626 
11627   elf_tdata (abfd)->sdt_note_head = cur;
11628 
11629   return true;
11630 }
11631 
11632 static bool
elfobj_grok_stapsdt_note(bfd * abfd,Elf_Internal_Note * note)11633 elfobj_grok_stapsdt_note (bfd *abfd, Elf_Internal_Note *note)
11634 {
11635   switch (note->type)
11636     {
11637     case NT_STAPSDT:
11638       return elfobj_grok_stapsdt_note_1 (abfd, note);
11639 
11640     default:
11641       return true;
11642     }
11643 }
11644 
11645 static bool
elfcore_grok_freebsd_psinfo(bfd * abfd,Elf_Internal_Note * note)11646 elfcore_grok_freebsd_psinfo (bfd *abfd, Elf_Internal_Note *note)
11647 {
11648   size_t offset;
11649 
11650   switch (elf_elfheader (abfd)->e_ident[EI_CLASS])
11651     {
11652     case ELFCLASS32:
11653       if (note->descsz < 108)
11654 	return false;
11655       break;
11656 
11657     case ELFCLASS64:
11658       if (note->descsz < 120)
11659 	return false;
11660       break;
11661 
11662     default:
11663       return false;
11664     }
11665 
11666   /* Check for version 1 in pr_version.  */
11667   if (bfd_h_get_32 (abfd, (bfd_byte *) note->descdata) != 1)
11668     return false;
11669 
11670   offset = 4;
11671 
11672   /* Skip over pr_psinfosz. */
11673   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS32)
11674     offset += 4;
11675   else
11676     {
11677       offset += 4;	/* Padding before pr_psinfosz. */
11678       offset += 8;
11679     }
11680 
11681   /* pr_fname is PRFNAMESZ (16) + 1 bytes in size.  */
11682   elf_tdata (abfd)->core->program
11683     = _bfd_elfcore_strndup (abfd, note->descdata + offset, 17);
11684   offset += 17;
11685 
11686   /* pr_psargs is PRARGSZ (80) + 1 bytes in size.  */
11687   elf_tdata (abfd)->core->command
11688     = _bfd_elfcore_strndup (abfd, note->descdata + offset, 81);
11689   offset += 81;
11690 
11691   /* Padding before pr_pid.  */
11692   offset += 2;
11693 
11694   /* The pr_pid field was added in version "1a".  */
11695   if (note->descsz < offset + 4)
11696     return true;
11697 
11698   elf_tdata (abfd)->core->pid
11699     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + offset);
11700 
11701   return true;
11702 }
11703 
11704 static bool
elfcore_grok_freebsd_prstatus(bfd * abfd,Elf_Internal_Note * note)11705 elfcore_grok_freebsd_prstatus (bfd *abfd, Elf_Internal_Note *note)
11706 {
11707   size_t offset;
11708   size_t size;
11709   size_t min_size;
11710 
11711   /* Compute offset of pr_getregsz, skipping over pr_statussz.
11712      Also compute minimum size of this note.  */
11713   switch (elf_elfheader (abfd)->e_ident[EI_CLASS])
11714     {
11715     case ELFCLASS32:
11716       offset = 4 + 4;
11717       min_size = offset + (4 * 2) + 4 + 4 + 4;
11718       break;
11719 
11720     case ELFCLASS64:
11721       offset = 4 + 4 + 8;	/* Includes padding before pr_statussz.  */
11722       min_size = offset + (8 * 2) + 4 + 4 + 4 + 4;
11723       break;
11724 
11725     default:
11726       return false;
11727     }
11728 
11729   if (note->descsz < min_size)
11730     return false;
11731 
11732   /* Check for version 1 in pr_version.  */
11733   if (bfd_h_get_32 (abfd, (bfd_byte *) note->descdata) != 1)
11734     return false;
11735 
11736   /* Extract size of pr_reg from pr_gregsetsz.  */
11737   /* Skip over pr_gregsetsz and pr_fpregsetsz.  */
11738   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS32)
11739     {
11740       size = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + offset);
11741       offset += 4 * 2;
11742     }
11743   else
11744     {
11745       size = bfd_h_get_64 (abfd, (bfd_byte *) note->descdata + offset);
11746       offset += 8 * 2;
11747     }
11748 
11749   /* Skip over pr_osreldate.  */
11750   offset += 4;
11751 
11752   /* Read signal from pr_cursig.  */
11753   if (elf_tdata (abfd)->core->signal == 0)
11754     elf_tdata (abfd)->core->signal
11755       = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + offset);
11756   offset += 4;
11757 
11758   /* Read TID from pr_pid.  */
11759   elf_tdata (abfd)->core->lwpid
11760       = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + offset);
11761   offset += 4;
11762 
11763   /* Padding before pr_reg.  */
11764   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
11765     offset += 4;
11766 
11767   /* Make sure that there is enough data remaining in the note.  */
11768   if ((note->descsz - offset) < size)
11769     return false;
11770 
11771   /* Make a ".reg/999" section and a ".reg" section.  */
11772   return _bfd_elfcore_make_pseudosection (abfd, ".reg",
11773 					  size, note->descpos + offset);
11774 }
11775 
11776 static bool
elfcore_grok_freebsd_note(bfd * abfd,Elf_Internal_Note * note)11777 elfcore_grok_freebsd_note (bfd *abfd, Elf_Internal_Note *note)
11778 {
11779   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11780 
11781   switch (note->type)
11782     {
11783     case NT_PRSTATUS:
11784       if (bed->elf_backend_grok_freebsd_prstatus)
11785 	if ((*bed->elf_backend_grok_freebsd_prstatus) (abfd, note))
11786 	  return true;
11787       return elfcore_grok_freebsd_prstatus (abfd, note);
11788 
11789     case NT_FPREGSET:
11790       return elfcore_grok_prfpreg (abfd, note);
11791 
11792     case NT_PRPSINFO:
11793       return elfcore_grok_freebsd_psinfo (abfd, note);
11794 
11795     case NT_FREEBSD_THRMISC:
11796       return elfcore_make_note_pseudosection (abfd, ".thrmisc", note);
11797 
11798     case NT_FREEBSD_PROCSTAT_PROC:
11799       return elfcore_make_note_pseudosection (abfd, ".note.freebsdcore.proc",
11800 					      note);
11801 
11802     case NT_FREEBSD_PROCSTAT_FILES:
11803       return elfcore_make_note_pseudosection (abfd, ".note.freebsdcore.files",
11804 					      note);
11805 
11806     case NT_FREEBSD_PROCSTAT_VMMAP:
11807       return elfcore_make_note_pseudosection (abfd, ".note.freebsdcore.vmmap",
11808 					      note);
11809 
11810     case NT_FREEBSD_PROCSTAT_AUXV:
11811       return elfcore_make_auxv_note_section (abfd, note, 4);
11812 
11813     case NT_FREEBSD_X86_SEGBASES:
11814       return elfcore_make_note_pseudosection (abfd, ".reg-x86-segbases", note);
11815 
11816     case NT_X86_XSTATE:
11817       return elfcore_grok_xstatereg (abfd, note);
11818 
11819     case NT_FREEBSD_PTLWPINFO:
11820       return elfcore_make_note_pseudosection (abfd, ".note.freebsdcore.lwpinfo",
11821 					      note);
11822 
11823     case NT_ARM_TLS:
11824       return elfcore_grok_aarch_tls (abfd, note);
11825 
11826     case NT_ARM_VFP:
11827       return elfcore_grok_arm_vfp (abfd, note);
11828 
11829     default:
11830       return true;
11831     }
11832 }
11833 
11834 static bool
elfcore_netbsd_get_lwpid(Elf_Internal_Note * note,int * lwpidp)11835 elfcore_netbsd_get_lwpid (Elf_Internal_Note *note, int *lwpidp)
11836 {
11837   char *cp;
11838 
11839   cp = strchr (note->namedata, '@');
11840   if (cp != NULL)
11841     {
11842       *lwpidp = atoi(cp + 1);
11843       return true;
11844     }
11845   return false;
11846 }
11847 
11848 static bool
elfcore_grok_netbsd_procinfo(bfd * abfd,Elf_Internal_Note * note)11849 elfcore_grok_netbsd_procinfo (bfd *abfd, Elf_Internal_Note *note)
11850 {
11851   if (note->descsz <= 0x7c + 31)
11852     return false;
11853 
11854   /* Signal number at offset 0x08. */
11855   elf_tdata (abfd)->core->signal
11856     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x08);
11857 
11858   /* Process ID at offset 0x50. */
11859   elf_tdata (abfd)->core->pid
11860     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x50);
11861 
11862   /* Command name at 0x7c (max 32 bytes, including nul). */
11863   elf_tdata (abfd)->core->command
11864     = _bfd_elfcore_strndup (abfd, note->descdata + 0x7c, 31);
11865 
11866   return elfcore_make_note_pseudosection (abfd, ".note.netbsdcore.procinfo",
11867 					  note);
11868 }
11869 
11870 static bool
elfcore_grok_netbsd_note(bfd * abfd,Elf_Internal_Note * note)11871 elfcore_grok_netbsd_note (bfd *abfd, Elf_Internal_Note *note)
11872 {
11873   int lwp;
11874 
11875   if (elfcore_netbsd_get_lwpid (note, &lwp))
11876     elf_tdata (abfd)->core->lwpid = lwp;
11877 
11878   switch (note->type)
11879     {
11880     case NT_NETBSDCORE_PROCINFO:
11881       /* NetBSD-specific core "procinfo".  Note that we expect to
11882 	 find this note before any of the others, which is fine,
11883 	 since the kernel writes this note out first when it
11884 	 creates a core file.  */
11885       return elfcore_grok_netbsd_procinfo (abfd, note);
11886     case NT_NETBSDCORE_AUXV:
11887       /* NetBSD-specific Elf Auxiliary Vector data. */
11888       return elfcore_make_auxv_note_section (abfd, note, 0);
11889     case NT_NETBSDCORE_LWPSTATUS:
11890       return elfcore_make_note_pseudosection (abfd,
11891 					      ".note.netbsdcore.lwpstatus",
11892 					      note);
11893     default:
11894       break;
11895     }
11896 
11897   /* As of March 2020 there are no other machine-independent notes
11898      defined for NetBSD core files.  If the note type is less
11899      than the start of the machine-dependent note types, we don't
11900      understand it.  */
11901 
11902   if (note->type < NT_NETBSDCORE_FIRSTMACH)
11903     return true;
11904 
11905 
11906   switch (bfd_get_arch (abfd))
11907     {
11908       /* On the Alpha, SPARC (32-bit and 64-bit), PT_GETREGS == mach+0 and
11909 	 PT_GETFPREGS == mach+2.  */
11910 
11911     case bfd_arch_aarch64:
11912     case bfd_arch_alpha:
11913     case bfd_arch_sparc:
11914       switch (note->type)
11915 	{
11916 	case NT_NETBSDCORE_FIRSTMACH+0:
11917 	  return elfcore_make_note_pseudosection (abfd, ".reg", note);
11918 
11919 	case NT_NETBSDCORE_FIRSTMACH+2:
11920 	  return elfcore_make_note_pseudosection (abfd, ".reg2", note);
11921 
11922 	default:
11923 	  return true;
11924 	}
11925 
11926       /* On SuperH, PT_GETREGS == mach+3 and PT_GETFPREGS == mach+5.
11927 	 There's also old PT___GETREGS40 == mach + 1 for old reg
11928 	 structure which lacks GBR.  */
11929 
11930     case bfd_arch_sh:
11931       switch (note->type)
11932 	{
11933 	case NT_NETBSDCORE_FIRSTMACH+3:
11934 	  return elfcore_make_note_pseudosection (abfd, ".reg", note);
11935 
11936 	case NT_NETBSDCORE_FIRSTMACH+5:
11937 	  return elfcore_make_note_pseudosection (abfd, ".reg2", note);
11938 
11939 	default:
11940 	  return true;
11941 	}
11942 
11943       /* On all other arch's, PT_GETREGS == mach+1 and
11944 	 PT_GETFPREGS == mach+3.  */
11945 
11946     default:
11947       switch (note->type)
11948 	{
11949 	case NT_NETBSDCORE_FIRSTMACH+1:
11950 	  return elfcore_make_note_pseudosection (abfd, ".reg", note);
11951 
11952 	case NT_NETBSDCORE_FIRSTMACH+3:
11953 	  return elfcore_make_note_pseudosection (abfd, ".reg2", note);
11954 
11955 	default:
11956 	  return true;
11957 	}
11958     }
11959     /* NOTREACHED */
11960 }
11961 
11962 static bool
elfcore_grok_openbsd_procinfo(bfd * abfd,Elf_Internal_Note * note)11963 elfcore_grok_openbsd_procinfo (bfd *abfd, Elf_Internal_Note *note)
11964 {
11965   if (note->descsz <= 0x48 + 31)
11966     return false;
11967 
11968   /* Signal number at offset 0x08. */
11969   elf_tdata (abfd)->core->signal
11970     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x08);
11971 
11972   /* Process ID at offset 0x20. */
11973   elf_tdata (abfd)->core->pid
11974     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x20);
11975 
11976   /* Command name at 0x48 (max 32 bytes, including nul). */
11977   elf_tdata (abfd)->core->command
11978     = _bfd_elfcore_strndup (abfd, note->descdata + 0x48, 31);
11979 
11980   return true;
11981 }
11982 
11983 /* Processes Solaris's process status note.
11984    sig_off ~ offsetof(prstatus_t, pr_cursig)
11985    pid_off ~ offsetof(prstatus_t, pr_pid)
11986    lwpid_off ~ offsetof(prstatus_t, pr_who)
11987    gregset_size ~ sizeof(gregset_t)
11988    gregset_offset ~ offsetof(prstatus_t, pr_reg)  */
11989 
11990 static bool
elfcore_grok_solaris_prstatus(bfd * abfd,Elf_Internal_Note * note,int sig_off,int pid_off,int lwpid_off,size_t gregset_size,size_t gregset_offset)11991 elfcore_grok_solaris_prstatus (bfd *abfd, Elf_Internal_Note* note, int sig_off,
11992 			       int pid_off, int lwpid_off, size_t gregset_size,
11993 			       size_t gregset_offset)
11994 {
11995   asection *sect = NULL;
11996   elf_tdata (abfd)->core->signal
11997     = bfd_get_16 (abfd, note->descdata + sig_off);
11998   elf_tdata (abfd)->core->pid
11999     = bfd_get_32 (abfd, note->descdata + pid_off);
12000   elf_tdata (abfd)->core->lwpid
12001     = bfd_get_32 (abfd, note->descdata + lwpid_off);
12002 
12003   sect = bfd_get_section_by_name (abfd, ".reg");
12004   if (sect != NULL)
12005     sect->size = gregset_size;
12006 
12007   return _bfd_elfcore_make_pseudosection (abfd, ".reg", gregset_size,
12008 					  note->descpos + gregset_offset);
12009 }
12010 
12011 /* Gets program and arguments from a core.
12012    prog_off ~ offsetof(prpsinfo | psinfo_t, pr_fname)
12013    comm_off ~ offsetof(prpsinfo | psinfo_t, pr_psargs)  */
12014 
12015 static bool
elfcore_grok_solaris_info(bfd * abfd,Elf_Internal_Note * note,int prog_off,int comm_off)12016 elfcore_grok_solaris_info(bfd *abfd, Elf_Internal_Note* note,
12017 			  int prog_off, int comm_off)
12018 {
12019   elf_tdata (abfd)->core->program
12020     = _bfd_elfcore_strndup (abfd, note->descdata + prog_off, 16);
12021   elf_tdata (abfd)->core->command
12022     = _bfd_elfcore_strndup (abfd, note->descdata + comm_off, 80);
12023 
12024   return true;
12025 }
12026 
12027 /* Processes Solaris's LWP status note.
12028    gregset_size ~ sizeof(gregset_t)
12029    gregset_off ~ offsetof(lwpstatus_t, pr_reg)
12030    fpregset_size ~ sizeof(fpregset_t)
12031    fpregset_off ~ offsetof(lwpstatus_t, pr_fpreg)  */
12032 
12033 static bool
elfcore_grok_solaris_lwpstatus(bfd * abfd,Elf_Internal_Note * note,size_t gregset_size,int gregset_off,size_t fpregset_size,int fpregset_off)12034 elfcore_grok_solaris_lwpstatus (bfd *abfd, Elf_Internal_Note* note,
12035 				size_t gregset_size, int gregset_off,
12036 				size_t fpregset_size, int fpregset_off)
12037 {
12038   asection *sect = NULL;
12039   char reg2_section_name[16] = { 0 };
12040 
12041   (void) snprintf (reg2_section_name, 16, "%s/%i", ".reg2",
12042 		   elf_tdata (abfd)->core->lwpid);
12043 
12044   /* offsetof(lwpstatus_t, pr_lwpid) */
12045   elf_tdata (abfd)->core->lwpid
12046     = bfd_get_32 (abfd, note->descdata + 4);
12047   /* offsetof(lwpstatus_t, pr_cursig) */
12048   elf_tdata (abfd)->core->signal
12049     = bfd_get_16 (abfd, note->descdata + 12);
12050 
12051   sect = bfd_get_section_by_name (abfd, ".reg");
12052   if (sect != NULL)
12053     sect->size = gregset_size;
12054   else if (!_bfd_elfcore_make_pseudosection (abfd, ".reg", gregset_size,
12055 					     note->descpos + gregset_off))
12056     return false;
12057 
12058   sect = bfd_get_section_by_name (abfd, reg2_section_name);
12059   if (sect != NULL)
12060     {
12061       sect->size = fpregset_size;
12062       sect->filepos = note->descpos + fpregset_off;
12063       sect->alignment_power = 2;
12064     }
12065   else if (!_bfd_elfcore_make_pseudosection (abfd, ".reg2", fpregset_size,
12066 					     note->descpos + fpregset_off))
12067     return false;
12068 
12069   return true;
12070 }
12071 
12072 static bool
elfcore_grok_solaris_note_impl(bfd * abfd,Elf_Internal_Note * note)12073 elfcore_grok_solaris_note_impl (bfd *abfd, Elf_Internal_Note *note)
12074 {
12075   if (note == NULL)
12076     return false;
12077 
12078   /* core files are identified as 32- or 64-bit, SPARC or x86,
12079      by the size of the descsz which matches the sizeof()
12080      the type appropriate for that note type (e.g., prstatus_t for
12081      SOLARIS_NT_PRSTATUS) for the corresponding architecture
12082      on Solaris. The core file bitness may differ from the bitness of
12083      gdb itself, so fixed values are used instead of sizeof().
12084      Appropriate fixed offsets are also used to obtain data from
12085      the note.  */
12086 
12087   switch ((int) note->type)
12088     {
12089     case SOLARIS_NT_PRSTATUS:
12090       switch (note->descsz)
12091 	{
12092 	case 508: /* sizeof(prstatus_t) SPARC 32-bit */
12093 	  return elfcore_grok_solaris_prstatus(abfd, note,
12094 					       136, 216, 308, 152, 356);
12095 	case 904: /* sizeof(prstatus_t) SPARC 64-bit */
12096 	  return elfcore_grok_solaris_prstatus(abfd, note,
12097 					       264, 360, 520, 304, 600);
12098 	case 432: /* sizeof(prstatus_t) Intel 32-bit */
12099 	  return elfcore_grok_solaris_prstatus(abfd, note,
12100 					       136, 216, 308, 76, 356);
12101 	case 824: /* sizeof(prstatus_t) Intel 64-bit */
12102 	  return elfcore_grok_solaris_prstatus(abfd, note,
12103 					       264, 360, 520, 224, 600);
12104 	default:
12105 	  return true;
12106 	}
12107 
12108     case SOLARIS_NT_PSINFO:
12109     case SOLARIS_NT_PRPSINFO:
12110       switch (note->descsz)
12111 	{
12112 	case 260: /* sizeof(prpsinfo_t) SPARC and Intel 32-bit */
12113 	  return elfcore_grok_solaris_info(abfd, note, 84, 100);
12114 	case 328: /* sizeof(prpsinfo_t) SPARC and Intel 64-bit */
12115 	  return elfcore_grok_solaris_info(abfd, note, 120, 136);
12116 	case 360: /* sizeof(psinfo_t) SPARC and Intel 32-bit */
12117 	  return elfcore_grok_solaris_info(abfd, note, 88, 104);
12118 	case 440: /* sizeof(psinfo_t) SPARC and Intel 64-bit */
12119 	  return elfcore_grok_solaris_info(abfd, note, 136, 152);
12120 	default:
12121 	  return true;
12122 	}
12123 
12124     case SOLARIS_NT_LWPSTATUS:
12125       switch (note->descsz)
12126 	{
12127 	case 896: /* sizeof(lwpstatus_t) SPARC 32-bit */
12128 	  return elfcore_grok_solaris_lwpstatus(abfd, note,
12129 						152, 344, 400, 496);
12130 	case 1392: /* sizeof(lwpstatus_t) SPARC 64-bit */
12131 	  return elfcore_grok_solaris_lwpstatus(abfd, note,
12132 						304, 544, 544, 848);
12133 	case 800: /* sizeof(lwpstatus_t) Intel 32-bit */
12134 	  return elfcore_grok_solaris_lwpstatus(abfd, note,
12135 						76, 344, 380, 420);
12136 	case 1296: /* sizeof(lwpstatus_t) Intel 64-bit */
12137 	  return elfcore_grok_solaris_lwpstatus(abfd, note,
12138 						224, 544, 528, 768);
12139 	default:
12140 	  return true;
12141 	}
12142 
12143     case SOLARIS_NT_LWPSINFO:
12144       /* sizeof(lwpsinfo_t) on 32- and 64-bit, respectively */
12145       if (note->descsz == 128 || note->descsz == 152)
12146 	elf_tdata (abfd)->core->lwpid =
12147 	  bfd_get_32 (abfd, note->descdata + 4);
12148       break;
12149 
12150     default:
12151       break;
12152     }
12153 
12154   return true;
12155 }
12156 
12157 /* For name starting with "CORE" this may be either a Solaris
12158    core file or a gdb-generated core file.  Do Solaris-specific
12159    processing on selected note types first with
12160    elfcore_grok_solaris_note(), then process the note
12161    in elfcore_grok_note().  */
12162 
12163 static bool
elfcore_grok_solaris_note(bfd * abfd,Elf_Internal_Note * note)12164 elfcore_grok_solaris_note (bfd *abfd, Elf_Internal_Note *note)
12165 {
12166   if (!elfcore_grok_solaris_note_impl (abfd, note))
12167     return false;
12168 
12169   return elfcore_grok_note (abfd, note);
12170 }
12171 
12172 static bool
elfcore_grok_openbsd_note(bfd * abfd,Elf_Internal_Note * note)12173 elfcore_grok_openbsd_note (bfd *abfd, Elf_Internal_Note *note)
12174 {
12175   if (note->type == NT_OPENBSD_PROCINFO)
12176     return elfcore_grok_openbsd_procinfo (abfd, note);
12177 
12178   if (note->type == NT_OPENBSD_REGS)
12179     return elfcore_make_note_pseudosection (abfd, ".reg", note);
12180 
12181   if (note->type == NT_OPENBSD_FPREGS)
12182     return elfcore_make_note_pseudosection (abfd, ".reg2", note);
12183 
12184   if (note->type == NT_OPENBSD_XFPREGS)
12185     return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
12186 
12187   if (note->type == NT_OPENBSD_AUXV)
12188     return elfcore_make_auxv_note_section (abfd, note, 0);
12189 
12190   if (note->type == NT_OPENBSD_WCOOKIE)
12191     {
12192       asection *sect = bfd_make_section_anyway_with_flags (abfd, ".wcookie",
12193 							   SEC_HAS_CONTENTS);
12194 
12195       if (sect == NULL)
12196 	return false;
12197       sect->size = note->descsz;
12198       sect->filepos = note->descpos;
12199       sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
12200 
12201       return true;
12202     }
12203 
12204   return true;
12205 }
12206 
12207 static bool
elfcore_grok_nto_status(bfd * abfd,Elf_Internal_Note * note,long * tid)12208 elfcore_grok_nto_status (bfd *abfd, Elf_Internal_Note *note, long *tid)
12209 {
12210   void *ddata = note->descdata;
12211   char buf[100];
12212   char *name;
12213   asection *sect;
12214   short sig;
12215   unsigned flags;
12216 
12217   if (note->descsz < 16)
12218     return false;
12219 
12220   /* nto_procfs_status 'pid' field is at offset 0.  */
12221   elf_tdata (abfd)->core->pid = bfd_get_32 (abfd, (bfd_byte *) ddata);
12222 
12223   /* nto_procfs_status 'tid' field is at offset 4.  Pass it back.  */
12224   *tid = bfd_get_32 (abfd, (bfd_byte *) ddata + 4);
12225 
12226   /* nto_procfs_status 'flags' field is at offset 8.  */
12227   flags = bfd_get_32 (abfd, (bfd_byte *) ddata + 8);
12228 
12229   /* nto_procfs_status 'what' field is at offset 14.  */
12230   if ((sig = bfd_get_16 (abfd, (bfd_byte *) ddata + 14)) > 0)
12231     {
12232       elf_tdata (abfd)->core->signal = sig;
12233       elf_tdata (abfd)->core->lwpid = *tid;
12234     }
12235 
12236   /* _DEBUG_FLAG_CURTID (current thread) is 0x80.  Some cores
12237      do not come from signals so we make sure we set the current
12238      thread just in case.  */
12239   if (flags & 0x00000080)
12240     elf_tdata (abfd)->core->lwpid = *tid;
12241 
12242   /* Make a ".qnx_core_status/%d" section.  */
12243   sprintf (buf, ".qnx_core_status/%ld", *tid);
12244 
12245   name = (char *) bfd_alloc (abfd, strlen (buf) + 1);
12246   if (name == NULL)
12247     return false;
12248   strcpy (name, buf);
12249 
12250   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
12251   if (sect == NULL)
12252     return false;
12253 
12254   sect->size		= note->descsz;
12255   sect->filepos		= note->descpos;
12256   sect->alignment_power = 2;
12257 
12258   return (elfcore_maybe_make_sect (abfd, ".qnx_core_status", sect));
12259 }
12260 
12261 static bool
elfcore_grok_nto_regs(bfd * abfd,Elf_Internal_Note * note,long tid,char * base)12262 elfcore_grok_nto_regs (bfd *abfd,
12263 		       Elf_Internal_Note *note,
12264 		       long tid,
12265 		       char *base)
12266 {
12267   char buf[100];
12268   char *name;
12269   asection *sect;
12270 
12271   /* Make a "(base)/%d" section.  */
12272   sprintf (buf, "%s/%ld", base, tid);
12273 
12274   name = (char *) bfd_alloc (abfd, strlen (buf) + 1);
12275   if (name == NULL)
12276     return false;
12277   strcpy (name, buf);
12278 
12279   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
12280   if (sect == NULL)
12281     return false;
12282 
12283   sect->size		= note->descsz;
12284   sect->filepos		= note->descpos;
12285   sect->alignment_power = 2;
12286 
12287   /* This is the current thread.  */
12288   if (elf_tdata (abfd)->core->lwpid == tid)
12289     return elfcore_maybe_make_sect (abfd, base, sect);
12290 
12291   return true;
12292 }
12293 
12294 static bool
elfcore_grok_nto_note(bfd * abfd,Elf_Internal_Note * note)12295 elfcore_grok_nto_note (bfd *abfd, Elf_Internal_Note *note)
12296 {
12297   /* Every GREG section has a STATUS section before it.  Store the
12298      tid from the previous call to pass down to the next gregs
12299      function.  */
12300   static long tid = 1;
12301 
12302   switch (note->type)
12303     {
12304     case QNT_CORE_INFO:
12305       return elfcore_make_note_pseudosection (abfd, ".qnx_core_info", note);
12306     case QNT_CORE_STATUS:
12307       return elfcore_grok_nto_status (abfd, note, &tid);
12308     case QNT_CORE_GREG:
12309       return elfcore_grok_nto_regs (abfd, note, tid, ".reg");
12310     case QNT_CORE_FPREG:
12311       return elfcore_grok_nto_regs (abfd, note, tid, ".reg2");
12312     default:
12313       return true;
12314     }
12315 }
12316 
12317 static bool
elfcore_grok_spu_note(bfd * abfd,Elf_Internal_Note * note)12318 elfcore_grok_spu_note (bfd *abfd, Elf_Internal_Note *note)
12319 {
12320   char *name;
12321   asection *sect;
12322   size_t len;
12323 
12324   /* Use note name as section name.  */
12325   len = note->namesz;
12326   name = (char *) bfd_alloc (abfd, len);
12327   if (name == NULL)
12328     return false;
12329   memcpy (name, note->namedata, len);
12330   name[len - 1] = '\0';
12331 
12332   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
12333   if (sect == NULL)
12334     return false;
12335 
12336   sect->size		= note->descsz;
12337   sect->filepos		= note->descpos;
12338   sect->alignment_power = 1;
12339 
12340   return true;
12341 }
12342 
12343 /* Function: elfcore_write_note
12344 
12345    Inputs:
12346      buffer to hold note, and current size of buffer
12347      name of note
12348      type of note
12349      data for note
12350      size of data for note
12351 
12352    Writes note to end of buffer.  ELF64 notes are written exactly as
12353    for ELF32, despite the current (as of 2006) ELF gabi specifying
12354    that they ought to have 8-byte namesz and descsz field, and have
12355    8-byte alignment.  Other writers, eg. Linux kernel, do the same.
12356 
12357    Return:
12358    Pointer to realloc'd buffer, *BUFSIZ updated.  */
12359 
12360 char *
elfcore_write_note(bfd * abfd,char * buf,int * bufsiz,const char * name,int type,const void * input,int size)12361 elfcore_write_note (bfd *abfd,
12362 		    char *buf,
12363 		    int *bufsiz,
12364 		    const char *name,
12365 		    int type,
12366 		    const void *input,
12367 		    int size)
12368 {
12369   Elf_External_Note *xnp;
12370   size_t namesz;
12371   size_t newspace;
12372   char *dest;
12373 
12374   namesz = 0;
12375   if (name != NULL)
12376     namesz = strlen (name) + 1;
12377 
12378   newspace = 12 + ((namesz + 3) & -4) + ((size + 3) & -4);
12379 
12380   buf = (char *) realloc (buf, *bufsiz + newspace);
12381   if (buf == NULL)
12382     return buf;
12383   dest = buf + *bufsiz;
12384   *bufsiz += newspace;
12385   xnp = (Elf_External_Note *) dest;
12386   H_PUT_32 (abfd, namesz, xnp->namesz);
12387   H_PUT_32 (abfd, size, xnp->descsz);
12388   H_PUT_32 (abfd, type, xnp->type);
12389   dest = xnp->name;
12390   if (name != NULL)
12391     {
12392       memcpy (dest, name, namesz);
12393       dest += namesz;
12394       while (namesz & 3)
12395 	{
12396 	  *dest++ = '\0';
12397 	  ++namesz;
12398 	}
12399     }
12400   memcpy (dest, input, size);
12401   dest += size;
12402   while (size & 3)
12403     {
12404       *dest++ = '\0';
12405       ++size;
12406     }
12407   return buf;
12408 }
12409 
12410 /* gcc-8 warns (*) on all the strncpy calls in this function about
12411    possible string truncation.  The "truncation" is not a bug.  We
12412    have an external representation of structs with fields that are not
12413    necessarily NULL terminated and corresponding internal
12414    representation fields that are one larger so that they can always
12415    be NULL terminated.
12416    gcc versions between 4.2 and 4.6 do not allow pragma control of
12417    diagnostics inside functions, giving a hard error if you try to use
12418    the finer control available with later versions.
12419    gcc prior to 4.2 warns about diagnostic push and pop.
12420    gcc-5, gcc-6 and gcc-7 warn that -Wstringop-truncation is unknown,
12421    unless you also add #pragma GCC diagnostic ignored "-Wpragma".
12422    (*) Depending on your system header files!  */
12423 #if GCC_VERSION >= 8000
12424 # pragma GCC diagnostic push
12425 # pragma GCC diagnostic ignored "-Wstringop-truncation"
12426 #endif
12427 char *
elfcore_write_prpsinfo(bfd * abfd,char * buf,int * bufsiz,const char * fname,const char * psargs)12428 elfcore_write_prpsinfo (bfd  *abfd,
12429 			char *buf,
12430 			int  *bufsiz,
12431 			const char *fname,
12432 			const char *psargs)
12433 {
12434   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12435 
12436   if (bed->elf_backend_write_core_note != NULL)
12437     {
12438       char *ret;
12439       ret = (*bed->elf_backend_write_core_note) (abfd, buf, bufsiz,
12440 						 NT_PRPSINFO, fname, psargs);
12441       if (ret != NULL)
12442 	return ret;
12443     }
12444 
12445 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
12446 # if defined (HAVE_PRPSINFO32_T) || defined (HAVE_PSINFO32_T)
12447   if (bed->s->elfclass == ELFCLASS32)
12448     {
12449 #  if defined (HAVE_PSINFO32_T)
12450       psinfo32_t data;
12451       int note_type = NT_PSINFO;
12452 #  else
12453       prpsinfo32_t data;
12454       int note_type = NT_PRPSINFO;
12455 #  endif
12456 
12457       memset (&data, 0, sizeof (data));
12458       strncpy (data.pr_fname, fname, sizeof (data.pr_fname));
12459       strncpy (data.pr_psargs, psargs, sizeof (data.pr_psargs));
12460       return elfcore_write_note (abfd, buf, bufsiz,
12461 				 "CORE", note_type, &data, sizeof (data));
12462     }
12463   else
12464 # endif
12465     {
12466 # if defined (HAVE_PSINFO_T)
12467       psinfo_t data;
12468       int note_type = NT_PSINFO;
12469 # else
12470       prpsinfo_t data;
12471       int note_type = NT_PRPSINFO;
12472 # endif
12473 
12474       memset (&data, 0, sizeof (data));
12475       strncpy (data.pr_fname, fname, sizeof (data.pr_fname));
12476       strncpy (data.pr_psargs, psargs, sizeof (data.pr_psargs));
12477       return elfcore_write_note (abfd, buf, bufsiz,
12478 				 "CORE", note_type, &data, sizeof (data));
12479     }
12480 #endif	/* PSINFO_T or PRPSINFO_T */
12481 
12482   free (buf);
12483   return NULL;
12484 }
12485 #if GCC_VERSION >= 8000
12486 # pragma GCC diagnostic pop
12487 #endif
12488 
12489 char *
elfcore_write_linux_prpsinfo32(bfd * abfd,char * buf,int * bufsiz,const struct elf_internal_linux_prpsinfo * prpsinfo)12490 elfcore_write_linux_prpsinfo32
12491   (bfd *abfd, char *buf, int *bufsiz,
12492    const struct elf_internal_linux_prpsinfo *prpsinfo)
12493 {
12494   if (get_elf_backend_data (abfd)->linux_prpsinfo32_ugid16)
12495     {
12496       struct elf_external_linux_prpsinfo32_ugid16 data;
12497 
12498       swap_linux_prpsinfo32_ugid16_out (abfd, prpsinfo, &data);
12499       return elfcore_write_note (abfd, buf, bufsiz, "CORE", NT_PRPSINFO,
12500 				 &data, sizeof (data));
12501     }
12502   else
12503     {
12504       struct elf_external_linux_prpsinfo32_ugid32 data;
12505 
12506       swap_linux_prpsinfo32_ugid32_out (abfd, prpsinfo, &data);
12507       return elfcore_write_note (abfd, buf, bufsiz, "CORE", NT_PRPSINFO,
12508 				 &data, sizeof (data));
12509     }
12510 }
12511 
12512 char *
elfcore_write_linux_prpsinfo64(bfd * abfd,char * buf,int * bufsiz,const struct elf_internal_linux_prpsinfo * prpsinfo)12513 elfcore_write_linux_prpsinfo64
12514   (bfd *abfd, char *buf, int *bufsiz,
12515    const struct elf_internal_linux_prpsinfo *prpsinfo)
12516 {
12517   if (get_elf_backend_data (abfd)->linux_prpsinfo64_ugid16)
12518     {
12519       struct elf_external_linux_prpsinfo64_ugid16 data;
12520 
12521       swap_linux_prpsinfo64_ugid16_out (abfd, prpsinfo, &data);
12522       return elfcore_write_note (abfd, buf, bufsiz,
12523 				 "CORE", NT_PRPSINFO, &data, sizeof (data));
12524     }
12525   else
12526     {
12527       struct elf_external_linux_prpsinfo64_ugid32 data;
12528 
12529       swap_linux_prpsinfo64_ugid32_out (abfd, prpsinfo, &data);
12530       return elfcore_write_note (abfd, buf, bufsiz,
12531 				 "CORE", NT_PRPSINFO, &data, sizeof (data));
12532     }
12533 }
12534 
12535 char *
elfcore_write_prstatus(bfd * abfd,char * buf,int * bufsiz,long pid,int cursig,const void * gregs)12536 elfcore_write_prstatus (bfd *abfd,
12537 			char *buf,
12538 			int *bufsiz,
12539 			long pid,
12540 			int cursig,
12541 			const void *gregs)
12542 {
12543   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12544 
12545   if (bed->elf_backend_write_core_note != NULL)
12546     {
12547       char *ret;
12548       ret = (*bed->elf_backend_write_core_note) (abfd, buf, bufsiz,
12549 						 NT_PRSTATUS,
12550 						 pid, cursig, gregs);
12551       if (ret != NULL)
12552 	return ret;
12553     }
12554 
12555 #if defined (HAVE_PRSTATUS_T)
12556 #if defined (HAVE_PRSTATUS32_T)
12557   if (bed->s->elfclass == ELFCLASS32)
12558     {
12559       prstatus32_t prstat;
12560 
12561       memset (&prstat, 0, sizeof (prstat));
12562       prstat.pr_pid = pid;
12563       prstat.pr_cursig = cursig;
12564       memcpy (&prstat.pr_reg, gregs, sizeof (prstat.pr_reg));
12565       return elfcore_write_note (abfd, buf, bufsiz, "CORE",
12566 				 NT_PRSTATUS, &prstat, sizeof (prstat));
12567     }
12568   else
12569 #endif
12570     {
12571       prstatus_t prstat;
12572 
12573       memset (&prstat, 0, sizeof (prstat));
12574       prstat.pr_pid = pid;
12575       prstat.pr_cursig = cursig;
12576       memcpy (&prstat.pr_reg, gregs, sizeof (prstat.pr_reg));
12577       return elfcore_write_note (abfd, buf, bufsiz, "CORE",
12578 				 NT_PRSTATUS, &prstat, sizeof (prstat));
12579     }
12580 #endif /* HAVE_PRSTATUS_T */
12581 
12582   free (buf);
12583   return NULL;
12584 }
12585 
12586 #if defined (HAVE_LWPSTATUS_T)
12587 char *
elfcore_write_lwpstatus(bfd * abfd,char * buf,int * bufsiz,long pid,int cursig,const void * gregs)12588 elfcore_write_lwpstatus (bfd *abfd,
12589 			 char *buf,
12590 			 int *bufsiz,
12591 			 long pid,
12592 			 int cursig,
12593 			 const void *gregs)
12594 {
12595   lwpstatus_t lwpstat;
12596   const char *note_name = "CORE";
12597 
12598   memset (&lwpstat, 0, sizeof (lwpstat));
12599   lwpstat.pr_lwpid  = pid >> 16;
12600   lwpstat.pr_cursig = cursig;
12601 #if defined (HAVE_LWPSTATUS_T_PR_REG)
12602   memcpy (&lwpstat.pr_reg, gregs, sizeof (lwpstat.pr_reg));
12603 #elif defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
12604 #if !defined(gregs)
12605   memcpy (lwpstat.pr_context.uc_mcontext.gregs,
12606 	  gregs, sizeof (lwpstat.pr_context.uc_mcontext.gregs));
12607 #else
12608   memcpy (lwpstat.pr_context.uc_mcontext.__gregs,
12609 	  gregs, sizeof (lwpstat.pr_context.uc_mcontext.__gregs));
12610 #endif
12611 #endif
12612   return elfcore_write_note (abfd, buf, bufsiz, note_name,
12613 			     NT_LWPSTATUS, &lwpstat, sizeof (lwpstat));
12614 }
12615 #endif /* HAVE_LWPSTATUS_T */
12616 
12617 #if defined (HAVE_PSTATUS_T)
12618 char *
elfcore_write_pstatus(bfd * abfd,char * buf,int * bufsiz,long pid,int cursig ATTRIBUTE_UNUSED,const void * gregs ATTRIBUTE_UNUSED)12619 elfcore_write_pstatus (bfd *abfd,
12620 		       char *buf,
12621 		       int *bufsiz,
12622 		       long pid,
12623 		       int cursig ATTRIBUTE_UNUSED,
12624 		       const void *gregs ATTRIBUTE_UNUSED)
12625 {
12626   const char *note_name = "CORE";
12627 #if defined (HAVE_PSTATUS32_T)
12628   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12629 
12630   if (bed->s->elfclass == ELFCLASS32)
12631     {
12632       pstatus32_t pstat;
12633 
12634       memset (&pstat, 0, sizeof (pstat));
12635       pstat.pr_pid = pid & 0xffff;
12636       buf = elfcore_write_note (abfd, buf, bufsiz, note_name,
12637 				NT_PSTATUS, &pstat, sizeof (pstat));
12638       return buf;
12639     }
12640   else
12641 #endif
12642     {
12643       pstatus_t pstat;
12644 
12645       memset (&pstat, 0, sizeof (pstat));
12646       pstat.pr_pid = pid & 0xffff;
12647       buf = elfcore_write_note (abfd, buf, bufsiz, note_name,
12648 				NT_PSTATUS, &pstat, sizeof (pstat));
12649       return buf;
12650     }
12651 }
12652 #endif /* HAVE_PSTATUS_T */
12653 
12654 char *
elfcore_write_prfpreg(bfd * abfd,char * buf,int * bufsiz,const void * fpregs,int size)12655 elfcore_write_prfpreg (bfd *abfd,
12656 		       char *buf,
12657 		       int *bufsiz,
12658 		       const void *fpregs,
12659 		       int size)
12660 {
12661   const char *note_name = "CORE";
12662   return elfcore_write_note (abfd, buf, bufsiz,
12663 			     note_name, NT_FPREGSET, fpregs, size);
12664 }
12665 
12666 char *
elfcore_write_prxfpreg(bfd * abfd,char * buf,int * bufsiz,const void * xfpregs,int size)12667 elfcore_write_prxfpreg (bfd *abfd,
12668 			char *buf,
12669 			int *bufsiz,
12670 			const void *xfpregs,
12671 			int size)
12672 {
12673   char *note_name = "LINUX";
12674   return elfcore_write_note (abfd, buf, bufsiz,
12675 			     note_name, NT_PRXFPREG, xfpregs, size);
12676 }
12677 
12678 char *
elfcore_write_xstatereg(bfd * abfd,char * buf,int * bufsiz,const void * xfpregs,int size)12679 elfcore_write_xstatereg (bfd *abfd, char *buf, int *bufsiz,
12680 			 const void *xfpregs, int size)
12681 {
12682   char *note_name;
12683   if (get_elf_backend_data (abfd)->elf_osabi == ELFOSABI_FREEBSD)
12684     note_name = "FreeBSD";
12685   else
12686     note_name = "LINUX";
12687   return elfcore_write_note (abfd, buf, bufsiz,
12688 			     note_name, NT_X86_XSTATE, xfpregs, size);
12689 }
12690 
12691 char *
elfcore_write_x86_segbases(bfd * abfd,char * buf,int * bufsiz,const void * regs,int size)12692 elfcore_write_x86_segbases (bfd *abfd, char *buf, int *bufsiz,
12693 			    const void *regs, int size)
12694 {
12695   char *note_name = "FreeBSD";
12696   return elfcore_write_note (abfd, buf, bufsiz,
12697 			     note_name, NT_FREEBSD_X86_SEGBASES, regs, size);
12698 }
12699 
12700 char *
elfcore_write_ppc_vmx(bfd * abfd,char * buf,int * bufsiz,const void * ppc_vmx,int size)12701 elfcore_write_ppc_vmx (bfd *abfd,
12702 		       char *buf,
12703 		       int *bufsiz,
12704 		       const void *ppc_vmx,
12705 		       int size)
12706 {
12707   char *note_name = "LINUX";
12708   return elfcore_write_note (abfd, buf, bufsiz,
12709 			     note_name, NT_PPC_VMX, ppc_vmx, size);
12710 }
12711 
12712 char *
elfcore_write_ppc_vsx(bfd * abfd,char * buf,int * bufsiz,const void * ppc_vsx,int size)12713 elfcore_write_ppc_vsx (bfd *abfd,
12714 		       char *buf,
12715 		       int *bufsiz,
12716 		       const void *ppc_vsx,
12717 		       int size)
12718 {
12719   char *note_name = "LINUX";
12720   return elfcore_write_note (abfd, buf, bufsiz,
12721 			     note_name, NT_PPC_VSX, ppc_vsx, size);
12722 }
12723 
12724 char *
elfcore_write_ppc_tar(bfd * abfd,char * buf,int * bufsiz,const void * ppc_tar,int size)12725 elfcore_write_ppc_tar (bfd *abfd,
12726 		       char *buf,
12727 		       int *bufsiz,
12728 		       const void *ppc_tar,
12729 		       int size)
12730 {
12731   char *note_name = "LINUX";
12732   return elfcore_write_note (abfd, buf, bufsiz,
12733 			     note_name, NT_PPC_TAR, ppc_tar, size);
12734 }
12735 
12736 char *
elfcore_write_ppc_ppr(bfd * abfd,char * buf,int * bufsiz,const void * ppc_ppr,int size)12737 elfcore_write_ppc_ppr (bfd *abfd,
12738 		       char *buf,
12739 		       int *bufsiz,
12740 		       const void *ppc_ppr,
12741 		       int size)
12742 {
12743   char *note_name = "LINUX";
12744   return elfcore_write_note (abfd, buf, bufsiz,
12745 			     note_name, NT_PPC_PPR, ppc_ppr, size);
12746 }
12747 
12748 char *
elfcore_write_ppc_dscr(bfd * abfd,char * buf,int * bufsiz,const void * ppc_dscr,int size)12749 elfcore_write_ppc_dscr (bfd *abfd,
12750 			char *buf,
12751 			int *bufsiz,
12752 			const void *ppc_dscr,
12753 			int size)
12754 {
12755   char *note_name = "LINUX";
12756   return elfcore_write_note (abfd, buf, bufsiz,
12757 			     note_name, NT_PPC_DSCR, ppc_dscr, size);
12758 }
12759 
12760 char *
elfcore_write_ppc_ebb(bfd * abfd,char * buf,int * bufsiz,const void * ppc_ebb,int size)12761 elfcore_write_ppc_ebb (bfd *abfd,
12762 		       char *buf,
12763 		       int *bufsiz,
12764 		       const void *ppc_ebb,
12765 		       int size)
12766 {
12767   char *note_name = "LINUX";
12768   return elfcore_write_note (abfd, buf, bufsiz,
12769 			     note_name, NT_PPC_EBB, ppc_ebb, size);
12770 }
12771 
12772 char *
elfcore_write_ppc_pmu(bfd * abfd,char * buf,int * bufsiz,const void * ppc_pmu,int size)12773 elfcore_write_ppc_pmu (bfd *abfd,
12774 		       char *buf,
12775 		       int *bufsiz,
12776 		       const void *ppc_pmu,
12777 		       int size)
12778 {
12779   char *note_name = "LINUX";
12780   return elfcore_write_note (abfd, buf, bufsiz,
12781 			     note_name, NT_PPC_PMU, ppc_pmu, size);
12782 }
12783 
12784 char *
elfcore_write_ppc_tm_cgpr(bfd * abfd,char * buf,int * bufsiz,const void * ppc_tm_cgpr,int size)12785 elfcore_write_ppc_tm_cgpr (bfd *abfd,
12786 			   char *buf,
12787 			   int *bufsiz,
12788 			   const void *ppc_tm_cgpr,
12789 			   int size)
12790 {
12791   char *note_name = "LINUX";
12792   return elfcore_write_note (abfd, buf, bufsiz,
12793 			     note_name, NT_PPC_TM_CGPR, ppc_tm_cgpr, size);
12794 }
12795 
12796 char *
elfcore_write_ppc_tm_cfpr(bfd * abfd,char * buf,int * bufsiz,const void * ppc_tm_cfpr,int size)12797 elfcore_write_ppc_tm_cfpr (bfd *abfd,
12798 			   char *buf,
12799 			   int *bufsiz,
12800 			   const void *ppc_tm_cfpr,
12801 			   int size)
12802 {
12803   char *note_name = "LINUX";
12804   return elfcore_write_note (abfd, buf, bufsiz,
12805 			     note_name, NT_PPC_TM_CFPR, ppc_tm_cfpr, size);
12806 }
12807 
12808 char *
elfcore_write_ppc_tm_cvmx(bfd * abfd,char * buf,int * bufsiz,const void * ppc_tm_cvmx,int size)12809 elfcore_write_ppc_tm_cvmx (bfd *abfd,
12810 			   char *buf,
12811 			   int *bufsiz,
12812 			   const void *ppc_tm_cvmx,
12813 			   int size)
12814 {
12815   char *note_name = "LINUX";
12816   return elfcore_write_note (abfd, buf, bufsiz,
12817 			     note_name, NT_PPC_TM_CVMX, ppc_tm_cvmx, size);
12818 }
12819 
12820 char *
elfcore_write_ppc_tm_cvsx(bfd * abfd,char * buf,int * bufsiz,const void * ppc_tm_cvsx,int size)12821 elfcore_write_ppc_tm_cvsx (bfd *abfd,
12822 			   char *buf,
12823 			   int *bufsiz,
12824 			   const void *ppc_tm_cvsx,
12825 			   int size)
12826 {
12827   char *note_name = "LINUX";
12828   return elfcore_write_note (abfd, buf, bufsiz,
12829 			     note_name, NT_PPC_TM_CVSX, ppc_tm_cvsx, size);
12830 }
12831 
12832 char *
elfcore_write_ppc_tm_spr(bfd * abfd,char * buf,int * bufsiz,const void * ppc_tm_spr,int size)12833 elfcore_write_ppc_tm_spr (bfd *abfd,
12834 			  char *buf,
12835 			  int *bufsiz,
12836 			  const void *ppc_tm_spr,
12837 			  int size)
12838 {
12839   char *note_name = "LINUX";
12840   return elfcore_write_note (abfd, buf, bufsiz,
12841 			     note_name, NT_PPC_TM_SPR, ppc_tm_spr, size);
12842 }
12843 
12844 char *
elfcore_write_ppc_tm_ctar(bfd * abfd,char * buf,int * bufsiz,const void * ppc_tm_ctar,int size)12845 elfcore_write_ppc_tm_ctar (bfd *abfd,
12846 			   char *buf,
12847 			   int *bufsiz,
12848 			   const void *ppc_tm_ctar,
12849 			   int size)
12850 {
12851   char *note_name = "LINUX";
12852   return elfcore_write_note (abfd, buf, bufsiz,
12853 			     note_name, NT_PPC_TM_CTAR, ppc_tm_ctar, size);
12854 }
12855 
12856 char *
elfcore_write_ppc_tm_cppr(bfd * abfd,char * buf,int * bufsiz,const void * ppc_tm_cppr,int size)12857 elfcore_write_ppc_tm_cppr (bfd *abfd,
12858 			   char *buf,
12859 			   int *bufsiz,
12860 			   const void *ppc_tm_cppr,
12861 			   int size)
12862 {
12863   char *note_name = "LINUX";
12864   return elfcore_write_note (abfd, buf, bufsiz,
12865 			     note_name, NT_PPC_TM_CPPR, ppc_tm_cppr, size);
12866 }
12867 
12868 char *
elfcore_write_ppc_tm_cdscr(bfd * abfd,char * buf,int * bufsiz,const void * ppc_tm_cdscr,int size)12869 elfcore_write_ppc_tm_cdscr (bfd *abfd,
12870 			    char *buf,
12871 			    int *bufsiz,
12872 			    const void *ppc_tm_cdscr,
12873 			    int size)
12874 {
12875   char *note_name = "LINUX";
12876   return elfcore_write_note (abfd, buf, bufsiz,
12877 			     note_name, NT_PPC_TM_CDSCR, ppc_tm_cdscr, size);
12878 }
12879 
12880 static char *
elfcore_write_s390_high_gprs(bfd * abfd,char * buf,int * bufsiz,const void * s390_high_gprs,int size)12881 elfcore_write_s390_high_gprs (bfd *abfd,
12882 			      char *buf,
12883 			      int *bufsiz,
12884 			      const void *s390_high_gprs,
12885 			      int size)
12886 {
12887   char *note_name = "LINUX";
12888   return elfcore_write_note (abfd, buf, bufsiz,
12889 			     note_name, NT_S390_HIGH_GPRS,
12890 			     s390_high_gprs, size);
12891 }
12892 
12893 char *
elfcore_write_s390_timer(bfd * abfd,char * buf,int * bufsiz,const void * s390_timer,int size)12894 elfcore_write_s390_timer (bfd *abfd,
12895 			  char *buf,
12896 			  int *bufsiz,
12897 			  const void *s390_timer,
12898 			  int size)
12899 {
12900   char *note_name = "LINUX";
12901   return elfcore_write_note (abfd, buf, bufsiz,
12902 			     note_name, NT_S390_TIMER, s390_timer, size);
12903 }
12904 
12905 char *
elfcore_write_s390_todcmp(bfd * abfd,char * buf,int * bufsiz,const void * s390_todcmp,int size)12906 elfcore_write_s390_todcmp (bfd *abfd,
12907 			   char *buf,
12908 			   int *bufsiz,
12909 			   const void *s390_todcmp,
12910 			   int size)
12911 {
12912   char *note_name = "LINUX";
12913   return elfcore_write_note (abfd, buf, bufsiz,
12914 			     note_name, NT_S390_TODCMP, s390_todcmp, size);
12915 }
12916 
12917 char *
elfcore_write_s390_todpreg(bfd * abfd,char * buf,int * bufsiz,const void * s390_todpreg,int size)12918 elfcore_write_s390_todpreg (bfd *abfd,
12919 			    char *buf,
12920 			    int *bufsiz,
12921 			    const void *s390_todpreg,
12922 			    int size)
12923 {
12924   char *note_name = "LINUX";
12925   return elfcore_write_note (abfd, buf, bufsiz,
12926 			     note_name, NT_S390_TODPREG, s390_todpreg, size);
12927 }
12928 
12929 char *
elfcore_write_s390_ctrs(bfd * abfd,char * buf,int * bufsiz,const void * s390_ctrs,int size)12930 elfcore_write_s390_ctrs (bfd *abfd,
12931 			 char *buf,
12932 			 int *bufsiz,
12933 			 const void *s390_ctrs,
12934 			 int size)
12935 {
12936   char *note_name = "LINUX";
12937   return elfcore_write_note (abfd, buf, bufsiz,
12938 			     note_name, NT_S390_CTRS, s390_ctrs, size);
12939 }
12940 
12941 char *
elfcore_write_s390_prefix(bfd * abfd,char * buf,int * bufsiz,const void * s390_prefix,int size)12942 elfcore_write_s390_prefix (bfd *abfd,
12943 			   char *buf,
12944 			   int *bufsiz,
12945 			   const void *s390_prefix,
12946 			   int size)
12947 {
12948   char *note_name = "LINUX";
12949   return elfcore_write_note (abfd, buf, bufsiz,
12950 			     note_name, NT_S390_PREFIX, s390_prefix, size);
12951 }
12952 
12953 char *
elfcore_write_s390_last_break(bfd * abfd,char * buf,int * bufsiz,const void * s390_last_break,int size)12954 elfcore_write_s390_last_break (bfd *abfd,
12955 			       char *buf,
12956 			       int *bufsiz,
12957 			       const void *s390_last_break,
12958 			       int size)
12959 {
12960   char *note_name = "LINUX";
12961   return elfcore_write_note (abfd, buf, bufsiz,
12962 			     note_name, NT_S390_LAST_BREAK,
12963 			     s390_last_break, size);
12964 }
12965 
12966 char *
elfcore_write_s390_system_call(bfd * abfd,char * buf,int * bufsiz,const void * s390_system_call,int size)12967 elfcore_write_s390_system_call (bfd *abfd,
12968 				char *buf,
12969 				int *bufsiz,
12970 				const void *s390_system_call,
12971 				int size)
12972 {
12973   char *note_name = "LINUX";
12974   return elfcore_write_note (abfd, buf, bufsiz,
12975 			     note_name, NT_S390_SYSTEM_CALL,
12976 			     s390_system_call, size);
12977 }
12978 
12979 char *
elfcore_write_s390_tdb(bfd * abfd,char * buf,int * bufsiz,const void * s390_tdb,int size)12980 elfcore_write_s390_tdb (bfd *abfd,
12981 			char *buf,
12982 			int *bufsiz,
12983 			const void *s390_tdb,
12984 			int size)
12985 {
12986   char *note_name = "LINUX";
12987   return elfcore_write_note (abfd, buf, bufsiz,
12988 			     note_name, NT_S390_TDB, s390_tdb, size);
12989 }
12990 
12991 char *
elfcore_write_s390_vxrs_low(bfd * abfd,char * buf,int * bufsiz,const void * s390_vxrs_low,int size)12992 elfcore_write_s390_vxrs_low (bfd *abfd,
12993 			     char *buf,
12994 			     int *bufsiz,
12995 			     const void *s390_vxrs_low,
12996 			     int size)
12997 {
12998   char *note_name = "LINUX";
12999   return elfcore_write_note (abfd, buf, bufsiz,
13000 			     note_name, NT_S390_VXRS_LOW, s390_vxrs_low, size);
13001 }
13002 
13003 char *
elfcore_write_s390_vxrs_high(bfd * abfd,char * buf,int * bufsiz,const void * s390_vxrs_high,int size)13004 elfcore_write_s390_vxrs_high (bfd *abfd,
13005 			     char *buf,
13006 			     int *bufsiz,
13007 			     const void *s390_vxrs_high,
13008 			     int size)
13009 {
13010   char *note_name = "LINUX";
13011   return elfcore_write_note (abfd, buf, bufsiz,
13012 			     note_name, NT_S390_VXRS_HIGH,
13013 			     s390_vxrs_high, size);
13014 }
13015 
13016 char *
elfcore_write_s390_gs_cb(bfd * abfd,char * buf,int * bufsiz,const void * s390_gs_cb,int size)13017 elfcore_write_s390_gs_cb (bfd *abfd,
13018 			  char *buf,
13019 			  int *bufsiz,
13020 			  const void *s390_gs_cb,
13021 			  int size)
13022 {
13023   char *note_name = "LINUX";
13024   return elfcore_write_note (abfd, buf, bufsiz,
13025 			     note_name, NT_S390_GS_CB,
13026 			     s390_gs_cb, size);
13027 }
13028 
13029 char *
elfcore_write_s390_gs_bc(bfd * abfd,char * buf,int * bufsiz,const void * s390_gs_bc,int size)13030 elfcore_write_s390_gs_bc (bfd *abfd,
13031 			  char *buf,
13032 			  int *bufsiz,
13033 			  const void *s390_gs_bc,
13034 			  int size)
13035 {
13036   char *note_name = "LINUX";
13037   return elfcore_write_note (abfd, buf, bufsiz,
13038 			     note_name, NT_S390_GS_BC,
13039 			     s390_gs_bc, size);
13040 }
13041 
13042 char *
elfcore_write_arm_vfp(bfd * abfd,char * buf,int * bufsiz,const void * arm_vfp,int size)13043 elfcore_write_arm_vfp (bfd *abfd,
13044 		       char *buf,
13045 		       int *bufsiz,
13046 		       const void *arm_vfp,
13047 		       int size)
13048 {
13049   char *note_name = "LINUX";
13050   return elfcore_write_note (abfd, buf, bufsiz,
13051 			     note_name, NT_ARM_VFP, arm_vfp, size);
13052 }
13053 
13054 char *
elfcore_write_aarch_tls(bfd * abfd,char * buf,int * bufsiz,const void * aarch_tls,int size)13055 elfcore_write_aarch_tls (bfd *abfd,
13056 		       char *buf,
13057 		       int *bufsiz,
13058 		       const void *aarch_tls,
13059 		       int size)
13060 {
13061   char *note_name = "LINUX";
13062   return elfcore_write_note (abfd, buf, bufsiz,
13063 			     note_name, NT_ARM_TLS, aarch_tls, size);
13064 }
13065 
13066 char *
elfcore_write_aarch_hw_break(bfd * abfd,char * buf,int * bufsiz,const void * aarch_hw_break,int size)13067 elfcore_write_aarch_hw_break (bfd *abfd,
13068 			    char *buf,
13069 			    int *bufsiz,
13070 			    const void *aarch_hw_break,
13071 			    int size)
13072 {
13073   char *note_name = "LINUX";
13074   return elfcore_write_note (abfd, buf, bufsiz,
13075 			     note_name, NT_ARM_HW_BREAK, aarch_hw_break, size);
13076 }
13077 
13078 char *
elfcore_write_aarch_hw_watch(bfd * abfd,char * buf,int * bufsiz,const void * aarch_hw_watch,int size)13079 elfcore_write_aarch_hw_watch (bfd *abfd,
13080 			    char *buf,
13081 			    int *bufsiz,
13082 			    const void *aarch_hw_watch,
13083 			    int size)
13084 {
13085   char *note_name = "LINUX";
13086   return elfcore_write_note (abfd, buf, bufsiz,
13087 			     note_name, NT_ARM_HW_WATCH, aarch_hw_watch, size);
13088 }
13089 
13090 char *
elfcore_write_aarch_sve(bfd * abfd,char * buf,int * bufsiz,const void * aarch_sve,int size)13091 elfcore_write_aarch_sve (bfd *abfd,
13092 			 char *buf,
13093 			 int *bufsiz,
13094 			 const void *aarch_sve,
13095 			 int size)
13096 {
13097   char *note_name = "LINUX";
13098   return elfcore_write_note (abfd, buf, bufsiz,
13099 			     note_name, NT_ARM_SVE, aarch_sve, size);
13100 }
13101 
13102 char *
elfcore_write_aarch_pauth(bfd * abfd,char * buf,int * bufsiz,const void * aarch_pauth,int size)13103 elfcore_write_aarch_pauth (bfd *abfd,
13104 			   char *buf,
13105 			   int *bufsiz,
13106 			   const void *aarch_pauth,
13107 			   int size)
13108 {
13109   char *note_name = "LINUX";
13110   return elfcore_write_note (abfd, buf, bufsiz,
13111 			     note_name, NT_ARM_PAC_MASK, aarch_pauth, size);
13112 }
13113 
13114 char *
elfcore_write_aarch_mte(bfd * abfd,char * buf,int * bufsiz,const void * aarch_mte,int size)13115 elfcore_write_aarch_mte (bfd *abfd,
13116 				      char *buf,
13117 				      int *bufsiz,
13118 				      const void *aarch_mte,
13119 				      int size)
13120 {
13121   char *note_name = "LINUX";
13122   return elfcore_write_note (abfd, buf, bufsiz,
13123 			     note_name, NT_ARM_TAGGED_ADDR_CTRL,
13124 			     aarch_mte,
13125 			     size);
13126 }
13127 
13128 char *
elfcore_write_aarch_ssve(bfd * abfd,char * buf,int * bufsiz,const void * aarch_ssve,int size)13129 elfcore_write_aarch_ssve (bfd *abfd,
13130 			  char *buf,
13131 			  int *bufsiz,
13132 			  const void *aarch_ssve,
13133 			  int size)
13134 {
13135   char *note_name = "LINUX";
13136   return elfcore_write_note (abfd, buf, bufsiz,
13137 			     note_name, NT_ARM_SSVE,
13138 			     aarch_ssve,
13139 			     size);
13140 }
13141 
13142 char *
elfcore_write_aarch_za(bfd * abfd,char * buf,int * bufsiz,const void * aarch_za,int size)13143 elfcore_write_aarch_za (bfd *abfd,
13144 			char *buf,
13145 			int *bufsiz,
13146 			const void *aarch_za,
13147 			int size)
13148 {
13149   char *note_name = "LINUX";
13150   return elfcore_write_note (abfd, buf, bufsiz,
13151 			     note_name, NT_ARM_ZA,
13152 			     aarch_za,
13153 			     size);
13154 }
13155 
13156 /* Write the buffer of zt register values in aarch_zt (length SIZE) into
13157    the note buffer BUF and update *BUFSIZ.  ABFD is the bfd the note is being
13158    written into.  Return a pointer to the new start of the note buffer, to
13159    replace BUF which may no longer be valid.  */
13160 
13161 char *
elfcore_write_aarch_zt(bfd * abfd,char * buf,int * bufsiz,const void * aarch_zt,int size)13162 elfcore_write_aarch_zt (bfd *abfd,
13163 			char *buf,
13164 			int *bufsiz,
13165 			const void *aarch_zt,
13166 			int size)
13167 {
13168   char *note_name = "LINUX";
13169   return elfcore_write_note (abfd, buf, bufsiz,
13170 			     note_name, NT_ARM_ZT,
13171 			     aarch_zt,
13172 			     size);
13173 }
13174 
13175 char *
elfcore_write_arc_v2(bfd * abfd,char * buf,int * bufsiz,const void * arc_v2,int size)13176 elfcore_write_arc_v2 (bfd *abfd,
13177 		      char *buf,
13178 		      int *bufsiz,
13179 		      const void *arc_v2,
13180 		      int size)
13181 {
13182   char *note_name = "LINUX";
13183   return elfcore_write_note (abfd, buf, bufsiz,
13184 			     note_name, NT_ARC_V2, arc_v2, size);
13185 }
13186 
13187 char *
elfcore_write_loongarch_cpucfg(bfd * abfd,char * buf,int * bufsiz,const void * loongarch_cpucfg,int size)13188 elfcore_write_loongarch_cpucfg (bfd *abfd,
13189 				char *buf,
13190 				int *bufsiz,
13191 				const void *loongarch_cpucfg,
13192 				int size)
13193 {
13194   char *note_name = "LINUX";
13195   return elfcore_write_note (abfd, buf, bufsiz,
13196 			     note_name, NT_LARCH_CPUCFG,
13197 			     loongarch_cpucfg, size);
13198 }
13199 
13200 char *
elfcore_write_loongarch_lbt(bfd * abfd,char * buf,int * bufsiz,const void * loongarch_lbt,int size)13201 elfcore_write_loongarch_lbt (bfd *abfd,
13202 			     char *buf,
13203 			     int *bufsiz,
13204 			     const void *loongarch_lbt,
13205 			     int size)
13206 {
13207   char *note_name = "LINUX";
13208   return elfcore_write_note (abfd, buf, bufsiz,
13209 			     note_name, NT_LARCH_LBT, loongarch_lbt, size);
13210 }
13211 
13212 char *
elfcore_write_loongarch_lsx(bfd * abfd,char * buf,int * bufsiz,const void * loongarch_lsx,int size)13213 elfcore_write_loongarch_lsx (bfd *abfd,
13214 			     char *buf,
13215 			     int *bufsiz,
13216 			     const void *loongarch_lsx,
13217 			     int size)
13218 {
13219   char *note_name = "LINUX";
13220   return elfcore_write_note (abfd, buf, bufsiz,
13221 			     note_name, NT_LARCH_LSX, loongarch_lsx, size);
13222 }
13223 
13224 char *
elfcore_write_loongarch_lasx(bfd * abfd,char * buf,int * bufsiz,const void * loongarch_lasx,int size)13225 elfcore_write_loongarch_lasx (bfd *abfd,
13226 			      char *buf,
13227 			      int *bufsiz,
13228 			      const void *loongarch_lasx,
13229 			      int size)
13230 {
13231   char *note_name = "LINUX";
13232   return elfcore_write_note (abfd, buf, bufsiz,
13233 			     note_name, NT_LARCH_LASX, loongarch_lasx, size);
13234 }
13235 
13236 /* Write the buffer of csr values in CSRS (length SIZE) into the note
13237    buffer BUF and update *BUFSIZ.  ABFD is the bfd the note is being
13238    written into.  Return a pointer to the new start of the note buffer, to
13239    replace BUF which may no longer be valid.  */
13240 
13241 char *
elfcore_write_riscv_csr(bfd * abfd,char * buf,int * bufsiz,const void * csrs,int size)13242 elfcore_write_riscv_csr (bfd *abfd,
13243 			 char *buf,
13244 			 int *bufsiz,
13245 			 const void *csrs,
13246 			 int size)
13247 {
13248   const char *note_name = "GDB";
13249   return elfcore_write_note (abfd, buf, bufsiz,
13250 			     note_name, NT_RISCV_CSR, csrs, size);
13251 }
13252 
13253 /* Write the target description (a string) pointed to by TDESC, length
13254    SIZE, into the note buffer BUF, and update *BUFSIZ.  ABFD is the bfd the
13255    note is being written into.  Return a pointer to the new start of the
13256    note buffer, to replace BUF which may no longer be valid.  */
13257 
13258 char *
elfcore_write_gdb_tdesc(bfd * abfd,char * buf,int * bufsiz,const void * tdesc,int size)13259 elfcore_write_gdb_tdesc (bfd *abfd,
13260 			 char *buf,
13261 			 int *bufsiz,
13262 			 const void *tdesc,
13263 			 int size)
13264 {
13265   const char *note_name = "GDB";
13266   return elfcore_write_note (abfd, buf, bufsiz,
13267 			     note_name, NT_GDB_TDESC, tdesc, size);
13268 }
13269 
13270 char *
elfcore_write_register_note(bfd * abfd,char * buf,int * bufsiz,const char * section,const void * data,int size)13271 elfcore_write_register_note (bfd *abfd,
13272 			     char *buf,
13273 			     int *bufsiz,
13274 			     const char *section,
13275 			     const void *data,
13276 			     int size)
13277 {
13278   if (strcmp (section, ".reg2") == 0)
13279     return elfcore_write_prfpreg (abfd, buf, bufsiz, data, size);
13280   if (strcmp (section, ".reg-xfp") == 0)
13281     return elfcore_write_prxfpreg (abfd, buf, bufsiz, data, size);
13282   if (strcmp (section, ".reg-xstate") == 0)
13283     return elfcore_write_xstatereg (abfd, buf, bufsiz, data, size);
13284   if (strcmp (section, ".reg-x86-segbases") == 0)
13285     return elfcore_write_x86_segbases (abfd, buf, bufsiz, data, size);
13286   if (strcmp (section, ".reg-ppc-vmx") == 0)
13287     return elfcore_write_ppc_vmx (abfd, buf, bufsiz, data, size);
13288   if (strcmp (section, ".reg-ppc-vsx") == 0)
13289     return elfcore_write_ppc_vsx (abfd, buf, bufsiz, data, size);
13290   if (strcmp (section, ".reg-ppc-tar") == 0)
13291     return elfcore_write_ppc_tar (abfd, buf, bufsiz, data, size);
13292   if (strcmp (section, ".reg-ppc-ppr") == 0)
13293     return elfcore_write_ppc_ppr (abfd, buf, bufsiz, data, size);
13294   if (strcmp (section, ".reg-ppc-dscr") == 0)
13295     return elfcore_write_ppc_dscr (abfd, buf, bufsiz, data, size);
13296   if (strcmp (section, ".reg-ppc-ebb") == 0)
13297     return elfcore_write_ppc_ebb (abfd, buf, bufsiz, data, size);
13298   if (strcmp (section, ".reg-ppc-pmu") == 0)
13299     return elfcore_write_ppc_pmu (abfd, buf, bufsiz, data, size);
13300   if (strcmp (section, ".reg-ppc-tm-cgpr") == 0)
13301     return elfcore_write_ppc_tm_cgpr (abfd, buf, bufsiz, data, size);
13302   if (strcmp (section, ".reg-ppc-tm-cfpr") == 0)
13303     return elfcore_write_ppc_tm_cfpr (abfd, buf, bufsiz, data, size);
13304   if (strcmp (section, ".reg-ppc-tm-cvmx") == 0)
13305     return elfcore_write_ppc_tm_cvmx (abfd, buf, bufsiz, data, size);
13306   if (strcmp (section, ".reg-ppc-tm-cvsx") == 0)
13307     return elfcore_write_ppc_tm_cvsx (abfd, buf, bufsiz, data, size);
13308   if (strcmp (section, ".reg-ppc-tm-spr") == 0)
13309     return elfcore_write_ppc_tm_spr (abfd, buf, bufsiz, data, size);
13310   if (strcmp (section, ".reg-ppc-tm-ctar") == 0)
13311     return elfcore_write_ppc_tm_ctar (abfd, buf, bufsiz, data, size);
13312   if (strcmp (section, ".reg-ppc-tm-cppr") == 0)
13313     return elfcore_write_ppc_tm_cppr (abfd, buf, bufsiz, data, size);
13314   if (strcmp (section, ".reg-ppc-tm-cdscr") == 0)
13315     return elfcore_write_ppc_tm_cdscr (abfd, buf, bufsiz, data, size);
13316   if (strcmp (section, ".reg-s390-high-gprs") == 0)
13317     return elfcore_write_s390_high_gprs (abfd, buf, bufsiz, data, size);
13318   if (strcmp (section, ".reg-s390-timer") == 0)
13319     return elfcore_write_s390_timer (abfd, buf, bufsiz, data, size);
13320   if (strcmp (section, ".reg-s390-todcmp") == 0)
13321     return elfcore_write_s390_todcmp (abfd, buf, bufsiz, data, size);
13322   if (strcmp (section, ".reg-s390-todpreg") == 0)
13323     return elfcore_write_s390_todpreg (abfd, buf, bufsiz, data, size);
13324   if (strcmp (section, ".reg-s390-ctrs") == 0)
13325     return elfcore_write_s390_ctrs (abfd, buf, bufsiz, data, size);
13326   if (strcmp (section, ".reg-s390-prefix") == 0)
13327     return elfcore_write_s390_prefix (abfd, buf, bufsiz, data, size);
13328   if (strcmp (section, ".reg-s390-last-break") == 0)
13329     return elfcore_write_s390_last_break (abfd, buf, bufsiz, data, size);
13330   if (strcmp (section, ".reg-s390-system-call") == 0)
13331     return elfcore_write_s390_system_call (abfd, buf, bufsiz, data, size);
13332   if (strcmp (section, ".reg-s390-tdb") == 0)
13333     return elfcore_write_s390_tdb (abfd, buf, bufsiz, data, size);
13334   if (strcmp (section, ".reg-s390-vxrs-low") == 0)
13335     return elfcore_write_s390_vxrs_low (abfd, buf, bufsiz, data, size);
13336   if (strcmp (section, ".reg-s390-vxrs-high") == 0)
13337     return elfcore_write_s390_vxrs_high (abfd, buf, bufsiz, data, size);
13338   if (strcmp (section, ".reg-s390-gs-cb") == 0)
13339     return elfcore_write_s390_gs_cb (abfd, buf, bufsiz, data, size);
13340   if (strcmp (section, ".reg-s390-gs-bc") == 0)
13341     return elfcore_write_s390_gs_bc (abfd, buf, bufsiz, data, size);
13342   if (strcmp (section, ".reg-arm-vfp") == 0)
13343     return elfcore_write_arm_vfp (abfd, buf, bufsiz, data, size);
13344   if (strcmp (section, ".reg-aarch-tls") == 0)
13345     return elfcore_write_aarch_tls (abfd, buf, bufsiz, data, size);
13346   if (strcmp (section, ".reg-aarch-hw-break") == 0)
13347     return elfcore_write_aarch_hw_break (abfd, buf, bufsiz, data, size);
13348   if (strcmp (section, ".reg-aarch-hw-watch") == 0)
13349     return elfcore_write_aarch_hw_watch (abfd, buf, bufsiz, data, size);
13350   if (strcmp (section, ".reg-aarch-sve") == 0)
13351     return elfcore_write_aarch_sve (abfd, buf, bufsiz, data, size);
13352   if (strcmp (section, ".reg-aarch-pauth") == 0)
13353     return elfcore_write_aarch_pauth (abfd, buf, bufsiz, data, size);
13354   if (strcmp (section, ".reg-aarch-mte") == 0)
13355     return elfcore_write_aarch_mte (abfd, buf, bufsiz, data, size);
13356   if (strcmp (section, ".reg-aarch-ssve") == 0)
13357     return elfcore_write_aarch_ssve (abfd, buf, bufsiz, data, size);
13358   if (strcmp (section, ".reg-aarch-za") == 0)
13359     return elfcore_write_aarch_za (abfd, buf, bufsiz, data, size);
13360   if (strcmp (section, ".reg-aarch-zt") == 0)
13361     return elfcore_write_aarch_zt (abfd, buf, bufsiz, data, size);
13362   if (strcmp (section, ".reg-arc-v2") == 0)
13363     return elfcore_write_arc_v2 (abfd, buf, bufsiz, data, size);
13364   if (strcmp (section, ".gdb-tdesc") == 0)
13365     return elfcore_write_gdb_tdesc (abfd, buf, bufsiz, data, size);
13366   if (strcmp (section, ".reg-riscv-csr") == 0)
13367     return elfcore_write_riscv_csr (abfd, buf, bufsiz, data, size);
13368   if (strcmp (section, ".reg-loongarch-cpucfg") == 0)
13369     return elfcore_write_loongarch_cpucfg (abfd, buf, bufsiz, data, size);
13370   if (strcmp (section, ".reg-loongarch-lbt") == 0)
13371     return elfcore_write_loongarch_lbt (abfd, buf, bufsiz, data, size);
13372   if (strcmp (section, ".reg-loongarch-lsx") == 0)
13373     return elfcore_write_loongarch_lsx (abfd, buf, bufsiz, data, size);
13374   if (strcmp (section, ".reg-loongarch-lasx") == 0)
13375     return elfcore_write_loongarch_lasx (abfd, buf, bufsiz, data, size);
13376   return NULL;
13377 }
13378 
13379 char *
elfcore_write_file_note(bfd * obfd,char * note_data,int * note_size,const void * buf,int bufsiz)13380 elfcore_write_file_note (bfd *obfd, char *note_data, int *note_size,
13381 			 const void *buf, int bufsiz)
13382 {
13383   return elfcore_write_note (obfd, note_data, note_size,
13384 			     "CORE", NT_FILE, buf, bufsiz);
13385 }
13386 
13387 static bool
elf_parse_notes(bfd * abfd,char * buf,size_t size,file_ptr offset,size_t align)13388 elf_parse_notes (bfd *abfd, char *buf, size_t size, file_ptr offset,
13389 		 size_t align)
13390 {
13391   char *p;
13392 
13393   /* NB: CORE PT_NOTE segments may have p_align values of 0 or 1.
13394      gABI specifies that PT_NOTE alignment should be aligned to 4
13395      bytes for 32-bit objects and to 8 bytes for 64-bit objects.  If
13396      align is less than 4, we use 4 byte alignment.   */
13397   if (align < 4)
13398     align = 4;
13399   if (align != 4 && align != 8)
13400     return false;
13401 
13402   p = buf;
13403   while (p < buf + size)
13404     {
13405       Elf_External_Note *xnp = (Elf_External_Note *) p;
13406       Elf_Internal_Note in;
13407 
13408       if (offsetof (Elf_External_Note, name) > buf - p + size)
13409 	return false;
13410 
13411       in.type = H_GET_32 (abfd, xnp->type);
13412 
13413       in.namesz = H_GET_32 (abfd, xnp->namesz);
13414       in.namedata = xnp->name;
13415       if (in.namesz > buf - in.namedata + size)
13416 	return false;
13417 
13418       in.descsz = H_GET_32 (abfd, xnp->descsz);
13419       in.descdata = p + ELF_NOTE_DESC_OFFSET (in.namesz, align);
13420       in.descpos = offset + (in.descdata - buf);
13421       if (in.descsz != 0
13422 	  && (in.descdata >= buf + size
13423 	      || in.descsz > buf - in.descdata + size))
13424 	return false;
13425 
13426       switch (bfd_get_format (abfd))
13427 	{
13428 	default:
13429 	  return true;
13430 
13431 	case bfd_core:
13432 	  {
13433 #define GROKER_ELEMENT(S,F) {S, sizeof (S) - 1, F}
13434 	    struct
13435 	    {
13436 	      const char * string;
13437 	      size_t len;
13438 	      bool (*func) (bfd *, Elf_Internal_Note *);
13439 	    }
13440 	    grokers[] =
13441 	    {
13442 	      GROKER_ELEMENT ("", elfcore_grok_note),
13443 	      GROKER_ELEMENT ("FreeBSD", elfcore_grok_freebsd_note),
13444 	      GROKER_ELEMENT ("NetBSD-CORE", elfcore_grok_netbsd_note),
13445 	      GROKER_ELEMENT ("OpenBSD", elfcore_grok_openbsd_note),
13446 	      GROKER_ELEMENT ("QNX", elfcore_grok_nto_note),
13447 	      GROKER_ELEMENT ("SPU/", elfcore_grok_spu_note),
13448 	      GROKER_ELEMENT ("GNU", elfobj_grok_gnu_note),
13449 	      GROKER_ELEMENT ("CORE", elfcore_grok_solaris_note)
13450 	    };
13451 #undef GROKER_ELEMENT
13452 	    int i;
13453 
13454 	    for (i = ARRAY_SIZE (grokers); i--;)
13455 	      {
13456 		if (in.namesz >= grokers[i].len
13457 		    && strncmp (in.namedata, grokers[i].string,
13458 				grokers[i].len) == 0)
13459 		  {
13460 		    if (! grokers[i].func (abfd, & in))
13461 		      return false;
13462 		    break;
13463 		  }
13464 	      }
13465 	    break;
13466 	  }
13467 
13468 	case bfd_object:
13469 	  if (in.namesz == sizeof "GNU" && strcmp (in.namedata, "GNU") == 0)
13470 	    {
13471 	      if (! elfobj_grok_gnu_note (abfd, &in))
13472 		return false;
13473 	    }
13474 	  else if (in.namesz == sizeof "stapsdt"
13475 		   && strcmp (in.namedata, "stapsdt") == 0)
13476 	    {
13477 	      if (! elfobj_grok_stapsdt_note (abfd, &in))
13478 		return false;
13479 	    }
13480 	  break;
13481 	}
13482 
13483       p += ELF_NOTE_NEXT_OFFSET (in.namesz, in.descsz, align);
13484     }
13485 
13486   return true;
13487 }
13488 
13489 bool
elf_read_notes(bfd * abfd,file_ptr offset,bfd_size_type size,size_t align)13490 elf_read_notes (bfd *abfd, file_ptr offset, bfd_size_type size,
13491 		size_t align)
13492 {
13493   char *buf;
13494 
13495   if (size == 0 || (size + 1) == 0)
13496     return true;
13497 
13498   if (bfd_seek (abfd, offset, SEEK_SET) != 0)
13499     return false;
13500 
13501   buf = (char *) _bfd_malloc_and_read (abfd, size + 1, size);
13502   if (buf == NULL)
13503     return false;
13504 
13505   /* PR 17512: file: ec08f814
13506      0-termintate the buffer so that string searches will not overflow.  */
13507   buf[size] = 0;
13508 
13509   if (!elf_parse_notes (abfd, buf, size, offset, align))
13510     {
13511       free (buf);
13512       return false;
13513     }
13514 
13515   free (buf);
13516   return true;
13517 }
13518 
13519 /* Providing external access to the ELF program header table.  */
13520 
13521 /* Return an upper bound on the number of bytes required to store a
13522    copy of ABFD's program header table entries.  Return -1 if an error
13523    occurs; bfd_get_error will return an appropriate code.  */
13524 
13525 long
bfd_get_elf_phdr_upper_bound(bfd * abfd)13526 bfd_get_elf_phdr_upper_bound (bfd *abfd)
13527 {
13528   if (abfd->xvec->flavour != bfd_target_elf_flavour)
13529     {
13530       bfd_set_error (bfd_error_wrong_format);
13531       return -1;
13532     }
13533 
13534   return elf_elfheader (abfd)->e_phnum * sizeof (Elf_Internal_Phdr);
13535 }
13536 
13537 /* Copy ABFD's program header table entries to *PHDRS.  The entries
13538    will be stored as an array of Elf_Internal_Phdr structures, as
13539    defined in include/elf/internal.h.  To find out how large the
13540    buffer needs to be, call bfd_get_elf_phdr_upper_bound.
13541 
13542    Return the number of program header table entries read, or -1 if an
13543    error occurs; bfd_get_error will return an appropriate code.  */
13544 
13545 int
bfd_get_elf_phdrs(bfd * abfd,void * phdrs)13546 bfd_get_elf_phdrs (bfd *abfd, void *phdrs)
13547 {
13548   int num_phdrs;
13549 
13550   if (abfd->xvec->flavour != bfd_target_elf_flavour)
13551     {
13552       bfd_set_error (bfd_error_wrong_format);
13553       return -1;
13554     }
13555 
13556   num_phdrs = elf_elfheader (abfd)->e_phnum;
13557   if (num_phdrs != 0)
13558     memcpy (phdrs, elf_tdata (abfd)->phdr,
13559 	    num_phdrs * sizeof (Elf_Internal_Phdr));
13560 
13561   return num_phdrs;
13562 }
13563 
13564 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)13565 _bfd_elf_reloc_type_class (const struct bfd_link_info *info ATTRIBUTE_UNUSED,
13566 			   const asection *rel_sec ATTRIBUTE_UNUSED,
13567 			   const Elf_Internal_Rela *rela ATTRIBUTE_UNUSED)
13568 {
13569   return reloc_class_normal;
13570 }
13571 
13572 /* For RELA architectures, return the relocation value for a
13573    relocation against a local symbol.  */
13574 
13575 bfd_vma
_bfd_elf_rela_local_sym(bfd * abfd,Elf_Internal_Sym * sym,asection ** psec,Elf_Internal_Rela * rel)13576 _bfd_elf_rela_local_sym (bfd *abfd,
13577 			 Elf_Internal_Sym *sym,
13578 			 asection **psec,
13579 			 Elf_Internal_Rela *rel)
13580 {
13581   asection *sec = *psec;
13582   bfd_vma relocation;
13583 
13584   relocation = (sec->output_section->vma
13585 		+ sec->output_offset
13586 		+ sym->st_value);
13587   if ((sec->flags & SEC_MERGE)
13588       && ELF_ST_TYPE (sym->st_info) == STT_SECTION
13589       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
13590     {
13591       rel->r_addend =
13592 	_bfd_merged_section_offset (abfd, psec,
13593 				    elf_section_data (sec)->sec_info,
13594 				    sym->st_value + rel->r_addend);
13595       if (sec != *psec)
13596 	{
13597 	  /* If we have changed the section, and our original section is
13598 	     marked with SEC_EXCLUDE, it means that the original
13599 	     SEC_MERGE section has been completely subsumed in some
13600 	     other SEC_MERGE section.  In this case, we need to leave
13601 	     some info around for --emit-relocs.  */
13602 	  if ((sec->flags & SEC_EXCLUDE) != 0)
13603 	    sec->kept_section = *psec;
13604 	  sec = *psec;
13605 	}
13606       rel->r_addend -= relocation;
13607       rel->r_addend += sec->output_section->vma + sec->output_offset;
13608     }
13609   return relocation;
13610 }
13611 
13612 bfd_vma
_bfd_elf_rel_local_sym(bfd * abfd,Elf_Internal_Sym * sym,asection ** psec,bfd_vma addend)13613 _bfd_elf_rel_local_sym (bfd *abfd,
13614 			Elf_Internal_Sym *sym,
13615 			asection **psec,
13616 			bfd_vma addend)
13617 {
13618   asection *sec = *psec;
13619 
13620   if (sec->sec_info_type != SEC_INFO_TYPE_MERGE)
13621     return sym->st_value + addend;
13622 
13623   return _bfd_merged_section_offset (abfd, psec,
13624 				     elf_section_data (sec)->sec_info,
13625 				     sym->st_value + addend);
13626 }
13627 
13628 /* Adjust an address within a section.  Given OFFSET within SEC, return
13629    the new offset within the section, based upon changes made to the
13630    section.  Returns -1 if the offset is now invalid.
13631    The offset (in abnd out) is in target sized bytes, however big a
13632    byte may be.  */
13633 
13634 bfd_vma
_bfd_elf_section_offset(bfd * abfd,struct bfd_link_info * info,asection * sec,bfd_vma offset)13635 _bfd_elf_section_offset (bfd *abfd,
13636 			 struct bfd_link_info *info,
13637 			 asection *sec,
13638 			 bfd_vma offset)
13639 {
13640   switch (sec->sec_info_type)
13641     {
13642     case SEC_INFO_TYPE_STABS:
13643       return _bfd_stab_section_offset (sec, elf_section_data (sec)->sec_info,
13644 				       offset);
13645     case SEC_INFO_TYPE_EH_FRAME:
13646       return _bfd_elf_eh_frame_section_offset (abfd, info, sec, offset);
13647 
13648     default:
13649       if ((sec->flags & SEC_ELF_REVERSE_COPY) != 0)
13650 	{
13651 	  /* Reverse the offset.  */
13652 	  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13653 	  bfd_size_type address_size = bed->s->arch_size / 8;
13654 
13655 	  /* address_size and sec->size are in octets.  Convert
13656 	     to bytes before subtracting the original offset.  */
13657 	  offset = ((sec->size - address_size)
13658 		    / bfd_octets_per_byte (abfd, sec) - offset);
13659 	}
13660       return offset;
13661     }
13662 }
13663 
13664 long
_bfd_elf_get_synthetic_symtab(bfd * abfd,long symcount ATTRIBUTE_UNUSED,asymbol ** syms ATTRIBUTE_UNUSED,long dynsymcount,asymbol ** dynsyms,asymbol ** ret)13665 _bfd_elf_get_synthetic_symtab (bfd *abfd,
13666 			       long symcount ATTRIBUTE_UNUSED,
13667 			       asymbol **syms ATTRIBUTE_UNUSED,
13668 			       long dynsymcount,
13669 			       asymbol **dynsyms,
13670 			       asymbol **ret)
13671 {
13672   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13673   asection *relplt;
13674   asymbol *s;
13675   const char *relplt_name;
13676   bool (*slurp_relocs) (bfd *, asection *, asymbol **, bool);
13677   arelent *p;
13678   long count, i, n;
13679   size_t size;
13680   Elf_Internal_Shdr *hdr;
13681   char *names;
13682   asection *plt;
13683 
13684   *ret = NULL;
13685 
13686   if ((abfd->flags & (DYNAMIC | EXEC_P)) == 0)
13687     return 0;
13688 
13689   if (dynsymcount <= 0)
13690     return 0;
13691 
13692   if (!bed->plt_sym_val)
13693     return 0;
13694 
13695   relplt_name = bed->relplt_name;
13696   if (relplt_name == NULL)
13697     relplt_name = bed->rela_plts_and_copies_p ? ".rela.plt" : ".rel.plt";
13698   relplt = bfd_get_section_by_name (abfd, relplt_name);
13699   if (relplt == NULL)
13700     return 0;
13701 
13702   hdr = &elf_section_data (relplt)->this_hdr;
13703   if (hdr->sh_link != elf_dynsymtab (abfd)
13704       || (hdr->sh_type != SHT_REL && hdr->sh_type != SHT_RELA))
13705     return 0;
13706 
13707   plt = bfd_get_section_by_name (abfd, ".plt");
13708   if (plt == NULL)
13709     return 0;
13710 
13711   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
13712   if (! (*slurp_relocs) (abfd, relplt, dynsyms, true))
13713     return -1;
13714 
13715   count = NUM_SHDR_ENTRIES (hdr);
13716   size = count * sizeof (asymbol);
13717   p = relplt->relocation;
13718   for (i = 0; i < count; i++, p += bed->s->int_rels_per_ext_rel)
13719     {
13720       size += strlen ((*p->sym_ptr_ptr)->name) + sizeof ("@plt");
13721       if (p->addend != 0)
13722 	{
13723 #ifdef BFD64
13724 	  size += sizeof ("+0x") - 1 + 8 + 8 * (bed->s->elfclass == ELFCLASS64);
13725 #else
13726 	  size += sizeof ("+0x") - 1 + 8;
13727 #endif
13728 	}
13729     }
13730 
13731   s = *ret = (asymbol *) bfd_malloc (size);
13732   if (s == NULL)
13733     return -1;
13734 
13735   names = (char *) (s + count);
13736   p = relplt->relocation;
13737   n = 0;
13738   for (i = 0; i < count; i++, p += bed->s->int_rels_per_ext_rel)
13739     {
13740       size_t len;
13741       bfd_vma addr;
13742 
13743       addr = bed->plt_sym_val (i, plt, p);
13744       if (addr == (bfd_vma) -1)
13745 	continue;
13746 
13747       *s = **p->sym_ptr_ptr;
13748       /* Undefined syms won't have BSF_LOCAL or BSF_GLOBAL set.  Since
13749 	 we are defining a symbol, ensure one of them is set.  */
13750       if ((s->flags & BSF_LOCAL) == 0)
13751 	s->flags |= BSF_GLOBAL;
13752       s->flags |= BSF_SYNTHETIC;
13753       s->section = plt;
13754       s->value = addr - plt->vma;
13755       s->name = names;
13756       s->udata.p = NULL;
13757       len = strlen ((*p->sym_ptr_ptr)->name);
13758       memcpy (names, (*p->sym_ptr_ptr)->name, len);
13759       names += len;
13760       if (p->addend != 0)
13761 	{
13762 	  char buf[30], *a;
13763 
13764 	  memcpy (names, "+0x", sizeof ("+0x") - 1);
13765 	  names += sizeof ("+0x") - 1;
13766 	  bfd_sprintf_vma (abfd, buf, p->addend);
13767 	  for (a = buf; *a == '0'; ++a)
13768 	    ;
13769 	  len = strlen (a);
13770 	  memcpy (names, a, len);
13771 	  names += len;
13772 	}
13773       memcpy (names, "@plt", sizeof ("@plt"));
13774       names += sizeof ("@plt");
13775       ++s, ++n;
13776     }
13777 
13778   return n;
13779 }
13780 
13781 /* It is only used by x86-64 so far.
13782    ??? This repeats *COM* id of zero.  sec->id is supposed to be unique,
13783    but current usage would allow all of _bfd_std_section to be zero.  */
13784 static const asymbol lcomm_sym
13785   = GLOBAL_SYM_INIT ("LARGE_COMMON", &_bfd_elf_large_com_section);
13786 asection _bfd_elf_large_com_section
13787   = BFD_FAKE_SECTION (_bfd_elf_large_com_section, &lcomm_sym,
13788 		      "LARGE_COMMON", 0, SEC_IS_COMMON);
13789 
13790 bool
_bfd_elf_final_write_processing(bfd * abfd)13791 _bfd_elf_final_write_processing (bfd *abfd)
13792 {
13793   Elf_Internal_Ehdr *i_ehdrp;	/* ELF file header, internal form.  */
13794 
13795   i_ehdrp = elf_elfheader (abfd);
13796 
13797   if (i_ehdrp->e_ident[EI_OSABI] == ELFOSABI_NONE)
13798     i_ehdrp->e_ident[EI_OSABI] = get_elf_backend_data (abfd)->elf_osabi;
13799 
13800   /* Set the osabi field to ELFOSABI_GNU if the binary contains
13801      SHF_GNU_MBIND or SHF_GNU_RETAIN sections or symbols of STT_GNU_IFUNC type
13802      or STB_GNU_UNIQUE binding.  */
13803   if (elf_tdata (abfd)->has_gnu_osabi != 0)
13804     {
13805       if (i_ehdrp->e_ident[EI_OSABI] == ELFOSABI_NONE)
13806 	i_ehdrp->e_ident[EI_OSABI] = ELFOSABI_GNU;
13807       else if (i_ehdrp->e_ident[EI_OSABI] != ELFOSABI_GNU
13808 	       && i_ehdrp->e_ident[EI_OSABI] != ELFOSABI_FREEBSD)
13809 	{
13810 	  if (elf_tdata (abfd)->has_gnu_osabi & elf_gnu_osabi_mbind)
13811 	    _bfd_error_handler (_("GNU_MBIND section is supported only by GNU "
13812 				  "and FreeBSD targets"));
13813 	  if (elf_tdata (abfd)->has_gnu_osabi & elf_gnu_osabi_ifunc)
13814 	    _bfd_error_handler (_("symbol type STT_GNU_IFUNC is supported "
13815 				  "only by GNU and FreeBSD targets"));
13816 	  if (elf_tdata (abfd)->has_gnu_osabi & elf_gnu_osabi_unique)
13817 	    _bfd_error_handler (_("symbol binding STB_GNU_UNIQUE is supported "
13818 				  "only by GNU and FreeBSD targets"));
13819 	  if (elf_tdata (abfd)->has_gnu_osabi & elf_gnu_osabi_retain)
13820 	    _bfd_error_handler (_("GNU_RETAIN section is supported "
13821 				  "only by GNU and FreeBSD targets"));
13822 	  bfd_set_error (bfd_error_sorry);
13823 	  return false;
13824 	}
13825     }
13826   return true;
13827 }
13828 
13829 
13830 /* Return TRUE for ELF symbol types that represent functions.
13831    This is the default version of this function, which is sufficient for
13832    most targets.  It returns true if TYPE is STT_FUNC or STT_GNU_IFUNC.  */
13833 
13834 bool
_bfd_elf_is_function_type(unsigned int type)13835 _bfd_elf_is_function_type (unsigned int type)
13836 {
13837   return (type == STT_FUNC
13838 	  || type == STT_GNU_IFUNC);
13839 }
13840 
13841 /* If the ELF symbol SYM might be a function in SEC, return the
13842    function size and set *CODE_OFF to the function's entry point,
13843    otherwise return zero.  */
13844 
13845 bfd_size_type
_bfd_elf_maybe_function_sym(const asymbol * sym,asection * sec,bfd_vma * code_off)13846 _bfd_elf_maybe_function_sym (const asymbol *sym, asection *sec,
13847 			     bfd_vma *code_off)
13848 {
13849   bfd_size_type size;
13850   elf_symbol_type * elf_sym = (elf_symbol_type *) sym;
13851 
13852   if ((sym->flags & (BSF_SECTION_SYM | BSF_FILE | BSF_OBJECT
13853 		     | BSF_THREAD_LOCAL | BSF_RELC | BSF_SRELC)) != 0
13854       || sym->section != sec)
13855     return 0;
13856 
13857   size = (sym->flags & BSF_SYNTHETIC) ? 0 : elf_sym->internal_elf_sym.st_size;
13858 
13859   /* In theory we should check that the symbol's type satisfies
13860      _bfd_elf_is_function_type(), but there are some function-like
13861      symbols which would fail this test.  (eg _start).  Instead
13862      we check for hidden, local, notype symbols with zero size.
13863      This type of symbol is generated by the annobin plugin for gcc
13864      and clang, and should not be considered to be a function symbol.  */
13865   if (size == 0
13866       && ((sym->flags & (BSF_SYNTHETIC | BSF_LOCAL)) == BSF_LOCAL)
13867       && ELF_ST_TYPE (elf_sym->internal_elf_sym.st_info) == STT_NOTYPE
13868       && ELF_ST_VISIBILITY (elf_sym->internal_elf_sym.st_other) == STV_HIDDEN)
13869     return 0;
13870 
13871   *code_off = sym->value;
13872   /* Do not return 0 for the function's size.  */
13873   return size ? size : 1;
13874 }
13875 
13876 /* Set to non-zero to enable some debug messages.  */
13877 #define DEBUG_SECONDARY_RELOCS	 0
13878 
13879 /* An internal-to-the-bfd-library only section type
13880    used to indicate a cached secondary reloc section.  */
13881 #define SHT_SECONDARY_RELOC	 (SHT_LOOS + SHT_RELA)
13882 
13883 /* Create a BFD section to hold a secondary reloc section.  */
13884 
13885 bool
_bfd_elf_init_secondary_reloc_section(bfd * abfd,Elf_Internal_Shdr * hdr,const char * name,unsigned int shindex)13886 _bfd_elf_init_secondary_reloc_section (bfd * abfd,
13887 				       Elf_Internal_Shdr *hdr,
13888 				       const char * name,
13889 				       unsigned int shindex)
13890 {
13891   /* We only support RELA secondary relocs.  */
13892   if (hdr->sh_type != SHT_RELA)
13893     return false;
13894 
13895 #if DEBUG_SECONDARY_RELOCS
13896   fprintf (stderr, "secondary reloc section %s encountered\n", name);
13897 #endif
13898   hdr->sh_type = SHT_SECONDARY_RELOC;
13899   return _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
13900 }
13901 
13902 /* Read in any secondary relocs associated with SEC.  */
13903 
13904 bool
_bfd_elf_slurp_secondary_reloc_section(bfd * abfd,asection * sec,asymbol ** symbols,bool dynamic)13905 _bfd_elf_slurp_secondary_reloc_section (bfd *       abfd,
13906 					asection *  sec,
13907 					asymbol **  symbols,
13908 					bool dynamic)
13909 {
13910   const struct elf_backend_data * const ebd = get_elf_backend_data (abfd);
13911   asection * relsec;
13912   bool result = true;
13913   bfd_vma (*r_sym) (bfd_vma);
13914   ufile_ptr filesize;
13915 
13916 #if BFD_DEFAULT_TARGET_SIZE > 32
13917   if (bfd_arch_bits_per_address (abfd) != 32)
13918     r_sym = elf64_r_sym;
13919   else
13920 #endif
13921     r_sym = elf32_r_sym;
13922 
13923   if (!elf_section_data (sec)->has_secondary_relocs)
13924     return true;
13925 
13926   /* Discover if there are any secondary reloc sections
13927      associated with SEC.  */
13928   filesize = bfd_get_file_size (abfd);
13929   for (relsec = abfd->sections; relsec != NULL; relsec = relsec->next)
13930     {
13931       Elf_Internal_Shdr * hdr = & elf_section_data (relsec)->this_hdr;
13932 
13933       if (hdr->sh_type == SHT_SECONDARY_RELOC
13934 	  && hdr->sh_info == (unsigned) elf_section_data (sec)->this_idx
13935 	  && (hdr->sh_entsize == ebd->s->sizeof_rel
13936 	      || hdr->sh_entsize == ebd->s->sizeof_rela))
13937 	{
13938 	  bfd_byte * native_relocs;
13939 	  bfd_byte * native_reloc;
13940 	  arelent * internal_relocs;
13941 	  arelent * internal_reloc;
13942 	  size_t i;
13943 	  unsigned int entsize;
13944 	  unsigned int symcount;
13945 	  bfd_size_type reloc_count;
13946 	  size_t amt;
13947 
13948 	  if (ebd->elf_info_to_howto == NULL)
13949 	    return false;
13950 
13951 #if DEBUG_SECONDARY_RELOCS
13952 	  fprintf (stderr, "read secondary relocs for %s from %s\n",
13953 		   sec->name, relsec->name);
13954 #endif
13955 	  entsize = hdr->sh_entsize;
13956 
13957 	  if (filesize != 0
13958 	      && ((ufile_ptr) hdr->sh_offset > filesize
13959 		  || hdr->sh_size > filesize - hdr->sh_offset))
13960 	    {
13961 	      bfd_set_error (bfd_error_file_truncated);
13962 	      result = false;
13963 	      continue;
13964 	    }
13965 
13966 	  native_relocs = bfd_malloc (hdr->sh_size);
13967 	  if (native_relocs == NULL)
13968 	    {
13969 	      result = false;
13970 	      continue;
13971 	    }
13972 
13973 	  reloc_count = NUM_SHDR_ENTRIES (hdr);
13974 	  if (_bfd_mul_overflow (reloc_count, sizeof (arelent), & amt))
13975 	    {
13976 	      free (native_relocs);
13977 	      bfd_set_error (bfd_error_file_too_big);
13978 	      result = false;
13979 	      continue;
13980 	    }
13981 
13982 	  internal_relocs = (arelent *) bfd_alloc (abfd, amt);
13983 	  if (internal_relocs == NULL)
13984 	    {
13985 	      free (native_relocs);
13986 	      result = false;
13987 	      continue;
13988 	    }
13989 
13990 	  if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
13991 	      || bfd_read (native_relocs, hdr->sh_size, abfd) != hdr->sh_size)
13992 	    {
13993 	      free (native_relocs);
13994 	      /* The internal_relocs will be freed when
13995 		 the memory for the bfd is released.  */
13996 	      result = false;
13997 	      continue;
13998 	    }
13999 
14000 	  if (dynamic)
14001 	    symcount = bfd_get_dynamic_symcount (abfd);
14002 	  else
14003 	    symcount = bfd_get_symcount (abfd);
14004 
14005 	  for (i = 0, internal_reloc = internal_relocs,
14006 		 native_reloc = native_relocs;
14007 	       i < reloc_count;
14008 	       i++, internal_reloc++, native_reloc += entsize)
14009 	    {
14010 	      bool res;
14011 	      Elf_Internal_Rela rela;
14012 
14013 	      if (entsize == ebd->s->sizeof_rel)
14014 		ebd->s->swap_reloc_in (abfd, native_reloc, & rela);
14015 	      else /* entsize == ebd->s->sizeof_rela */
14016 		ebd->s->swap_reloca_in (abfd, native_reloc, & rela);
14017 
14018 	      /* The address of an ELF reloc is section relative for an object
14019 		 file, and absolute for an executable file or shared library.
14020 		 The address of a normal BFD reloc is always section relative,
14021 		 and the address of a dynamic reloc is absolute..  */
14022 	      if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0)
14023 		internal_reloc->address = rela.r_offset;
14024 	      else
14025 		internal_reloc->address = rela.r_offset - sec->vma;
14026 
14027 	      if (r_sym (rela.r_info) == STN_UNDEF)
14028 		{
14029 		  /* FIXME: This and the error case below mean that we
14030 		     have a symbol on relocs that is not elf_symbol_type.  */
14031 		  internal_reloc->sym_ptr_ptr =
14032 		    bfd_abs_section_ptr->symbol_ptr_ptr;
14033 		}
14034 	      else if (r_sym (rela.r_info) > symcount)
14035 		{
14036 		  _bfd_error_handler
14037 		    /* xgettext:c-format */
14038 		    (_("%pB(%pA): relocation %zu has invalid symbol index %lu"),
14039 		     abfd, sec, i, (long) r_sym (rela.r_info));
14040 		  bfd_set_error (bfd_error_bad_value);
14041 		  internal_reloc->sym_ptr_ptr =
14042 		    bfd_abs_section_ptr->symbol_ptr_ptr;
14043 		  result = false;
14044 		}
14045 	      else
14046 		{
14047 		  asymbol **ps;
14048 
14049 		  ps = symbols + r_sym (rela.r_info) - 1;
14050 		  internal_reloc->sym_ptr_ptr = ps;
14051 		  /* Make sure that this symbol is not removed by strip.  */
14052 		  (*ps)->flags |= BSF_KEEP;
14053 		}
14054 
14055 	      internal_reloc->addend = rela.r_addend;
14056 
14057 	      res = ebd->elf_info_to_howto (abfd, internal_reloc, & rela);
14058 	      if (! res || internal_reloc->howto == NULL)
14059 		{
14060 #if DEBUG_SECONDARY_RELOCS
14061 		  fprintf (stderr,
14062 			   "there is no howto associated with reloc %lx\n",
14063 			   rela.r_info);
14064 #endif
14065 		  result = false;
14066 		}
14067 	    }
14068 
14069 	  free (native_relocs);
14070 	  /* Store the internal relocs.  */
14071 	  elf_section_data (relsec)->sec_info = internal_relocs;
14072 	}
14073     }
14074 
14075   return result;
14076 }
14077 
14078 /* Set the ELF section header fields of an output secondary reloc section.  */
14079 
14080 bool
_bfd_elf_copy_special_section_fields(const bfd * ibfd ATTRIBUTE_UNUSED,bfd * obfd ATTRIBUTE_UNUSED,const Elf_Internal_Shdr * isection,Elf_Internal_Shdr * osection)14081 _bfd_elf_copy_special_section_fields (const bfd *ibfd ATTRIBUTE_UNUSED,
14082 				      bfd *obfd ATTRIBUTE_UNUSED,
14083 				      const Elf_Internal_Shdr *isection,
14084 				      Elf_Internal_Shdr *osection)
14085 {
14086   asection * isec;
14087   asection * osec;
14088   struct bfd_elf_section_data * esd;
14089 
14090   if (isection == NULL)
14091     return false;
14092 
14093   if (isection->sh_type != SHT_SECONDARY_RELOC)
14094     return true;
14095 
14096   isec = isection->bfd_section;
14097   if (isec == NULL)
14098     return false;
14099 
14100   osec = osection->bfd_section;
14101   if (osec == NULL)
14102     return false;
14103 
14104   esd = elf_section_data (osec);
14105   BFD_ASSERT (esd->sec_info == NULL);
14106   esd->sec_info = elf_section_data (isec)->sec_info;
14107   osection->sh_type = SHT_RELA;
14108   osection->sh_link = elf_onesymtab (obfd);
14109   if (osection->sh_link == 0)
14110     {
14111       /* There is no symbol table - we are hosed...  */
14112       _bfd_error_handler
14113 	/* xgettext:c-format */
14114 	(_("%pB(%pA): link section cannot be set"
14115 	   " because the output file does not have a symbol table"),
14116 	obfd, osec);
14117       bfd_set_error (bfd_error_bad_value);
14118       return false;
14119     }
14120 
14121   /* Find the output section that corresponds to the isection's
14122      sh_info link.  */
14123   if (isection->sh_info == 0
14124       || isection->sh_info >= elf_numsections (ibfd))
14125     {
14126       _bfd_error_handler
14127 	/* xgettext:c-format */
14128 	(_("%pB(%pA): info section index is invalid"),
14129 	obfd, osec);
14130       bfd_set_error (bfd_error_bad_value);
14131       return false;
14132     }
14133 
14134   isection = elf_elfsections (ibfd)[isection->sh_info];
14135 
14136   if (isection == NULL
14137       || isection->bfd_section == NULL
14138       || isection->bfd_section->output_section == NULL)
14139     {
14140       _bfd_error_handler
14141 	/* xgettext:c-format */
14142 	(_("%pB(%pA): info section index cannot be set"
14143 	   " because the section is not in the output"),
14144 	obfd, osec);
14145       bfd_set_error (bfd_error_bad_value);
14146       return false;
14147     }
14148 
14149   esd = elf_section_data (isection->bfd_section->output_section);
14150   BFD_ASSERT (esd != NULL);
14151   osection->sh_info = esd->this_idx;
14152   esd->has_secondary_relocs = true;
14153 #if DEBUG_SECONDARY_RELOCS
14154   fprintf (stderr, "update header of %s, sh_link = %u, sh_info = %u\n",
14155 	   osec->name, osection->sh_link, osection->sh_info);
14156   fprintf (stderr, "mark section %s as having secondary relocs\n",
14157 	   bfd_section_name (isection->bfd_section->output_section));
14158 #endif
14159 
14160   return true;
14161 }
14162 
14163 /* Write out a secondary reloc section.
14164 
14165    FIXME: Currently this function can result in a serious performance penalty
14166    for files with secondary relocs and lots of sections.  The proper way to
14167    fix this is for _bfd_elf_copy_special_section_fields() to chain secondary
14168    relocs together and then to have this function just walk that chain.  */
14169 
14170 bool
_bfd_elf_write_secondary_reloc_section(bfd * abfd,asection * sec)14171 _bfd_elf_write_secondary_reloc_section (bfd *abfd, asection *sec)
14172 {
14173   const struct elf_backend_data * const ebd = get_elf_backend_data (abfd);
14174   bfd_vma addr_offset;
14175   asection * relsec;
14176   bfd_vma (*r_info) (bfd_vma, bfd_vma);
14177   bool result = true;
14178 
14179   if (sec == NULL)
14180     return false;
14181 
14182 #if BFD_DEFAULT_TARGET_SIZE > 32
14183   if (bfd_arch_bits_per_address (abfd) != 32)
14184     r_info = elf64_r_info;
14185   else
14186 #endif
14187     r_info = elf32_r_info;
14188 
14189   /* The address of an ELF reloc is section relative for an object
14190      file, and absolute for an executable file or shared library.
14191      The address of a BFD reloc is always section relative.  */
14192   addr_offset = 0;
14193   if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
14194     addr_offset = sec->vma;
14195 
14196   /* Discover if there are any secondary reloc sections
14197      associated with SEC.  */
14198   for (relsec = abfd->sections; relsec != NULL; relsec = relsec->next)
14199     {
14200       const struct bfd_elf_section_data * const esd = elf_section_data (relsec);
14201       Elf_Internal_Shdr * const hdr = (Elf_Internal_Shdr *) & esd->this_hdr;
14202 
14203       if (hdr->sh_type == SHT_RELA
14204 	  && hdr->sh_info == (unsigned) elf_section_data (sec)->this_idx)
14205 	{
14206 	  asymbol *    last_sym;
14207 	  int          last_sym_idx;
14208 	  size_t       reloc_count;
14209 	  size_t       idx;
14210 	  bfd_size_type entsize;
14211 	  arelent *    src_irel;
14212 	  bfd_byte *   dst_rela;
14213 
14214 	  if (hdr->contents != NULL)
14215 	    {
14216 	      _bfd_error_handler
14217 		/* xgettext:c-format */
14218 		(_("%pB(%pA): error: secondary reloc section processed twice"),
14219 		 abfd, relsec);
14220 	      bfd_set_error (bfd_error_bad_value);
14221 	      result = false;
14222 	      continue;
14223 	    }
14224 
14225 	  entsize = hdr->sh_entsize;
14226 	  if (entsize == 0)
14227 	    {
14228 	      _bfd_error_handler
14229 		/* xgettext:c-format */
14230 		(_("%pB(%pA): error: secondary reloc section"
14231 		   " has zero sized entries"),
14232 		 abfd, relsec);
14233 	      bfd_set_error (bfd_error_bad_value);
14234 	      result = false;
14235 	      continue;
14236 	    }
14237 	  else if (entsize != ebd->s->sizeof_rel
14238 		   && entsize != ebd->s->sizeof_rela)
14239 	    {
14240 	      _bfd_error_handler
14241 		/* xgettext:c-format */
14242 		(_("%pB(%pA): error: secondary reloc section"
14243 		   " has non-standard sized entries"),
14244 		 abfd, relsec);
14245 	      bfd_set_error (bfd_error_bad_value);
14246 	      result = false;
14247 	      continue;
14248 	    }
14249 
14250 	  reloc_count = hdr->sh_size / entsize;
14251 	  hdr->sh_size = entsize * reloc_count;
14252 	  if (reloc_count == 0)
14253 	    {
14254 	      _bfd_error_handler
14255 		/* xgettext:c-format */
14256 		(_("%pB(%pA): error: secondary reloc section is empty!"),
14257 		 abfd, relsec);
14258 	      bfd_set_error (bfd_error_bad_value);
14259 	      result = false;
14260 	      continue;
14261 	    }
14262 
14263 	  hdr->contents = bfd_alloc (abfd, hdr->sh_size);
14264 	  if (hdr->contents == NULL)
14265 	    continue;
14266 
14267 #if DEBUG_SECONDARY_RELOCS
14268 	  fprintf (stderr, "write %u secondary relocs for %s from %s\n",
14269 		   reloc_count, sec->name, relsec->name);
14270 #endif
14271 	  last_sym = NULL;
14272 	  last_sym_idx = 0;
14273 	  dst_rela = hdr->contents;
14274 	  src_irel = (arelent *) esd->sec_info;
14275 	  if (src_irel == NULL)
14276 	    {
14277 	      _bfd_error_handler
14278 		/* xgettext:c-format */
14279 		(_("%pB(%pA): error: internal relocs missing"
14280 		   " for secondary reloc section"),
14281 		 abfd, relsec);
14282 	      bfd_set_error (bfd_error_bad_value);
14283 	      result = false;
14284 	      continue;
14285 	    }
14286 
14287 	  for (idx = 0; idx < reloc_count; idx++, dst_rela += entsize)
14288 	    {
14289 	      Elf_Internal_Rela src_rela;
14290 	      arelent *ptr;
14291 	      asymbol *sym;
14292 	      int n;
14293 
14294 	      ptr = src_irel + idx;
14295 	      if (ptr == NULL)
14296 		{
14297 		  _bfd_error_handler
14298 		    /* xgettext:c-format */
14299 		    (_("%pB(%pA): error: reloc table entry %zu is empty"),
14300 		     abfd, relsec, idx);
14301 		  bfd_set_error (bfd_error_bad_value);
14302 		  result = false;
14303 		  break;
14304 		}
14305 
14306 	      if (ptr->sym_ptr_ptr == NULL)
14307 		{
14308 		  /* FIXME: Is this an error ? */
14309 		  n = 0;
14310 		}
14311 	      else
14312 		{
14313 		  sym = *ptr->sym_ptr_ptr;
14314 
14315 		  if (sym == last_sym)
14316 		    n = last_sym_idx;
14317 		  else
14318 		    {
14319 		      n = _bfd_elf_symbol_from_bfd_symbol (abfd, & sym);
14320 		      if (n < 0)
14321 			{
14322 			  _bfd_error_handler
14323 			    /* xgettext:c-format */
14324 			    (_("%pB(%pA): error: secondary reloc %zu"
14325 			       " references a missing symbol"),
14326 			     abfd, relsec, idx);
14327 			  bfd_set_error (bfd_error_bad_value);
14328 			  result = false;
14329 			  n = 0;
14330 			}
14331 
14332 		      last_sym = sym;
14333 		      last_sym_idx = n;
14334 		    }
14335 
14336 		  if (sym->the_bfd != NULL
14337 		      && sym->the_bfd->xvec != abfd->xvec
14338 		      && ! _bfd_elf_validate_reloc (abfd, ptr))
14339 		    {
14340 		      _bfd_error_handler
14341 			/* xgettext:c-format */
14342 			(_("%pB(%pA): error: secondary reloc %zu"
14343 			   " references a deleted symbol"),
14344 			 abfd, relsec, idx);
14345 		      bfd_set_error (bfd_error_bad_value);
14346 		      result = false;
14347 		      n = 0;
14348 		    }
14349 		}
14350 
14351 	      src_rela.r_offset = ptr->address + addr_offset;
14352 	      if (ptr->howto == NULL)
14353 		{
14354 		  _bfd_error_handler
14355 		    /* xgettext:c-format */
14356 		    (_("%pB(%pA): error: secondary reloc %zu"
14357 		       " is of an unknown type"),
14358 		     abfd, relsec, idx);
14359 		  bfd_set_error (bfd_error_bad_value);
14360 		  result = false;
14361 		  src_rela.r_info = r_info (0, 0);
14362 		}
14363 	      else
14364 		src_rela.r_info = r_info (n, ptr->howto->type);
14365 	      src_rela.r_addend = ptr->addend;
14366 
14367 	      if (entsize == ebd->s->sizeof_rel)
14368 		ebd->s->swap_reloc_out (abfd, &src_rela, dst_rela);
14369 	      else /* entsize == ebd->s->sizeof_rela */
14370 		ebd->s->swap_reloca_out (abfd, &src_rela, dst_rela);
14371 	    }
14372 	}
14373     }
14374 
14375   return result;
14376 }
14377