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