1 /* RISC-V-specific support for NN-bit ELF.
2    Copyright (C) 2011-2021 Free Software Foundation, Inc.
3 
4    Contributed by Andrew Waterman (andrew@sifive.com).
5    Based on TILE-Gx and MIPS targets.
6 
7    This file is part of BFD, the Binary File Descriptor library.
8 
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13 
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18 
19    You should have received a copy of the GNU General Public License
20    along with this program; see the file COPYING3. If not,
21    see <http://www.gnu.org/licenses/>.  */
22 
23 /* This file handles RISC-V ELF targets.  */
24 
25 #include "sysdep.h"
26 #include "bfd.h"
27 #include "libbfd.h"
28 #include "bfdlink.h"
29 #include "genlink.h"
30 #include "elf-bfd.h"
31 #include "elfxx-riscv.h"
32 #include "elf/riscv.h"
33 #include "opcode/riscv.h"
34 #include "objalloc.h"
35 #include "cpu-riscv.h"
36 
37 #include <limits.h>
38 #ifndef CHAR_BIT
39 #define CHAR_BIT 8
40 #endif
41 
42 /* Internal relocations used exclusively by the relaxation pass.  */
43 #define R_RISCV_DELETE (R_RISCV_max + 1)
44 
45 #define ARCH_SIZE NN
46 
47 #define MINUS_ONE ((bfd_vma)0 - 1)
48 
49 #define RISCV_ELF_LOG_WORD_BYTES (ARCH_SIZE == 32 ? 2 : 3)
50 
51 #define RISCV_ELF_WORD_BYTES (1 << RISCV_ELF_LOG_WORD_BYTES)
52 
53 /* The name of the dynamic interpreter.  This is put in the .interp
54    section.  */
55 
56 #define ELF64_DYNAMIC_INTERPRETER "/lib/ld.so.1"
57 #define ELF32_DYNAMIC_INTERPRETER "/lib32/ld.so.1"
58 
59 #define ELF_ARCH			bfd_arch_riscv
60 #define ELF_TARGET_ID			RISCV_ELF_DATA
61 #define ELF_MACHINE_CODE		EM_RISCV
62 #define ELF_MAXPAGESIZE			0x1000
63 #define ELF_COMMONPAGESIZE		0x1000
64 
65 /* RISC-V ELF linker hash entry.  */
66 
67 struct riscv_elf_link_hash_entry
68 {
69   struct elf_link_hash_entry elf;
70 
71 #define GOT_UNKNOWN	0
72 #define GOT_NORMAL	1
73 #define GOT_TLS_GD	2
74 #define GOT_TLS_IE	4
75 #define GOT_TLS_LE	8
76   char tls_type;
77 };
78 
79 #define riscv_elf_hash_entry(ent) \
80   ((struct riscv_elf_link_hash_entry *) (ent))
81 
82 struct _bfd_riscv_elf_obj_tdata
83 {
84   struct elf_obj_tdata root;
85 
86   /* tls_type for each local got entry.  */
87   char *local_got_tls_type;
88 };
89 
90 #define _bfd_riscv_elf_tdata(abfd) \
91   ((struct _bfd_riscv_elf_obj_tdata *) (abfd)->tdata.any)
92 
93 #define _bfd_riscv_elf_local_got_tls_type(abfd) \
94   (_bfd_riscv_elf_tdata (abfd)->local_got_tls_type)
95 
96 #define _bfd_riscv_elf_tls_type(abfd, h, symndx)		\
97   (*((h) != NULL ? &riscv_elf_hash_entry (h)->tls_type		\
98      : &_bfd_riscv_elf_local_got_tls_type (abfd) [symndx]))
99 
100 #define is_riscv_elf(bfd)				\
101   (bfd_get_flavour (bfd) == bfd_target_elf_flavour	\
102    && elf_tdata (bfd) != NULL				\
103    && elf_object_id (bfd) == RISCV_ELF_DATA)
104 
105 static bool
elfNN_riscv_mkobject(bfd * abfd)106 elfNN_riscv_mkobject (bfd *abfd)
107 {
108   return bfd_elf_allocate_object (abfd,
109 				  sizeof (struct _bfd_riscv_elf_obj_tdata),
110 				  RISCV_ELF_DATA);
111 }
112 
113 #include "elf/common.h"
114 #include "elf/internal.h"
115 
116 struct riscv_elf_link_hash_table
117 {
118   struct elf_link_hash_table elf;
119 
120   /* Short-cuts to get to dynamic linker sections.  */
121   asection *sdyntdata;
122 
123   /* The max alignment of output sections.  */
124   bfd_vma max_alignment;
125 
126   /* Used by local STT_GNU_IFUNC symbols.  */
127   htab_t loc_hash_table;
128   void * loc_hash_memory;
129 
130   /* The index of the last unused .rel.iplt slot.  */
131   bfd_vma last_iplt_index;
132 
133   /* Re-run the relaxations from relax pass 0 if TRUE.  */
134   bool restart_relax;
135 
136   /* The data segment phase, don't relax the section
137      when it is exp_seg_relro_adjust.  */
138   int *data_segment_phase;
139 };
140 
141 /* Instruction access functions. */
142 #define riscv_get_insn(bits, ptr)		\
143   ((bits) == 16 ? bfd_getl16 (ptr)		\
144    : (bits) == 32 ? bfd_getl32 (ptr)		\
145    : (bits) == 64 ? bfd_getl64 (ptr)		\
146    : (abort (), (bfd_vma) - 1))
147 #define riscv_put_insn(bits, val, ptr)		\
148   ((bits) == 16 ? bfd_putl16 (val, ptr)		\
149    : (bits) == 32 ? bfd_putl32 (val, ptr)	\
150    : (bits) == 64 ? bfd_putl64 (val, ptr)	\
151    : (abort (), (void) 0))
152 
153 /* Get the RISC-V ELF linker hash table from a link_info structure.  */
154 #define riscv_elf_hash_table(p) \
155   ((is_elf_hash_table ((p)->hash)					\
156     && elf_hash_table_id (elf_hash_table (p)) == RISCV_ELF_DATA)	\
157    ? (struct riscv_elf_link_hash_table *) (p)->hash : NULL)
158 
159 static bool
riscv_info_to_howto_rela(bfd * abfd,arelent * cache_ptr,Elf_Internal_Rela * dst)160 riscv_info_to_howto_rela (bfd *abfd,
161 			  arelent *cache_ptr,
162 			  Elf_Internal_Rela *dst)
163 {
164   cache_ptr->howto = riscv_elf_rtype_to_howto (abfd, ELFNN_R_TYPE (dst->r_info));
165   return cache_ptr->howto != NULL;
166 }
167 
168 static void
riscv_elf_append_rela(bfd * abfd,asection * s,Elf_Internal_Rela * rel)169 riscv_elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
170 {
171   const struct elf_backend_data *bed;
172   bfd_byte *loc;
173 
174   bed = get_elf_backend_data (abfd);
175   loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
176   bed->s->swap_reloca_out (abfd, rel, loc);
177 }
178 
179 /* Return true if a relocation is modifying an instruction. */
180 
181 static bool
riscv_is_insn_reloc(const reloc_howto_type * howto)182 riscv_is_insn_reloc (const reloc_howto_type *howto)
183 {
184   /* Heuristic: A multibyte destination with a nontrivial mask
185      is an instruction */
186   return (howto->bitsize > 8
187 	  && howto->dst_mask != 0
188 	  && ~(howto->dst_mask | (howto->bitsize < sizeof(bfd_vma) * CHAR_BIT
189 	       ? (MINUS_ONE << howto->bitsize) : (bfd_vma)0)) != 0);
190 }
191 
192 /* PLT/GOT stuff.  */
193 #define PLT_HEADER_INSNS 8
194 #define PLT_ENTRY_INSNS 4
195 #define PLT_HEADER_SIZE (PLT_HEADER_INSNS * 4)
196 #define PLT_ENTRY_SIZE (PLT_ENTRY_INSNS * 4)
197 #define GOT_ENTRY_SIZE RISCV_ELF_WORD_BYTES
198 /* Reserve two entries of GOTPLT for ld.so, one is used for PLT resolver,
199    the other is used for link map.  Other targets also reserve one more
200    entry used for runtime profile?  */
201 #define GOTPLT_HEADER_SIZE (2 * GOT_ENTRY_SIZE)
202 
203 #define sec_addr(sec) ((sec)->output_section->vma + (sec)->output_offset)
204 
205 #if ARCH_SIZE == 32
206 # define MATCH_LREG MATCH_LW
207 #else
208 # define MATCH_LREG MATCH_LD
209 #endif
210 
211 /* Generate a PLT header.  */
212 
213 static bool
riscv_make_plt_header(bfd * output_bfd,bfd_vma gotplt_addr,bfd_vma addr,uint32_t * entry)214 riscv_make_plt_header (bfd *output_bfd, bfd_vma gotplt_addr, bfd_vma addr,
215 		       uint32_t *entry)
216 {
217   bfd_vma gotplt_offset_high = RISCV_PCREL_HIGH_PART (gotplt_addr, addr);
218   bfd_vma gotplt_offset_low = RISCV_PCREL_LOW_PART (gotplt_addr, addr);
219 
220   /* RVE has no t3 register, so this won't work, and is not supported.  */
221   if (elf_elfheader (output_bfd)->e_flags & EF_RISCV_RVE)
222     {
223       _bfd_error_handler (_("%pB: warning: RVE PLT generation not supported"),
224 			  output_bfd);
225       return false;
226     }
227 
228   /* auipc  t2, %hi(.got.plt)
229      sub    t1, t1, t3		     # shifted .got.plt offset + hdr size + 12
230      l[w|d] t3, %lo(.got.plt)(t2)    # _dl_runtime_resolve
231      addi   t1, t1, -(hdr size + 12) # shifted .got.plt offset
232      addi   t0, t2, %lo(.got.plt)    # &.got.plt
233      srli   t1, t1, log2(16/PTRSIZE) # .got.plt offset
234      l[w|d] t0, PTRSIZE(t0)	     # link map
235      jr	    t3  */
236 
237   entry[0] = RISCV_UTYPE (AUIPC, X_T2, gotplt_offset_high);
238   entry[1] = RISCV_RTYPE (SUB, X_T1, X_T1, X_T3);
239   entry[2] = RISCV_ITYPE (LREG, X_T3, X_T2, gotplt_offset_low);
240   entry[3] = RISCV_ITYPE (ADDI, X_T1, X_T1, (uint32_t) -(PLT_HEADER_SIZE + 12));
241   entry[4] = RISCV_ITYPE (ADDI, X_T0, X_T2, gotplt_offset_low);
242   entry[5] = RISCV_ITYPE (SRLI, X_T1, X_T1, 4 - RISCV_ELF_LOG_WORD_BYTES);
243   entry[6] = RISCV_ITYPE (LREG, X_T0, X_T0, RISCV_ELF_WORD_BYTES);
244   entry[7] = RISCV_ITYPE (JALR, 0, X_T3, 0);
245 
246   return true;
247 }
248 
249 /* Generate a PLT entry.  */
250 
251 static bool
riscv_make_plt_entry(bfd * output_bfd,bfd_vma got,bfd_vma addr,uint32_t * entry)252 riscv_make_plt_entry (bfd *output_bfd, bfd_vma got, bfd_vma addr,
253 		      uint32_t *entry)
254 {
255   /* RVE has no t3 register, so this won't work, and is not supported.  */
256   if (elf_elfheader (output_bfd)->e_flags & EF_RISCV_RVE)
257     {
258       _bfd_error_handler (_("%pB: warning: RVE PLT generation not supported"),
259 			  output_bfd);
260       return false;
261     }
262 
263   /* auipc  t3, %hi(.got.plt entry)
264      l[w|d] t3, %lo(.got.plt entry)(t3)
265      jalr   t1, t3
266      nop  */
267 
268   entry[0] = RISCV_UTYPE (AUIPC, X_T3, RISCV_PCREL_HIGH_PART (got, addr));
269   entry[1] = RISCV_ITYPE (LREG,  X_T3, X_T3, RISCV_PCREL_LOW_PART (got, addr));
270   entry[2] = RISCV_ITYPE (JALR, X_T1, X_T3, 0);
271   entry[3] = RISCV_NOP;
272 
273   return true;
274 }
275 
276 /* Create an entry in an RISC-V ELF linker hash table.  */
277 
278 static struct bfd_hash_entry *
link_hash_newfunc(struct bfd_hash_entry * entry,struct bfd_hash_table * table,const char * string)279 link_hash_newfunc (struct bfd_hash_entry *entry,
280 		   struct bfd_hash_table *table, const char *string)
281 {
282   /* Allocate the structure if it has not already been allocated by a
283      subclass.  */
284   if (entry == NULL)
285     {
286       entry =
287 	bfd_hash_allocate (table,
288 			   sizeof (struct riscv_elf_link_hash_entry));
289       if (entry == NULL)
290 	return entry;
291     }
292 
293   /* Call the allocation method of the superclass.  */
294   entry = _bfd_elf_link_hash_newfunc (entry, table, string);
295   if (entry != NULL)
296     {
297       struct riscv_elf_link_hash_entry *eh;
298 
299       eh = (struct riscv_elf_link_hash_entry *) entry;
300       eh->tls_type = GOT_UNKNOWN;
301     }
302 
303   return entry;
304 }
305 
306 /* Compute a hash of a local hash entry.  We use elf_link_hash_entry
307    for local symbol so that we can handle local STT_GNU_IFUNC symbols
308    as global symbol.  We reuse indx and dynstr_index for local symbol
309    hash since they aren't used by global symbols in this backend.  */
310 
311 static hashval_t
riscv_elf_local_htab_hash(const void * ptr)312 riscv_elf_local_htab_hash (const void *ptr)
313 {
314   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) ptr;
315   return ELF_LOCAL_SYMBOL_HASH (h->indx, h->dynstr_index);
316 }
317 
318 /* Compare local hash entries.  */
319 
320 static int
riscv_elf_local_htab_eq(const void * ptr1,const void * ptr2)321 riscv_elf_local_htab_eq (const void *ptr1, const void *ptr2)
322 {
323   struct elf_link_hash_entry *h1 = (struct elf_link_hash_entry *) ptr1;
324   struct elf_link_hash_entry *h2 = (struct elf_link_hash_entry *) ptr2;
325 
326   return h1->indx == h2->indx && h1->dynstr_index == h2->dynstr_index;
327 }
328 
329 /* Find and/or create a hash entry for local symbol.  */
330 
331 static struct elf_link_hash_entry *
riscv_elf_get_local_sym_hash(struct riscv_elf_link_hash_table * htab,bfd * abfd,const Elf_Internal_Rela * rel,bool create)332 riscv_elf_get_local_sym_hash (struct riscv_elf_link_hash_table *htab,
333 			      bfd *abfd, const Elf_Internal_Rela *rel,
334 			      bool create)
335 {
336   struct riscv_elf_link_hash_entry eh, *ret;
337   asection *sec = abfd->sections;
338   hashval_t h = ELF_LOCAL_SYMBOL_HASH (sec->id,
339 				       ELFNN_R_SYM (rel->r_info));
340   void **slot;
341 
342   eh.elf.indx = sec->id;
343   eh.elf.dynstr_index = ELFNN_R_SYM (rel->r_info);
344   slot = htab_find_slot_with_hash (htab->loc_hash_table, &eh, h,
345 				   create ? INSERT : NO_INSERT);
346 
347   if (!slot)
348     return NULL;
349 
350   if (*slot)
351     {
352       ret = (struct riscv_elf_link_hash_entry *) *slot;
353       return &ret->elf;
354     }
355 
356   ret = (struct riscv_elf_link_hash_entry *)
357 	objalloc_alloc ((struct objalloc *) htab->loc_hash_memory,
358 			sizeof (struct riscv_elf_link_hash_entry));
359   if (ret)
360     {
361       memset (ret, 0, sizeof (*ret));
362       ret->elf.indx = sec->id;
363       ret->elf.dynstr_index = ELFNN_R_SYM (rel->r_info);
364       ret->elf.dynindx = -1;
365       *slot = ret;
366     }
367   return &ret->elf;
368 }
369 
370 /* Destroy a RISC-V elf linker hash table.  */
371 
372 static void
riscv_elf_link_hash_table_free(bfd * obfd)373 riscv_elf_link_hash_table_free (bfd *obfd)
374 {
375   struct riscv_elf_link_hash_table *ret
376     = (struct riscv_elf_link_hash_table *) obfd->link.hash;
377 
378   if (ret->loc_hash_table)
379     htab_delete (ret->loc_hash_table);
380   if (ret->loc_hash_memory)
381     objalloc_free ((struct objalloc *) ret->loc_hash_memory);
382 
383   _bfd_elf_link_hash_table_free (obfd);
384 }
385 
386 /* Create a RISC-V ELF linker hash table.  */
387 
388 static struct bfd_link_hash_table *
riscv_elf_link_hash_table_create(bfd * abfd)389 riscv_elf_link_hash_table_create (bfd *abfd)
390 {
391   struct riscv_elf_link_hash_table *ret;
392   size_t amt = sizeof (struct riscv_elf_link_hash_table);
393 
394   ret = (struct riscv_elf_link_hash_table *) bfd_zmalloc (amt);
395   if (ret == NULL)
396     return NULL;
397 
398   if (!_bfd_elf_link_hash_table_init (&ret->elf, abfd, link_hash_newfunc,
399 				      sizeof (struct riscv_elf_link_hash_entry),
400 				      RISCV_ELF_DATA))
401     {
402       free (ret);
403       return NULL;
404     }
405 
406   ret->max_alignment = (bfd_vma) -1;
407   ret->restart_relax = false;
408 
409   /* Create hash table for local ifunc.  */
410   ret->loc_hash_table = htab_try_create (1024,
411 					 riscv_elf_local_htab_hash,
412 					 riscv_elf_local_htab_eq,
413 					 NULL);
414   ret->loc_hash_memory = objalloc_create ();
415   if (!ret->loc_hash_table || !ret->loc_hash_memory)
416     {
417       riscv_elf_link_hash_table_free (abfd);
418       return NULL;
419     }
420   ret->elf.root.hash_table_free = riscv_elf_link_hash_table_free;
421 
422   return &ret->elf.root;
423 }
424 
425 /* Create the .got section.  */
426 
427 static bool
riscv_elf_create_got_section(bfd * abfd,struct bfd_link_info * info)428 riscv_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
429 {
430   flagword flags;
431   asection *s, *s_got;
432   struct elf_link_hash_entry *h;
433   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
434   struct elf_link_hash_table *htab = elf_hash_table (info);
435 
436   /* This function may be called more than once.  */
437   if (htab->sgot != NULL)
438     return true;
439 
440   flags = bed->dynamic_sec_flags;
441 
442   s = bfd_make_section_anyway_with_flags (abfd,
443 					  (bed->rela_plts_and_copies_p
444 					   ? ".rela.got" : ".rel.got"),
445 					  (bed->dynamic_sec_flags
446 					   | SEC_READONLY));
447   if (s == NULL
448       || !bfd_set_section_alignment (s, bed->s->log_file_align))
449     return false;
450   htab->srelgot = s;
451 
452   s = s_got = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
453   if (s == NULL
454       || !bfd_set_section_alignment (s, bed->s->log_file_align))
455     return false;
456   htab->sgot = s;
457 
458   /* The first bit of the global offset table is the header.  */
459   s->size += bed->got_header_size;
460 
461   if (bed->want_got_plt)
462     {
463       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
464       if (s == NULL
465 	  || !bfd_set_section_alignment (s, bed->s->log_file_align))
466 	return false;
467       htab->sgotplt = s;
468 
469       /* Reserve room for the header.  */
470       s->size += GOTPLT_HEADER_SIZE;
471     }
472 
473   if (bed->want_got_sym)
474     {
475       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
476 	 section.  We don't do this in the linker script because we don't want
477 	 to define the symbol if we are not creating a global offset
478 	 table.  */
479       h = _bfd_elf_define_linkage_sym (abfd, info, s_got,
480 				       "_GLOBAL_OFFSET_TABLE_");
481       elf_hash_table (info)->hgot = h;
482       if (h == NULL)
483 	return false;
484     }
485 
486   return true;
487 }
488 
489 /* Create .plt, .rela.plt, .got, .got.plt, .rela.got, .dynbss, and
490    .rela.bss sections in DYNOBJ, and set up shortcuts to them in our
491    hash table.  */
492 
493 static bool
riscv_elf_create_dynamic_sections(bfd * dynobj,struct bfd_link_info * info)494 riscv_elf_create_dynamic_sections (bfd *dynobj,
495 				   struct bfd_link_info *info)
496 {
497   struct riscv_elf_link_hash_table *htab;
498 
499   htab = riscv_elf_hash_table (info);
500   BFD_ASSERT (htab != NULL);
501 
502   if (!riscv_elf_create_got_section (dynobj, info))
503     return false;
504 
505   if (!_bfd_elf_create_dynamic_sections (dynobj, info))
506     return false;
507 
508   if (!bfd_link_pic (info))
509     {
510       /* Technically, this section doesn't have contents.  It is used as the
511 	 target of TLS copy relocs, to copy TLS data from shared libraries into
512 	 the executable.  However, if we don't mark it as loadable, then it
513 	 matches the IS_TBSS test in ldlang.c, and there is no run-time address
514 	 space allocated for it even though it has SEC_ALLOC.  That test is
515 	 correct for .tbss, but not correct for this section.  There is also
516 	 a second problem that having a section with no contents can only work
517 	 if it comes after all sections with contents in the same segment,
518 	 but the linker script does not guarantee that.  This is just mixed in
519 	 with other .tdata.* sections.  We can fix both problems by lying and
520 	 saying that there are contents.  This section is expected to be small
521 	 so this should not cause a significant extra program startup cost.  */
522       htab->sdyntdata =
523 	bfd_make_section_anyway_with_flags (dynobj, ".tdata.dyn",
524 					    (SEC_ALLOC | SEC_THREAD_LOCAL
525 					     | SEC_LOAD | SEC_DATA
526 					     | SEC_HAS_CONTENTS
527 					     | SEC_LINKER_CREATED));
528     }
529 
530   if (!htab->elf.splt || !htab->elf.srelplt || !htab->elf.sdynbss
531       || (!bfd_link_pic (info) && (!htab->elf.srelbss || !htab->sdyntdata)))
532     abort ();
533 
534   return true;
535 }
536 
537 /* Copy the extra info we tack onto an elf_link_hash_entry.  */
538 
539 static void
riscv_elf_copy_indirect_symbol(struct bfd_link_info * info,struct elf_link_hash_entry * dir,struct elf_link_hash_entry * ind)540 riscv_elf_copy_indirect_symbol (struct bfd_link_info *info,
541 				struct elf_link_hash_entry *dir,
542 				struct elf_link_hash_entry *ind)
543 {
544   struct riscv_elf_link_hash_entry *edir, *eind;
545 
546   edir = (struct riscv_elf_link_hash_entry *) dir;
547   eind = (struct riscv_elf_link_hash_entry *) ind;
548 
549   if (ind->root.type == bfd_link_hash_indirect
550       && dir->got.refcount <= 0)
551     {
552       edir->tls_type = eind->tls_type;
553       eind->tls_type = GOT_UNKNOWN;
554     }
555   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
556 }
557 
558 static bool
riscv_elf_record_tls_type(bfd * abfd,struct elf_link_hash_entry * h,unsigned long symndx,char tls_type)559 riscv_elf_record_tls_type (bfd *abfd, struct elf_link_hash_entry *h,
560 			   unsigned long symndx, char tls_type)
561 {
562   char *new_tls_type = &_bfd_riscv_elf_tls_type (abfd, h, symndx);
563 
564   *new_tls_type |= tls_type;
565   if ((*new_tls_type & GOT_NORMAL) && (*new_tls_type & ~GOT_NORMAL))
566     {
567       (*_bfd_error_handler)
568 	(_("%pB: `%s' accessed both as normal and thread local symbol"),
569 	 abfd, h ? h->root.root.string : "<local>");
570       return false;
571     }
572   return true;
573 }
574 
575 static bool
riscv_elf_record_got_reference(bfd * abfd,struct bfd_link_info * info,struct elf_link_hash_entry * h,long symndx)576 riscv_elf_record_got_reference (bfd *abfd, struct bfd_link_info *info,
577 				struct elf_link_hash_entry *h, long symndx)
578 {
579   struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
580   Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
581 
582   if (htab->elf.sgot == NULL)
583     {
584       if (!riscv_elf_create_got_section (htab->elf.dynobj, info))
585 	return false;
586     }
587 
588   if (h != NULL)
589     {
590       h->got.refcount += 1;
591       return true;
592     }
593 
594   /* This is a global offset table entry for a local symbol.  */
595   if (elf_local_got_refcounts (abfd) == NULL)
596     {
597       bfd_size_type size = symtab_hdr->sh_info * (sizeof (bfd_vma) + 1);
598       if (!(elf_local_got_refcounts (abfd) = bfd_zalloc (abfd, size)))
599 	return false;
600       _bfd_riscv_elf_local_got_tls_type (abfd)
601 	= (char *) (elf_local_got_refcounts (abfd) + symtab_hdr->sh_info);
602     }
603   elf_local_got_refcounts (abfd) [symndx] += 1;
604 
605   return true;
606 }
607 
608 static bool
bad_static_reloc(bfd * abfd,unsigned r_type,struct elf_link_hash_entry * h)609 bad_static_reloc (bfd *abfd, unsigned r_type, struct elf_link_hash_entry *h)
610 {
611   reloc_howto_type * r = riscv_elf_rtype_to_howto (abfd, r_type);
612 
613   /* We propably can improve the information to tell users that they
614      should be recompile the code with -fPIC or -fPIE, just like what
615      x86 does.  */
616   (*_bfd_error_handler)
617     (_("%pB: relocation %s against `%s' can not be used when making a shared "
618        "object; recompile with -fPIC"),
619      abfd, r ? r->name : _("<unknown>"),
620      h != NULL ? h->root.root.string : "a local symbol");
621   bfd_set_error (bfd_error_bad_value);
622   return false;
623 }
624 
625 /* Look through the relocs for a section during the first phase, and
626    allocate space in the global offset table or procedure linkage
627    table.  */
628 
629 static bool
riscv_elf_check_relocs(bfd * abfd,struct bfd_link_info * info,asection * sec,const Elf_Internal_Rela * relocs)630 riscv_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
631 			asection *sec, const Elf_Internal_Rela *relocs)
632 {
633   struct riscv_elf_link_hash_table *htab;
634   Elf_Internal_Shdr *symtab_hdr;
635   struct elf_link_hash_entry **sym_hashes;
636   const Elf_Internal_Rela *rel;
637   asection *sreloc = NULL;
638 
639   if (bfd_link_relocatable (info))
640     return true;
641 
642   htab = riscv_elf_hash_table (info);
643   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
644   sym_hashes = elf_sym_hashes (abfd);
645 
646   if (htab->elf.dynobj == NULL)
647     htab->elf.dynobj = abfd;
648 
649   for (rel = relocs; rel < relocs + sec->reloc_count; rel++)
650     {
651       unsigned int r_type;
652       unsigned int r_symndx;
653       struct elf_link_hash_entry *h;
654 
655       r_symndx = ELFNN_R_SYM (rel->r_info);
656       r_type = ELFNN_R_TYPE (rel->r_info);
657 
658       if (r_symndx >= NUM_SHDR_ENTRIES (symtab_hdr))
659 	{
660 	  (*_bfd_error_handler) (_("%pB: bad symbol index: %d"),
661 				 abfd, r_symndx);
662 	  return false;
663 	}
664 
665       if (r_symndx < symtab_hdr->sh_info)
666 	{
667 	  /* A local symbol.  */
668 	  Elf_Internal_Sym *isym = bfd_sym_from_r_symndx (&htab->elf.sym_cache,
669 							  abfd, r_symndx);
670 	  if (isym == NULL)
671 	    return false;
672 
673 	  /* Check relocation against local STT_GNU_IFUNC symbol.  */
674 	  if (ELF_ST_TYPE (isym->st_info) == STT_GNU_IFUNC)
675 	    {
676 	      h = riscv_elf_get_local_sym_hash (htab, abfd, rel, true);
677 	      if (h == NULL)
678 		return false;
679 
680 	      /* Fake STT_GNU_IFUNC global symbol.  */
681 	      h->root.root.string = bfd_elf_sym_name (abfd, symtab_hdr,
682 						      isym, NULL);
683 	      h->type = STT_GNU_IFUNC;
684 	      h->def_regular = 1;
685 	      h->ref_regular = 1;
686 	      h->forced_local = 1;
687 	      h->root.type = bfd_link_hash_defined;
688 	    }
689 	  else
690 	    h = NULL;
691 	}
692       else
693 	{
694 	  h = sym_hashes[r_symndx - symtab_hdr->sh_info];
695 	  while (h->root.type == bfd_link_hash_indirect
696 		 || h->root.type == bfd_link_hash_warning)
697 	    h = (struct elf_link_hash_entry *) h->root.u.i.link;
698 	}
699 
700       if (h != NULL)
701 	{
702 	  switch (r_type)
703 	    {
704 	    case R_RISCV_32:
705 	    case R_RISCV_64:
706 	    case R_RISCV_CALL:
707 	    case R_RISCV_CALL_PLT:
708 	    case R_RISCV_HI20:
709 	    case R_RISCV_GOT_HI20:
710 	    case R_RISCV_PCREL_HI20:
711 	      /* Create the ifunc sections, iplt and ipltgot, for static
712 		 executables.  */
713 	      if (h->type == STT_GNU_IFUNC
714 		  && !_bfd_elf_create_ifunc_sections (htab->elf.dynobj, info))
715 		return false;
716 	      break;
717 
718 	    default:
719 	      break;
720 	    }
721 
722 	  /* It is referenced by a non-shared object.  */
723 	  h->ref_regular = 1;
724 	}
725 
726       switch (r_type)
727 	{
728 	case R_RISCV_TLS_GD_HI20:
729 	  if (!riscv_elf_record_got_reference (abfd, info, h, r_symndx)
730 	      || !riscv_elf_record_tls_type (abfd, h, r_symndx, GOT_TLS_GD))
731 	    return false;
732 	  break;
733 
734 	case R_RISCV_TLS_GOT_HI20:
735 	  if (bfd_link_pic (info))
736 	    info->flags |= DF_STATIC_TLS;
737 	  if (!riscv_elf_record_got_reference (abfd, info, h, r_symndx)
738 	      || !riscv_elf_record_tls_type (abfd, h, r_symndx, GOT_TLS_IE))
739 	    return false;
740 	  break;
741 
742 	case R_RISCV_GOT_HI20:
743 	  if (!riscv_elf_record_got_reference (abfd, info, h, r_symndx)
744 	      || !riscv_elf_record_tls_type (abfd, h, r_symndx, GOT_NORMAL))
745 	    return false;
746 	  break;
747 
748 	case R_RISCV_CALL:
749 	case R_RISCV_CALL_PLT:
750 	  /* These symbol requires a procedure linkage table entry.
751 	     We actually build the entry in adjust_dynamic_symbol,
752 	     because these might be a case of linking PIC code without
753 	     linking in any dynamic objects, in which case we don't
754 	     need to generate a procedure linkage table after all.  */
755 
756 	  /* If it is a local symbol, then we resolve it directly
757 	     without creating a PLT entry.  */
758 	  if (h == NULL)
759 	    continue;
760 
761 	  h->needs_plt = 1;
762 	  h->plt.refcount += 1;
763 	  break;
764 
765 	case R_RISCV_PCREL_HI20:
766 	  if (h != NULL
767 	      && h->type == STT_GNU_IFUNC)
768 	    {
769 	      h->non_got_ref = 1;
770 	      h->pointer_equality_needed = 1;
771 
772 	      /* We don't use the PCREL_HI20 in the data section,
773 		 so we always need the plt when it refers to
774 		 ifunc symbol.  */
775 	      h->plt.refcount += 1;
776 	    }
777 	  /* Fall through.  */
778 
779 	case R_RISCV_JAL:
780 	case R_RISCV_BRANCH:
781 	case R_RISCV_RVC_BRANCH:
782 	case R_RISCV_RVC_JUMP:
783 	  /* In shared libraries and pie, these relocs are known
784 	     to bind locally.  */
785 	  if (bfd_link_pic (info))
786 	    break;
787 	  goto static_reloc;
788 
789 	case R_RISCV_TPREL_HI20:
790 	  if (!bfd_link_executable (info))
791 	    return bad_static_reloc (abfd, r_type, h);
792 	  if (h != NULL)
793 	    riscv_elf_record_tls_type (abfd, h, r_symndx, GOT_TLS_LE);
794 	  goto static_reloc;
795 
796 	case R_RISCV_HI20:
797 	  if (bfd_link_pic (info))
798 	    return bad_static_reloc (abfd, r_type, h);
799 	  /* Fall through.  */
800 
801 	case R_RISCV_COPY:
802 	case R_RISCV_JUMP_SLOT:
803 	case R_RISCV_RELATIVE:
804 	case R_RISCV_64:
805 	case R_RISCV_32:
806 	  /* Fall through.  */
807 
808 	static_reloc:
809 
810 	  if (h != NULL
811 	      && (!bfd_link_pic (info)
812 		  || h->type == STT_GNU_IFUNC))
813 	    {
814 	      /* This reloc might not bind locally.  */
815 	      h->non_got_ref = 1;
816 	      h->pointer_equality_needed = 1;
817 
818 	      if (!h->def_regular
819 		  || (sec->flags & (SEC_CODE | SEC_READONLY)) != 0)
820 		{
821 		  /* We may need a .plt entry if the symbol is a function
822 		     defined in a shared lib or is a function referenced
823 		     from the code or read-only section.  */
824 		  h->plt.refcount += 1;
825 		}
826 	    }
827 
828 	  /* If we are creating a shared library, and this is a reloc
829 	     against a global symbol, or a non PC relative reloc
830 	     against a local symbol, then we need to copy the reloc
831 	     into the shared library.  However, if we are linking with
832 	     -Bsymbolic, we do not need to copy a reloc against a
833 	     global symbol which is defined in an object we are
834 	     including in the link (i.e., DEF_REGULAR is set).  At
835 	     this point we have not seen all the input files, so it is
836 	     possible that DEF_REGULAR is not set now but will be set
837 	     later (it is never cleared).  In case of a weak definition,
838 	     DEF_REGULAR may be cleared later by a strong definition in
839 	     a shared library.  We account for that possibility below by
840 	     storing information in the relocs_copied field of the hash
841 	     table entry.  A similar situation occurs when creating
842 	     shared libraries and symbol visibility changes render the
843 	     symbol local.
844 
845 	     If on the other hand, we are creating an executable, we
846 	     may need to keep relocations for symbols satisfied by a
847 	     dynamic library if we manage to avoid copy relocs for the
848 	     symbol.
849 
850 	     Generate dynamic pointer relocation against STT_GNU_IFUNC
851 	     symbol in the non-code section (R_RISCV_32/R_RISCV_64).  */
852 	  reloc_howto_type * r = riscv_elf_rtype_to_howto (abfd, r_type);
853 
854 	  if ((bfd_link_pic (info)
855 	       && (sec->flags & SEC_ALLOC) != 0
856 	       && ((r != NULL && !r->pc_relative)
857 		   || (h != NULL
858 		       && (!info->symbolic
859 			   || h->root.type == bfd_link_hash_defweak
860 			   || !h->def_regular))))
861 	      || (!bfd_link_pic (info)
862 		  && (sec->flags & SEC_ALLOC) != 0
863 		  && h != NULL
864 		  && (h->root.type == bfd_link_hash_defweak
865 		      || !h->def_regular))
866 	      || (!bfd_link_pic (info)
867 		  && h != NULL
868 		  && h->type == STT_GNU_IFUNC
869 		  && (sec->flags & SEC_CODE) == 0))
870 	    {
871 	      struct elf_dyn_relocs *p;
872 	      struct elf_dyn_relocs **head;
873 
874 	      /* When creating a shared object, we must copy these
875 		 relocs into the output file.  We create a reloc
876 		 section in dynobj and make room for the reloc.  */
877 	      if (sreloc == NULL)
878 		{
879 		  sreloc = _bfd_elf_make_dynamic_reloc_section
880 		    (sec, htab->elf.dynobj, RISCV_ELF_LOG_WORD_BYTES,
881 		    abfd, /*rela?*/ true);
882 
883 		  if (sreloc == NULL)
884 		    return false;
885 		}
886 
887 	      /* If this is a global symbol, we count the number of
888 		 relocations we need for this symbol.  */
889 	      if (h != NULL)
890 		head = &h->dyn_relocs;
891 	      else
892 		{
893 		  /* Track dynamic relocs needed for local syms too.
894 		     We really need local syms available to do this
895 		     easily.  Oh well.  */
896 
897 		  asection *s;
898 		  void *vpp;
899 		  Elf_Internal_Sym *isym;
900 
901 		  isym = bfd_sym_from_r_symndx (&htab->elf.sym_cache,
902 						abfd, r_symndx);
903 		  if (isym == NULL)
904 		    return false;
905 
906 		  s = bfd_section_from_elf_index (abfd, isym->st_shndx);
907 		  if (s == NULL)
908 		    s = sec;
909 
910 		  vpp = &elf_section_data (s)->local_dynrel;
911 		  head = (struct elf_dyn_relocs **) vpp;
912 		}
913 
914 	      p = *head;
915 	      if (p == NULL || p->sec != sec)
916 		{
917 		  size_t amt = sizeof *p;
918 		  p = ((struct elf_dyn_relocs *)
919 		       bfd_alloc (htab->elf.dynobj, amt));
920 		  if (p == NULL)
921 		    return false;
922 		  p->next = *head;
923 		  *head = p;
924 		  p->sec = sec;
925 		  p->count = 0;
926 		  p->pc_count = 0;
927 		}
928 
929 	      p->count += 1;
930 	      p->pc_count += r == NULL ? 0 : r->pc_relative;
931 	    }
932 
933 	  break;
934 
935 	case R_RISCV_GNU_VTINHERIT:
936 	  if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
937 	    return false;
938 	  break;
939 
940 	case R_RISCV_GNU_VTENTRY:
941 	  if (!bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_addend))
942 	    return false;
943 	  break;
944 
945 	default:
946 	  break;
947 	}
948     }
949 
950   return true;
951 }
952 
953 static asection *
riscv_elf_gc_mark_hook(asection * sec,struct bfd_link_info * info,Elf_Internal_Rela * rel,struct elf_link_hash_entry * h,Elf_Internal_Sym * sym)954 riscv_elf_gc_mark_hook (asection *sec,
955 			struct bfd_link_info *info,
956 			Elf_Internal_Rela *rel,
957 			struct elf_link_hash_entry *h,
958 			Elf_Internal_Sym *sym)
959 {
960   if (h != NULL)
961     switch (ELFNN_R_TYPE (rel->r_info))
962       {
963       case R_RISCV_GNU_VTINHERIT:
964       case R_RISCV_GNU_VTENTRY:
965 	return NULL;
966       }
967 
968   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
969 }
970 
971 /* Adjust a symbol defined by a dynamic object and referenced by a
972    regular object.  The current definition is in some section of the
973    dynamic object, but we're not including those sections.  We have to
974    change the definition to something the rest of the link can
975    understand.  */
976 
977 static bool
riscv_elf_adjust_dynamic_symbol(struct bfd_link_info * info,struct elf_link_hash_entry * h)978 riscv_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
979 				 struct elf_link_hash_entry *h)
980 {
981   struct riscv_elf_link_hash_table *htab;
982   struct riscv_elf_link_hash_entry * eh;
983   bfd *dynobj;
984   asection *s, *srel;
985 
986   htab = riscv_elf_hash_table (info);
987   BFD_ASSERT (htab != NULL);
988 
989   dynobj = htab->elf.dynobj;
990 
991   /* Make sure we know what is going on here.  */
992   BFD_ASSERT (dynobj != NULL
993 	      && (h->needs_plt
994 		  || h->type == STT_GNU_IFUNC
995 		  || h->is_weakalias
996 		  || (h->def_dynamic
997 		      && h->ref_regular
998 		      && !h->def_regular)));
999 
1000   /* If this is a function, put it in the procedure linkage table.  We
1001      will fill in the contents of the procedure linkage table later
1002      (although we could actually do it here).  */
1003   if (h->type == STT_FUNC || h->type == STT_GNU_IFUNC || h->needs_plt)
1004     {
1005       if (h->plt.refcount <= 0
1006 	  || (h->type != STT_GNU_IFUNC
1007 	      && (SYMBOL_CALLS_LOCAL (info, h)
1008 		  || (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1009 		      && h->root.type == bfd_link_hash_undefweak))))
1010 	{
1011 	  /* This case can occur if we saw a R_RISCV_CALL_PLT reloc in an
1012 	     input file, but the symbol was never referred to by a dynamic
1013 	     object, or if all references were garbage collected.  In such
1014 	     a case, we don't actually need to build a PLT entry.  */
1015 	  h->plt.offset = (bfd_vma) -1;
1016 	  h->needs_plt = 0;
1017 	}
1018 
1019       return true;
1020     }
1021   else
1022     h->plt.offset = (bfd_vma) -1;
1023 
1024   /* If this is a weak symbol, and there is a real definition, the
1025      processor independent code will have arranged for us to see the
1026      real definition first, and we can just use the same value.  */
1027   if (h->is_weakalias)
1028     {
1029       struct elf_link_hash_entry *def = weakdef (h);
1030       BFD_ASSERT (def->root.type == bfd_link_hash_defined);
1031       h->root.u.def.section = def->root.u.def.section;
1032       h->root.u.def.value = def->root.u.def.value;
1033       return true;
1034     }
1035 
1036   /* This is a reference to a symbol defined by a dynamic object which
1037      is not a function.  */
1038 
1039   /* If we are creating a shared library, we must presume that the
1040      only references to the symbol are via the global offset table.
1041      For such cases we need not do anything here; the relocations will
1042      be handled correctly by relocate_section.  */
1043   if (bfd_link_pic (info))
1044     return true;
1045 
1046   /* If there are no references to this symbol that do not use the
1047      GOT, we don't need to generate a copy reloc.  */
1048   if (!h->non_got_ref)
1049     return true;
1050 
1051   /* If -z nocopyreloc was given, we won't generate them either.  */
1052   if (info->nocopyreloc)
1053     {
1054       h->non_got_ref = 0;
1055       return true;
1056     }
1057 
1058   /* If we don't find any dynamic relocs in read-only sections, then
1059      we'll be keeping the dynamic relocs and avoiding the copy reloc.  */
1060   if (!_bfd_elf_readonly_dynrelocs (h))
1061     {
1062       h->non_got_ref = 0;
1063       return true;
1064     }
1065 
1066   /* We must allocate the symbol in our .dynbss section, which will
1067      become part of the .bss section of the executable.  There will be
1068      an entry for this symbol in the .dynsym section.  The dynamic
1069      object will contain position independent code, so all references
1070      from the dynamic object to this symbol will go through the global
1071      offset table.  The dynamic linker will use the .dynsym entry to
1072      determine the address it must put in the global offset table, so
1073      both the dynamic object and the regular object will refer to the
1074      same memory location for the variable.  */
1075 
1076   /* We must generate a R_RISCV_COPY reloc to tell the dynamic linker
1077      to copy the initial value out of the dynamic object and into the
1078      runtime process image.  We need to remember the offset into the
1079      .rel.bss section we are going to use.  */
1080   eh = (struct riscv_elf_link_hash_entry *) h;
1081   if (eh->tls_type & ~GOT_NORMAL)
1082     {
1083       s = htab->sdyntdata;
1084       srel = htab->elf.srelbss;
1085     }
1086   else if ((h->root.u.def.section->flags & SEC_READONLY) != 0)
1087     {
1088       s = htab->elf.sdynrelro;
1089       srel = htab->elf.sreldynrelro;
1090     }
1091   else
1092     {
1093       s = htab->elf.sdynbss;
1094       srel = htab->elf.srelbss;
1095     }
1096   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0 && h->size != 0)
1097     {
1098       srel->size += sizeof (ElfNN_External_Rela);
1099       h->needs_copy = 1;
1100     }
1101 
1102   return _bfd_elf_adjust_dynamic_copy (info, h, s);
1103 }
1104 
1105 /* Allocate space in .plt, .got and associated reloc sections for
1106    dynamic relocs.  */
1107 
1108 static bool
allocate_dynrelocs(struct elf_link_hash_entry * h,void * inf)1109 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
1110 {
1111   struct bfd_link_info *info;
1112   struct riscv_elf_link_hash_table *htab;
1113   struct elf_dyn_relocs *p;
1114 
1115   if (h->root.type == bfd_link_hash_indirect)
1116     return true;
1117 
1118   info = (struct bfd_link_info *) inf;
1119   htab = riscv_elf_hash_table (info);
1120   BFD_ASSERT (htab != NULL);
1121 
1122   /* When we are generating pde, make sure gp symbol is output as a
1123      dynamic symbol.  Then ld.so can set the gp register earlier, before
1124      resolving the ifunc.  */
1125   if (!bfd_link_pic (info)
1126       && htab->elf.dynamic_sections_created
1127       && strcmp (h->root.root.string, RISCV_GP_SYMBOL) == 0
1128       && !bfd_elf_link_record_dynamic_symbol (info, h))
1129     return false;
1130 
1131   /* Since STT_GNU_IFUNC symbols must go through PLT, we handle them
1132      in the allocate_ifunc_dynrelocs and allocate_local_ifunc_dynrelocs,
1133      if they are defined and referenced in a non-shared object.  */
1134   if (h->type == STT_GNU_IFUNC
1135       && h->def_regular)
1136     return true;
1137   else if (htab->elf.dynamic_sections_created
1138 	   && h->plt.refcount > 0)
1139     {
1140       /* Make sure this symbol is output as a dynamic symbol.
1141 	 Undefined weak syms won't yet be marked as dynamic.  */
1142       if (h->dynindx == -1
1143 	  && !h->forced_local)
1144 	{
1145 	  if (! bfd_elf_link_record_dynamic_symbol (info, h))
1146 	    return false;
1147 	}
1148 
1149       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (1, bfd_link_pic (info), h))
1150 	{
1151 	  asection *s = htab->elf.splt;
1152 
1153 	  if (s->size == 0)
1154 	    s->size = PLT_HEADER_SIZE;
1155 
1156 	  h->plt.offset = s->size;
1157 
1158 	  /* Make room for this entry.  */
1159 	  s->size += PLT_ENTRY_SIZE;
1160 
1161 	  /* We also need to make an entry in the .got.plt section.  */
1162 	  htab->elf.sgotplt->size += GOT_ENTRY_SIZE;
1163 
1164 	  /* We also need to make an entry in the .rela.plt section.  */
1165 	  htab->elf.srelplt->size += sizeof (ElfNN_External_Rela);
1166 
1167 	  /* If this symbol is not defined in a regular file, and we are
1168 	     not generating a shared library, then set the symbol to this
1169 	     location in the .plt.  This is required to make function
1170 	     pointers compare as equal between the normal executable and
1171 	     the shared library.  */
1172 	  if (! bfd_link_pic (info)
1173 	      && !h->def_regular)
1174 	    {
1175 	      h->root.u.def.section = s;
1176 	      h->root.u.def.value = h->plt.offset;
1177 	    }
1178 	}
1179       else
1180 	{
1181 	  h->plt.offset = (bfd_vma) -1;
1182 	  h->needs_plt = 0;
1183 	}
1184     }
1185   else
1186     {
1187       h->plt.offset = (bfd_vma) -1;
1188       h->needs_plt = 0;
1189     }
1190 
1191   if (h->got.refcount > 0)
1192     {
1193       asection *s;
1194       bool dyn;
1195       int tls_type = riscv_elf_hash_entry (h)->tls_type;
1196 
1197       /* Make sure this symbol is output as a dynamic symbol.
1198 	 Undefined weak syms won't yet be marked as dynamic.  */
1199       if (h->dynindx == -1
1200 	  && !h->forced_local)
1201 	{
1202 	  if (! bfd_elf_link_record_dynamic_symbol (info, h))
1203 	    return false;
1204 	}
1205 
1206       s = htab->elf.sgot;
1207       h->got.offset = s->size;
1208       dyn = htab->elf.dynamic_sections_created;
1209       if (tls_type & (GOT_TLS_GD | GOT_TLS_IE))
1210 	{
1211 	  /* TLS_GD needs two dynamic relocs and two GOT slots.  */
1212 	  if (tls_type & GOT_TLS_GD)
1213 	    {
1214 	      s->size += 2 * RISCV_ELF_WORD_BYTES;
1215 	      htab->elf.srelgot->size += 2 * sizeof (ElfNN_External_Rela);
1216 	    }
1217 
1218 	  /* TLS_IE needs one dynamic reloc and one GOT slot.  */
1219 	  if (tls_type & GOT_TLS_IE)
1220 	    {
1221 	      s->size += RISCV_ELF_WORD_BYTES;
1222 	      htab->elf.srelgot->size += sizeof (ElfNN_External_Rela);
1223 	    }
1224 	}
1225       else
1226 	{
1227 	  s->size += RISCV_ELF_WORD_BYTES;
1228 	  if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, bfd_link_pic (info), h)
1229 	      && ! UNDEFWEAK_NO_DYNAMIC_RELOC (info, h))
1230 	    htab->elf.srelgot->size += sizeof (ElfNN_External_Rela);
1231 	}
1232     }
1233   else
1234     h->got.offset = (bfd_vma) -1;
1235 
1236   if (h->dyn_relocs == NULL)
1237     return true;
1238 
1239   /* In the shared -Bsymbolic case, discard space allocated for
1240      dynamic pc-relative relocs against symbols which turn out to be
1241      defined in regular objects.  For the normal shared case, discard
1242      space for pc-relative relocs that have become local due to symbol
1243      visibility changes.  */
1244 
1245   if (bfd_link_pic (info))
1246     {
1247       if (SYMBOL_CALLS_LOCAL (info, h))
1248 	{
1249 	  struct elf_dyn_relocs **pp;
1250 
1251 	  for (pp = &h->dyn_relocs; (p = *pp) != NULL; )
1252 	    {
1253 	      p->count -= p->pc_count;
1254 	      p->pc_count = 0;
1255 	      if (p->count == 0)
1256 		*pp = p->next;
1257 	      else
1258 		pp = &p->next;
1259 	    }
1260 	}
1261 
1262       /* Also discard relocs on undefined weak syms with non-default
1263 	 visibility.  */
1264       if (h->dyn_relocs != NULL
1265 	  && h->root.type == bfd_link_hash_undefweak)
1266 	{
1267 	  if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1268 	      || UNDEFWEAK_NO_DYNAMIC_RELOC (info, h))
1269 	    h->dyn_relocs = NULL;
1270 
1271 	  /* Make sure undefined weak symbols are output as a dynamic
1272 	     symbol in PIEs.  */
1273 	  else if (h->dynindx == -1
1274 		   && !h->forced_local)
1275 	    {
1276 	      if (! bfd_elf_link_record_dynamic_symbol (info, h))
1277 		return false;
1278 	    }
1279 	}
1280     }
1281   else
1282     {
1283       /* For the non-shared case, discard space for relocs against
1284 	 symbols which turn out to need copy relocs or are not
1285 	 dynamic.  */
1286 
1287       if (!h->non_got_ref
1288 	  && ((h->def_dynamic
1289 	       && !h->def_regular)
1290 	      || (htab->elf.dynamic_sections_created
1291 		  && (h->root.type == bfd_link_hash_undefweak
1292 		      || h->root.type == bfd_link_hash_undefined))))
1293 	{
1294 	  /* Make sure this symbol is output as a dynamic symbol.
1295 	     Undefined weak syms won't yet be marked as dynamic.  */
1296 	  if (h->dynindx == -1
1297 	      && !h->forced_local)
1298 	    {
1299 	      if (! bfd_elf_link_record_dynamic_symbol (info, h))
1300 		return false;
1301 	    }
1302 
1303 	  /* If that succeeded, we know we'll be keeping all the
1304 	     relocs.  */
1305 	  if (h->dynindx != -1)
1306 	    goto keep;
1307 	}
1308 
1309       h->dyn_relocs = NULL;
1310 
1311     keep: ;
1312     }
1313 
1314   /* Finally, allocate space.  */
1315   for (p = h->dyn_relocs; p != NULL; p = p->next)
1316     {
1317       asection *sreloc = elf_section_data (p->sec)->sreloc;
1318       sreloc->size += p->count * sizeof (ElfNN_External_Rela);
1319     }
1320 
1321   return true;
1322 }
1323 
1324 /* Allocate space in .plt, .got and associated reloc sections for
1325    ifunc dynamic relocs.  */
1326 
1327 static bool
allocate_ifunc_dynrelocs(struct elf_link_hash_entry * h,void * inf)1328 allocate_ifunc_dynrelocs (struct elf_link_hash_entry *h,
1329 			  void *inf)
1330 {
1331   struct bfd_link_info *info;
1332 
1333   if (h->root.type == bfd_link_hash_indirect)
1334     return true;
1335 
1336   if (h->root.type == bfd_link_hash_warning)
1337     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1338 
1339   info = (struct bfd_link_info *) inf;
1340 
1341   /* Since STT_GNU_IFUNC symbol must go through PLT, we handle it
1342      here if it is defined and referenced in a non-shared object.  */
1343   if (h->type == STT_GNU_IFUNC
1344       && h->def_regular)
1345     return _bfd_elf_allocate_ifunc_dyn_relocs (info, h,
1346 					       &h->dyn_relocs,
1347 					       PLT_ENTRY_SIZE,
1348 					       PLT_HEADER_SIZE,
1349 					       GOT_ENTRY_SIZE,
1350 					       true);
1351   return true;
1352 }
1353 
1354 /* Allocate space in .plt, .got and associated reloc sections for
1355    local ifunc dynamic relocs.  */
1356 
1357 static int
allocate_local_ifunc_dynrelocs(void ** slot,void * inf)1358 allocate_local_ifunc_dynrelocs (void **slot, void *inf)
1359 {
1360   struct elf_link_hash_entry *h
1361     = (struct elf_link_hash_entry *) *slot;
1362 
1363   if (h->type != STT_GNU_IFUNC
1364       || !h->def_regular
1365       || !h->ref_regular
1366       || !h->forced_local
1367       || h->root.type != bfd_link_hash_defined)
1368     abort ();
1369 
1370   return allocate_ifunc_dynrelocs (h, inf);
1371 }
1372 
1373 static bool
riscv_elf_size_dynamic_sections(bfd * output_bfd,struct bfd_link_info * info)1374 riscv_elf_size_dynamic_sections (bfd *output_bfd, struct bfd_link_info *info)
1375 {
1376   struct riscv_elf_link_hash_table *htab;
1377   bfd *dynobj;
1378   asection *s;
1379   bfd *ibfd;
1380 
1381   htab = riscv_elf_hash_table (info);
1382   BFD_ASSERT (htab != NULL);
1383   dynobj = htab->elf.dynobj;
1384   BFD_ASSERT (dynobj != NULL);
1385 
1386   if (elf_hash_table (info)->dynamic_sections_created)
1387     {
1388       /* Set the contents of the .interp section to the interpreter.  */
1389       if (bfd_link_executable (info) && !info->nointerp)
1390 	{
1391 	  s = bfd_get_linker_section (dynobj, ".interp");
1392 	  BFD_ASSERT (s != NULL);
1393 	  s->size = strlen (ELFNN_DYNAMIC_INTERPRETER) + 1;
1394 	  s->contents = (unsigned char *) ELFNN_DYNAMIC_INTERPRETER;
1395 	}
1396     }
1397 
1398   /* Set up .got offsets for local syms, and space for local dynamic
1399      relocs.  */
1400   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
1401     {
1402       bfd_signed_vma *local_got;
1403       bfd_signed_vma *end_local_got;
1404       char *local_tls_type;
1405       bfd_size_type locsymcount;
1406       Elf_Internal_Shdr *symtab_hdr;
1407       asection *srel;
1408 
1409       if (! is_riscv_elf (ibfd))
1410 	continue;
1411 
1412       for (s = ibfd->sections; s != NULL; s = s->next)
1413 	{
1414 	  struct elf_dyn_relocs *p;
1415 
1416 	  for (p = elf_section_data (s)->local_dynrel; p != NULL; p = p->next)
1417 	    {
1418 	      if (!bfd_is_abs_section (p->sec)
1419 		  && bfd_is_abs_section (p->sec->output_section))
1420 		{
1421 		  /* Input section has been discarded, either because
1422 		     it is a copy of a linkonce section or due to
1423 		     linker script /DISCARD/, so we'll be discarding
1424 		     the relocs too.  */
1425 		}
1426 	      else if (p->count != 0)
1427 		{
1428 		  srel = elf_section_data (p->sec)->sreloc;
1429 		  srel->size += p->count * sizeof (ElfNN_External_Rela);
1430 		  if ((p->sec->output_section->flags & SEC_READONLY) != 0)
1431 		    info->flags |= DF_TEXTREL;
1432 		}
1433 	    }
1434 	}
1435 
1436       local_got = elf_local_got_refcounts (ibfd);
1437       if (!local_got)
1438 	continue;
1439 
1440       symtab_hdr = &elf_symtab_hdr (ibfd);
1441       locsymcount = symtab_hdr->sh_info;
1442       end_local_got = local_got + locsymcount;
1443       local_tls_type = _bfd_riscv_elf_local_got_tls_type (ibfd);
1444       s = htab->elf.sgot;
1445       srel = htab->elf.srelgot;
1446       for (; local_got < end_local_got; ++local_got, ++local_tls_type)
1447 	{
1448 	  if (*local_got > 0)
1449 	    {
1450 	      *local_got = s->size;
1451 	      s->size += RISCV_ELF_WORD_BYTES;
1452 	      if (*local_tls_type & GOT_TLS_GD)
1453 		s->size += RISCV_ELF_WORD_BYTES;
1454 	      if (bfd_link_pic (info)
1455 		  || (*local_tls_type & (GOT_TLS_GD | GOT_TLS_IE)))
1456 		srel->size += sizeof (ElfNN_External_Rela);
1457 	    }
1458 	  else
1459 	    *local_got = (bfd_vma) -1;
1460 	}
1461     }
1462 
1463   /* Allocate .plt and .got entries and space dynamic relocs for
1464      global symbols.  */
1465   elf_link_hash_traverse (&htab->elf, allocate_dynrelocs, info);
1466 
1467   /* Allocate .plt and .got entries and space dynamic relocs for
1468      global ifunc symbols.  */
1469   elf_link_hash_traverse (&htab->elf, allocate_ifunc_dynrelocs, info);
1470 
1471   /* Allocate .plt and .got entries and space dynamic relocs for
1472      local ifunc symbols.  */
1473   htab_traverse (htab->loc_hash_table, allocate_local_ifunc_dynrelocs, info);
1474 
1475   /* Used to resolve the dynamic relocs overwite problems when
1476      generating static executable.  */
1477   if (htab->elf.irelplt)
1478     htab->last_iplt_index = htab->elf.irelplt->reloc_count - 1;
1479 
1480   if (htab->elf.sgotplt)
1481     {
1482       struct elf_link_hash_entry *got;
1483       got = elf_link_hash_lookup (elf_hash_table (info),
1484 				  "_GLOBAL_OFFSET_TABLE_",
1485 				  false, false, false);
1486 
1487       /* Don't allocate .got.plt section if there are no GOT nor PLT
1488 	 entries and there is no refeence to _GLOBAL_OFFSET_TABLE_.  */
1489       if ((got == NULL
1490 	   || !got->ref_regular_nonweak)
1491 	  && (htab->elf.sgotplt->size == GOTPLT_HEADER_SIZE)
1492 	  && (htab->elf.splt == NULL
1493 	      || htab->elf.splt->size == 0)
1494 	  && (htab->elf.sgot == NULL
1495 	      || (htab->elf.sgot->size
1496 		  == get_elf_backend_data (output_bfd)->got_header_size)))
1497 	htab->elf.sgotplt->size = 0;
1498     }
1499 
1500   /* The check_relocs and adjust_dynamic_symbol entry points have
1501      determined the sizes of the various dynamic sections.  Allocate
1502      memory for them.  */
1503   for (s = dynobj->sections; s != NULL; s = s->next)
1504     {
1505       if ((s->flags & SEC_LINKER_CREATED) == 0)
1506 	continue;
1507 
1508       if (s == htab->elf.splt
1509 	  || s == htab->elf.sgot
1510 	  || s == htab->elf.sgotplt
1511 	  || s == htab->elf.iplt
1512 	  || s == htab->elf.igotplt
1513 	  || s == htab->elf.sdynbss
1514 	  || s == htab->elf.sdynrelro
1515 	  || s == htab->sdyntdata)
1516 	{
1517 	  /* Strip this section if we don't need it; see the
1518 	     comment below.  */
1519 	}
1520       else if (startswith (s->name, ".rela"))
1521 	{
1522 	  if (s->size != 0)
1523 	    {
1524 	      /* We use the reloc_count field as a counter if we need
1525 		 to copy relocs into the output file.  */
1526 	      s->reloc_count = 0;
1527 	    }
1528 	}
1529       else
1530 	{
1531 	  /* It's not one of our sections.  */
1532 	  continue;
1533 	}
1534 
1535       if (s->size == 0)
1536 	{
1537 	  /* If we don't need this section, strip it from the
1538 	     output file.  This is mostly to handle .rela.bss and
1539 	     .rela.plt.  We must create both sections in
1540 	     create_dynamic_sections, because they must be created
1541 	     before the linker maps input sections to output
1542 	     sections.  The linker does that before
1543 	     adjust_dynamic_symbol is called, and it is that
1544 	     function which decides whether anything needs to go
1545 	     into these sections.  */
1546 	  s->flags |= SEC_EXCLUDE;
1547 	  continue;
1548 	}
1549 
1550       if ((s->flags & SEC_HAS_CONTENTS) == 0)
1551 	continue;
1552 
1553       /* Allocate memory for the section contents.  Zero the memory
1554 	 for the benefit of .rela.plt, which has 4 unused entries
1555 	 at the beginning, and we don't want garbage.  */
1556       s->contents = (bfd_byte *) bfd_zalloc (dynobj, s->size);
1557       if (s->contents == NULL)
1558 	return false;
1559     }
1560 
1561   return _bfd_elf_add_dynamic_tags (output_bfd, info, true);
1562 }
1563 
1564 #define TP_OFFSET 0
1565 #define DTP_OFFSET 0x800
1566 
1567 /* Return the relocation value for a TLS dtp-relative reloc.  */
1568 
1569 static bfd_vma
dtpoff(struct bfd_link_info * info,bfd_vma address)1570 dtpoff (struct bfd_link_info *info, bfd_vma address)
1571 {
1572   /* If tls_sec is NULL, we should have signalled an error already.  */
1573   if (elf_hash_table (info)->tls_sec == NULL)
1574     return 0;
1575   return address - elf_hash_table (info)->tls_sec->vma - DTP_OFFSET;
1576 }
1577 
1578 /* Return the relocation value for a static TLS tp-relative relocation.  */
1579 
1580 static bfd_vma
tpoff(struct bfd_link_info * info,bfd_vma address)1581 tpoff (struct bfd_link_info *info, bfd_vma address)
1582 {
1583   /* If tls_sec is NULL, we should have signalled an error already.  */
1584   if (elf_hash_table (info)->tls_sec == NULL)
1585     return 0;
1586   return address - elf_hash_table (info)->tls_sec->vma - TP_OFFSET;
1587 }
1588 
1589 /* Return the global pointer's value, or 0 if it is not in use.  */
1590 
1591 static bfd_vma
riscv_global_pointer_value(struct bfd_link_info * info)1592 riscv_global_pointer_value (struct bfd_link_info *info)
1593 {
1594   struct bfd_link_hash_entry *h;
1595 
1596   h = bfd_link_hash_lookup (info->hash, RISCV_GP_SYMBOL, false, false, true);
1597   if (h == NULL || h->type != bfd_link_hash_defined)
1598     return 0;
1599 
1600   return h->u.def.value + sec_addr (h->u.def.section);
1601 }
1602 
1603 /* Emplace a static relocation.  */
1604 
1605 static bfd_reloc_status_type
perform_relocation(const reloc_howto_type * howto,const Elf_Internal_Rela * rel,bfd_vma value,asection * input_section,bfd * input_bfd,bfd_byte * contents)1606 perform_relocation (const reloc_howto_type *howto,
1607 		    const Elf_Internal_Rela *rel,
1608 		    bfd_vma value,
1609 		    asection *input_section,
1610 		    bfd *input_bfd,
1611 		    bfd_byte *contents)
1612 {
1613   if (howto->pc_relative)
1614     value -= sec_addr (input_section) + rel->r_offset;
1615   value += rel->r_addend;
1616 
1617   switch (ELFNN_R_TYPE (rel->r_info))
1618     {
1619     case R_RISCV_HI20:
1620     case R_RISCV_TPREL_HI20:
1621     case R_RISCV_PCREL_HI20:
1622     case R_RISCV_GOT_HI20:
1623     case R_RISCV_TLS_GOT_HI20:
1624     case R_RISCV_TLS_GD_HI20:
1625       if (ARCH_SIZE > 32 && !VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (value)))
1626 	return bfd_reloc_overflow;
1627       value = ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value));
1628       break;
1629 
1630     case R_RISCV_LO12_I:
1631     case R_RISCV_GPREL_I:
1632     case R_RISCV_TPREL_LO12_I:
1633     case R_RISCV_TPREL_I:
1634     case R_RISCV_PCREL_LO12_I:
1635       value = ENCODE_ITYPE_IMM (value);
1636       break;
1637 
1638     case R_RISCV_LO12_S:
1639     case R_RISCV_GPREL_S:
1640     case R_RISCV_TPREL_LO12_S:
1641     case R_RISCV_TPREL_S:
1642     case R_RISCV_PCREL_LO12_S:
1643       value = ENCODE_STYPE_IMM (value);
1644       break;
1645 
1646     case R_RISCV_CALL:
1647     case R_RISCV_CALL_PLT:
1648       if (ARCH_SIZE > 32 && !VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (value)))
1649 	return bfd_reloc_overflow;
1650       value = ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value))
1651 	      | (ENCODE_ITYPE_IMM (value) << 32);
1652       break;
1653 
1654     case R_RISCV_JAL:
1655       if (!VALID_JTYPE_IMM (value))
1656 	return bfd_reloc_overflow;
1657       value = ENCODE_JTYPE_IMM (value);
1658       break;
1659 
1660     case R_RISCV_BRANCH:
1661       if (!VALID_BTYPE_IMM (value))
1662 	return bfd_reloc_overflow;
1663       value = ENCODE_BTYPE_IMM (value);
1664       break;
1665 
1666     case R_RISCV_RVC_BRANCH:
1667       if (!VALID_CBTYPE_IMM (value))
1668 	return bfd_reloc_overflow;
1669       value = ENCODE_CBTYPE_IMM (value);
1670       break;
1671 
1672     case R_RISCV_RVC_JUMP:
1673       if (!VALID_CJTYPE_IMM (value))
1674 	return bfd_reloc_overflow;
1675       value = ENCODE_CJTYPE_IMM (value);
1676       break;
1677 
1678     case R_RISCV_RVC_LUI:
1679       if (RISCV_CONST_HIGH_PART (value) == 0)
1680 	{
1681 	  /* Linker relaxation can convert an address equal to or greater than
1682 	     0x800 to slightly below 0x800.  C.LUI does not accept zero as a
1683 	     valid immediate.  We can fix this by converting it to a C.LI.  */
1684 	  bfd_vma insn = riscv_get_insn (howto->bitsize,
1685 					 contents + rel->r_offset);
1686 	  insn = (insn & ~MATCH_C_LUI) | MATCH_C_LI;
1687 	  riscv_put_insn (howto->bitsize, insn, contents + rel->r_offset);
1688 	  value = ENCODE_CITYPE_IMM (0);
1689 	}
1690       else if (!VALID_CITYPE_LUI_IMM (RISCV_CONST_HIGH_PART (value)))
1691 	return bfd_reloc_overflow;
1692       else
1693 	value = ENCODE_CITYPE_LUI_IMM (RISCV_CONST_HIGH_PART (value));
1694       break;
1695 
1696     case R_RISCV_32:
1697     case R_RISCV_64:
1698     case R_RISCV_ADD8:
1699     case R_RISCV_ADD16:
1700     case R_RISCV_ADD32:
1701     case R_RISCV_ADD64:
1702     case R_RISCV_SUB6:
1703     case R_RISCV_SUB8:
1704     case R_RISCV_SUB16:
1705     case R_RISCV_SUB32:
1706     case R_RISCV_SUB64:
1707     case R_RISCV_SET6:
1708     case R_RISCV_SET8:
1709     case R_RISCV_SET16:
1710     case R_RISCV_SET32:
1711     case R_RISCV_32_PCREL:
1712     case R_RISCV_TLS_DTPREL32:
1713     case R_RISCV_TLS_DTPREL64:
1714       break;
1715 
1716     case R_RISCV_DELETE:
1717       return bfd_reloc_ok;
1718 
1719     default:
1720       return bfd_reloc_notsupported;
1721     }
1722 
1723   bfd_vma word;
1724   if (riscv_is_insn_reloc (howto))
1725     word = riscv_get_insn (howto->bitsize, contents + rel->r_offset);
1726   else
1727     word = bfd_get (howto->bitsize, input_bfd, contents + rel->r_offset);
1728   word = (word & ~howto->dst_mask) | (value & howto->dst_mask);
1729   if (riscv_is_insn_reloc (howto))
1730     riscv_put_insn (howto->bitsize, word, contents + rel->r_offset);
1731   else
1732     bfd_put (howto->bitsize, input_bfd, word, contents + rel->r_offset);
1733 
1734   return bfd_reloc_ok;
1735 }
1736 
1737 /* Remember all PC-relative high-part relocs we've encountered to help us
1738    later resolve the corresponding low-part relocs.  */
1739 
1740 typedef struct
1741 {
1742   /* PC value.  */
1743   bfd_vma address;
1744   /* Relocation value with addend.  */
1745   bfd_vma value;
1746   /* Original reloc type.  */
1747   int type;
1748 } riscv_pcrel_hi_reloc;
1749 
1750 typedef struct riscv_pcrel_lo_reloc
1751 {
1752   /* PC value of auipc.  */
1753   bfd_vma address;
1754   /* Internal relocation.  */
1755   const Elf_Internal_Rela *reloc;
1756   /* Record the following information helps to resolve the %pcrel
1757      which cross different input section.  For now we build a hash
1758      for pcrel at the start of riscv_elf_relocate_section, and then
1759      free the hash at the end.  But riscv_elf_relocate_section only
1760      handles an input section at a time, so that means we can only
1761      resolve the %pcrel_hi and %pcrel_lo which are in the same input
1762      section.  Otherwise, we will report dangerous relocation errors
1763      for those %pcrel which are not in the same input section.  */
1764   asection *input_section;
1765   struct bfd_link_info *info;
1766   reloc_howto_type *howto;
1767   bfd_byte *contents;
1768   /* The next riscv_pcrel_lo_reloc.  */
1769   struct riscv_pcrel_lo_reloc *next;
1770 } riscv_pcrel_lo_reloc;
1771 
1772 typedef struct
1773 {
1774   /* Hash table for riscv_pcrel_hi_reloc.  */
1775   htab_t hi_relocs;
1776   /* Linked list for riscv_pcrel_lo_reloc.  */
1777   riscv_pcrel_lo_reloc *lo_relocs;
1778 } riscv_pcrel_relocs;
1779 
1780 static hashval_t
riscv_pcrel_reloc_hash(const void * entry)1781 riscv_pcrel_reloc_hash (const void *entry)
1782 {
1783   const riscv_pcrel_hi_reloc *e = entry;
1784   return (hashval_t)(e->address >> 2);
1785 }
1786 
1787 static int
riscv_pcrel_reloc_eq(const void * entry1,const void * entry2)1788 riscv_pcrel_reloc_eq (const void *entry1, const void *entry2)
1789 {
1790   const riscv_pcrel_hi_reloc *e1 = entry1, *e2 = entry2;
1791   return e1->address == e2->address;
1792 }
1793 
1794 static bool
riscv_init_pcrel_relocs(riscv_pcrel_relocs * p)1795 riscv_init_pcrel_relocs (riscv_pcrel_relocs *p)
1796 {
1797   p->lo_relocs = NULL;
1798   p->hi_relocs = htab_create (1024, riscv_pcrel_reloc_hash,
1799 			      riscv_pcrel_reloc_eq, free);
1800   return p->hi_relocs != NULL;
1801 }
1802 
1803 static void
riscv_free_pcrel_relocs(riscv_pcrel_relocs * p)1804 riscv_free_pcrel_relocs (riscv_pcrel_relocs *p)
1805 {
1806   riscv_pcrel_lo_reloc *cur = p->lo_relocs;
1807 
1808   while (cur != NULL)
1809     {
1810       riscv_pcrel_lo_reloc *next = cur->next;
1811       free (cur);
1812       cur = next;
1813     }
1814 
1815   htab_delete (p->hi_relocs);
1816 }
1817 
1818 static bool
riscv_zero_pcrel_hi_reloc(Elf_Internal_Rela * rel,struct bfd_link_info * info,bfd_vma pc,bfd_vma addr,bfd_byte * contents,const reloc_howto_type * howto)1819 riscv_zero_pcrel_hi_reloc (Elf_Internal_Rela *rel,
1820 			   struct bfd_link_info *info,
1821 			   bfd_vma pc,
1822 			   bfd_vma addr,
1823 			   bfd_byte *contents,
1824 			   const reloc_howto_type *howto)
1825 {
1826   /* We may need to reference low addreses in PC-relative modes even when the
1827      PC is far away from these addresses.  For example, undefweak references
1828      need to produce the address 0 when linked.  As 0 is far from the arbitrary
1829      addresses that we can link PC-relative programs at, the linker can't
1830      actually relocate references to those symbols.  In order to allow these
1831      programs to work we simply convert the PC-relative auipc sequences to
1832      0-relative lui sequences.  */
1833   if (bfd_link_pic (info))
1834     return false;
1835 
1836   /* If it's possible to reference the symbol using auipc we do so, as that's
1837      more in the spirit of the PC-relative relocations we're processing.  */
1838   bfd_vma offset = addr - pc;
1839   if (ARCH_SIZE == 32 || VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (offset)))
1840     return false;
1841 
1842   /* If it's impossible to reference this with a LUI-based offset then don't
1843      bother to convert it at all so users still see the PC-relative relocation
1844      in the truncation message.  */
1845   if (ARCH_SIZE > 32 && !VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (addr)))
1846     return false;
1847 
1848   rel->r_info = ELFNN_R_INFO (addr, R_RISCV_HI20);
1849 
1850   bfd_vma insn = riscv_get_insn (howto->bitsize, contents + rel->r_offset);
1851   insn = (insn & ~MASK_AUIPC) | MATCH_LUI;
1852   riscv_put_insn (howto->bitsize, insn, contents + rel->r_offset);
1853   return true;
1854 }
1855 
1856 static bool
riscv_record_pcrel_hi_reloc(riscv_pcrel_relocs * p,bfd_vma addr,bfd_vma value,int type,bool absolute)1857 riscv_record_pcrel_hi_reloc (riscv_pcrel_relocs *p,
1858 			     bfd_vma addr,
1859 			     bfd_vma value,
1860 			     int type,
1861 			     bool absolute)
1862 {
1863   bfd_vma offset = absolute ? value : value - addr;
1864   riscv_pcrel_hi_reloc entry = {addr, offset, type};
1865   riscv_pcrel_hi_reloc **slot =
1866     (riscv_pcrel_hi_reloc **) htab_find_slot (p->hi_relocs, &entry, INSERT);
1867 
1868   BFD_ASSERT (*slot == NULL);
1869   *slot = (riscv_pcrel_hi_reloc *) bfd_malloc (sizeof (riscv_pcrel_hi_reloc));
1870   if (*slot == NULL)
1871     return false;
1872   **slot = entry;
1873   return true;
1874 }
1875 
1876 static bool
riscv_record_pcrel_lo_reloc(riscv_pcrel_relocs * p,bfd_vma addr,const Elf_Internal_Rela * reloc,asection * input_section,struct bfd_link_info * info,reloc_howto_type * howto,bfd_byte * contents)1877 riscv_record_pcrel_lo_reloc (riscv_pcrel_relocs *p,
1878 			     bfd_vma addr,
1879 			     const Elf_Internal_Rela *reloc,
1880 			     asection *input_section,
1881 			     struct bfd_link_info *info,
1882 			     reloc_howto_type *howto,
1883 			     bfd_byte *contents)
1884 {
1885   riscv_pcrel_lo_reloc *entry;
1886   entry = (riscv_pcrel_lo_reloc *) bfd_malloc (sizeof (riscv_pcrel_lo_reloc));
1887   if (entry == NULL)
1888     return false;
1889   *entry = (riscv_pcrel_lo_reloc) {addr, reloc, input_section, info,
1890 				   howto, contents, p->lo_relocs};
1891   p->lo_relocs = entry;
1892   return true;
1893 }
1894 
1895 static bool
riscv_resolve_pcrel_lo_relocs(riscv_pcrel_relocs * p)1896 riscv_resolve_pcrel_lo_relocs (riscv_pcrel_relocs *p)
1897 {
1898   riscv_pcrel_lo_reloc *r;
1899 
1900   for (r = p->lo_relocs; r != NULL; r = r->next)
1901     {
1902       bfd *input_bfd = r->input_section->owner;
1903 
1904       riscv_pcrel_hi_reloc search = {r->address, 0, 0};
1905       riscv_pcrel_hi_reloc *entry = htab_find (p->hi_relocs, &search);
1906       /* There may be a risk if the %pcrel_lo with addend refers to
1907 	 an IFUNC symbol.  The %pcrel_hi has been relocated to plt,
1908 	 so the corresponding %pcrel_lo with addend looks wrong.  */
1909       char *string = NULL;
1910       if (entry == NULL)
1911 	string = _("%pcrel_lo missing matching %pcrel_hi");
1912       else if (entry->type == R_RISCV_GOT_HI20
1913 	       && r->reloc->r_addend != 0)
1914 	string = _("%pcrel_lo with addend isn't allowed for R_RISCV_GOT_HI20");
1915       else if (RISCV_CONST_HIGH_PART (entry->value)
1916 	       != RISCV_CONST_HIGH_PART (entry->value + r->reloc->r_addend))
1917 	{
1918 	  /* Check the overflow when adding reloc addend.  */
1919 	  if (asprintf (&string,
1920 			_("%%pcrel_lo overflow with an addend, the "
1921 			  "value of %%pcrel_hi is 0x%" PRIx64 " without "
1922 			  "any addend, but may be 0x%" PRIx64 " after "
1923 			  "adding the %%pcrel_lo addend"),
1924 			(int64_t) RISCV_CONST_HIGH_PART (entry->value),
1925 			(int64_t) RISCV_CONST_HIGH_PART
1926 				(entry->value + r->reloc->r_addend)) == -1)
1927 	    string = _("%pcrel_lo overflow with an addend");
1928 	}
1929 
1930       if (string != NULL)
1931 	{
1932 	  (*r->info->callbacks->reloc_dangerous)
1933 	    (r->info, string, input_bfd, r->input_section, r->reloc->r_offset);
1934 	  return true;
1935 	}
1936 
1937       perform_relocation (r->howto, r->reloc, entry->value, r->input_section,
1938 			  input_bfd, r->contents);
1939     }
1940 
1941   return true;
1942 }
1943 
1944 /* Relocate a RISC-V ELF section.
1945 
1946    The RELOCATE_SECTION function is called by the new ELF backend linker
1947    to handle the relocations for a section.
1948 
1949    The relocs are always passed as Rela structures.
1950 
1951    This function is responsible for adjusting the section contents as
1952    necessary, and (if generating a relocatable output file) adjusting
1953    the reloc addend as necessary.
1954 
1955    This function does not have to worry about setting the reloc
1956    address or the reloc symbol index.
1957 
1958    LOCAL_SYMS is a pointer to the swapped in local symbols.
1959 
1960    LOCAL_SECTIONS is an array giving the section in the input file
1961    corresponding to the st_shndx field of each local symbol.
1962 
1963    The global hash table entry for the global symbols can be found
1964    via elf_sym_hashes (input_bfd).
1965 
1966    When generating relocatable output, this function must handle
1967    STB_LOCAL/STT_SECTION symbols specially.  The output symbol is
1968    going to be the section symbol corresponding to the output
1969    section, which means that the addend must be adjusted
1970    accordingly.  */
1971 
1972 static int
riscv_elf_relocate_section(bfd * output_bfd,struct bfd_link_info * info,bfd * input_bfd,asection * input_section,bfd_byte * contents,Elf_Internal_Rela * relocs,Elf_Internal_Sym * local_syms,asection ** local_sections)1973 riscv_elf_relocate_section (bfd *output_bfd,
1974 			    struct bfd_link_info *info,
1975 			    bfd *input_bfd,
1976 			    asection *input_section,
1977 			    bfd_byte *contents,
1978 			    Elf_Internal_Rela *relocs,
1979 			    Elf_Internal_Sym *local_syms,
1980 			    asection **local_sections)
1981 {
1982   Elf_Internal_Rela *rel;
1983   Elf_Internal_Rela *relend;
1984   riscv_pcrel_relocs pcrel_relocs;
1985   bool ret = false;
1986   struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
1987   Elf_Internal_Shdr *symtab_hdr = &elf_symtab_hdr (input_bfd);
1988   struct elf_link_hash_entry **sym_hashes = elf_sym_hashes (input_bfd);
1989   bfd_vma *local_got_offsets = elf_local_got_offsets (input_bfd);
1990   bool absolute;
1991 
1992   if (!riscv_init_pcrel_relocs (&pcrel_relocs))
1993     return false;
1994 
1995   relend = relocs + input_section->reloc_count;
1996   for (rel = relocs; rel < relend; rel++)
1997     {
1998       unsigned long r_symndx;
1999       struct elf_link_hash_entry *h;
2000       Elf_Internal_Sym *sym;
2001       asection *sec;
2002       bfd_vma relocation;
2003       bfd_reloc_status_type r = bfd_reloc_ok;
2004       const char *name = NULL;
2005       bfd_vma off, ie_off;
2006       bool unresolved_reloc, is_ie = false;
2007       bfd_vma pc = sec_addr (input_section) + rel->r_offset;
2008       int r_type = ELFNN_R_TYPE (rel->r_info), tls_type;
2009       reloc_howto_type *howto = riscv_elf_rtype_to_howto (input_bfd, r_type);
2010       const char *msg = NULL;
2011       char *msg_buf = NULL;
2012       bool resolved_to_zero;
2013 
2014       if (howto == NULL
2015 	  || r_type == R_RISCV_GNU_VTINHERIT || r_type == R_RISCV_GNU_VTENTRY)
2016 	continue;
2017 
2018       /* This is a final link.  */
2019       r_symndx = ELFNN_R_SYM (rel->r_info);
2020       h = NULL;
2021       sym = NULL;
2022       sec = NULL;
2023       unresolved_reloc = false;
2024       if (r_symndx < symtab_hdr->sh_info)
2025 	{
2026 	  sym = local_syms + r_symndx;
2027 	  sec = local_sections[r_symndx];
2028 	  relocation = _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
2029 
2030 	  /* Relocate against local STT_GNU_IFUNC symbol.  */
2031 	  if (!bfd_link_relocatable (info)
2032 	      && ELF_ST_TYPE (sym->st_info) == STT_GNU_IFUNC)
2033 	    {
2034 	      h = riscv_elf_get_local_sym_hash (htab, input_bfd, rel, false);
2035 	      if (h == NULL)
2036 		abort ();
2037 
2038 	      /* Set STT_GNU_IFUNC symbol value.  */
2039 	      h->root.u.def.value = sym->st_value;
2040 	      h->root.u.def.section = sec;
2041 	    }
2042 	}
2043       else
2044 	{
2045 	  bool warned, ignored;
2046 
2047 	  RELOC_FOR_GLOBAL_SYMBOL (info, input_bfd, input_section, rel,
2048 				   r_symndx, symtab_hdr, sym_hashes,
2049 				   h, sec, relocation,
2050 				   unresolved_reloc, warned, ignored);
2051 	  if (warned)
2052 	    {
2053 	      /* To avoid generating warning messages about truncated
2054 		 relocations, set the relocation's address to be the same as
2055 		 the start of this section.  */
2056 	      if (input_section->output_section != NULL)
2057 		relocation = input_section->output_section->vma;
2058 	      else
2059 		relocation = 0;
2060 	    }
2061 	}
2062 
2063       if (sec != NULL && discarded_section (sec))
2064 	RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
2065 					 rel, 1, relend, howto, 0, contents);
2066 
2067       if (bfd_link_relocatable (info))
2068 	continue;
2069 
2070       /* Since STT_GNU_IFUNC symbol must go through PLT, we handle
2071 	 it here if it is defined in a non-shared object.  */
2072       if (h != NULL
2073 	  && h->type == STT_GNU_IFUNC
2074 	  && h->def_regular)
2075 	{
2076 	  asection *plt, *base_got;
2077 
2078 	  if ((input_section->flags & SEC_ALLOC) == 0)
2079 	    {
2080 	      /* If this is a SHT_NOTE section without SHF_ALLOC, treat
2081 		 STT_GNU_IFUNC symbol as STT_FUNC.  */
2082 	      if (elf_section_type (input_section) == SHT_NOTE)
2083 		goto skip_ifunc;
2084 
2085 	      /* Dynamic relocs are not propagated for SEC_DEBUGGING
2086 		 sections because such sections are not SEC_ALLOC and
2087 		 thus ld.so will not process them.  */
2088 	      if ((input_section->flags & SEC_DEBUGGING) != 0)
2089 		continue;
2090 
2091 	      abort ();
2092 	    }
2093 	  else if (h->plt.offset == (bfd_vma) -1
2094 		   /* The following relocation may not need the .plt entries
2095 		      when all references to a STT_GNU_IFUNC symbols are done
2096 		      via GOT or static function pointers.  */
2097 		   && r_type != R_RISCV_32
2098 		   && r_type != R_RISCV_64
2099 		   && r_type != R_RISCV_HI20
2100 		   && r_type != R_RISCV_GOT_HI20
2101 		   && r_type != R_RISCV_LO12_I
2102 		   && r_type != R_RISCV_LO12_S)
2103 	    goto bad_ifunc_reloc;
2104 
2105 	  /* STT_GNU_IFUNC symbol must go through PLT.  */
2106 	  plt = htab->elf.splt ? htab->elf.splt : htab->elf.iplt;
2107 	  relocation = plt->output_section->vma
2108 		       + plt->output_offset
2109 		       + h->plt.offset;
2110 
2111 	  switch (r_type)
2112 	    {
2113 	    case R_RISCV_32:
2114 	    case R_RISCV_64:
2115 	      if (rel->r_addend != 0)
2116 		{
2117 		  if (h->root.root.string)
2118 		    name = h->root.root.string;
2119 		  else
2120 		    name = bfd_elf_sym_name (input_bfd, symtab_hdr, sym, NULL);
2121 
2122 		  _bfd_error_handler
2123 		    /* xgettext:c-format */
2124 		    (_("%pB: relocation %s against STT_GNU_IFUNC "
2125 		       "symbol `%s' has non-zero addend: %" PRId64),
2126 		     input_bfd, howto->name, name, (int64_t) rel->r_addend);
2127 		  bfd_set_error (bfd_error_bad_value);
2128 		  return false;
2129 		}
2130 
2131 		/* Generate dynamic relocation only when there is a non-GOT
2132 		   reference in a shared object or there is no PLT.  */
2133 		if ((bfd_link_pic (info) && h->non_got_ref)
2134 		    || h->plt.offset == (bfd_vma) -1)
2135 		  {
2136 		    Elf_Internal_Rela outrel;
2137 		    asection *sreloc;
2138 
2139 		    /* Need a dynamic relocation to get the real function
2140 		       address.  */
2141 		    outrel.r_offset = _bfd_elf_section_offset (output_bfd,
2142 							       info,
2143 							       input_section,
2144 							       rel->r_offset);
2145 		    if (outrel.r_offset == (bfd_vma) -1
2146 			|| outrel.r_offset == (bfd_vma) -2)
2147 		      abort ();
2148 
2149 		    outrel.r_offset += input_section->output_section->vma
2150 				       + input_section->output_offset;
2151 
2152 		    if (h->dynindx == -1
2153 			|| h->forced_local
2154 			|| bfd_link_executable (info))
2155 		      {
2156 			info->callbacks->minfo
2157 			  (_("Local IFUNC function `%s' in %pB\n"),
2158 			   h->root.root.string,
2159 			   h->root.u.def.section->owner);
2160 
2161 			/* This symbol is resolved locally.  */
2162 			outrel.r_info = ELFNN_R_INFO (0, R_RISCV_IRELATIVE);
2163 			outrel.r_addend = h->root.u.def.value
2164 			  + h->root.u.def.section->output_section->vma
2165 			  + h->root.u.def.section->output_offset;
2166 		      }
2167 		    else
2168 		      {
2169 			outrel.r_info = ELFNN_R_INFO (h->dynindx, r_type);
2170 			outrel.r_addend = 0;
2171 		      }
2172 
2173 		    /* Dynamic relocations are stored in
2174 		       1. .rela.ifunc section in PIC object.
2175 		       2. .rela.got section in dynamic executable.
2176 		       3. .rela.iplt section in static executable.  */
2177 		    if (bfd_link_pic (info))
2178 		      sreloc = htab->elf.irelifunc;
2179 		    else if (htab->elf.splt != NULL)
2180 		      sreloc = htab->elf.srelgot;
2181 		    else
2182 		      sreloc = htab->elf.irelplt;
2183 
2184 		    riscv_elf_append_rela (output_bfd, sreloc, &outrel);
2185 
2186 		    /* If this reloc is against an external symbol, we
2187 		       do not want to fiddle with the addend.  Otherwise,
2188 		       we need to include the symbol value so that it
2189 		       becomes an addend for the dynamic reloc.  For an
2190 		       internal symbol, we have updated addend.  */
2191 		    continue;
2192 		  }
2193 		goto do_relocation;
2194 
2195 	      case R_RISCV_GOT_HI20:
2196 		base_got = htab->elf.sgot;
2197 		off = h->got.offset;
2198 
2199 		if (base_got == NULL)
2200 		  abort ();
2201 
2202 		if (off == (bfd_vma) -1)
2203 		  {
2204 		    bfd_vma plt_idx;
2205 
2206 		    /* We can't use h->got.offset here to save state, or
2207 		       even just remember the offset, as finish_dynamic_symbol
2208 		       would use that as offset into .got.  */
2209 
2210 		    if (htab->elf.splt != NULL)
2211 		      {
2212 			plt_idx = (h->plt.offset - PLT_HEADER_SIZE)
2213 				  / PLT_ENTRY_SIZE;
2214 			off = GOTPLT_HEADER_SIZE + (plt_idx * GOT_ENTRY_SIZE);
2215 			base_got = htab->elf.sgotplt;
2216 		      }
2217 		    else
2218 		      {
2219 			plt_idx = h->plt.offset / PLT_ENTRY_SIZE;
2220 			off = plt_idx * GOT_ENTRY_SIZE;
2221 			base_got = htab->elf.igotplt;
2222 		      }
2223 
2224 		    if (h->dynindx == -1
2225 			|| h->forced_local
2226 			|| info->symbolic)
2227 		      {
2228 			/* This references the local definition.  We must
2229 			   initialize this entry in the global offset table.
2230 			   Since the offset must always be a multiple of 8,
2231 			   we use the least significant bit to record
2232 			   whether we have initialized it already.
2233 
2234 			   When doing a dynamic link, we create a .rela.got
2235 			   relocation entry to initialize the value.  This
2236 			   is done in the finish_dynamic_symbol routine.   */
2237 			if ((off & 1) != 0)
2238 			  off &= ~1;
2239 			else
2240 			  {
2241 			    bfd_put_NN (output_bfd, relocation,
2242 					base_got->contents + off);
2243 			    /* Note that this is harmless for the case,
2244 			       as -1 | 1 still is -1.  */
2245 			    h->got.offset |= 1;
2246 			  }
2247 		      }
2248 		  }
2249 
2250 		relocation = base_got->output_section->vma
2251 			     + base_got->output_offset + off;
2252 
2253 		if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2254 						  relocation, r_type,
2255 						  false))
2256 		  r = bfd_reloc_overflow;
2257 		goto do_relocation;
2258 
2259 	      case R_RISCV_CALL:
2260 	      case R_RISCV_CALL_PLT:
2261 	      case R_RISCV_HI20:
2262 	      case R_RISCV_LO12_I:
2263 	      case R_RISCV_LO12_S:
2264 		goto do_relocation;
2265 
2266 	      case R_RISCV_PCREL_HI20:
2267 		if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2268 						  relocation, r_type,
2269 						  false))
2270 		  r = bfd_reloc_overflow;
2271 		goto do_relocation;
2272 
2273 	    default:
2274 	    bad_ifunc_reloc:
2275 	      if (h->root.root.string)
2276 		name = h->root.root.string;
2277 	      else
2278 		/* The entry of local ifunc is fake in global hash table,
2279 		   we should find the name by the original local symbol.  */
2280 		name = bfd_elf_sym_name (input_bfd, symtab_hdr, sym, NULL);
2281 
2282 	      _bfd_error_handler
2283 	      /* xgettext:c-format */
2284 	      (_("%pB: relocation %s against STT_GNU_IFUNC "
2285 		 "symbol `%s' isn't supported"), input_bfd,
2286 	       howto->name, name);
2287 	      bfd_set_error (bfd_error_bad_value);
2288 	      return false;
2289 	    }
2290 	}
2291 
2292     skip_ifunc:
2293       if (h != NULL)
2294 	name = h->root.root.string;
2295       else
2296 	{
2297 	  name = (bfd_elf_string_from_elf_section
2298 		  (input_bfd, symtab_hdr->sh_link, sym->st_name));
2299 	  if (name == NULL || *name == '\0')
2300 	    name = bfd_section_name (sec);
2301 	}
2302 
2303       resolved_to_zero = (h != NULL
2304 			  && UNDEFWEAK_NO_DYNAMIC_RELOC (info, h));
2305 
2306       switch (r_type)
2307 	{
2308 	case R_RISCV_NONE:
2309 	case R_RISCV_RELAX:
2310 	case R_RISCV_TPREL_ADD:
2311 	case R_RISCV_COPY:
2312 	case R_RISCV_JUMP_SLOT:
2313 	case R_RISCV_RELATIVE:
2314 	  /* These require nothing of us at all.  */
2315 	  continue;
2316 
2317 	case R_RISCV_HI20:
2318 	case R_RISCV_BRANCH:
2319 	case R_RISCV_RVC_BRANCH:
2320 	case R_RISCV_RVC_LUI:
2321 	case R_RISCV_LO12_I:
2322 	case R_RISCV_LO12_S:
2323 	case R_RISCV_SET6:
2324 	case R_RISCV_SET8:
2325 	case R_RISCV_SET16:
2326 	case R_RISCV_SET32:
2327 	case R_RISCV_32_PCREL:
2328 	case R_RISCV_DELETE:
2329 	  /* These require no special handling beyond perform_relocation.  */
2330 	  break;
2331 
2332 	case R_RISCV_GOT_HI20:
2333 	  if (h != NULL)
2334 	    {
2335 	      bool dyn, pic;
2336 
2337 	      off = h->got.offset;
2338 	      BFD_ASSERT (off != (bfd_vma) -1);
2339 	      dyn = elf_hash_table (info)->dynamic_sections_created;
2340 	      pic = bfd_link_pic (info);
2341 
2342 	      if (! WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, pic, h)
2343 		  || (pic && SYMBOL_REFERENCES_LOCAL (info, h)))
2344 		{
2345 		  /* This is actually a static link, or it is a
2346 		     -Bsymbolic link and the symbol is defined
2347 		     locally, or the symbol was forced to be local
2348 		     because of a version file.  We must initialize
2349 		     this entry in the global offset table.  Since the
2350 		     offset must always be a multiple of the word size,
2351 		     we use the least significant bit to record whether
2352 		     we have initialized it already.
2353 
2354 		     When doing a dynamic link, we create a .rela.got
2355 		     relocation entry to initialize the value.  This
2356 		     is done in the finish_dynamic_symbol routine.  */
2357 		  if ((off & 1) != 0)
2358 		    off &= ~1;
2359 		  else
2360 		    {
2361 		      bfd_put_NN (output_bfd, relocation,
2362 				  htab->elf.sgot->contents + off);
2363 		      h->got.offset |= 1;
2364 		    }
2365 		}
2366 	      else
2367 		unresolved_reloc = false;
2368 	    }
2369 	  else
2370 	    {
2371 	      BFD_ASSERT (local_got_offsets != NULL
2372 			  && local_got_offsets[r_symndx] != (bfd_vma) -1);
2373 
2374 	      off = local_got_offsets[r_symndx];
2375 
2376 	      /* The offset must always be a multiple of the word size.
2377 		 So, we can use the least significant bit to record
2378 		 whether we have already processed this entry.  */
2379 	      if ((off & 1) != 0)
2380 		off &= ~1;
2381 	      else
2382 		{
2383 		  if (bfd_link_pic (info))
2384 		    {
2385 		      asection *s;
2386 		      Elf_Internal_Rela outrel;
2387 
2388 		      /* We need to generate a R_RISCV_RELATIVE reloc
2389 			 for the dynamic linker.  */
2390 		      s = htab->elf.srelgot;
2391 		      BFD_ASSERT (s != NULL);
2392 
2393 		      outrel.r_offset = sec_addr (htab->elf.sgot) + off;
2394 		      outrel.r_info =
2395 			ELFNN_R_INFO (0, R_RISCV_RELATIVE);
2396 		      outrel.r_addend = relocation;
2397 		      relocation = 0;
2398 		      riscv_elf_append_rela (output_bfd, s, &outrel);
2399 		    }
2400 
2401 		  bfd_put_NN (output_bfd, relocation,
2402 			      htab->elf.sgot->contents + off);
2403 		  local_got_offsets[r_symndx] |= 1;
2404 		}
2405 	    }
2406 
2407 	  if (rel->r_addend != 0)
2408 	    {
2409 	      msg = _("The addend isn't allowed for R_RISCV_GOT_HI20");
2410 	      r = bfd_reloc_dangerous;
2411 	    }
2412 	  else
2413 	    {
2414 	      /* Address of got entry.  */
2415 	      relocation = sec_addr (htab->elf.sgot) + off;
2416 	      absolute = riscv_zero_pcrel_hi_reloc (rel, info, pc,
2417 						    relocation, contents,
2418 						    howto);
2419 	      /* Update howto if relocation is changed.  */
2420 	      howto = riscv_elf_rtype_to_howto (input_bfd,
2421 						ELFNN_R_TYPE (rel->r_info));
2422 	      if (howto == NULL)
2423 		r = bfd_reloc_notsupported;
2424 	      else if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2425 						     relocation, r_type,
2426 						     absolute))
2427 		r = bfd_reloc_overflow;
2428 	    }
2429 	  break;
2430 
2431 	case R_RISCV_ADD8:
2432 	case R_RISCV_ADD16:
2433 	case R_RISCV_ADD32:
2434 	case R_RISCV_ADD64:
2435 	  {
2436 	    bfd_vma old_value = bfd_get (howto->bitsize, input_bfd,
2437 					 contents + rel->r_offset);
2438 	    relocation = old_value + relocation;
2439 	  }
2440 	  break;
2441 
2442 	case R_RISCV_SUB6:
2443 	case R_RISCV_SUB8:
2444 	case R_RISCV_SUB16:
2445 	case R_RISCV_SUB32:
2446 	case R_RISCV_SUB64:
2447 	  {
2448 	    bfd_vma old_value = bfd_get (howto->bitsize, input_bfd,
2449 					 contents + rel->r_offset);
2450 	    relocation = old_value - relocation;
2451 	  }
2452 	  break;
2453 
2454 	case R_RISCV_CALL:
2455 	case R_RISCV_CALL_PLT:
2456 	  /* Handle a call to an undefined weak function.  This won't be
2457 	     relaxed, so we have to handle it here.  */
2458 	  if (h != NULL && h->root.type == bfd_link_hash_undefweak
2459 	      && (!bfd_link_pic (info) || h->plt.offset == MINUS_ONE))
2460 	    {
2461 	      /* We can use x0 as the base register.  */
2462 	      bfd_vma insn = bfd_getl32 (contents + rel->r_offset + 4);
2463 	      insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
2464 	      bfd_putl32 (insn, contents + rel->r_offset + 4);
2465 	      /* Set the relocation value so that we get 0 after the pc
2466 		 relative adjustment.  */
2467 	      relocation = sec_addr (input_section) + rel->r_offset;
2468 	    }
2469 	  /* Fall through.  */
2470 
2471 	case R_RISCV_JAL:
2472 	case R_RISCV_RVC_JUMP:
2473 	  /* This line has to match the check in _bfd_riscv_relax_section.  */
2474 	  if (bfd_link_pic (info) && h != NULL && h->plt.offset != MINUS_ONE)
2475 	    {
2476 	      /* Refer to the PLT entry.  */
2477 	      relocation = sec_addr (htab->elf.splt) + h->plt.offset;
2478 	      unresolved_reloc = false;
2479 	    }
2480 	  break;
2481 
2482 	case R_RISCV_TPREL_HI20:
2483 	  relocation = tpoff (info, relocation);
2484 	  break;
2485 
2486 	case R_RISCV_TPREL_LO12_I:
2487 	case R_RISCV_TPREL_LO12_S:
2488 	  relocation = tpoff (info, relocation);
2489 	  break;
2490 
2491 	case R_RISCV_TPREL_I:
2492 	case R_RISCV_TPREL_S:
2493 	  relocation = tpoff (info, relocation);
2494 	  if (VALID_ITYPE_IMM (relocation + rel->r_addend))
2495 	    {
2496 	      /* We can use tp as the base register.  */
2497 	      bfd_vma insn = bfd_getl32 (contents + rel->r_offset);
2498 	      insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
2499 	      insn |= X_TP << OP_SH_RS1;
2500 	      bfd_putl32 (insn, contents + rel->r_offset);
2501 	    }
2502 	  else
2503 	    r = bfd_reloc_overflow;
2504 	  break;
2505 
2506 	case R_RISCV_GPREL_I:
2507 	case R_RISCV_GPREL_S:
2508 	  {
2509 	    bfd_vma gp = riscv_global_pointer_value (info);
2510 	    bool x0_base = VALID_ITYPE_IMM (relocation + rel->r_addend);
2511 	    if (x0_base || VALID_ITYPE_IMM (relocation + rel->r_addend - gp))
2512 	      {
2513 		/* We can use x0 or gp as the base register.  */
2514 		bfd_vma insn = bfd_getl32 (contents + rel->r_offset);
2515 		insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
2516 		if (!x0_base)
2517 		  {
2518 		    rel->r_addend -= gp;
2519 		    insn |= X_GP << OP_SH_RS1;
2520 		  }
2521 		bfd_putl32 (insn, contents + rel->r_offset);
2522 	      }
2523 	    else
2524 	      r = bfd_reloc_overflow;
2525 	    break;
2526 	  }
2527 
2528 	case R_RISCV_PCREL_HI20:
2529 	  absolute = riscv_zero_pcrel_hi_reloc (rel, info, pc, relocation,
2530 						contents, howto);
2531 	  /* Update howto if relocation is changed.  */
2532 	  howto = riscv_elf_rtype_to_howto (input_bfd,
2533 					    ELFNN_R_TYPE (rel->r_info));
2534 	  if (howto == NULL)
2535 	    r = bfd_reloc_notsupported;
2536 	  else if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2537 						 relocation + rel->r_addend,
2538 						 r_type, absolute))
2539 	    r = bfd_reloc_overflow;
2540 	  break;
2541 
2542 	case R_RISCV_PCREL_LO12_I:
2543 	case R_RISCV_PCREL_LO12_S:
2544 	  /* We don't allow section symbols plus addends as the auipc address,
2545 	     because then riscv_relax_delete_bytes would have to search through
2546 	     all relocs to update these addends.  This is also ambiguous, as
2547 	     we do allow offsets to be added to the target address, which are
2548 	     not to be used to find the auipc address.  */
2549 	  if (((sym != NULL && (ELF_ST_TYPE (sym->st_info) == STT_SECTION))
2550 	       || (h != NULL && h->type == STT_SECTION))
2551 	      && rel->r_addend)
2552 	    {
2553 	      msg = _("%pcrel_lo section symbol with an addend");
2554 	      r = bfd_reloc_dangerous;
2555 	      break;
2556 	    }
2557 
2558 	  if (riscv_record_pcrel_lo_reloc (&pcrel_relocs, relocation, rel,
2559 					   input_section, info, howto,
2560 					   contents))
2561 	    continue;
2562 	  r = bfd_reloc_overflow;
2563 	  break;
2564 
2565 	case R_RISCV_TLS_DTPREL32:
2566 	case R_RISCV_TLS_DTPREL64:
2567 	  relocation = dtpoff (info, relocation);
2568 	  break;
2569 
2570 	case R_RISCV_32:
2571 	case R_RISCV_64:
2572 	  if ((input_section->flags & SEC_ALLOC) == 0)
2573 	    break;
2574 
2575 	  if ((bfd_link_pic (info)
2576 	       && (h == NULL
2577 		   || (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2578 		       && !resolved_to_zero)
2579 		   || h->root.type != bfd_link_hash_undefweak)
2580 	       && (!howto->pc_relative
2581 		   || !SYMBOL_CALLS_LOCAL (info, h)))
2582 	      || (!bfd_link_pic (info)
2583 		  && h != NULL
2584 		  && h->dynindx != -1
2585 		  && !h->non_got_ref
2586 		  && ((h->def_dynamic
2587 		       && !h->def_regular)
2588 		      || h->root.type == bfd_link_hash_undefweak
2589 		      || h->root.type == bfd_link_hash_undefined)))
2590 	    {
2591 	      Elf_Internal_Rela outrel;
2592 	      asection *sreloc;
2593 	      bool skip_static_relocation, skip_dynamic_relocation;
2594 
2595 	      /* When generating a shared object, these relocations
2596 		 are copied into the output file to be resolved at run
2597 		 time.  */
2598 
2599 	      outrel.r_offset =
2600 		_bfd_elf_section_offset (output_bfd, info, input_section,
2601 					 rel->r_offset);
2602 	      skip_static_relocation = outrel.r_offset != (bfd_vma) -2;
2603 	      skip_dynamic_relocation = outrel.r_offset >= (bfd_vma) -2;
2604 	      outrel.r_offset += sec_addr (input_section);
2605 
2606 	      if (skip_dynamic_relocation)
2607 		memset (&outrel, 0, sizeof outrel);
2608 	      else if (h != NULL && h->dynindx != -1
2609 		       && !(bfd_link_pic (info)
2610 			    && SYMBOLIC_BIND (info, h)
2611 			    && h->def_regular))
2612 		{
2613 		  outrel.r_info = ELFNN_R_INFO (h->dynindx, r_type);
2614 		  outrel.r_addend = rel->r_addend;
2615 		}
2616 	      else
2617 		{
2618 		  outrel.r_info = ELFNN_R_INFO (0, R_RISCV_RELATIVE);
2619 		  outrel.r_addend = relocation + rel->r_addend;
2620 		}
2621 
2622 	      sreloc = elf_section_data (input_section)->sreloc;
2623 	      riscv_elf_append_rela (output_bfd, sreloc, &outrel);
2624 	      if (skip_static_relocation)
2625 		continue;
2626 	    }
2627 	  break;
2628 
2629 	case R_RISCV_TLS_GOT_HI20:
2630 	  is_ie = true;
2631 	  /* Fall through.  */
2632 
2633 	case R_RISCV_TLS_GD_HI20:
2634 	  if (h != NULL)
2635 	    {
2636 	      off = h->got.offset;
2637 	      h->got.offset |= 1;
2638 	    }
2639 	  else
2640 	    {
2641 	      off = local_got_offsets[r_symndx];
2642 	      local_got_offsets[r_symndx] |= 1;
2643 	    }
2644 
2645 	  tls_type = _bfd_riscv_elf_tls_type (input_bfd, h, r_symndx);
2646 	  BFD_ASSERT (tls_type & (GOT_TLS_IE | GOT_TLS_GD));
2647 	  /* If this symbol is referenced by both GD and IE TLS, the IE
2648 	     reference's GOT slot follows the GD reference's slots.  */
2649 	  ie_off = 0;
2650 	  if ((tls_type & GOT_TLS_GD) && (tls_type & GOT_TLS_IE))
2651 	    ie_off = 2 * GOT_ENTRY_SIZE;
2652 
2653 	  if ((off & 1) != 0)
2654 	    off &= ~1;
2655 	  else
2656 	    {
2657 	      Elf_Internal_Rela outrel;
2658 	      int indx = 0;
2659 	      bool need_relocs = false;
2660 
2661 	      if (htab->elf.srelgot == NULL)
2662 		abort ();
2663 
2664 	      if (h != NULL)
2665 		{
2666 		  bool dyn, pic;
2667 		  dyn = htab->elf.dynamic_sections_created;
2668 		  pic = bfd_link_pic (info);
2669 
2670 		  if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, pic, h)
2671 		      && (!pic || !SYMBOL_REFERENCES_LOCAL (info, h)))
2672 		    indx = h->dynindx;
2673 		}
2674 
2675 	      /* The GOT entries have not been initialized yet.  Do it
2676 		 now, and emit any relocations.  */
2677 	      if ((bfd_link_pic (info) || indx != 0)
2678 		  && (h == NULL
2679 		      || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2680 		      || h->root.type != bfd_link_hash_undefweak))
2681 		    need_relocs = true;
2682 
2683 	      if (tls_type & GOT_TLS_GD)
2684 		{
2685 		  if (need_relocs)
2686 		    {
2687 		      outrel.r_offset = sec_addr (htab->elf.sgot) + off;
2688 		      outrel.r_addend = 0;
2689 		      outrel.r_info = ELFNN_R_INFO (indx, R_RISCV_TLS_DTPMODNN);
2690 		      bfd_put_NN (output_bfd, 0,
2691 				  htab->elf.sgot->contents + off);
2692 		      riscv_elf_append_rela (output_bfd, htab->elf.srelgot, &outrel);
2693 		      if (indx == 0)
2694 			{
2695 			  BFD_ASSERT (! unresolved_reloc);
2696 			  bfd_put_NN (output_bfd,
2697 				      dtpoff (info, relocation),
2698 				      (htab->elf.sgot->contents
2699 				       + off + RISCV_ELF_WORD_BYTES));
2700 			}
2701 		      else
2702 			{
2703 			  bfd_put_NN (output_bfd, 0,
2704 				      (htab->elf.sgot->contents
2705 				       + off + RISCV_ELF_WORD_BYTES));
2706 			  outrel.r_info = ELFNN_R_INFO (indx, R_RISCV_TLS_DTPRELNN);
2707 			  outrel.r_offset += RISCV_ELF_WORD_BYTES;
2708 			  riscv_elf_append_rela (output_bfd, htab->elf.srelgot, &outrel);
2709 			}
2710 		    }
2711 		  else
2712 		    {
2713 		      /* If we are not emitting relocations for a
2714 			 general dynamic reference, then we must be in a
2715 			 static link or an executable link with the
2716 			 symbol binding locally.  Mark it as belonging
2717 			 to module 1, the executable.  */
2718 		      bfd_put_NN (output_bfd, 1,
2719 				  htab->elf.sgot->contents + off);
2720 		      bfd_put_NN (output_bfd,
2721 				  dtpoff (info, relocation),
2722 				  (htab->elf.sgot->contents
2723 				   + off + RISCV_ELF_WORD_BYTES));
2724 		   }
2725 		}
2726 
2727 	      if (tls_type & GOT_TLS_IE)
2728 		{
2729 		  if (need_relocs)
2730 		    {
2731 		      bfd_put_NN (output_bfd, 0,
2732 				  htab->elf.sgot->contents + off + ie_off);
2733 		      outrel.r_offset = sec_addr (htab->elf.sgot)
2734 					+ off + ie_off;
2735 		      outrel.r_addend = 0;
2736 		      if (indx == 0)
2737 			outrel.r_addend = tpoff (info, relocation);
2738 		      outrel.r_info = ELFNN_R_INFO (indx, R_RISCV_TLS_TPRELNN);
2739 		      riscv_elf_append_rela (output_bfd, htab->elf.srelgot, &outrel);
2740 		    }
2741 		  else
2742 		    {
2743 		      bfd_put_NN (output_bfd, tpoff (info, relocation),
2744 				  htab->elf.sgot->contents + off + ie_off);
2745 		    }
2746 		}
2747 	    }
2748 
2749 	  BFD_ASSERT (off < (bfd_vma) -2);
2750 	  relocation = sec_addr (htab->elf.sgot) + off + (is_ie ? ie_off : 0);
2751 	  if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2752 					    relocation, r_type,
2753 					    false))
2754 	    r = bfd_reloc_overflow;
2755 	  unresolved_reloc = false;
2756 	  break;
2757 
2758 	default:
2759 	  r = bfd_reloc_notsupported;
2760 	}
2761 
2762       /* Dynamic relocs are not propagated for SEC_DEBUGGING sections
2763 	 because such sections are not SEC_ALLOC and thus ld.so will
2764 	 not process them.  */
2765       if (unresolved_reloc
2766 	  && !((input_section->flags & SEC_DEBUGGING) != 0
2767 	       && h->def_dynamic)
2768 	  && _bfd_elf_section_offset (output_bfd, info, input_section,
2769 				      rel->r_offset) != (bfd_vma) -1)
2770 	{
2771 	  switch (r_type)
2772 	    {
2773 	    case R_RISCV_JAL:
2774 	    case R_RISCV_RVC_JUMP:
2775 	      if (asprintf (&msg_buf,
2776 			    _("%%X%%P: relocation %s against `%s' can "
2777 			      "not be used when making a shared object; "
2778 			      "recompile with -fPIC\n"),
2779 			    howto->name,
2780 			    h->root.root.string) == -1)
2781 		msg_buf = NULL;
2782 	      break;
2783 
2784 	    default:
2785 	      if (asprintf (&msg_buf,
2786 			    _("%%X%%P: unresolvable %s relocation against "
2787 			      "symbol `%s'\n"),
2788 			    howto->name,
2789 			    h->root.root.string) == -1)
2790 		msg_buf = NULL;
2791 	      break;
2792 	    }
2793 
2794 	  msg = msg_buf;
2795 	  r = bfd_reloc_notsupported;
2796 	}
2797 
2798  do_relocation:
2799       if (r == bfd_reloc_ok)
2800 	r = perform_relocation (howto, rel, relocation, input_section,
2801 				input_bfd, contents);
2802 
2803       /* We should have already detected the error and set message before.
2804 	 If the error message isn't set since the linker runs out of memory
2805 	 or we don't set it before, then we should set the default message
2806 	 with the "internal error" string here.  */
2807       switch (r)
2808 	{
2809 	case bfd_reloc_ok:
2810 	  continue;
2811 
2812 	case bfd_reloc_overflow:
2813 	  info->callbacks->reloc_overflow
2814 	    (info, (h ? &h->root : NULL), name, howto->name,
2815 	     (bfd_vma) 0, input_bfd, input_section, rel->r_offset);
2816 	  break;
2817 
2818 	case bfd_reloc_undefined:
2819 	  info->callbacks->undefined_symbol
2820 	    (info, name, input_bfd, input_section, rel->r_offset,
2821 	     true);
2822 	  break;
2823 
2824 	case bfd_reloc_outofrange:
2825 	  if (msg == NULL)
2826 	    msg = _("%X%P: internal error: out of range error\n");
2827 	  break;
2828 
2829 	case bfd_reloc_notsupported:
2830 	  if (msg == NULL)
2831 	    msg = _("%X%P: internal error: unsupported relocation error\n");
2832 	  break;
2833 
2834 	case bfd_reloc_dangerous:
2835 	  /* The error message should already be set.  */
2836 	  if (msg == NULL)
2837 	    msg = _("dangerous relocation error");
2838 	  info->callbacks->reloc_dangerous
2839 	    (info, msg, input_bfd, input_section, rel->r_offset);
2840 	  break;
2841 
2842 	default:
2843 	  msg = _("%X%P: internal error: unknown error\n");
2844 	  break;
2845 	}
2846 
2847       /* Do not report error message for the dangerous relocation again.  */
2848       if (msg && r != bfd_reloc_dangerous)
2849 	info->callbacks->einfo (msg);
2850 
2851       /* Free the unused `msg_buf`.  */
2852       free (msg_buf);
2853 
2854       /* We already reported the error via a callback, so don't try to report
2855 	 it again by returning false.  That leads to spurious errors.  */
2856       ret = true;
2857       goto out;
2858     }
2859 
2860   ret = riscv_resolve_pcrel_lo_relocs (&pcrel_relocs);
2861  out:
2862   riscv_free_pcrel_relocs (&pcrel_relocs);
2863   return ret;
2864 }
2865 
2866 /* Finish up dynamic symbol handling.  We set the contents of various
2867    dynamic sections here.  */
2868 
2869 static bool
riscv_elf_finish_dynamic_symbol(bfd * output_bfd,struct bfd_link_info * info,struct elf_link_hash_entry * h,Elf_Internal_Sym * sym)2870 riscv_elf_finish_dynamic_symbol (bfd *output_bfd,
2871 				 struct bfd_link_info *info,
2872 				 struct elf_link_hash_entry *h,
2873 				 Elf_Internal_Sym *sym)
2874 {
2875   struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
2876   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
2877 
2878   if (h->plt.offset != (bfd_vma) -1)
2879     {
2880       /* We've decided to create a PLT entry for this symbol.  */
2881       bfd_byte *loc;
2882       bfd_vma i, header_address, plt_idx, got_offset, got_address;
2883       uint32_t plt_entry[PLT_ENTRY_INSNS];
2884       Elf_Internal_Rela rela;
2885       asection *plt, *gotplt, *relplt;
2886 
2887       /* When building a static executable, use .iplt, .igot.plt and
2888 	 .rela.iplt sections for STT_GNU_IFUNC symbols.  */
2889       if (htab->elf.splt != NULL)
2890         {
2891           plt = htab->elf.splt;
2892           gotplt = htab->elf.sgotplt;
2893           relplt = htab->elf.srelplt;
2894         }
2895       else
2896         {
2897           plt = htab->elf.iplt;
2898           gotplt = htab->elf.igotplt;
2899           relplt = htab->elf.irelplt;
2900         }
2901 
2902       /* This symbol has an entry in the procedure linkage table.  Set
2903          it up.  */
2904       if ((h->dynindx == -1
2905 	   && !((h->forced_local || bfd_link_executable (info))
2906 		&& h->def_regular
2907 		&& h->type == STT_GNU_IFUNC))
2908 	  || plt == NULL
2909 	  || gotplt == NULL
2910 	  || relplt == NULL)
2911 	return false;
2912 
2913       /* Calculate the address of the PLT header.  */
2914       header_address = sec_addr (plt);
2915 
2916       /* Calculate the index of the entry and the offset of .got.plt entry.
2917 	 For static executables, we don't reserve anything.  */
2918       if (plt == htab->elf.splt)
2919 	{
2920 	  plt_idx = (h->plt.offset - PLT_HEADER_SIZE) / PLT_ENTRY_SIZE;
2921 	  got_offset = GOTPLT_HEADER_SIZE + (plt_idx * GOT_ENTRY_SIZE);
2922 	}
2923       else
2924 	{
2925 	  plt_idx = h->plt.offset / PLT_ENTRY_SIZE;
2926 	  got_offset = plt_idx * GOT_ENTRY_SIZE;
2927 	}
2928 
2929       /* Calculate the address of the .got.plt entry.  */
2930       got_address = sec_addr (gotplt) + got_offset;
2931 
2932       /* Find out where the .plt entry should go.  */
2933       loc = plt->contents + h->plt.offset;
2934 
2935       /* Fill in the PLT entry itself.  */
2936       if (! riscv_make_plt_entry (output_bfd, got_address,
2937 				  header_address + h->plt.offset,
2938 				  plt_entry))
2939 	return false;
2940 
2941       for (i = 0; i < PLT_ENTRY_INSNS; i++)
2942 	bfd_putl32 (plt_entry[i], loc + 4*i);
2943 
2944       /* Fill in the initial value of the .got.plt entry.  */
2945       loc = gotplt->contents + (got_address - sec_addr (gotplt));
2946       bfd_put_NN (output_bfd, sec_addr (plt), loc);
2947 
2948       rela.r_offset = got_address;
2949 
2950       if (h->dynindx == -1
2951 	  || ((bfd_link_executable (info)
2952 	       || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2953 	      && h->def_regular
2954 	      && h->type == STT_GNU_IFUNC))
2955 	{
2956 	  info->callbacks->minfo (_("Local IFUNC function `%s' in %pB\n"),
2957 				  h->root.root.string,
2958 				  h->root.u.def.section->owner);
2959 
2960 	  /* If an STT_GNU_IFUNC symbol is locally defined, generate
2961 	     R_RISCV_IRELATIVE instead of R_RISCV_JUMP_SLOT.  */
2962 	  asection *sec = h->root.u.def.section;
2963 	  rela.r_info = ELFNN_R_INFO (0, R_RISCV_IRELATIVE);
2964 	  rela.r_addend = h->root.u.def.value
2965 			  + sec->output_section->vma
2966 			  + sec->output_offset;
2967 	}
2968       else
2969 	{
2970 	  /* Fill in the entry in the .rela.plt section.  */
2971 	  rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_JUMP_SLOT);
2972 	  rela.r_addend = 0;
2973 	}
2974 
2975       loc = relplt->contents + plt_idx * sizeof (ElfNN_External_Rela);
2976       bed->s->swap_reloca_out (output_bfd, &rela, loc);
2977 
2978       if (!h->def_regular)
2979 	{
2980 	  /* Mark the symbol as undefined, rather than as defined in
2981 	     the .plt section.  Leave the value alone.  */
2982 	  sym->st_shndx = SHN_UNDEF;
2983 	  /* If the symbol is weak, we do need to clear the value.
2984 	     Otherwise, the PLT entry would provide a definition for
2985 	     the symbol even if the symbol wasn't defined anywhere,
2986 	     and so the symbol would never be NULL.  */
2987 	  if (!h->ref_regular_nonweak)
2988 	    sym->st_value = 0;
2989 	}
2990     }
2991 
2992   if (h->got.offset != (bfd_vma) -1
2993       && !(riscv_elf_hash_entry (h)->tls_type & (GOT_TLS_GD | GOT_TLS_IE))
2994       && !UNDEFWEAK_NO_DYNAMIC_RELOC (info, h))
2995     {
2996       asection *sgot;
2997       asection *srela;
2998       Elf_Internal_Rela rela;
2999       bool use_elf_append_rela = true;
3000 
3001       /* This symbol has an entry in the GOT.  Set it up.  */
3002 
3003       sgot = htab->elf.sgot;
3004       srela = htab->elf.srelgot;
3005       BFD_ASSERT (sgot != NULL && srela != NULL);
3006 
3007       rela.r_offset = sec_addr (sgot) + (h->got.offset &~ (bfd_vma) 1);
3008 
3009       /* Handle the ifunc symbol in GOT entry.  */
3010       if (h->def_regular
3011 	  && h->type == STT_GNU_IFUNC)
3012 	{
3013 	  if (h->plt.offset == (bfd_vma) -1)
3014 	    {
3015 	      /* STT_GNU_IFUNC is referenced without PLT.  */
3016 
3017 	      if (htab->elf.splt == NULL)
3018 		{
3019 		  /* Use .rela.iplt section to store .got relocations
3020 		     in static executable.  */
3021 		  srela = htab->elf.irelplt;
3022 
3023 		  /* Do not use riscv_elf_append_rela to add dynamic
3024 		     relocs.  */
3025 		  use_elf_append_rela = false;
3026 		}
3027 
3028 	      if (SYMBOL_REFERENCES_LOCAL (info, h))
3029 		{
3030 		  info->callbacks->minfo (_("Local IFUNC function `%s' in %pB\n"),
3031 					  h->root.root.string,
3032 					  h->root.u.def.section->owner);
3033 
3034 		  rela.r_info = ELFNN_R_INFO (0, R_RISCV_IRELATIVE);
3035 		  rela.r_addend = (h->root.u.def.value
3036 				   + h->root.u.def.section->output_section->vma
3037 				   + h->root.u.def.section->output_offset);
3038 		}
3039 	      else
3040 		{
3041 		  /* Generate R_RISCV_NN.  */
3042 		  BFD_ASSERT ((h->got.offset & 1) == 0);
3043 		  BFD_ASSERT (h->dynindx != -1);
3044 		  rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_NN);
3045 		  rela.r_addend = 0;
3046 		}
3047 	    }
3048 	  else if (bfd_link_pic (info))
3049 	    {
3050 	      /* Generate R_RISCV_NN.  */
3051 	      BFD_ASSERT ((h->got.offset & 1) == 0);
3052 	      BFD_ASSERT (h->dynindx != -1);
3053 	      rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_NN);
3054 	      rela.r_addend = 0;
3055 	    }
3056 	  else
3057 	    {
3058 	      asection *plt;
3059 
3060 	      if (!h->pointer_equality_needed)
3061 		abort ();
3062 
3063 	      /* For non-shared object, we can't use .got.plt, which
3064 		 contains the real function address if we need pointer
3065 		 equality.  We load the GOT entry with the PLT entry.  */
3066 	      plt = htab->elf.splt ? htab->elf.splt : htab->elf.iplt;
3067 	      bfd_put_NN (output_bfd, (plt->output_section->vma
3068 				       + plt->output_offset
3069 				       + h->plt.offset),
3070 			  htab->elf.sgot->contents
3071 			  + (h->got.offset & ~(bfd_vma) 1));
3072 	      return true;
3073 	    }
3074 	}
3075       else if (bfd_link_pic (info)
3076 	       && SYMBOL_REFERENCES_LOCAL (info, h))
3077 	{
3078 	  /* If this is a local symbol reference, we just want to emit
3079 	     a RELATIVE reloc.  This can happen if it is a -Bsymbolic link,
3080 	     or a pie link, or the symbol was forced to be local because
3081 	     of a version file.  The entry in the global offset table will
3082 	     already have been initialized in the relocate_section function.  */
3083 	  BFD_ASSERT ((h->got.offset & 1) != 0);
3084 	  asection *sec = h->root.u.def.section;
3085 	  rela.r_info = ELFNN_R_INFO (0, R_RISCV_RELATIVE);
3086 	  rela.r_addend = (h->root.u.def.value
3087 			   + sec->output_section->vma
3088 			   + sec->output_offset);
3089 	}
3090       else
3091 	{
3092 	  BFD_ASSERT ((h->got.offset & 1) == 0);
3093 	  BFD_ASSERT (h->dynindx != -1);
3094 	  rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_NN);
3095 	  rela.r_addend = 0;
3096 	}
3097 
3098       bfd_put_NN (output_bfd, 0,
3099 		  sgot->contents + (h->got.offset & ~(bfd_vma) 1));
3100 
3101       if (use_elf_append_rela)
3102 	riscv_elf_append_rela (output_bfd, srela, &rela);
3103       else
3104 	{
3105 	  /* Use riscv_elf_append_rela to add the dynamic relocs into
3106 	     .rela.iplt may cause the overwrite problems.  Since we insert
3107 	     the relocs for PLT didn't handle the reloc_index of .rela.iplt,
3108 	     but the riscv_elf_append_rela adds the relocs to the place
3109 	     that are calculated from the reloc_index (in seqential).
3110 
3111 	     One solution is that add these dynamic relocs (GOT IFUNC)
3112 	     from the last of .rela.iplt section.  */
3113 	  bfd_vma iplt_idx = htab->last_iplt_index--;
3114 	  bfd_byte *loc = srela->contents
3115 			  + iplt_idx * sizeof (ElfNN_External_Rela);
3116 	  bed->s->swap_reloca_out (output_bfd, &rela, loc);
3117 	}
3118     }
3119 
3120   if (h->needs_copy)
3121     {
3122       Elf_Internal_Rela rela;
3123       asection *s;
3124 
3125       /* This symbols needs a copy reloc.  Set it up.  */
3126       BFD_ASSERT (h->dynindx != -1);
3127 
3128       rela.r_offset = sec_addr (h->root.u.def.section) + h->root.u.def.value;
3129       rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_COPY);
3130       rela.r_addend = 0;
3131       if (h->root.u.def.section == htab->elf.sdynrelro)
3132 	s = htab->elf.sreldynrelro;
3133       else
3134 	s = htab->elf.srelbss;
3135       riscv_elf_append_rela (output_bfd, s, &rela);
3136     }
3137 
3138   /* Mark some specially defined symbols as absolute.  */
3139   if (h == htab->elf.hdynamic
3140       || (h == htab->elf.hgot || h == htab->elf.hplt))
3141     sym->st_shndx = SHN_ABS;
3142 
3143   return true;
3144 }
3145 
3146 /* Finish up local dynamic symbol handling.  We set the contents of
3147    various dynamic sections here.  */
3148 
3149 static int
riscv_elf_finish_local_dynamic_symbol(void ** slot,void * inf)3150 riscv_elf_finish_local_dynamic_symbol (void **slot, void *inf)
3151 {
3152   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) *slot;
3153   struct bfd_link_info *info = (struct bfd_link_info *) inf;
3154 
3155   return riscv_elf_finish_dynamic_symbol (info->output_bfd, info, h, NULL);
3156 }
3157 
3158 /* Finish up the dynamic sections.  */
3159 
3160 static bool
riscv_finish_dyn(bfd * output_bfd,struct bfd_link_info * info,bfd * dynobj,asection * sdyn)3161 riscv_finish_dyn (bfd *output_bfd, struct bfd_link_info *info,
3162 		  bfd *dynobj, asection *sdyn)
3163 {
3164   struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
3165   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
3166   size_t dynsize = bed->s->sizeof_dyn;
3167   bfd_byte *dyncon, *dynconend;
3168 
3169   dynconend = sdyn->contents + sdyn->size;
3170   for (dyncon = sdyn->contents; dyncon < dynconend; dyncon += dynsize)
3171     {
3172       Elf_Internal_Dyn dyn;
3173       asection *s;
3174 
3175       bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
3176 
3177       switch (dyn.d_tag)
3178 	{
3179 	case DT_PLTGOT:
3180 	  s = htab->elf.sgotplt;
3181 	  dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
3182 	  break;
3183 	case DT_JMPREL:
3184 	  s = htab->elf.srelplt;
3185 	  dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
3186 	  break;
3187 	case DT_PLTRELSZ:
3188 	  s = htab->elf.srelplt;
3189 	  dyn.d_un.d_val = s->size;
3190 	  break;
3191 	default:
3192 	  continue;
3193 	}
3194 
3195       bed->s->swap_dyn_out (output_bfd, &dyn, dyncon);
3196     }
3197   return true;
3198 }
3199 
3200 static bool
riscv_elf_finish_dynamic_sections(bfd * output_bfd,struct bfd_link_info * info)3201 riscv_elf_finish_dynamic_sections (bfd *output_bfd,
3202 				   struct bfd_link_info *info)
3203 {
3204   bfd *dynobj;
3205   asection *sdyn;
3206   struct riscv_elf_link_hash_table *htab;
3207 
3208   htab = riscv_elf_hash_table (info);
3209   BFD_ASSERT (htab != NULL);
3210   dynobj = htab->elf.dynobj;
3211 
3212   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3213 
3214   if (elf_hash_table (info)->dynamic_sections_created)
3215     {
3216       asection *splt;
3217       bool ret;
3218 
3219       splt = htab->elf.splt;
3220       BFD_ASSERT (splt != NULL && sdyn != NULL);
3221 
3222       ret = riscv_finish_dyn (output_bfd, info, dynobj, sdyn);
3223 
3224       if (!ret)
3225 	return ret;
3226 
3227       /* Fill in the head and tail entries in the procedure linkage table.  */
3228       if (splt->size > 0)
3229 	{
3230 	  int i;
3231 	  uint32_t plt_header[PLT_HEADER_INSNS];
3232 	  ret = riscv_make_plt_header (output_bfd,
3233 				       sec_addr (htab->elf.sgotplt),
3234 				       sec_addr (splt), plt_header);
3235 	  if (!ret)
3236 	    return ret;
3237 
3238 	  for (i = 0; i < PLT_HEADER_INSNS; i++)
3239 	    bfd_putl32 (plt_header[i], splt->contents + 4*i);
3240 
3241 	  elf_section_data (splt->output_section)->this_hdr.sh_entsize
3242 	    = PLT_ENTRY_SIZE;
3243 	}
3244     }
3245 
3246   if (htab->elf.sgotplt)
3247     {
3248       asection *output_section = htab->elf.sgotplt->output_section;
3249 
3250       if (bfd_is_abs_section (output_section))
3251 	{
3252 	  (*_bfd_error_handler)
3253 	    (_("discarded output section: `%pA'"), htab->elf.sgotplt);
3254 	  return false;
3255 	}
3256 
3257       if (htab->elf.sgotplt->size > 0)
3258 	{
3259 	  /* Write the first two entries in .got.plt, needed for the dynamic
3260 	     linker.  */
3261 	  bfd_put_NN (output_bfd, (bfd_vma) -1, htab->elf.sgotplt->contents);
3262 	  bfd_put_NN (output_bfd, (bfd_vma) 0,
3263 		      htab->elf.sgotplt->contents + GOT_ENTRY_SIZE);
3264 	}
3265 
3266       elf_section_data (output_section)->this_hdr.sh_entsize = GOT_ENTRY_SIZE;
3267     }
3268 
3269   if (htab->elf.sgot)
3270     {
3271       asection *output_section = htab->elf.sgot->output_section;
3272 
3273       if (htab->elf.sgot->size > 0)
3274 	{
3275 	  /* Set the first entry in the global offset table to the address of
3276 	     the dynamic section.  */
3277 	  bfd_vma val = sdyn ? sec_addr (sdyn) : 0;
3278 	  bfd_put_NN (output_bfd, val, htab->elf.sgot->contents);
3279 	}
3280 
3281       elf_section_data (output_section)->this_hdr.sh_entsize = GOT_ENTRY_SIZE;
3282     }
3283 
3284   /* Fill PLT and GOT entries for local STT_GNU_IFUNC symbols.  */
3285   htab_traverse (htab->loc_hash_table,
3286 		 riscv_elf_finish_local_dynamic_symbol,
3287 		 info);
3288 
3289   return true;
3290 }
3291 
3292 /* Return address for Ith PLT stub in section PLT, for relocation REL
3293    or (bfd_vma) -1 if it should not be included.  */
3294 
3295 static bfd_vma
riscv_elf_plt_sym_val(bfd_vma i,const asection * plt,const arelent * rel ATTRIBUTE_UNUSED)3296 riscv_elf_plt_sym_val (bfd_vma i, const asection *plt,
3297 		       const arelent *rel ATTRIBUTE_UNUSED)
3298 {
3299   return plt->vma + PLT_HEADER_SIZE + i * PLT_ENTRY_SIZE;
3300 }
3301 
3302 static enum elf_reloc_type_class
riscv_reloc_type_class(const struct bfd_link_info * info ATTRIBUTE_UNUSED,const asection * rel_sec ATTRIBUTE_UNUSED,const Elf_Internal_Rela * rela)3303 riscv_reloc_type_class (const struct bfd_link_info *info ATTRIBUTE_UNUSED,
3304 			const asection *rel_sec ATTRIBUTE_UNUSED,
3305 			const Elf_Internal_Rela *rela)
3306 {
3307   switch (ELFNN_R_TYPE (rela->r_info))
3308     {
3309     case R_RISCV_RELATIVE:
3310       return reloc_class_relative;
3311     case R_RISCV_JUMP_SLOT:
3312       return reloc_class_plt;
3313     case R_RISCV_COPY:
3314       return reloc_class_copy;
3315     default:
3316       return reloc_class_normal;
3317     }
3318 }
3319 
3320 /* Given the ELF header flags in FLAGS, it returns a string that describes the
3321    float ABI.  */
3322 
3323 static const char *
riscv_float_abi_string(flagword flags)3324 riscv_float_abi_string (flagword flags)
3325 {
3326   switch (flags & EF_RISCV_FLOAT_ABI)
3327     {
3328     case EF_RISCV_FLOAT_ABI_SOFT:
3329       return "soft-float";
3330       break;
3331     case EF_RISCV_FLOAT_ABI_SINGLE:
3332       return "single-float";
3333       break;
3334     case EF_RISCV_FLOAT_ABI_DOUBLE:
3335       return "double-float";
3336       break;
3337     case EF_RISCV_FLOAT_ABI_QUAD:
3338       return "quad-float";
3339       break;
3340     default:
3341       abort ();
3342     }
3343 }
3344 
3345 /* The information of architecture elf attributes.  */
3346 static riscv_subset_list_t in_subsets;
3347 static riscv_subset_list_t out_subsets;
3348 static riscv_subset_list_t merged_subsets;
3349 
3350 /* Predicator for standard extension.  */
3351 
3352 static bool
riscv_std_ext_p(const char * name)3353 riscv_std_ext_p (const char *name)
3354 {
3355   return (strlen (name) == 1) && (name[0] != 'x') && (name[0] != 's');
3356 }
3357 
3358 /* Check if the versions are compatible.  */
3359 
3360 static bool
riscv_version_mismatch(bfd * ibfd,struct riscv_subset_t * in,struct riscv_subset_t * out)3361 riscv_version_mismatch (bfd *ibfd,
3362 			struct riscv_subset_t *in,
3363 			struct riscv_subset_t *out)
3364 {
3365   if (in == NULL || out == NULL)
3366     return true;
3367 
3368   /* Since there are no version conflicts for now, we just report
3369      warning when the versions are mis-matched.  */
3370   if (in->major_version != out->major_version
3371       || in->minor_version != out->minor_version)
3372     {
3373       if ((in->major_version == RISCV_UNKNOWN_VERSION
3374 	   && in->minor_version == RISCV_UNKNOWN_VERSION)
3375 	  || (out->major_version == RISCV_UNKNOWN_VERSION
3376 	      && out->minor_version == RISCV_UNKNOWN_VERSION))
3377 	{
3378 	  /* Do not report the warning when the version of input
3379 	     or output is RISCV_UNKNOWN_VERSION, since the extension
3380 	     is added implicitly.  */
3381 	}
3382       else
3383 	_bfd_error_handler
3384 	  (_("warning: %pB: mis-matched ISA version %d.%d for '%s' "
3385 	     "extension, the output version is %d.%d"),
3386 	   ibfd,
3387 	   in->major_version,
3388 	   in->minor_version,
3389 	   in->name,
3390 	   out->major_version,
3391 	   out->minor_version);
3392 
3393       /* Update the output ISA versions to the newest ones.  */
3394       if ((in->major_version > out->major_version)
3395 	  || (in->major_version == out->major_version
3396 	      && in->minor_version > out->minor_version))
3397 	{
3398 	  out->major_version = in->major_version;
3399 	  out->minor_version = in->minor_version;
3400 	}
3401     }
3402 
3403   return true;
3404 }
3405 
3406 /* Return true if subset is 'i' or 'e'.  */
3407 
3408 static bool
riscv_i_or_e_p(bfd * ibfd,const char * arch,struct riscv_subset_t * subset)3409 riscv_i_or_e_p (bfd *ibfd,
3410 		const char *arch,
3411 		struct riscv_subset_t *subset)
3412 {
3413   if ((strcasecmp (subset->name, "e") != 0)
3414       && (strcasecmp (subset->name, "i") != 0))
3415     {
3416       _bfd_error_handler
3417 	(_("error: %pB: corrupted ISA string '%s'.  "
3418 	   "First letter should be 'i' or 'e' but got '%s'"),
3419 	   ibfd, arch, subset->name);
3420       return false;
3421     }
3422   return true;
3423 }
3424 
3425 /* Merge standard extensions.
3426 
3427    Return Value:
3428      Return FALSE if failed to merge.
3429 
3430    Arguments:
3431      `bfd`: bfd handler.
3432      `in_arch`: Raw ISA string for input object.
3433      `out_arch`: Raw ISA string for output object.
3434      `pin`: Subset list for input object.
3435      `pout`: Subset list for output object.  */
3436 
3437 static bool
riscv_merge_std_ext(bfd * ibfd,const char * in_arch,const char * out_arch,struct riscv_subset_t ** pin,struct riscv_subset_t ** pout)3438 riscv_merge_std_ext (bfd *ibfd,
3439 		     const char *in_arch,
3440 		     const char *out_arch,
3441 		     struct riscv_subset_t **pin,
3442 		     struct riscv_subset_t **pout)
3443 {
3444   const char *standard_exts = riscv_supported_std_ext ();
3445   const char *p;
3446   struct riscv_subset_t *in = *pin;
3447   struct riscv_subset_t *out = *pout;
3448 
3449   /* First letter should be 'i' or 'e'.  */
3450   if (!riscv_i_or_e_p (ibfd, in_arch, in))
3451     return false;
3452 
3453   if (!riscv_i_or_e_p (ibfd, out_arch, out))
3454     return false;
3455 
3456   if (strcasecmp (in->name, out->name) != 0)
3457     {
3458       /* TODO: We might allow merge 'i' with 'e'.  */
3459       _bfd_error_handler
3460 	(_("error: %pB: mis-matched ISA string to merge '%s' and '%s'"),
3461 	 ibfd, in->name, out->name);
3462       return false;
3463     }
3464   else if (!riscv_version_mismatch (ibfd, in, out))
3465     return false;
3466   else
3467     riscv_add_subset (&merged_subsets,
3468 		      out->name, out->major_version, out->minor_version);
3469 
3470   in = in->next;
3471   out = out->next;
3472 
3473   /* Handle standard extension first.  */
3474   for (p = standard_exts; *p; ++p)
3475     {
3476       struct riscv_subset_t *ext_in, *ext_out, *ext_merged;
3477       char find_ext[2] = {*p, '\0'};
3478       bool find_in, find_out;
3479 
3480       find_in = riscv_lookup_subset (&in_subsets, find_ext, &ext_in);
3481       find_out = riscv_lookup_subset (&out_subsets, find_ext, &ext_out);
3482 
3483       if (!find_in && !find_out)
3484 	continue;
3485 
3486       if (find_in
3487 	  && find_out
3488 	  && !riscv_version_mismatch (ibfd, ext_in, ext_out))
3489 	return false;
3490 
3491       ext_merged = find_out ? ext_out : ext_in;
3492       riscv_add_subset (&merged_subsets, ext_merged->name,
3493 			ext_merged->major_version, ext_merged->minor_version);
3494     }
3495 
3496   /* Skip all standard extensions.  */
3497   while ((in != NULL) && riscv_std_ext_p (in->name)) in = in->next;
3498   while ((out != NULL) && riscv_std_ext_p (out->name)) out = out->next;
3499 
3500   *pin = in;
3501   *pout = out;
3502 
3503   return true;
3504 }
3505 
3506 /* Merge multi letter extensions.  PIN is a pointer to the head of the input
3507    object subset list.  Likewise for POUT and the output object.  Return TRUE
3508    on success and FALSE when a conflict is found.  */
3509 
3510 static bool
riscv_merge_multi_letter_ext(bfd * ibfd,riscv_subset_t ** pin,riscv_subset_t ** pout)3511 riscv_merge_multi_letter_ext (bfd *ibfd,
3512 			      riscv_subset_t **pin,
3513 			      riscv_subset_t **pout)
3514 {
3515   riscv_subset_t *in = *pin;
3516   riscv_subset_t *out = *pout;
3517   riscv_subset_t *tail;
3518 
3519   int cmp;
3520 
3521   while (in && out)
3522     {
3523       cmp = riscv_compare_subsets (in->name, out->name);
3524 
3525       if (cmp < 0)
3526 	{
3527 	  /* `in' comes before `out', append `in' and increment.  */
3528 	  riscv_add_subset (&merged_subsets, in->name, in->major_version,
3529 			    in->minor_version);
3530 	  in = in->next;
3531 	}
3532       else if (cmp > 0)
3533 	{
3534 	  /* `out' comes before `in', append `out' and increment.  */
3535 	  riscv_add_subset (&merged_subsets, out->name, out->major_version,
3536 			    out->minor_version);
3537 	  out = out->next;
3538 	}
3539       else
3540 	{
3541 	  /* Both present, check version and increment both.  */
3542 	  if (!riscv_version_mismatch (ibfd, in, out))
3543 	    return false;
3544 
3545 	  riscv_add_subset (&merged_subsets, out->name, out->major_version,
3546 			    out->minor_version);
3547 	  out = out->next;
3548 	  in = in->next;
3549 	}
3550     }
3551 
3552   if (in || out)
3553     {
3554       /* If we're here, either `in' or `out' is running longer than
3555 	 the other. So, we need to append the corresponding tail.  */
3556       tail = in ? in : out;
3557       while (tail)
3558 	{
3559 	  riscv_add_subset (&merged_subsets, tail->name, tail->major_version,
3560 			    tail->minor_version);
3561 	  tail = tail->next;
3562 	}
3563     }
3564 
3565   return true;
3566 }
3567 
3568 /* Merge Tag_RISCV_arch attribute.  */
3569 
3570 static char *
riscv_merge_arch_attr_info(bfd * ibfd,char * in_arch,char * out_arch)3571 riscv_merge_arch_attr_info (bfd *ibfd, char *in_arch, char *out_arch)
3572 {
3573   riscv_subset_t *in, *out;
3574   char *merged_arch_str;
3575 
3576   unsigned xlen_in, xlen_out;
3577   merged_subsets.head = NULL;
3578   merged_subsets.tail = NULL;
3579 
3580   riscv_parse_subset_t rpe_in;
3581   riscv_parse_subset_t rpe_out;
3582 
3583   /* Only assembler needs to check the default version of ISA, so just set
3584      the rpe_in.get_default_version and rpe_out.get_default_version to NULL.  */
3585   rpe_in.subset_list = &in_subsets;
3586   rpe_in.error_handler = _bfd_error_handler;
3587   rpe_in.xlen = &xlen_in;
3588   rpe_in.get_default_version = NULL;
3589   rpe_in.check_unknown_prefixed_ext = false;
3590 
3591   rpe_out.subset_list = &out_subsets;
3592   rpe_out.error_handler = _bfd_error_handler;
3593   rpe_out.xlen = &xlen_out;
3594   rpe_out.get_default_version = NULL;
3595   rpe_out.check_unknown_prefixed_ext = false;
3596 
3597   if (in_arch == NULL && out_arch == NULL)
3598     return NULL;
3599 
3600   if (in_arch == NULL && out_arch != NULL)
3601     return out_arch;
3602 
3603   if (in_arch != NULL && out_arch == NULL)
3604     return in_arch;
3605 
3606   /* Parse subset from ISA string.  */
3607   if (!riscv_parse_subset (&rpe_in, in_arch))
3608     return NULL;
3609 
3610   if (!riscv_parse_subset (&rpe_out, out_arch))
3611     return NULL;
3612 
3613   /* Checking XLEN.  */
3614   if (xlen_out != xlen_in)
3615     {
3616       _bfd_error_handler
3617 	(_("error: %pB: ISA string of input (%s) doesn't match "
3618 	   "output (%s)"), ibfd, in_arch, out_arch);
3619       return NULL;
3620     }
3621 
3622   /* Merge subset list.  */
3623   in = in_subsets.head;
3624   out = out_subsets.head;
3625 
3626   /* Merge standard extension.  */
3627   if (!riscv_merge_std_ext (ibfd, in_arch, out_arch, &in, &out))
3628     return NULL;
3629 
3630   /* Merge all non-single letter extensions with single call.  */
3631   if (!riscv_merge_multi_letter_ext (ibfd, &in, &out))
3632     return NULL;
3633 
3634   if (xlen_in != xlen_out)
3635     {
3636       _bfd_error_handler
3637 	(_("error: %pB: XLEN of input (%u) doesn't match "
3638 	   "output (%u)"), ibfd, xlen_in, xlen_out);
3639       return NULL;
3640     }
3641 
3642   if (xlen_in != ARCH_SIZE)
3643     {
3644       _bfd_error_handler
3645 	(_("error: %pB: unsupported XLEN (%u), you might be "
3646 	   "using wrong emulation"), ibfd, xlen_in);
3647       return NULL;
3648     }
3649 
3650   merged_arch_str = riscv_arch_str (ARCH_SIZE, &merged_subsets);
3651 
3652   /* Release the subset lists.  */
3653   riscv_release_subset_list (&in_subsets);
3654   riscv_release_subset_list (&out_subsets);
3655   riscv_release_subset_list (&merged_subsets);
3656 
3657   return merged_arch_str;
3658 }
3659 
3660 /* Merge object attributes from IBFD into output_bfd of INFO.
3661    Raise an error if there are conflicting attributes.  */
3662 
3663 static bool
riscv_merge_attributes(bfd * ibfd,struct bfd_link_info * info)3664 riscv_merge_attributes (bfd *ibfd, struct bfd_link_info *info)
3665 {
3666   bfd *obfd = info->output_bfd;
3667   obj_attribute *in_attr;
3668   obj_attribute *out_attr;
3669   bool result = true;
3670   bool priv_attrs_merged = false;
3671   const char *sec_name = get_elf_backend_data (ibfd)->obj_attrs_section;
3672   unsigned int i;
3673 
3674   /* Skip linker created files.  */
3675   if (ibfd->flags & BFD_LINKER_CREATED)
3676     return true;
3677 
3678   /* Skip any input that doesn't have an attribute section.
3679      This enables to link object files without attribute section with
3680      any others.  */
3681   if (bfd_get_section_by_name (ibfd, sec_name) == NULL)
3682     return true;
3683 
3684   if (!elf_known_obj_attributes_proc (obfd)[0].i)
3685     {
3686       /* This is the first object.  Copy the attributes.  */
3687       _bfd_elf_copy_obj_attributes (ibfd, obfd);
3688 
3689       out_attr = elf_known_obj_attributes_proc (obfd);
3690 
3691       /* Use the Tag_null value to indicate the attributes have been
3692 	 initialized.  */
3693       out_attr[0].i = 1;
3694 
3695       return true;
3696     }
3697 
3698   in_attr = elf_known_obj_attributes_proc (ibfd);
3699   out_attr = elf_known_obj_attributes_proc (obfd);
3700 
3701   for (i = LEAST_KNOWN_OBJ_ATTRIBUTE; i < NUM_KNOWN_OBJ_ATTRIBUTES; i++)
3702     {
3703     switch (i)
3704       {
3705       case Tag_RISCV_arch:
3706 	if (!out_attr[Tag_RISCV_arch].s)
3707 	  out_attr[Tag_RISCV_arch].s = in_attr[Tag_RISCV_arch].s;
3708 	else if (in_attr[Tag_RISCV_arch].s
3709 		 && out_attr[Tag_RISCV_arch].s)
3710 	  {
3711 	    /* Check compatible.  */
3712 	    char *merged_arch =
3713 		riscv_merge_arch_attr_info (ibfd,
3714 					    in_attr[Tag_RISCV_arch].s,
3715 					    out_attr[Tag_RISCV_arch].s);
3716 	    if (merged_arch == NULL)
3717 	      {
3718 		result = false;
3719 		out_attr[Tag_RISCV_arch].s = "";
3720 	      }
3721 	    else
3722 	      out_attr[Tag_RISCV_arch].s = merged_arch;
3723 	  }
3724 	break;
3725 
3726       case Tag_RISCV_priv_spec:
3727       case Tag_RISCV_priv_spec_minor:
3728       case Tag_RISCV_priv_spec_revision:
3729 	/* If we have handled the privileged elf attributes, then skip it.  */
3730 	if (!priv_attrs_merged)
3731 	  {
3732 	    unsigned int Tag_a = Tag_RISCV_priv_spec;
3733 	    unsigned int Tag_b = Tag_RISCV_priv_spec_minor;
3734 	    unsigned int Tag_c = Tag_RISCV_priv_spec_revision;
3735 	    enum riscv_spec_class in_priv_spec = PRIV_SPEC_CLASS_NONE;
3736 	    enum riscv_spec_class out_priv_spec = PRIV_SPEC_CLASS_NONE;
3737 
3738 	    /* Get the privileged spec class from elf attributes.  */
3739 	    riscv_get_priv_spec_class_from_numbers (in_attr[Tag_a].i,
3740 						    in_attr[Tag_b].i,
3741 						    in_attr[Tag_c].i,
3742 						    &in_priv_spec);
3743 	    riscv_get_priv_spec_class_from_numbers (out_attr[Tag_a].i,
3744 						    out_attr[Tag_b].i,
3745 						    out_attr[Tag_c].i,
3746 						    &out_priv_spec);
3747 
3748 	    /* Allow to link the object without the privileged specs.  */
3749 	    if (out_priv_spec == PRIV_SPEC_CLASS_NONE)
3750 	      {
3751 		out_attr[Tag_a].i = in_attr[Tag_a].i;
3752 		out_attr[Tag_b].i = in_attr[Tag_b].i;
3753 		out_attr[Tag_c].i = in_attr[Tag_c].i;
3754 	      }
3755 	    else if (in_priv_spec != PRIV_SPEC_CLASS_NONE
3756 		     && in_priv_spec != out_priv_spec)
3757 	      {
3758 		_bfd_error_handler
3759 		  (_("warning: %pB use privileged spec version %u.%u.%u but "
3760 		     "the output use version %u.%u.%u"),
3761 		   ibfd,
3762 		   in_attr[Tag_a].i,
3763 		   in_attr[Tag_b].i,
3764 		   in_attr[Tag_c].i,
3765 		   out_attr[Tag_a].i,
3766 		   out_attr[Tag_b].i,
3767 		   out_attr[Tag_c].i);
3768 
3769 		/* The privileged spec v1.9.1 can not be linked with others
3770 		   since the conflicts, so we plan to drop it in a year or
3771 		   two.  */
3772 		if (in_priv_spec == PRIV_SPEC_CLASS_1P9P1
3773 		    || out_priv_spec == PRIV_SPEC_CLASS_1P9P1)
3774 		  {
3775 		    _bfd_error_handler
3776 		      (_("warning: privileged spec version 1.9.1 can not be "
3777 			 "linked with other spec versions"));
3778 		  }
3779 
3780 		/* Update the output privileged spec to the newest one.  */
3781 		if (in_priv_spec > out_priv_spec)
3782 		  {
3783 		    out_attr[Tag_a].i = in_attr[Tag_a].i;
3784 		    out_attr[Tag_b].i = in_attr[Tag_b].i;
3785 		    out_attr[Tag_c].i = in_attr[Tag_c].i;
3786 		  }
3787 	      }
3788 	    priv_attrs_merged = true;
3789 	  }
3790 	break;
3791 
3792       case Tag_RISCV_unaligned_access:
3793 	out_attr[i].i |= in_attr[i].i;
3794 	break;
3795 
3796       case Tag_RISCV_stack_align:
3797 	if (out_attr[i].i == 0)
3798 	  out_attr[i].i = in_attr[i].i;
3799 	else if (in_attr[i].i != 0
3800 		 && out_attr[i].i != 0
3801 		 && out_attr[i].i != in_attr[i].i)
3802 	  {
3803 	    _bfd_error_handler
3804 	      (_("error: %pB use %u-byte stack aligned but the output "
3805 		 "use %u-byte stack aligned"),
3806 	       ibfd, in_attr[i].i, out_attr[i].i);
3807 	    result = false;
3808 	  }
3809 	break;
3810 
3811       default:
3812 	result &= _bfd_elf_merge_unknown_attribute_low (ibfd, obfd, i);
3813       }
3814 
3815       /* If out_attr was copied from in_attr then it won't have a type yet.  */
3816       if (in_attr[i].type && !out_attr[i].type)
3817 	out_attr[i].type = in_attr[i].type;
3818     }
3819 
3820   /* Merge Tag_compatibility attributes and any common GNU ones.  */
3821   if (!_bfd_elf_merge_object_attributes (ibfd, info))
3822     return false;
3823 
3824   /* Check for any attributes not known on RISC-V.  */
3825   result &= _bfd_elf_merge_unknown_attribute_list (ibfd, obfd);
3826 
3827   return result;
3828 }
3829 
3830 /* Merge backend specific data from an object file to the output
3831    object file when linking.  */
3832 
3833 static bool
_bfd_riscv_elf_merge_private_bfd_data(bfd * ibfd,struct bfd_link_info * info)3834 _bfd_riscv_elf_merge_private_bfd_data (bfd *ibfd, struct bfd_link_info *info)
3835 {
3836   bfd *obfd = info->output_bfd;
3837   flagword new_flags, old_flags;
3838 
3839   if (!is_riscv_elf (ibfd) || !is_riscv_elf (obfd))
3840     return true;
3841 
3842   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
3843     {
3844       (*_bfd_error_handler)
3845 	(_("%pB: ABI is incompatible with that of the selected emulation:\n"
3846 	   "  target emulation `%s' does not match `%s'"),
3847 	 ibfd, bfd_get_target (ibfd), bfd_get_target (obfd));
3848       return false;
3849     }
3850 
3851   if (!_bfd_elf_merge_object_attributes (ibfd, info))
3852     return false;
3853 
3854   if (!riscv_merge_attributes (ibfd, info))
3855     return false;
3856 
3857   /* Check to see if the input BFD actually contains any sections.  If not,
3858      its flags may not have been initialized either, but it cannot actually
3859      cause any incompatibility.  Do not short-circuit dynamic objects; their
3860      section list may be emptied by elf_link_add_object_symbols.
3861 
3862      Also check to see if there are no code sections in the input.  In this
3863      case, there is no need to check for code specific flags.  */
3864   if (!(ibfd->flags & DYNAMIC))
3865     {
3866       bool null_input_bfd = true;
3867       bool only_data_sections = true;
3868       asection *sec;
3869 
3870       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
3871 	{
3872 	  null_input_bfd = false;
3873 
3874 	  if ((bfd_section_flags (sec)
3875 	       & (SEC_LOAD | SEC_CODE | SEC_HAS_CONTENTS))
3876 	      == (SEC_LOAD | SEC_CODE | SEC_HAS_CONTENTS))
3877 	    {
3878 	      only_data_sections = false;
3879 	      break;
3880 	    }
3881 	}
3882 
3883       if (null_input_bfd || only_data_sections)
3884 	return true;
3885     }
3886 
3887   new_flags = elf_elfheader (ibfd)->e_flags;
3888   old_flags = elf_elfheader (obfd)->e_flags;
3889 
3890   if (!elf_flags_init (obfd))
3891     {
3892       elf_flags_init (obfd) = true;
3893       elf_elfheader (obfd)->e_flags = new_flags;
3894       return true;
3895     }
3896 
3897   /* Disallow linking different float ABIs.  */
3898   if ((old_flags ^ new_flags) & EF_RISCV_FLOAT_ABI)
3899     {
3900       (*_bfd_error_handler)
3901 	(_("%pB: can't link %s modules with %s modules"), ibfd,
3902 	 riscv_float_abi_string (new_flags),
3903 	 riscv_float_abi_string (old_flags));
3904       goto fail;
3905     }
3906 
3907   /* Disallow linking RVE and non-RVE.  */
3908   if ((old_flags ^ new_flags) & EF_RISCV_RVE)
3909     {
3910       (*_bfd_error_handler)
3911        (_("%pB: can't link RVE with other target"), ibfd);
3912       goto fail;
3913     }
3914 
3915   /* Allow linking RVC and non-RVC, and keep the RVC flag.  */
3916   elf_elfheader (obfd)->e_flags |= new_flags & EF_RISCV_RVC;
3917 
3918   return true;
3919 
3920  fail:
3921   bfd_set_error (bfd_error_bad_value);
3922   return false;
3923 }
3924 
3925 /* Delete some bytes from a section while relaxing.  */
3926 
3927 static bool
riscv_relax_delete_bytes(bfd * abfd,asection * sec,bfd_vma addr,size_t count,struct bfd_link_info * link_info)3928 riscv_relax_delete_bytes (bfd *abfd, asection *sec, bfd_vma addr, size_t count,
3929 			  struct bfd_link_info *link_info)
3930 {
3931   unsigned int i, symcount;
3932   bfd_vma toaddr = sec->size;
3933   struct elf_link_hash_entry **sym_hashes = elf_sym_hashes (abfd);
3934   Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
3935   unsigned int sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
3936   struct bfd_elf_section_data *data = elf_section_data (sec);
3937   bfd_byte *contents = data->this_hdr.contents;
3938 
3939   /* Actually delete the bytes.  */
3940   sec->size -= count;
3941   memmove (contents + addr, contents + addr + count, toaddr - addr - count);
3942 
3943   /* Adjust the location of all of the relocs.  Note that we need not
3944      adjust the addends, since all PC-relative references must be against
3945      symbols, which we will adjust below.  */
3946   for (i = 0; i < sec->reloc_count; i++)
3947     if (data->relocs[i].r_offset > addr && data->relocs[i].r_offset < toaddr)
3948       data->relocs[i].r_offset -= count;
3949 
3950   /* Adjust the local symbols defined in this section.  */
3951   for (i = 0; i < symtab_hdr->sh_info; i++)
3952     {
3953       Elf_Internal_Sym *sym = (Elf_Internal_Sym *) symtab_hdr->contents + i;
3954       if (sym->st_shndx == sec_shndx)
3955 	{
3956 	  /* If the symbol is in the range of memory we just moved, we
3957 	     have to adjust its value.  */
3958 	  if (sym->st_value > addr && sym->st_value <= toaddr)
3959 	    sym->st_value -= count;
3960 
3961 	  /* If the symbol *spans* the bytes we just deleted (i.e. its
3962 	     *end* is in the moved bytes but its *start* isn't), then we
3963 	     must adjust its size.
3964 
3965 	     This test needs to use the original value of st_value, otherwise
3966 	     we might accidentally decrease size when deleting bytes right
3967 	     before the symbol.  But since deleted relocs can't span across
3968 	     symbols, we can't have both a st_value and a st_size decrease,
3969 	     so it is simpler to just use an else.  */
3970 	  else if (sym->st_value <= addr
3971 		   && sym->st_value + sym->st_size > addr
3972 		   && sym->st_value + sym->st_size <= toaddr)
3973 	    sym->st_size -= count;
3974 	}
3975     }
3976 
3977   /* Now adjust the global symbols defined in this section.  */
3978   symcount = ((symtab_hdr->sh_size / sizeof (ElfNN_External_Sym))
3979 	      - symtab_hdr->sh_info);
3980 
3981   for (i = 0; i < symcount; i++)
3982     {
3983       struct elf_link_hash_entry *sym_hash = sym_hashes[i];
3984 
3985       /* The '--wrap SYMBOL' option is causing a pain when the object file,
3986 	 containing the definition of __wrap_SYMBOL, includes a direct
3987 	 call to SYMBOL as well. Since both __wrap_SYMBOL and SYMBOL reference
3988 	 the same symbol (which is __wrap_SYMBOL), but still exist as two
3989 	 different symbols in 'sym_hashes', we don't want to adjust
3990 	 the global symbol __wrap_SYMBOL twice.
3991 
3992 	 The same problem occurs with symbols that are versioned_hidden, as
3993 	 foo becomes an alias for foo@BAR, and hence they need the same
3994 	 treatment.  */
3995       if (link_info->wrap_hash != NULL
3996 	  || sym_hash->versioned != unversioned)
3997 	{
3998 	  struct elf_link_hash_entry **cur_sym_hashes;
3999 
4000 	  /* Loop only over the symbols which have already been checked.  */
4001 	  for (cur_sym_hashes = sym_hashes; cur_sym_hashes < &sym_hashes[i];
4002 	       cur_sym_hashes++)
4003 	    {
4004 	      /* If the current symbol is identical to 'sym_hash', that means
4005 		 the symbol was already adjusted (or at least checked).  */
4006 	      if (*cur_sym_hashes == sym_hash)
4007 		break;
4008 	    }
4009 	  /* Don't adjust the symbol again.  */
4010 	  if (cur_sym_hashes < &sym_hashes[i])
4011 	    continue;
4012 	}
4013 
4014       if ((sym_hash->root.type == bfd_link_hash_defined
4015 	   || sym_hash->root.type == bfd_link_hash_defweak)
4016 	  && sym_hash->root.u.def.section == sec)
4017 	{
4018 	  /* As above, adjust the value if needed.  */
4019 	  if (sym_hash->root.u.def.value > addr
4020 	      && sym_hash->root.u.def.value <= toaddr)
4021 	    sym_hash->root.u.def.value -= count;
4022 
4023 	  /* As above, adjust the size if needed.  */
4024 	  else if (sym_hash->root.u.def.value <= addr
4025 		   && sym_hash->root.u.def.value + sym_hash->size > addr
4026 		   && sym_hash->root.u.def.value + sym_hash->size <= toaddr)
4027 	    sym_hash->size -= count;
4028 	}
4029     }
4030 
4031   return true;
4032 }
4033 
4034 /* A second format for recording PC-relative hi relocations.  This stores the
4035    information required to relax them to GP-relative addresses.  */
4036 
4037 typedef struct riscv_pcgp_hi_reloc riscv_pcgp_hi_reloc;
4038 struct riscv_pcgp_hi_reloc
4039 {
4040   bfd_vma hi_sec_off;
4041   bfd_vma hi_addend;
4042   bfd_vma hi_addr;
4043   unsigned hi_sym;
4044   asection *sym_sec;
4045   bool undefined_weak;
4046   riscv_pcgp_hi_reloc *next;
4047 };
4048 
4049 typedef struct riscv_pcgp_lo_reloc riscv_pcgp_lo_reloc;
4050 struct riscv_pcgp_lo_reloc
4051 {
4052   bfd_vma hi_sec_off;
4053   riscv_pcgp_lo_reloc *next;
4054 };
4055 
4056 typedef struct
4057 {
4058   riscv_pcgp_hi_reloc *hi;
4059   riscv_pcgp_lo_reloc *lo;
4060 } riscv_pcgp_relocs;
4061 
4062 /* Initialize the pcgp reloc info in P.  */
4063 
4064 static bool
riscv_init_pcgp_relocs(riscv_pcgp_relocs * p)4065 riscv_init_pcgp_relocs (riscv_pcgp_relocs *p)
4066 {
4067   p->hi = NULL;
4068   p->lo = NULL;
4069   return true;
4070 }
4071 
4072 /* Free the pcgp reloc info in P.  */
4073 
4074 static void
riscv_free_pcgp_relocs(riscv_pcgp_relocs * p,bfd * abfd ATTRIBUTE_UNUSED,asection * sec ATTRIBUTE_UNUSED)4075 riscv_free_pcgp_relocs (riscv_pcgp_relocs *p,
4076 			bfd *abfd ATTRIBUTE_UNUSED,
4077 			asection *sec ATTRIBUTE_UNUSED)
4078 {
4079   riscv_pcgp_hi_reloc *c;
4080   riscv_pcgp_lo_reloc *l;
4081 
4082   for (c = p->hi; c != NULL; )
4083     {
4084       riscv_pcgp_hi_reloc *next = c->next;
4085       free (c);
4086       c = next;
4087     }
4088 
4089   for (l = p->lo; l != NULL; )
4090     {
4091       riscv_pcgp_lo_reloc *next = l->next;
4092       free (l);
4093       l = next;
4094     }
4095 }
4096 
4097 /* Record pcgp hi part reloc info in P, using HI_SEC_OFF as the lookup index.
4098    The HI_ADDEND, HI_ADDR, HI_SYM, and SYM_SEC args contain info required to
4099    relax the corresponding lo part reloc.  */
4100 
4101 static bool
riscv_record_pcgp_hi_reloc(riscv_pcgp_relocs * p,bfd_vma hi_sec_off,bfd_vma hi_addend,bfd_vma hi_addr,unsigned hi_sym,asection * sym_sec,bool undefined_weak)4102 riscv_record_pcgp_hi_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off,
4103 			    bfd_vma hi_addend, bfd_vma hi_addr,
4104 			    unsigned hi_sym, asection *sym_sec,
4105 			    bool undefined_weak)
4106 {
4107   riscv_pcgp_hi_reloc *new = bfd_malloc (sizeof (*new));
4108   if (!new)
4109     return false;
4110   new->hi_sec_off = hi_sec_off;
4111   new->hi_addend = hi_addend;
4112   new->hi_addr = hi_addr;
4113   new->hi_sym = hi_sym;
4114   new->sym_sec = sym_sec;
4115   new->undefined_weak = undefined_weak;
4116   new->next = p->hi;
4117   p->hi = new;
4118   return true;
4119 }
4120 
4121 /* Look up hi part pcgp reloc info in P, using HI_SEC_OFF as the lookup index.
4122    This is used by a lo part reloc to find the corresponding hi part reloc.  */
4123 
4124 static riscv_pcgp_hi_reloc *
riscv_find_pcgp_hi_reloc(riscv_pcgp_relocs * p,bfd_vma hi_sec_off)4125 riscv_find_pcgp_hi_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off)
4126 {
4127   riscv_pcgp_hi_reloc *c;
4128 
4129   for (c = p->hi; c != NULL; c = c->next)
4130     if (c->hi_sec_off == hi_sec_off)
4131       return c;
4132   return NULL;
4133 }
4134 
4135 /* Record pcgp lo part reloc info in P, using HI_SEC_OFF as the lookup info.
4136    This is used to record relocs that can't be relaxed.  */
4137 
4138 static bool
riscv_record_pcgp_lo_reloc(riscv_pcgp_relocs * p,bfd_vma hi_sec_off)4139 riscv_record_pcgp_lo_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off)
4140 {
4141   riscv_pcgp_lo_reloc *new = bfd_malloc (sizeof (*new));
4142   if (!new)
4143     return false;
4144   new->hi_sec_off = hi_sec_off;
4145   new->next = p->lo;
4146   p->lo = new;
4147   return true;
4148 }
4149 
4150 /* Look up lo part pcgp reloc info in P, using HI_SEC_OFF as the lookup index.
4151    This is used by a hi part reloc to find the corresponding lo part reloc.  */
4152 
4153 static bool
riscv_find_pcgp_lo_reloc(riscv_pcgp_relocs * p,bfd_vma hi_sec_off)4154 riscv_find_pcgp_lo_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off)
4155 {
4156   riscv_pcgp_lo_reloc *c;
4157 
4158   for (c = p->lo; c != NULL; c = c->next)
4159     if (c->hi_sec_off == hi_sec_off)
4160       return true;
4161   return false;
4162 }
4163 
4164 typedef bool (*relax_func_t) (bfd *, asection *, asection *,
4165 			      struct bfd_link_info *,
4166 			      Elf_Internal_Rela *,
4167 			      bfd_vma, bfd_vma, bfd_vma, bool *,
4168 			      riscv_pcgp_relocs *,
4169 			      bool undefined_weak);
4170 
4171 /* Relax AUIPC + JALR into JAL.  */
4172 
4173 static bool
_bfd_riscv_relax_call(bfd * abfd,asection * sec,asection * sym_sec,struct bfd_link_info * link_info,Elf_Internal_Rela * rel,bfd_vma symval,bfd_vma max_alignment,bfd_vma reserve_size ATTRIBUTE_UNUSED,bool * again,riscv_pcgp_relocs * pcgp_relocs ATTRIBUTE_UNUSED,bool undefined_weak ATTRIBUTE_UNUSED)4174 _bfd_riscv_relax_call (bfd *abfd, asection *sec, asection *sym_sec,
4175 		       struct bfd_link_info *link_info,
4176 		       Elf_Internal_Rela *rel,
4177 		       bfd_vma symval,
4178 		       bfd_vma max_alignment,
4179 		       bfd_vma reserve_size ATTRIBUTE_UNUSED,
4180 		       bool *again,
4181 		       riscv_pcgp_relocs *pcgp_relocs ATTRIBUTE_UNUSED,
4182 		       bool undefined_weak ATTRIBUTE_UNUSED)
4183 {
4184   bfd_byte *contents = elf_section_data (sec)->this_hdr.contents;
4185   bfd_vma foff = symval - (sec_addr (sec) + rel->r_offset);
4186   bool near_zero = (symval + RISCV_IMM_REACH / 2) < RISCV_IMM_REACH;
4187   bfd_vma auipc, jalr;
4188   int rd, r_type, len = 4, rvc = elf_elfheader (abfd)->e_flags & EF_RISCV_RVC;
4189 
4190   /* If the call crosses section boundaries, an alignment directive could
4191      cause the PC-relative offset to later increase, so we need to add in the
4192      max alignment of any section inclusive from the call to the target.
4193      Otherwise, we only need to use the alignment of the current section.  */
4194   if (VALID_JTYPE_IMM (foff))
4195     {
4196       if (sym_sec->output_section == sec->output_section
4197 	  && sym_sec->output_section != bfd_abs_section_ptr)
4198 	max_alignment = (bfd_vma) 1 << sym_sec->output_section->alignment_power;
4199       foff += ((bfd_signed_vma) foff < 0 ? -max_alignment : max_alignment);
4200     }
4201 
4202   /* See if this function call can be shortened.  */
4203   if (!VALID_JTYPE_IMM (foff) && !(!bfd_link_pic (link_info) && near_zero))
4204     return true;
4205 
4206   /* Shorten the function call.  */
4207   BFD_ASSERT (rel->r_offset + 8 <= sec->size);
4208 
4209   auipc = bfd_getl32 (contents + rel->r_offset);
4210   jalr = bfd_getl32 (contents + rel->r_offset + 4);
4211   rd = (jalr >> OP_SH_RD) & OP_MASK_RD;
4212   rvc = rvc && VALID_CJTYPE_IMM (foff);
4213 
4214   /* C.J exists on RV32 and RV64, but C.JAL is RV32-only.  */
4215   rvc = rvc && (rd == 0 || (rd == X_RA && ARCH_SIZE == 32));
4216 
4217   if (rvc)
4218     {
4219       /* Relax to C.J[AL] rd, addr.  */
4220       r_type = R_RISCV_RVC_JUMP;
4221       auipc = rd == 0 ? MATCH_C_J : MATCH_C_JAL;
4222       len = 2;
4223     }
4224   else if (VALID_JTYPE_IMM (foff))
4225     {
4226       /* Relax to JAL rd, addr.  */
4227       r_type = R_RISCV_JAL;
4228       auipc = MATCH_JAL | (rd << OP_SH_RD);
4229     }
4230   else
4231     {
4232       /* Near zero, relax to JALR rd, x0, addr.  */
4233       r_type = R_RISCV_LO12_I;
4234       auipc = MATCH_JALR | (rd << OP_SH_RD);
4235     }
4236 
4237   /* Replace the R_RISCV_CALL reloc.  */
4238   rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), r_type);
4239   /* Replace the AUIPC.  */
4240   riscv_put_insn (8 * len, auipc, contents + rel->r_offset);
4241 
4242   /* Delete unnecessary JALR.  */
4243   *again = true;
4244   return riscv_relax_delete_bytes (abfd, sec, rel->r_offset + len, 8 - len,
4245 				   link_info);
4246 }
4247 
4248 /* Traverse all output sections and return the max alignment.  */
4249 
4250 static bfd_vma
_bfd_riscv_get_max_alignment(asection * sec)4251 _bfd_riscv_get_max_alignment (asection *sec)
4252 {
4253   unsigned int max_alignment_power = 0;
4254   asection *o;
4255 
4256   for (o = sec->output_section->owner->sections; o != NULL; o = o->next)
4257     {
4258       if (o->alignment_power > max_alignment_power)
4259 	max_alignment_power = o->alignment_power;
4260     }
4261 
4262   return (bfd_vma) 1 << max_alignment_power;
4263 }
4264 
4265 /* Relax non-PIC global variable references to GP-relative references.  */
4266 
4267 static bool
_bfd_riscv_relax_lui(bfd * abfd,asection * sec,asection * sym_sec,struct bfd_link_info * link_info,Elf_Internal_Rela * rel,bfd_vma symval,bfd_vma max_alignment,bfd_vma reserve_size,bool * again,riscv_pcgp_relocs * pcgp_relocs ATTRIBUTE_UNUSED,bool undefined_weak)4268 _bfd_riscv_relax_lui (bfd *abfd,
4269 		      asection *sec,
4270 		      asection *sym_sec,
4271 		      struct bfd_link_info *link_info,
4272 		      Elf_Internal_Rela *rel,
4273 		      bfd_vma symval,
4274 		      bfd_vma max_alignment,
4275 		      bfd_vma reserve_size,
4276 		      bool *again,
4277 		      riscv_pcgp_relocs *pcgp_relocs ATTRIBUTE_UNUSED,
4278 		      bool undefined_weak)
4279 {
4280   bfd_byte *contents = elf_section_data (sec)->this_hdr.contents;
4281   bfd_vma gp = riscv_global_pointer_value (link_info);
4282   int use_rvc = elf_elfheader (abfd)->e_flags & EF_RISCV_RVC;
4283 
4284   BFD_ASSERT (rel->r_offset + 4 <= sec->size);
4285 
4286   if (gp)
4287     {
4288       /* If gp and the symbol are in the same output section, which is not the
4289 	 abs section, then consider only that output section's alignment.  */
4290       struct bfd_link_hash_entry *h =
4291 	bfd_link_hash_lookup (link_info->hash, RISCV_GP_SYMBOL, false, false,
4292 			      true);
4293       if (h->u.def.section->output_section == sym_sec->output_section
4294 	  && sym_sec->output_section != bfd_abs_section_ptr)
4295 	max_alignment = (bfd_vma) 1 << sym_sec->output_section->alignment_power;
4296     }
4297 
4298   /* Is the reference in range of x0 or gp?
4299      Valid gp range conservatively because of alignment issue.  */
4300   if (undefined_weak
4301       || (VALID_ITYPE_IMM (symval)
4302 	  || (symval >= gp
4303 	      && VALID_ITYPE_IMM (symval - gp + max_alignment + reserve_size))
4304 	  || (symval < gp
4305 	      && VALID_ITYPE_IMM (symval - gp - max_alignment - reserve_size))))
4306     {
4307       unsigned sym = ELFNN_R_SYM (rel->r_info);
4308       switch (ELFNN_R_TYPE (rel->r_info))
4309 	{
4310 	case R_RISCV_LO12_I:
4311 	  if (undefined_weak)
4312 	    {
4313 	      /* Change the RS1 to zero.  */
4314 	      bfd_vma insn = bfd_getl32 (contents + rel->r_offset);
4315 	      insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
4316 	      bfd_putl32 (insn, contents + rel->r_offset);
4317 	    }
4318 	  else
4319 	    rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_I);
4320 	  return true;
4321 
4322 	case R_RISCV_LO12_S:
4323 	  if (undefined_weak)
4324 	    {
4325 	      /* Change the RS1 to zero.  */
4326 	      bfd_vma insn = bfd_getl32 (contents + rel->r_offset);
4327 	      insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
4328 	      bfd_putl32 (insn, contents + rel->r_offset);
4329 	    }
4330 	  else
4331 	    rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_S);
4332 	  return true;
4333 
4334 	case R_RISCV_HI20:
4335 	  /* We can delete the unnecessary LUI and reloc.  */
4336 	  rel->r_info = ELFNN_R_INFO (0, R_RISCV_NONE);
4337 	  *again = true;
4338 	  return riscv_relax_delete_bytes (abfd, sec, rel->r_offset, 4,
4339 					   link_info);
4340 
4341 	default:
4342 	  abort ();
4343 	}
4344     }
4345 
4346   /* Can we relax LUI to C.LUI?  Alignment might move the section forward;
4347      account for this assuming page alignment at worst. In the presence of
4348      RELRO segment the linker aligns it by one page size, therefore sections
4349      after the segment can be moved more than one page. */
4350 
4351   if (use_rvc
4352       && ELFNN_R_TYPE (rel->r_info) == R_RISCV_HI20
4353       && VALID_CITYPE_LUI_IMM (RISCV_CONST_HIGH_PART (symval))
4354       && VALID_CITYPE_LUI_IMM (RISCV_CONST_HIGH_PART (symval)
4355 			    + (link_info->relro ? 2 * ELF_MAXPAGESIZE
4356 			       : ELF_MAXPAGESIZE)))
4357     {
4358       /* Replace LUI with C.LUI if legal (i.e., rd != x0 and rd != x2/sp).  */
4359       bfd_vma lui = bfd_getl32 (contents + rel->r_offset);
4360       unsigned rd = ((unsigned)lui >> OP_SH_RD) & OP_MASK_RD;
4361       if (rd == 0 || rd == X_SP)
4362 	return true;
4363 
4364       lui = (lui & (OP_MASK_RD << OP_SH_RD)) | MATCH_C_LUI;
4365       bfd_putl32 (lui, contents + rel->r_offset);
4366 
4367       /* Replace the R_RISCV_HI20 reloc.  */
4368       rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), R_RISCV_RVC_LUI);
4369 
4370       *again = true;
4371       return riscv_relax_delete_bytes (abfd, sec, rel->r_offset + 2, 2,
4372 				       link_info);
4373     }
4374 
4375   return true;
4376 }
4377 
4378 /* Relax non-PIC TLS references to TP-relative references.  */
4379 
4380 static bool
_bfd_riscv_relax_tls_le(bfd * abfd,asection * sec,asection * sym_sec ATTRIBUTE_UNUSED,struct bfd_link_info * link_info,Elf_Internal_Rela * rel,bfd_vma symval,bfd_vma max_alignment ATTRIBUTE_UNUSED,bfd_vma reserve_size ATTRIBUTE_UNUSED,bool * again,riscv_pcgp_relocs * prcel_relocs ATTRIBUTE_UNUSED,bool undefined_weak ATTRIBUTE_UNUSED)4381 _bfd_riscv_relax_tls_le (bfd *abfd,
4382 			 asection *sec,
4383 			 asection *sym_sec ATTRIBUTE_UNUSED,
4384 			 struct bfd_link_info *link_info,
4385 			 Elf_Internal_Rela *rel,
4386 			 bfd_vma symval,
4387 			 bfd_vma max_alignment ATTRIBUTE_UNUSED,
4388 			 bfd_vma reserve_size ATTRIBUTE_UNUSED,
4389 			 bool *again,
4390 			 riscv_pcgp_relocs *prcel_relocs ATTRIBUTE_UNUSED,
4391 			 bool undefined_weak ATTRIBUTE_UNUSED)
4392 {
4393   /* See if this symbol is in range of tp.  */
4394   if (RISCV_CONST_HIGH_PART (tpoff (link_info, symval)) != 0)
4395     return true;
4396 
4397   BFD_ASSERT (rel->r_offset + 4 <= sec->size);
4398   switch (ELFNN_R_TYPE (rel->r_info))
4399     {
4400     case R_RISCV_TPREL_LO12_I:
4401       rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), R_RISCV_TPREL_I);
4402       return true;
4403 
4404     case R_RISCV_TPREL_LO12_S:
4405       rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), R_RISCV_TPREL_S);
4406       return true;
4407 
4408     case R_RISCV_TPREL_HI20:
4409     case R_RISCV_TPREL_ADD:
4410       /* We can delete the unnecessary instruction and reloc.  */
4411       rel->r_info = ELFNN_R_INFO (0, R_RISCV_NONE);
4412       *again = true;
4413       return riscv_relax_delete_bytes (abfd, sec, rel->r_offset, 4, link_info);
4414 
4415     default:
4416       abort ();
4417     }
4418 }
4419 
4420 /* Implement R_RISCV_ALIGN by deleting excess alignment NOPs.
4421    Once we've handled an R_RISCV_ALIGN, we can't relax anything else.  */
4422 
4423 static bool
_bfd_riscv_relax_align(bfd * abfd,asection * sec,asection * sym_sec,struct bfd_link_info * link_info,Elf_Internal_Rela * rel,bfd_vma symval,bfd_vma max_alignment ATTRIBUTE_UNUSED,bfd_vma reserve_size ATTRIBUTE_UNUSED,bool * again ATTRIBUTE_UNUSED,riscv_pcgp_relocs * pcrel_relocs ATTRIBUTE_UNUSED,bool undefined_weak ATTRIBUTE_UNUSED)4424 _bfd_riscv_relax_align (bfd *abfd, asection *sec,
4425 			asection *sym_sec,
4426 			struct bfd_link_info *link_info,
4427 			Elf_Internal_Rela *rel,
4428 			bfd_vma symval,
4429 			bfd_vma max_alignment ATTRIBUTE_UNUSED,
4430 			bfd_vma reserve_size ATTRIBUTE_UNUSED,
4431 			bool *again ATTRIBUTE_UNUSED,
4432 			riscv_pcgp_relocs *pcrel_relocs ATTRIBUTE_UNUSED,
4433 			bool undefined_weak ATTRIBUTE_UNUSED)
4434 {
4435   bfd_byte *contents = elf_section_data (sec)->this_hdr.contents;
4436   bfd_vma alignment = 1, pos;
4437   while (alignment <= rel->r_addend)
4438     alignment *= 2;
4439 
4440   symval -= rel->r_addend;
4441   bfd_vma aligned_addr = ((symval - 1) & ~(alignment - 1)) + alignment;
4442   bfd_vma nop_bytes = aligned_addr - symval;
4443 
4444   /* Make sure there are enough NOPs to actually achieve the alignment.  */
4445   if (rel->r_addend < nop_bytes)
4446     {
4447       _bfd_error_handler
4448 	(_("%pB(%pA+%#" PRIx64 "): %" PRId64 " bytes required for alignment "
4449 	   "to %" PRId64 "-byte boundary, but only %" PRId64 " present"),
4450 	 abfd, sym_sec, (uint64_t) rel->r_offset,
4451 	 (int64_t) nop_bytes, (int64_t) alignment, (int64_t) rel->r_addend);
4452       bfd_set_error (bfd_error_bad_value);
4453       return false;
4454     }
4455 
4456   /* Delete the reloc.  */
4457   rel->r_info = ELFNN_R_INFO (0, R_RISCV_NONE);
4458 
4459   /* If the number of NOPs is already correct, there's nothing to do.  */
4460   if (nop_bytes == rel->r_addend)
4461     return true;
4462 
4463   /* Write as many RISC-V NOPs as we need.  */
4464   for (pos = 0; pos < (nop_bytes & -4); pos += 4)
4465     bfd_putl32 (RISCV_NOP, contents + rel->r_offset + pos);
4466 
4467   /* Write a final RVC NOP if need be.  */
4468   if (nop_bytes % 4 != 0)
4469     bfd_putl16 (RVC_NOP, contents + rel->r_offset + pos);
4470 
4471   /* Delete the excess bytes.  */
4472   return riscv_relax_delete_bytes (abfd, sec, rel->r_offset + nop_bytes,
4473 				   rel->r_addend - nop_bytes, link_info);
4474 }
4475 
4476 /* Relax PC-relative references to GP-relative references.  */
4477 
4478 static bool
_bfd_riscv_relax_pc(bfd * abfd ATTRIBUTE_UNUSED,asection * sec,asection * sym_sec,struct bfd_link_info * link_info,Elf_Internal_Rela * rel,bfd_vma symval,bfd_vma max_alignment,bfd_vma reserve_size,bool * again ATTRIBUTE_UNUSED,riscv_pcgp_relocs * pcgp_relocs,bool undefined_weak)4479 _bfd_riscv_relax_pc (bfd *abfd ATTRIBUTE_UNUSED,
4480 		     asection *sec,
4481 		     asection *sym_sec,
4482 		     struct bfd_link_info *link_info,
4483 		     Elf_Internal_Rela *rel,
4484 		     bfd_vma symval,
4485 		     bfd_vma max_alignment,
4486 		     bfd_vma reserve_size,
4487 		     bool *again ATTRIBUTE_UNUSED,
4488 		     riscv_pcgp_relocs *pcgp_relocs,
4489 		     bool undefined_weak)
4490 {
4491   bfd_byte *contents = elf_section_data (sec)->this_hdr.contents;
4492   bfd_vma gp = riscv_global_pointer_value (link_info);
4493 
4494   BFD_ASSERT (rel->r_offset + 4 <= sec->size);
4495 
4496   /* Chain the _LO relocs to their cooresponding _HI reloc to compute the
4497      actual target address.  */
4498   riscv_pcgp_hi_reloc hi_reloc;
4499   memset (&hi_reloc, 0, sizeof (hi_reloc));
4500   switch (ELFNN_R_TYPE (rel->r_info))
4501     {
4502     case R_RISCV_PCREL_LO12_I:
4503     case R_RISCV_PCREL_LO12_S:
4504       {
4505 	/* If the %lo has an addend, it isn't for the label pointing at the
4506 	   hi part instruction, but rather for the symbol pointed at by the
4507 	   hi part instruction.  So we must subtract it here for the lookup.
4508 	   It is still used below in the final symbol address.  */
4509 	bfd_vma hi_sec_off = symval - sec_addr (sym_sec) - rel->r_addend;
4510 	riscv_pcgp_hi_reloc *hi = riscv_find_pcgp_hi_reloc (pcgp_relocs,
4511 							    hi_sec_off);
4512 	if (hi == NULL)
4513 	  {
4514 	    riscv_record_pcgp_lo_reloc (pcgp_relocs, hi_sec_off);
4515 	    return true;
4516 	  }
4517 
4518 	hi_reloc = *hi;
4519 	symval = hi_reloc.hi_addr;
4520 	sym_sec = hi_reloc.sym_sec;
4521 
4522 	/* We can not know whether the undefined weak symbol is referenced
4523 	   according to the information of R_RISCV_PCREL_LO12_I/S.  Therefore,
4524 	   we have to record the 'undefined_weak' flag when handling the
4525 	   corresponding R_RISCV_HI20 reloc in riscv_record_pcgp_hi_reloc.  */
4526 	undefined_weak = hi_reloc.undefined_weak;
4527       }
4528       break;
4529 
4530     case R_RISCV_PCREL_HI20:
4531       /* Mergeable symbols and code might later move out of range.  */
4532       if (! undefined_weak
4533 	  && sym_sec->flags & (SEC_MERGE | SEC_CODE))
4534 	return true;
4535 
4536       /* If the cooresponding lo relocation has already been seen then it's not
4537          safe to relax this relocation.  */
4538       if (riscv_find_pcgp_lo_reloc (pcgp_relocs, rel->r_offset))
4539 	return true;
4540 
4541       break;
4542 
4543     default:
4544       abort ();
4545     }
4546 
4547   if (gp)
4548     {
4549       /* If gp and the symbol are in the same output section, which is not the
4550 	 abs section, then consider only that output section's alignment.  */
4551       struct bfd_link_hash_entry *h =
4552 	bfd_link_hash_lookup (link_info->hash, RISCV_GP_SYMBOL, false, false,
4553 			      true);
4554       if (h->u.def.section->output_section == sym_sec->output_section
4555 	  && sym_sec->output_section != bfd_abs_section_ptr)
4556 	max_alignment = (bfd_vma) 1 << sym_sec->output_section->alignment_power;
4557     }
4558 
4559   /* Is the reference in range of x0 or gp?
4560      Valid gp range conservatively because of alignment issue.  */
4561   if (undefined_weak
4562       || (VALID_ITYPE_IMM (symval)
4563 	  || (symval >= gp
4564 	      && VALID_ITYPE_IMM (symval - gp + max_alignment + reserve_size))
4565 	  || (symval < gp
4566 	      && VALID_ITYPE_IMM (symval - gp - max_alignment - reserve_size))))
4567     {
4568       unsigned sym = hi_reloc.hi_sym;
4569       switch (ELFNN_R_TYPE (rel->r_info))
4570 	{
4571 	case R_RISCV_PCREL_LO12_I:
4572 	  if (undefined_weak)
4573 	    {
4574 	      /* Change the RS1 to zero, and then modify the relocation
4575 		 type to R_RISCV_LO12_I.  */
4576 	      bfd_vma insn = bfd_getl32 (contents + rel->r_offset);
4577 	      insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
4578 	      bfd_putl32 (insn, contents + rel->r_offset);
4579 	      rel->r_info = ELFNN_R_INFO (sym, R_RISCV_LO12_I);
4580 	      rel->r_addend = hi_reloc.hi_addend;
4581 	    }
4582 	  else
4583 	    {
4584 	      rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_I);
4585 	      rel->r_addend += hi_reloc.hi_addend;
4586 	    }
4587 	  return true;
4588 
4589 	case R_RISCV_PCREL_LO12_S:
4590 	  if (undefined_weak)
4591 	    {
4592 	      /* Change the RS1 to zero, and then modify the relocation
4593 		 type to R_RISCV_LO12_S.  */
4594 	      bfd_vma insn = bfd_getl32 (contents + rel->r_offset);
4595 	      insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
4596 	      bfd_putl32 (insn, contents + rel->r_offset);
4597 	      rel->r_info = ELFNN_R_INFO (sym, R_RISCV_LO12_S);
4598 	      rel->r_addend = hi_reloc.hi_addend;
4599 	    }
4600 	  else
4601 	    {
4602 	      rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_S);
4603 	      rel->r_addend += hi_reloc.hi_addend;
4604 	    }
4605 	  return true;
4606 
4607 	case R_RISCV_PCREL_HI20:
4608 	  riscv_record_pcgp_hi_reloc (pcgp_relocs,
4609 				      rel->r_offset,
4610 				      rel->r_addend,
4611 				      symval,
4612 				      ELFNN_R_SYM(rel->r_info),
4613 				      sym_sec,
4614 				      undefined_weak);
4615 	  /* We can delete the unnecessary AUIPC and reloc.  */
4616 	  rel->r_info = ELFNN_R_INFO (0, R_RISCV_DELETE);
4617 	  rel->r_addend = 4;
4618 	  return true;
4619 
4620 	default:
4621 	  abort ();
4622 	}
4623     }
4624 
4625   return true;
4626 }
4627 
4628 /* Delete the bytes for R_RISCV_DELETE.  */
4629 
4630 static bool
_bfd_riscv_relax_delete(bfd * abfd,asection * sec,asection * sym_sec ATTRIBUTE_UNUSED,struct bfd_link_info * link_info,Elf_Internal_Rela * rel,bfd_vma symval ATTRIBUTE_UNUSED,bfd_vma max_alignment ATTRIBUTE_UNUSED,bfd_vma reserve_size ATTRIBUTE_UNUSED,bool * again,riscv_pcgp_relocs * pcgp_relocs ATTRIBUTE_UNUSED,bool undefined_weak ATTRIBUTE_UNUSED)4631 _bfd_riscv_relax_delete (bfd *abfd,
4632 			 asection *sec,
4633 			 asection *sym_sec ATTRIBUTE_UNUSED,
4634 			 struct bfd_link_info *link_info,
4635 			 Elf_Internal_Rela *rel,
4636 			 bfd_vma symval ATTRIBUTE_UNUSED,
4637 			 bfd_vma max_alignment ATTRIBUTE_UNUSED,
4638 			 bfd_vma reserve_size ATTRIBUTE_UNUSED,
4639 			 bool *again,
4640 			 riscv_pcgp_relocs *pcgp_relocs ATTRIBUTE_UNUSED,
4641 			 bool undefined_weak ATTRIBUTE_UNUSED)
4642 {
4643   if (!riscv_relax_delete_bytes (abfd, sec, rel->r_offset, rel->r_addend,
4644 				 link_info))
4645     return false;
4646   rel->r_info = ELFNN_R_INFO (0, R_RISCV_NONE);
4647   *again = true;
4648   return true;
4649 }
4650 
4651 /* Called by after_allocation to set the information of data segment
4652    before relaxing.  */
4653 
4654 void
bfd_elfNN_riscv_set_data_segment_info(struct bfd_link_info * info,int * data_segment_phase)4655 bfd_elfNN_riscv_set_data_segment_info (struct bfd_link_info *info,
4656                                        int *data_segment_phase)
4657 {
4658   struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
4659   htab->data_segment_phase = data_segment_phase;
4660 }
4661 
4662 /* Called by after_allocation to check if we need to run the whole
4663    relaxations again.  */
4664 
4665 bool
bfd_elfNN_riscv_restart_relax_sections(struct bfd_link_info * info)4666 bfd_elfNN_riscv_restart_relax_sections (struct bfd_link_info *info)
4667 {
4668   struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
4669   bool restart = htab->restart_relax;
4670   /* Reset the flag.  */
4671   htab->restart_relax = false;
4672   return restart;
4673 }
4674 
4675 /* Relax a section.
4676 
4677    Pass 0: Shortens code sequences for LUI/CALL/TPREL relocs.
4678    Pass 1: Shortens code sequences for PCREL relocs.
4679    Pass 2: Deletes the bytes that pass 1 made obsolete.
4680    Pass 3: Which cannot be disabled, handles code alignment directives.
4681 
4682    The `again` is used to determine whether the relax pass itself needs to
4683    run again.  And the `restart_relax` is used to determine if we need to
4684    run the whole relax passes again from 0 to 2.  Once we have deleted the
4685    code between relax pass 0 to 2, the restart_relax will be set to TRUE,
4686    and we should run the whole relaxations again to give them more chances
4687    to shorten the code.
4688 
4689    Since we can't relax anything else once we start to handle the alignments,
4690    we will only enter into the relax pass 3 when the restart_relax is FALSE.  */
4691 
4692 static bool
_bfd_riscv_relax_section(bfd * abfd,asection * sec,struct bfd_link_info * info,bool * again)4693 _bfd_riscv_relax_section (bfd *abfd, asection *sec,
4694 			  struct bfd_link_info *info,
4695 			  bool *again)
4696 {
4697   Elf_Internal_Shdr *symtab_hdr = &elf_symtab_hdr (abfd);
4698   struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
4699   struct bfd_elf_section_data *data = elf_section_data (sec);
4700   Elf_Internal_Rela *relocs;
4701   bool ret = false;
4702   unsigned int i;
4703   bfd_vma max_alignment, reserve_size = 0;
4704   riscv_pcgp_relocs pcgp_relocs;
4705 
4706   *again = false;
4707 
4708   if (bfd_link_relocatable (info)
4709       || (sec->flags & SEC_RELOC) == 0
4710       || sec->reloc_count == 0
4711       || (info->disable_target_specific_optimizations
4712 	  && info->relax_pass < 2)
4713       || (htab->restart_relax
4714 	  && info->relax_pass == 3)
4715       /* The exp_seg_relro_adjust is enum phase_enum (0x4),
4716 	 and defined in ld/ldexp.h.  */
4717       || *(htab->data_segment_phase) == 4)
4718     return true;
4719 
4720   riscv_init_pcgp_relocs (&pcgp_relocs);
4721 
4722   /* Read this BFD's relocs if we haven't done so already.  */
4723   if (data->relocs)
4724     relocs = data->relocs;
4725   else if (!(relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
4726 						 info->keep_memory)))
4727     goto fail;
4728 
4729   if (htab)
4730     {
4731       max_alignment = htab->max_alignment;
4732       if (max_alignment == (bfd_vma) -1)
4733 	{
4734 	  max_alignment = _bfd_riscv_get_max_alignment (sec);
4735 	  htab->max_alignment = max_alignment;
4736 	}
4737     }
4738   else
4739     max_alignment = _bfd_riscv_get_max_alignment (sec);
4740 
4741   /* Examine and consider relaxing each reloc.  */
4742   for (i = 0; i < sec->reloc_count; i++)
4743     {
4744       asection *sym_sec;
4745       Elf_Internal_Rela *rel = relocs + i;
4746       relax_func_t relax_func;
4747       int type = ELFNN_R_TYPE (rel->r_info);
4748       bfd_vma symval;
4749       char symtype;
4750       bool undefined_weak = false;
4751 
4752       relax_func = NULL;
4753       if (info->relax_pass == 0)
4754 	{
4755 	  if (type == R_RISCV_CALL
4756 	      || type == R_RISCV_CALL_PLT)
4757 	    relax_func = _bfd_riscv_relax_call;
4758 	  else if (type == R_RISCV_HI20
4759 		   || type == R_RISCV_LO12_I
4760 		   || type == R_RISCV_LO12_S)
4761 	    relax_func = _bfd_riscv_relax_lui;
4762 	  else if (type == R_RISCV_TPREL_HI20
4763 		   || type == R_RISCV_TPREL_ADD
4764 		   || type == R_RISCV_TPREL_LO12_I
4765 		   || type == R_RISCV_TPREL_LO12_S)
4766 	    relax_func = _bfd_riscv_relax_tls_le;
4767 	  else
4768 	    continue;
4769 	}
4770       else if (info->relax_pass == 1
4771 	       && !bfd_link_pic (info)
4772 	       && (type == R_RISCV_PCREL_HI20
4773 		   || type == R_RISCV_PCREL_LO12_I
4774 		   || type == R_RISCV_PCREL_LO12_S))
4775 	relax_func = _bfd_riscv_relax_pc;
4776       else if (info->relax_pass == 2 && type == R_RISCV_DELETE)
4777 	relax_func = _bfd_riscv_relax_delete;
4778       else if (info->relax_pass == 3 && type == R_RISCV_ALIGN)
4779 	relax_func = _bfd_riscv_relax_align;
4780       else
4781 	continue;
4782 
4783       if (info->relax_pass < 2)
4784 	{
4785 	  /* Only relax this reloc if it is paired with R_RISCV_RELAX.  */
4786 	  if (i == sec->reloc_count - 1
4787 	      || ELFNN_R_TYPE ((rel + 1)->r_info) != R_RISCV_RELAX
4788 	      || rel->r_offset != (rel + 1)->r_offset)
4789 	    continue;
4790 
4791 	  /* Skip over the R_RISCV_RELAX.  */
4792 	  i++;
4793 	}
4794 
4795       data->relocs = relocs;
4796 
4797       /* Read this BFD's contents if we haven't done so already.  */
4798       if (!data->this_hdr.contents
4799 	  && !bfd_malloc_and_get_section (abfd, sec, &data->this_hdr.contents))
4800 	goto fail;
4801 
4802       /* Read this BFD's symbols if we haven't done so already.  */
4803       if (symtab_hdr->sh_info != 0
4804 	  && !symtab_hdr->contents
4805 	  && !(symtab_hdr->contents =
4806 	       (unsigned char *) bfd_elf_get_elf_syms (abfd, symtab_hdr,
4807 						       symtab_hdr->sh_info,
4808 						       0, NULL, NULL, NULL)))
4809 	goto fail;
4810 
4811       /* Get the value of the symbol referred to by the reloc.  */
4812       if (ELFNN_R_SYM (rel->r_info) < symtab_hdr->sh_info)
4813 	{
4814 	  /* A local symbol.  */
4815 	  Elf_Internal_Sym *isym = ((Elf_Internal_Sym *) symtab_hdr->contents
4816 				    + ELFNN_R_SYM (rel->r_info));
4817 	  reserve_size = (isym->st_size - rel->r_addend) > isym->st_size
4818 	    ? 0 : isym->st_size - rel->r_addend;
4819 
4820 	  /* Relocate against local STT_GNU_IFUNC symbol.  we have created
4821 	     a fake global symbol entry for this, so deal with the local ifunc
4822 	     as a global.  */
4823 	  if (ELF_ST_TYPE (isym->st_info) == STT_GNU_IFUNC)
4824 	    continue;
4825 
4826 	  if (isym->st_shndx == SHN_UNDEF)
4827 	    sym_sec = sec, symval = rel->r_offset;
4828 	  else
4829 	    {
4830 	      BFD_ASSERT (isym->st_shndx < elf_numsections (abfd));
4831 	      sym_sec = elf_elfsections (abfd)[isym->st_shndx]->bfd_section;
4832 #if 0
4833 	      /* The purpose of this code is unknown.  It breaks linker scripts
4834 		 for embedded development that place sections at address zero.
4835 		 This code is believed to be unnecessary.  Disabling it but not
4836 		 yet removing it, in case something breaks.  */
4837 	      if (sec_addr (sym_sec) == 0)
4838 		continue;
4839 #endif
4840 	      symval = isym->st_value;
4841 	    }
4842 	  symtype = ELF_ST_TYPE (isym->st_info);
4843 	}
4844       else
4845 	{
4846 	  unsigned long indx;
4847 	  struct elf_link_hash_entry *h;
4848 
4849 	  indx = ELFNN_R_SYM (rel->r_info) - symtab_hdr->sh_info;
4850 	  h = elf_sym_hashes (abfd)[indx];
4851 
4852 	  while (h->root.type == bfd_link_hash_indirect
4853 		 || h->root.type == bfd_link_hash_warning)
4854 	    h = (struct elf_link_hash_entry *) h->root.u.i.link;
4855 
4856 	  /* Disable the relaxation for ifunc.  */
4857 	  if (h != NULL && h->type == STT_GNU_IFUNC)
4858 	    continue;
4859 
4860 	  if (h->root.type == bfd_link_hash_undefweak
4861 	      && (relax_func == _bfd_riscv_relax_lui
4862 		  || relax_func == _bfd_riscv_relax_pc))
4863 	    {
4864 	      /* For the lui and auipc relaxations, since the symbol
4865 		 value of an undefined weak symbol is always be zero,
4866 		 we can optimize the patterns into a single LI/MV/ADDI
4867 		 instruction.
4868 
4869 		 Note that, creating shared libraries and pie output may
4870 		 break the rule above.  Fortunately, since we do not relax
4871 		 pc relocs when creating shared libraries and pie output,
4872 		 and the absolute address access for R_RISCV_HI20 isn't
4873 		 allowed when "-fPIC" is set, the problem of creating shared
4874 		 libraries can not happen currently.  Once we support the
4875 		 auipc relaxations when creating shared libraries, then we will
4876 		 need the more rigorous checking for this optimization.  */
4877 	      undefined_weak = true;
4878 	    }
4879 
4880 	  /* This line has to match the check in riscv_elf_relocate_section
4881 	     in the R_RISCV_CALL[_PLT] case.  */
4882 	  if (bfd_link_pic (info) && h->plt.offset != MINUS_ONE)
4883 	    {
4884 	      sym_sec = htab->elf.splt;
4885 	      symval = h->plt.offset;
4886 	    }
4887 	  else if (undefined_weak)
4888 	    {
4889 	      symval = 0;
4890 	      sym_sec = bfd_und_section_ptr;
4891 	    }
4892 	  else if ((h->root.type == bfd_link_hash_defined
4893 		    || h->root.type == bfd_link_hash_defweak)
4894 		   && h->root.u.def.section != NULL
4895 		   && h->root.u.def.section->output_section != NULL)
4896 	    {
4897 	      symval = h->root.u.def.value;
4898 	      sym_sec = h->root.u.def.section;
4899 	    }
4900 	  else
4901 	    continue;
4902 
4903 	  if (h->type != STT_FUNC)
4904 	    reserve_size =
4905 	      (h->size - rel->r_addend) > h->size ? 0 : h->size - rel->r_addend;
4906 	  symtype = h->type;
4907 	}
4908 
4909       if (sym_sec->sec_info_type == SEC_INFO_TYPE_MERGE
4910           && (sym_sec->flags & SEC_MERGE))
4911 	{
4912 	  /* At this stage in linking, no SEC_MERGE symbol has been
4913 	     adjusted, so all references to such symbols need to be
4914 	     passed through _bfd_merged_section_offset.  (Later, in
4915 	     relocate_section, all SEC_MERGE symbols *except* for
4916 	     section symbols have been adjusted.)
4917 
4918 	     gas may reduce relocations against symbols in SEC_MERGE
4919 	     sections to a relocation against the section symbol when
4920 	     the original addend was zero.  When the reloc is against
4921 	     a section symbol we should include the addend in the
4922 	     offset passed to _bfd_merged_section_offset, since the
4923 	     location of interest is the original symbol.  On the
4924 	     other hand, an access to "sym+addend" where "sym" is not
4925 	     a section symbol should not include the addend;  Such an
4926 	     access is presumed to be an offset from "sym";  The
4927 	     location of interest is just "sym".  */
4928 	   if (symtype == STT_SECTION)
4929 	     symval += rel->r_addend;
4930 
4931 	   symval = _bfd_merged_section_offset (abfd, &sym_sec,
4932 						elf_section_data (sym_sec)->sec_info,
4933 						symval);
4934 
4935 	   if (symtype != STT_SECTION)
4936 	     symval += rel->r_addend;
4937 	}
4938       else
4939 	symval += rel->r_addend;
4940 
4941       symval += sec_addr (sym_sec);
4942 
4943       if (!relax_func (abfd, sec, sym_sec, info, rel, symval,
4944 		       max_alignment, reserve_size, again,
4945 		       &pcgp_relocs, undefined_weak))
4946 	goto fail;
4947     }
4948 
4949   ret = true;
4950 
4951  fail:
4952   if (relocs != data->relocs)
4953     free (relocs);
4954   riscv_free_pcgp_relocs (&pcgp_relocs, abfd, sec);
4955 
4956   if (*again)
4957     htab->restart_relax = true;
4958 
4959   return ret;
4960 }
4961 
4962 #if ARCH_SIZE == 32
4963 # define PRSTATUS_SIZE			204
4964 # define PRSTATUS_OFFSET_PR_CURSIG	12
4965 # define PRSTATUS_OFFSET_PR_PID		24
4966 # define PRSTATUS_OFFSET_PR_REG		72
4967 # define ELF_GREGSET_T_SIZE		128
4968 # define PRPSINFO_SIZE			128
4969 # define PRPSINFO_OFFSET_PR_PID		16
4970 # define PRPSINFO_OFFSET_PR_FNAME	32
4971 # define PRPSINFO_OFFSET_PR_PSARGS	48
4972 # define PRPSINFO_PR_FNAME_LENGTH	16
4973 # define PRPSINFO_PR_PSARGS_LENGTH	80
4974 #else
4975 # define PRSTATUS_SIZE			376
4976 # define PRSTATUS_OFFSET_PR_CURSIG	12
4977 # define PRSTATUS_OFFSET_PR_PID		32
4978 # define PRSTATUS_OFFSET_PR_REG		112
4979 # define ELF_GREGSET_T_SIZE		256
4980 # define PRPSINFO_SIZE			136
4981 # define PRPSINFO_OFFSET_PR_PID		24
4982 # define PRPSINFO_OFFSET_PR_FNAME	40
4983 # define PRPSINFO_OFFSET_PR_PSARGS	56
4984 # define PRPSINFO_PR_FNAME_LENGTH	16
4985 # define PRPSINFO_PR_PSARGS_LENGTH	80
4986 #endif
4987 
4988 /* Write PRSTATUS and PRPSINFO note into core file.  This will be called
4989    before the generic code in elf.c.  By checking the compiler defines we
4990    only perform any action here if the generic code would otherwise not be
4991    able to help us.  The intention is that bare metal core dumps (where the
4992    prstatus_t and/or prpsinfo_t might not be available) will use this code,
4993    while non bare metal tools will use the generic elf code.  */
4994 
4995 static char *
riscv_write_core_note(bfd * abfd ATTRIBUTE_UNUSED,char * buf ATTRIBUTE_UNUSED,int * bufsiz ATTRIBUTE_UNUSED,int note_type ATTRIBUTE_UNUSED,...)4996 riscv_write_core_note (bfd *abfd ATTRIBUTE_UNUSED,
4997                        char *buf ATTRIBUTE_UNUSED,
4998                        int *bufsiz ATTRIBUTE_UNUSED,
4999                        int note_type ATTRIBUTE_UNUSED, ...)
5000 {
5001   switch (note_type)
5002     {
5003     default:
5004       return NULL;
5005 
5006 #if !defined (HAVE_PRPSINFO_T)
5007     case NT_PRPSINFO:
5008       {
5009 	char data[PRPSINFO_SIZE] ATTRIBUTE_NONSTRING;
5010 	va_list ap;
5011 
5012 	va_start (ap, note_type);
5013 	memset (data, 0, sizeof (data));
5014 	strncpy (data + PRPSINFO_OFFSET_PR_FNAME, va_arg (ap, const char *),
5015                  PRPSINFO_PR_FNAME_LENGTH);
5016 #if GCC_VERSION == 8000 || GCC_VERSION == 8001
5017 	DIAGNOSTIC_PUSH;
5018 	/* GCC 8.0 and 8.1 warn about 80 equals destination size with
5019 	   -Wstringop-truncation:
5020 	   https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85643
5021 	 */
5022 	DIAGNOSTIC_IGNORE_STRINGOP_TRUNCATION;
5023 #endif
5024 	strncpy (data + PRPSINFO_OFFSET_PR_PSARGS, va_arg (ap, const char *),
5025                  PRPSINFO_PR_PSARGS_LENGTH);
5026 #if GCC_VERSION == 8000 || GCC_VERSION == 8001
5027 	DIAGNOSTIC_POP;
5028 #endif
5029 	va_end (ap);
5030 	return elfcore_write_note (abfd, buf, bufsiz,
5031 				   "CORE", note_type, data, sizeof (data));
5032       }
5033 #endif /* !HAVE_PRPSINFO_T */
5034 
5035 #if !defined (HAVE_PRSTATUS_T)
5036     case NT_PRSTATUS:
5037       {
5038         char data[PRSTATUS_SIZE];
5039         va_list ap;
5040         long pid;
5041         int cursig;
5042         const void *greg;
5043 
5044         va_start (ap, note_type);
5045         memset (data, 0, sizeof(data));
5046         pid = va_arg (ap, long);
5047         bfd_put_32 (abfd, pid, data + PRSTATUS_OFFSET_PR_PID);
5048         cursig = va_arg (ap, int);
5049         bfd_put_16 (abfd, cursig, data + PRSTATUS_OFFSET_PR_CURSIG);
5050         greg = va_arg (ap, const void *);
5051         memcpy (data + PRSTATUS_OFFSET_PR_REG, greg,
5052                 PRSTATUS_SIZE - PRSTATUS_OFFSET_PR_REG - ARCH_SIZE / 8);
5053         va_end (ap);
5054         return elfcore_write_note (abfd, buf, bufsiz,
5055                                    "CORE", note_type, data, sizeof (data));
5056       }
5057 #endif /* !HAVE_PRSTATUS_T */
5058     }
5059 }
5060 
5061 /* Support for core dump NOTE sections.  */
5062 
5063 static bool
riscv_elf_grok_prstatus(bfd * abfd,Elf_Internal_Note * note)5064 riscv_elf_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
5065 {
5066   switch (note->descsz)
5067     {
5068       default:
5069 	return false;
5070 
5071       case PRSTATUS_SIZE: /* sizeof(struct elf_prstatus) on Linux/RISC-V.  */
5072 	/* pr_cursig */
5073 	elf_tdata (abfd)->core->signal
5074 	  = bfd_get_16 (abfd, note->descdata + PRSTATUS_OFFSET_PR_CURSIG);
5075 
5076 	/* pr_pid */
5077 	elf_tdata (abfd)->core->lwpid
5078 	  = bfd_get_32 (abfd, note->descdata + PRSTATUS_OFFSET_PR_PID);
5079 	break;
5080     }
5081 
5082   /* Make a ".reg/999" section.  */
5083   return _bfd_elfcore_make_pseudosection (abfd, ".reg", ELF_GREGSET_T_SIZE,
5084 					  note->descpos + PRSTATUS_OFFSET_PR_REG);
5085 }
5086 
5087 static bool
riscv_elf_grok_psinfo(bfd * abfd,Elf_Internal_Note * note)5088 riscv_elf_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
5089 {
5090   switch (note->descsz)
5091     {
5092       default:
5093 	return false;
5094 
5095       case PRPSINFO_SIZE: /* sizeof(struct elf_prpsinfo) on Linux/RISC-V.  */
5096 	/* pr_pid */
5097 	elf_tdata (abfd)->core->pid
5098 	  = bfd_get_32 (abfd, note->descdata + PRPSINFO_OFFSET_PR_PID);
5099 
5100 	/* pr_fname */
5101 	elf_tdata (abfd)->core->program = _bfd_elfcore_strndup
5102 	  (abfd, note->descdata + PRPSINFO_OFFSET_PR_FNAME,
5103            PRPSINFO_PR_FNAME_LENGTH);
5104 
5105 	/* pr_psargs */
5106 	elf_tdata (abfd)->core->command = _bfd_elfcore_strndup
5107 	  (abfd, note->descdata + PRPSINFO_OFFSET_PR_PSARGS,
5108            PRPSINFO_PR_PSARGS_LENGTH);
5109 	break;
5110     }
5111 
5112   /* Note that for some reason, a spurious space is tacked
5113      onto the end of the args in some (at least one anyway)
5114      implementations, so strip it off if it exists.  */
5115 
5116   {
5117     char *command = elf_tdata (abfd)->core->command;
5118     int n = strlen (command);
5119 
5120     if (0 < n && command[n - 1] == ' ')
5121       command[n - 1] = '\0';
5122   }
5123 
5124   return true;
5125 }
5126 
5127 /* Set the right mach type.  */
5128 
5129 static bool
riscv_elf_object_p(bfd * abfd)5130 riscv_elf_object_p (bfd *abfd)
5131 {
5132   /* There are only two mach types in RISCV currently.  */
5133   if (strcmp (abfd->xvec->name, "elf32-littleriscv") == 0
5134       || strcmp (abfd->xvec->name, "elf32-bigriscv") == 0)
5135     bfd_default_set_arch_mach (abfd, bfd_arch_riscv, bfd_mach_riscv32);
5136   else
5137     bfd_default_set_arch_mach (abfd, bfd_arch_riscv, bfd_mach_riscv64);
5138 
5139   return true;
5140 }
5141 
5142 /* Determine whether an object attribute tag takes an integer, a
5143    string or both.  */
5144 
5145 static int
riscv_elf_obj_attrs_arg_type(int tag)5146 riscv_elf_obj_attrs_arg_type (int tag)
5147 {
5148   return (tag & 1) != 0 ? ATTR_TYPE_FLAG_STR_VAL : ATTR_TYPE_FLAG_INT_VAL;
5149 }
5150 
5151 /* PR27584, Omit local and empty symbols since they usually generated
5152    for pcrel relocations.  */
5153 
5154 static bool
riscv_elf_is_target_special_symbol(bfd * abfd,asymbol * sym)5155 riscv_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
5156 {
5157   return (!strcmp (sym->name, "")
5158 	  || _bfd_elf_is_local_label_name (abfd, sym->name));
5159 }
5160 
5161 #define TARGET_LITTLE_SYM			riscv_elfNN_vec
5162 #define TARGET_LITTLE_NAME			"elfNN-littleriscv"
5163 #define TARGET_BIG_SYM				riscv_elfNN_be_vec
5164 #define TARGET_BIG_NAME				"elfNN-bigriscv"
5165 
5166 #define elf_backend_reloc_type_class		riscv_reloc_type_class
5167 
5168 #define bfd_elfNN_bfd_reloc_name_lookup		riscv_reloc_name_lookup
5169 #define bfd_elfNN_bfd_link_hash_table_create	riscv_elf_link_hash_table_create
5170 #define bfd_elfNN_bfd_reloc_type_lookup		riscv_reloc_type_lookup
5171 #define bfd_elfNN_bfd_merge_private_bfd_data \
5172   _bfd_riscv_elf_merge_private_bfd_data
5173 #define bfd_elfNN_bfd_is_target_special_symbol	riscv_elf_is_target_special_symbol
5174 
5175 #define elf_backend_copy_indirect_symbol	riscv_elf_copy_indirect_symbol
5176 #define elf_backend_create_dynamic_sections	riscv_elf_create_dynamic_sections
5177 #define elf_backend_check_relocs		riscv_elf_check_relocs
5178 #define elf_backend_adjust_dynamic_symbol	riscv_elf_adjust_dynamic_symbol
5179 #define elf_backend_size_dynamic_sections	riscv_elf_size_dynamic_sections
5180 #define elf_backend_relocate_section		riscv_elf_relocate_section
5181 #define elf_backend_finish_dynamic_symbol	riscv_elf_finish_dynamic_symbol
5182 #define elf_backend_finish_dynamic_sections	riscv_elf_finish_dynamic_sections
5183 #define elf_backend_gc_mark_hook		riscv_elf_gc_mark_hook
5184 #define elf_backend_plt_sym_val			riscv_elf_plt_sym_val
5185 #define elf_backend_grok_prstatus		riscv_elf_grok_prstatus
5186 #define elf_backend_grok_psinfo			riscv_elf_grok_psinfo
5187 #define elf_backend_object_p			riscv_elf_object_p
5188 #define elf_backend_write_core_note		riscv_write_core_note
5189 #define elf_info_to_howto_rel			NULL
5190 #define elf_info_to_howto			riscv_info_to_howto_rela
5191 #define bfd_elfNN_bfd_relax_section		_bfd_riscv_relax_section
5192 #define bfd_elfNN_mkobject			elfNN_riscv_mkobject
5193 
5194 #define elf_backend_init_index_section		_bfd_elf_init_1_index_section
5195 
5196 #define elf_backend_can_gc_sections		1
5197 #define elf_backend_can_refcount		1
5198 #define elf_backend_want_got_plt		1
5199 #define elf_backend_plt_readonly		1
5200 #define elf_backend_plt_alignment		4
5201 #define elf_backend_want_plt_sym		1
5202 #define elf_backend_got_header_size		(ARCH_SIZE / 8)
5203 #define elf_backend_want_dynrelro		1
5204 #define elf_backend_rela_normal			1
5205 #define elf_backend_default_execstack		0
5206 
5207 #undef  elf_backend_obj_attrs_vendor
5208 #define elf_backend_obj_attrs_vendor		"riscv"
5209 #undef  elf_backend_obj_attrs_arg_type
5210 #define elf_backend_obj_attrs_arg_type		riscv_elf_obj_attrs_arg_type
5211 #undef  elf_backend_obj_attrs_section_type
5212 #define elf_backend_obj_attrs_section_type	SHT_RISCV_ATTRIBUTES
5213 #undef  elf_backend_obj_attrs_section
5214 #define elf_backend_obj_attrs_section		".riscv.attributes"
5215 
5216 #include "elfNN-target.h"
5217