[gdb/testsuite] Fix gdb.base/list-no-debug.exp on debian
[binutils-gdb.git] / bfd / elfnn-riscv.c
blob40ff08e934d75d8868e5b9adffd99847a153e4a3
1 /* RISC-V-specific support for NN-bit ELF.
2 Copyright (C) 2011-2024 Free Software Foundation, Inc.
4 Contributed by Andrew Waterman (andrew@sifive.com).
5 Based on TILE-Gx and MIPS targets.
7 This file is part of BFD, the Binary File Descriptor library.
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.
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.
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/>. */
23 /* This file handles RISC-V ELF targets. */
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"
36 #include <limits.h>
37 #ifndef CHAR_BIT
38 #define CHAR_BIT 8
39 #endif
41 /* True if dynamic relocation is needed. If we are creating a shared library,
42 and this is a reloc against a global symbol, or a non PC relative reloc
43 against a local symbol, then we need to copy the reloc into the shared
44 library. However, if we are linking with -Bsymbolic, we do not need to
45 copy a reloc against a global symbol which is defined in an object we are
46 including in the link (i.e., DEF_REGULAR is set).
48 At this point we have not seen all the input files, so it is possible that
49 DEF_REGULAR is not set now but will be set later (it is never cleared).
50 In case of a weak definition, DEF_REGULAR may be cleared later by a strong
51 definition in a shared library. We account for that possibility below by
52 storing information in the relocs_copied field of the hash table entry.
53 A similar situation occurs when creating shared libraries and symbol
54 visibility changes render the symbol local.
56 If on the other hand, we are creating an executable, we may need to keep
57 relocations for symbols satisfied by a dynamic library if we manage to
58 avoid copy relocs for the symbol.
60 Generate dynamic pointer relocation against STT_GNU_IFUNC symbol in the
61 non-code section (R_RISCV_32/R_RISCV_64). */
62 #define RISCV_NEED_DYNAMIC_RELOC(PCREL, INFO, H, SEC) \
63 ((bfd_link_pic (INFO) \
64 && ((SEC)->flags & SEC_ALLOC) != 0 \
65 && (!(PCREL) \
66 || ((H) != NULL \
67 && (!(INFO)->symbolic \
68 || (H)->root.type == bfd_link_hash_defweak \
69 || !(H)->def_regular)))) \
70 || (!bfd_link_pic (INFO) \
71 && ((SEC)->flags & SEC_ALLOC) != 0 \
72 && (H) != NULL \
73 && ((H)->root.type == bfd_link_hash_defweak \
74 || !(H)->def_regular)) \
75 || (!bfd_link_pic (INFO) \
76 && (H) != NULL \
77 && (H)->type == STT_GNU_IFUNC \
78 && ((SEC)->flags & SEC_CODE) == 0))
80 /* True if dynamic relocation should be generated. */
81 #define RISCV_GENERATE_DYNAMIC_RELOC(PCREL, INFO, H, RESOLVED_TO_ZERO) \
82 ((bfd_link_pic (INFO) \
83 && ((H) == NULL \
84 || (ELF_ST_VISIBILITY ((H)->other) == STV_DEFAULT && !(RESOLVED_TO_ZERO)) \
85 || (H)->root.type != bfd_link_hash_undefweak) \
86 && (!(PCREL) \
87 || !SYMBOL_CALLS_LOCAL ((INFO), (H)))) \
88 || (!bfd_link_pic (INFO) \
89 && (H) != NULL \
90 && (H)->dynindx != -1 \
91 && !(H)->non_got_ref \
92 && (((H)->def_dynamic && !(H)->def_regular) \
93 || (H)->root.type == bfd_link_hash_undefweak \
94 || (H)->root.type == bfd_link_hash_undefined)))
96 /* True if this input relocation should be copied to output. H->dynindx
97 may be -1 if this symbol was marked to become local. */
98 #define RISCV_COPY_INPUT_RELOC(INFO, H) \
99 ((H) != NULL \
100 && (H)->dynindx != -1 \
101 && (!bfd_link_pic (INFO) \
102 || !SYMBOLIC_BIND ((INFO), (H)) \
103 || !(H)->def_regular))
105 /* True if this is actually a static link, or it is a -Bsymbolic link
106 and the symbol is defined locally, or the symbol was forced to be
107 local because of a version file. */
108 #define RISCV_RESOLVED_LOCALLY(INFO, H) \
109 (!WILL_CALL_FINISH_DYNAMIC_SYMBOL (elf_hash_table (INFO)->dynamic_sections_created, \
110 bfd_link_pic (INFO), (H)) \
111 || (bfd_link_pic (INFO) \
112 && SYMBOL_REFERENCES_LOCAL ((INFO), (H))))
114 /* Set NEED_RELOC to true if TLS GD/IE needs dynamic relocations, and INDX will
115 be the dynamic index. PR22263, use the same check in allocate_dynrelocs and
116 riscv_elf_relocate_section for TLS GD/IE. */
117 #define RISCV_TLS_GD_IE_NEED_DYN_RELOC(INFO, DYN, H, INDX, NEED_RELOC) \
118 do \
120 if ((H) != NULL \
121 && (H)->dynindx != -1 \
122 && WILL_CALL_FINISH_DYNAMIC_SYMBOL ((DYN), bfd_link_pic (INFO), (H)) \
123 && (bfd_link_dll (INFO) || !SYMBOL_REFERENCES_LOCAL ((INFO), (H)))) \
124 (INDX) = (H)->dynindx; \
125 if ((bfd_link_dll (INFO) || (INDX) != 0) \
126 && ((H) == NULL \
127 || ELF_ST_VISIBILITY ((H)->other) == STV_DEFAULT \
128 || (H)->root.type != bfd_link_hash_undefweak)) \
129 (NEED_RELOC) = true; \
131 while (0)
133 #define ARCH_SIZE NN
135 #define MINUS_ONE ((bfd_vma)0 - 1)
137 #define RISCV_ELF_LOG_WORD_BYTES (ARCH_SIZE == 32 ? 2 : 3)
139 #define RISCV_ELF_WORD_BYTES (1 << RISCV_ELF_LOG_WORD_BYTES)
141 /* The name of the dynamic interpreter. This is put in the .interp
142 section. */
144 #define ELF64_DYNAMIC_INTERPRETER "/lib/ld.so.1"
145 #define ELF32_DYNAMIC_INTERPRETER "/lib32/ld.so.1"
147 #define ELF_ARCH bfd_arch_riscv
148 #define ELF_TARGET_ID RISCV_ELF_DATA
149 #define ELF_MACHINE_CODE EM_RISCV
150 #define ELF_MAXPAGESIZE 0x1000
151 #define ELF_COMMONPAGESIZE 0x1000
153 #define RISCV_ATTRIBUTES_SECTION_NAME ".riscv.attributes"
155 /* RISC-V ELF linker hash entry. */
157 struct riscv_elf_link_hash_entry
159 struct elf_link_hash_entry elf;
161 #define GOT_UNKNOWN 0
162 #define GOT_NORMAL 1
163 #define GOT_TLS_GD 2
164 #define GOT_TLS_IE 4
165 #define GOT_TLS_LE 8
166 #define GOT_TLSDESC 16
167 char tls_type;
170 #define riscv_elf_hash_entry(ent) \
171 ((struct riscv_elf_link_hash_entry *) (ent))
173 struct _bfd_riscv_elf_obj_tdata
175 struct elf_obj_tdata root;
177 /* tls_type for each local got entry. */
178 char *local_got_tls_type;
181 #define _bfd_riscv_elf_tdata(abfd) \
182 ((struct _bfd_riscv_elf_obj_tdata *) (abfd)->tdata.any)
184 #define _bfd_riscv_elf_local_got_tls_type(abfd) \
185 (_bfd_riscv_elf_tdata (abfd)->local_got_tls_type)
187 #define _bfd_riscv_elf_tls_type(abfd, h, symndx) \
188 (*((h) != NULL ? &riscv_elf_hash_entry (h)->tls_type \
189 : &_bfd_riscv_elf_local_got_tls_type (abfd) [symndx]))
191 #define is_riscv_elf(bfd) \
192 (bfd_get_flavour (bfd) == bfd_target_elf_flavour \
193 && elf_tdata (bfd) != NULL \
194 && elf_object_id (bfd) == RISCV_ELF_DATA)
196 static bool
197 elfNN_riscv_mkobject (bfd *abfd)
199 return bfd_elf_allocate_object (abfd,
200 sizeof (struct _bfd_riscv_elf_obj_tdata),
201 RISCV_ELF_DATA);
204 #include "elf/common.h"
205 #include "elf/internal.h"
207 struct riscv_elf_link_hash_table
209 struct elf_link_hash_table elf;
211 /* Various options and other info passed from the linker. */
212 struct riscv_elf_params *params;
214 /* Short-cuts to get to dynamic linker sections. */
215 asection *sdyntdata;
217 /* The max alignment of output sections. */
218 bfd_vma max_alignment;
220 /* The max alignment of output sections in [gp-2K, gp+2K) range. */
221 bfd_vma max_alignment_for_gp;
223 /* Used by local STT_GNU_IFUNC symbols. */
224 htab_t loc_hash_table;
225 void * loc_hash_memory;
227 /* The index of the last unused .rel.iplt slot. */
228 bfd_vma last_iplt_index;
230 /* The data segment phase, don't relax the section
231 when it is exp_seg_relro_adjust. */
232 int *data_segment_phase;
234 /* Relocations for variant CC symbols may be present. */
235 int variant_cc;
238 /* Instruction access functions. */
239 #define riscv_get_insn(bits, ptr) \
240 ((bits) == 16 ? bfd_getl16 (ptr) \
241 : (bits) == 32 ? bfd_getl32 (ptr) \
242 : (bits) == 64 ? bfd_getl64 (ptr) \
243 : (abort (), (bfd_vma) - 1))
244 #define riscv_put_insn(bits, val, ptr) \
245 ((bits) == 16 ? bfd_putl16 (val, ptr) \
246 : (bits) == 32 ? bfd_putl32 (val, ptr) \
247 : (bits) == 64 ? bfd_putl64 (val, ptr) \
248 : (abort (), (void) 0))
250 /* Get the RISC-V ELF linker hash table from a link_info structure. */
251 #define riscv_elf_hash_table(p) \
252 ((is_elf_hash_table ((p)->hash) \
253 && elf_hash_table_id (elf_hash_table (p)) == RISCV_ELF_DATA) \
254 ? (struct riscv_elf_link_hash_table *) (p)->hash : NULL)
256 void
257 riscv_elfNN_set_options (struct bfd_link_info *link_info,
258 struct riscv_elf_params *params)
260 riscv_elf_hash_table (link_info)->params = params;
263 static bool
264 riscv_info_to_howto_rela (bfd *abfd,
265 arelent *cache_ptr,
266 Elf_Internal_Rela *dst)
268 cache_ptr->howto = riscv_elf_rtype_to_howto (abfd, ELFNN_R_TYPE (dst->r_info));
269 return cache_ptr->howto != NULL;
272 static void
273 riscv_elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
275 const struct elf_backend_data *bed;
276 bfd_byte *loc;
278 bed = get_elf_backend_data (abfd);
279 loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
280 bed->s->swap_reloca_out (abfd, rel, loc);
283 /* Return true if a relocation is modifying an instruction. */
285 static bool
286 riscv_is_insn_reloc (const reloc_howto_type *howto)
288 /* Heuristic: A multibyte destination with a nontrivial mask
289 is an instruction */
290 return (howto->bitsize > 8
291 && howto->dst_mask != 0
292 && ~(howto->dst_mask | (howto->bitsize < sizeof(bfd_vma) * CHAR_BIT
293 ? (MINUS_ONE << howto->bitsize) : (bfd_vma)0)) != 0);
296 /* PLT/GOT stuff. */
297 #define PLT_HEADER_INSNS 8
298 #define PLT_ENTRY_INSNS 4
299 #define PLT_HEADER_SIZE (PLT_HEADER_INSNS * 4)
300 #define PLT_ENTRY_SIZE (PLT_ENTRY_INSNS * 4)
301 #define GOT_ENTRY_SIZE RISCV_ELF_WORD_BYTES
302 #define TLS_GD_GOT_ENTRY_SIZE (RISCV_ELF_WORD_BYTES * 2)
303 #define TLS_IE_GOT_ENTRY_SIZE RISCV_ELF_WORD_BYTES
304 #define TLSDESC_GOT_ENTRY_SIZE (RISCV_ELF_WORD_BYTES * 2)
305 /* Reserve two entries of GOTPLT for ld.so, one is used for PLT resolver,
306 the other is used for link map. Other targets also reserve one more
307 entry used for runtime profile? */
308 #define GOTPLT_HEADER_SIZE (2 * GOT_ENTRY_SIZE)
310 #define sec_addr(sec) ((sec)->output_section->vma + (sec)->output_offset)
312 #if ARCH_SIZE == 32
313 # define MATCH_LREG MATCH_LW
314 #else
315 # define MATCH_LREG MATCH_LD
316 #endif
318 /* Generate a PLT header. */
320 static bool
321 riscv_make_plt_header (bfd *output_bfd, bfd_vma gotplt_addr, bfd_vma addr,
322 uint32_t *entry)
324 bfd_vma gotplt_offset_high = RISCV_PCREL_HIGH_PART (gotplt_addr, addr);
325 bfd_vma gotplt_offset_low = RISCV_PCREL_LOW_PART (gotplt_addr, addr);
327 /* RVE has no t3 register, so this won't work, and is not supported. */
328 if (elf_elfheader (output_bfd)->e_flags & EF_RISCV_RVE)
330 _bfd_error_handler (_("%pB: warning: RVE PLT generation not supported"),
331 output_bfd);
332 return false;
335 /* auipc t2, %hi(.got.plt)
336 sub t1, t1, t3 # shifted .got.plt offset + hdr size + 12
337 l[w|d] t3, %lo(.got.plt)(t2) # _dl_runtime_resolve
338 addi t1, t1, -(hdr size + 12) # shifted .got.plt offset
339 addi t0, t2, %lo(.got.plt) # &.got.plt
340 srli t1, t1, log2(16/PTRSIZE) # .got.plt offset
341 l[w|d] t0, PTRSIZE(t0) # link map
342 jr t3 */
344 entry[0] = RISCV_UTYPE (AUIPC, X_T2, gotplt_offset_high);
345 entry[1] = RISCV_RTYPE (SUB, X_T1, X_T1, X_T3);
346 entry[2] = RISCV_ITYPE (LREG, X_T3, X_T2, gotplt_offset_low);
347 entry[3] = RISCV_ITYPE (ADDI, X_T1, X_T1, (uint32_t) -(PLT_HEADER_SIZE + 12));
348 entry[4] = RISCV_ITYPE (ADDI, X_T0, X_T2, gotplt_offset_low);
349 entry[5] = RISCV_ITYPE (SRLI, X_T1, X_T1, 4 - RISCV_ELF_LOG_WORD_BYTES);
350 entry[6] = RISCV_ITYPE (LREG, X_T0, X_T0, RISCV_ELF_WORD_BYTES);
351 entry[7] = RISCV_ITYPE (JALR, 0, X_T3, 0);
353 return true;
356 /* Generate a PLT entry. */
358 static bool
359 riscv_make_plt_entry (bfd *output_bfd, bfd_vma got, bfd_vma addr,
360 uint32_t *entry)
362 /* RVE has no t3 register, so this won't work, and is not supported. */
363 if (elf_elfheader (output_bfd)->e_flags & EF_RISCV_RVE)
365 _bfd_error_handler (_("%pB: warning: RVE PLT generation not supported"),
366 output_bfd);
367 return false;
370 /* auipc t3, %hi(.got.plt entry)
371 l[w|d] t3, %lo(.got.plt entry)(t3)
372 jalr t1, t3
373 nop */
375 entry[0] = RISCV_UTYPE (AUIPC, X_T3, RISCV_PCREL_HIGH_PART (got, addr));
376 entry[1] = RISCV_ITYPE (LREG, X_T3, X_T3, RISCV_PCREL_LOW_PART (got, addr));
377 entry[2] = RISCV_ITYPE (JALR, X_T1, X_T3, 0);
378 entry[3] = RISCV_NOP;
380 return true;
383 /* Create an entry in an RISC-V ELF linker hash table. */
385 static struct bfd_hash_entry *
386 link_hash_newfunc (struct bfd_hash_entry *entry,
387 struct bfd_hash_table *table, const char *string)
389 /* Allocate the structure if it has not already been allocated by a
390 subclass. */
391 if (entry == NULL)
393 entry =
394 bfd_hash_allocate (table,
395 sizeof (struct riscv_elf_link_hash_entry));
396 if (entry == NULL)
397 return entry;
400 /* Call the allocation method of the superclass. */
401 entry = _bfd_elf_link_hash_newfunc (entry, table, string);
402 if (entry != NULL)
404 struct riscv_elf_link_hash_entry *eh;
406 eh = (struct riscv_elf_link_hash_entry *) entry;
407 eh->tls_type = GOT_UNKNOWN;
410 return entry;
413 /* Compute a hash of a local hash entry. We use elf_link_hash_entry
414 for local symbol so that we can handle local STT_GNU_IFUNC symbols
415 as global symbol. We reuse indx and dynstr_index for local symbol
416 hash since they aren't used by global symbols in this backend. */
418 static hashval_t
419 riscv_elf_local_htab_hash (const void *ptr)
421 struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) ptr;
422 return ELF_LOCAL_SYMBOL_HASH (h->indx, h->dynstr_index);
425 /* Compare local hash entries. */
427 static int
428 riscv_elf_local_htab_eq (const void *ptr1, const void *ptr2)
430 struct elf_link_hash_entry *h1 = (struct elf_link_hash_entry *) ptr1;
431 struct elf_link_hash_entry *h2 = (struct elf_link_hash_entry *) ptr2;
433 return h1->indx == h2->indx && h1->dynstr_index == h2->dynstr_index;
436 /* Find and/or create a hash entry for local symbol. */
438 static struct elf_link_hash_entry *
439 riscv_elf_get_local_sym_hash (struct riscv_elf_link_hash_table *htab,
440 bfd *abfd, const Elf_Internal_Rela *rel,
441 bool create)
443 struct riscv_elf_link_hash_entry eh, *ret;
444 asection *sec = abfd->sections;
445 hashval_t h = ELF_LOCAL_SYMBOL_HASH (sec->id,
446 ELFNN_R_SYM (rel->r_info));
447 void **slot;
449 eh.elf.indx = sec->id;
450 eh.elf.dynstr_index = ELFNN_R_SYM (rel->r_info);
451 slot = htab_find_slot_with_hash (htab->loc_hash_table, &eh, h,
452 create ? INSERT : NO_INSERT);
454 if (!slot)
455 return NULL;
457 if (*slot)
459 ret = (struct riscv_elf_link_hash_entry *) *slot;
460 return &ret->elf;
463 ret = (struct riscv_elf_link_hash_entry *)
464 objalloc_alloc ((struct objalloc *) htab->loc_hash_memory,
465 sizeof (struct riscv_elf_link_hash_entry));
466 if (ret)
468 memset (ret, 0, sizeof (*ret));
469 ret->elf.indx = sec->id;
470 ret->elf.dynstr_index = ELFNN_R_SYM (rel->r_info);
471 ret->elf.dynindx = -1;
472 *slot = ret;
474 return &ret->elf;
477 /* Destroy a RISC-V elf linker hash table. */
479 static void
480 riscv_elf_link_hash_table_free (bfd *obfd)
482 struct riscv_elf_link_hash_table *ret
483 = (struct riscv_elf_link_hash_table *) obfd->link.hash;
485 if (ret->loc_hash_table)
486 htab_delete (ret->loc_hash_table);
487 if (ret->loc_hash_memory)
488 objalloc_free ((struct objalloc *) ret->loc_hash_memory);
490 _bfd_elf_link_hash_table_free (obfd);
493 /* Create a RISC-V ELF linker hash table. */
495 static struct bfd_link_hash_table *
496 riscv_elf_link_hash_table_create (bfd *abfd)
498 struct riscv_elf_link_hash_table *ret;
499 size_t amt = sizeof (struct riscv_elf_link_hash_table);
501 ret = (struct riscv_elf_link_hash_table *) bfd_zmalloc (amt);
502 if (ret == NULL)
503 return NULL;
505 if (!_bfd_elf_link_hash_table_init (&ret->elf, abfd, link_hash_newfunc,
506 sizeof (struct riscv_elf_link_hash_entry),
507 RISCV_ELF_DATA))
509 free (ret);
510 return NULL;
513 ret->max_alignment = (bfd_vma) -1;
514 ret->max_alignment_for_gp = (bfd_vma) -1;
516 /* Create hash table for local ifunc. */
517 ret->loc_hash_table = htab_try_create (1024,
518 riscv_elf_local_htab_hash,
519 riscv_elf_local_htab_eq,
520 NULL);
521 ret->loc_hash_memory = objalloc_create ();
522 if (!ret->loc_hash_table || !ret->loc_hash_memory)
524 riscv_elf_link_hash_table_free (abfd);
525 return NULL;
527 ret->elf.root.hash_table_free = riscv_elf_link_hash_table_free;
529 return &ret->elf.root;
532 /* Create the .got section. */
534 static bool
535 riscv_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
537 flagword flags;
538 asection *s, *s_got;
539 struct elf_link_hash_entry *h;
540 const struct elf_backend_data *bed = get_elf_backend_data (abfd);
541 struct elf_link_hash_table *htab = elf_hash_table (info);
543 /* This function may be called more than once. */
544 if (htab->sgot != NULL)
545 return true;
547 flags = bed->dynamic_sec_flags;
549 s = bfd_make_section_anyway_with_flags (abfd,
550 (bed->rela_plts_and_copies_p
551 ? ".rela.got" : ".rel.got"),
552 (bed->dynamic_sec_flags
553 | SEC_READONLY));
554 if (s == NULL
555 || !bfd_set_section_alignment (s, bed->s->log_file_align))
556 return false;
557 htab->srelgot = s;
559 s = s_got = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
560 if (s == NULL
561 || !bfd_set_section_alignment (s, bed->s->log_file_align))
562 return false;
563 htab->sgot = s;
565 /* The first bit of the global offset table is the header. */
566 s->size += bed->got_header_size;
568 if (bed->want_got_plt)
570 s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
571 if (s == NULL
572 || !bfd_set_section_alignment (s, bed->s->log_file_align))
573 return false;
574 htab->sgotplt = s;
576 /* Reserve room for the header. */
577 s->size += GOTPLT_HEADER_SIZE;
580 if (bed->want_got_sym)
582 /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
583 section. We don't do this in the linker script because we don't want
584 to define the symbol if we are not creating a global offset
585 table. */
586 h = _bfd_elf_define_linkage_sym (abfd, info, s_got,
587 "_GLOBAL_OFFSET_TABLE_");
588 elf_hash_table (info)->hgot = h;
589 if (h == NULL)
590 return false;
593 return true;
596 /* Create .plt, .rela.plt, .got, .got.plt, .rela.got, .dynbss, and
597 .rela.bss sections in DYNOBJ, and set up shortcuts to them in our
598 hash table. */
600 static bool
601 riscv_elf_create_dynamic_sections (bfd *dynobj,
602 struct bfd_link_info *info)
604 struct riscv_elf_link_hash_table *htab;
606 htab = riscv_elf_hash_table (info);
607 BFD_ASSERT (htab != NULL);
609 if (!riscv_elf_create_got_section (dynobj, info))
610 return false;
612 if (!_bfd_elf_create_dynamic_sections (dynobj, info))
613 return false;
615 if (!bfd_link_pic (info))
617 /* Technically, this section doesn't have contents. It is used as the
618 target of TLS copy relocs, to copy TLS data from shared libraries into
619 the executable. However, if we don't mark it as loadable, then it
620 matches the IS_TBSS test in ldlang.c, and there is no run-time address
621 space allocated for it even though it has SEC_ALLOC. That test is
622 correct for .tbss, but not correct for this section. There is also
623 a second problem that having a section with no contents can only work
624 if it comes after all sections with contents in the same segment,
625 but the linker script does not guarantee that. This is just mixed in
626 with other .tdata.* sections. We can fix both problems by lying and
627 saying that there are contents. This section is expected to be small
628 so this should not cause a significant extra program startup cost. */
629 htab->sdyntdata =
630 bfd_make_section_anyway_with_flags (dynobj, ".tdata.dyn",
631 (SEC_ALLOC | SEC_THREAD_LOCAL
632 | SEC_LOAD | SEC_DATA
633 | SEC_HAS_CONTENTS
634 | SEC_LINKER_CREATED));
637 if (!htab->elf.splt || !htab->elf.srelplt || !htab->elf.sdynbss
638 || (!bfd_link_pic (info) && (!htab->elf.srelbss || !htab->sdyntdata)))
639 abort ();
641 return true;
644 /* Copy the extra info we tack onto an elf_link_hash_entry. */
646 static void
647 riscv_elf_copy_indirect_symbol (struct bfd_link_info *info,
648 struct elf_link_hash_entry *dir,
649 struct elf_link_hash_entry *ind)
651 struct riscv_elf_link_hash_entry *edir, *eind;
653 edir = (struct riscv_elf_link_hash_entry *) dir;
654 eind = (struct riscv_elf_link_hash_entry *) ind;
656 if (ind->root.type == bfd_link_hash_indirect
657 && dir->got.refcount <= 0)
659 edir->tls_type = eind->tls_type;
660 eind->tls_type = GOT_UNKNOWN;
662 _bfd_elf_link_hash_copy_indirect (info, dir, ind);
665 static bool
666 riscv_elf_record_tls_type (bfd *abfd, struct elf_link_hash_entry *h,
667 unsigned long symndx, char tls_type)
669 char *new_tls_type = &_bfd_riscv_elf_tls_type (abfd, h, symndx);
671 *new_tls_type |= tls_type;
672 if ((*new_tls_type & GOT_NORMAL) && (*new_tls_type & ~GOT_NORMAL))
674 (*_bfd_error_handler)
675 (_("%pB: `%s' accessed both as normal and thread local symbol"),
676 abfd, h ? h->root.root.string : "<local>");
677 return false;
679 return true;
682 static bool
683 riscv_elf_record_got_reference (bfd *abfd, struct bfd_link_info *info,
684 struct elf_link_hash_entry *h, long symndx)
686 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
687 Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
689 if (htab->elf.sgot == NULL)
691 if (!riscv_elf_create_got_section (htab->elf.dynobj, info))
692 return false;
695 if (h != NULL)
697 h->got.refcount += 1;
698 return true;
701 /* This is a global offset table entry for a local symbol. */
702 if (elf_local_got_refcounts (abfd) == NULL)
704 bfd_size_type size = symtab_hdr->sh_info * (sizeof (bfd_vma) + 1);
705 if (!(elf_local_got_refcounts (abfd) = bfd_zalloc (abfd, size)))
706 return false;
707 _bfd_riscv_elf_local_got_tls_type (abfd)
708 = (char *) (elf_local_got_refcounts (abfd) + symtab_hdr->sh_info);
710 elf_local_got_refcounts (abfd) [symndx] += 1;
712 return true;
715 static bool
716 bad_static_reloc (bfd *abfd, unsigned r_type, struct elf_link_hash_entry *h)
718 reloc_howto_type * r = riscv_elf_rtype_to_howto (abfd, r_type);
720 /* We propably can improve the information to tell users that they
721 should be recompile the code with -fPIC or -fPIE, just like what
722 x86 does. */
723 (*_bfd_error_handler)
724 (_("%pB: relocation %s against `%s' can not be used when making a shared "
725 "object; recompile with -fPIC"),
726 abfd, r ? r->name : _("<unknown>"),
727 h != NULL ? h->root.root.string : "a local symbol");
728 bfd_set_error (bfd_error_bad_value);
729 return false;
732 /* Look through the relocs for a section during the first phase, and
733 allocate space in the global offset table or procedure linkage
734 table. */
736 static bool
737 riscv_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
738 asection *sec, const Elf_Internal_Rela *relocs)
740 struct riscv_elf_link_hash_table *htab;
741 Elf_Internal_Shdr *symtab_hdr;
742 struct elf_link_hash_entry **sym_hashes;
743 const Elf_Internal_Rela *rel;
744 asection *sreloc = NULL;
746 if (bfd_link_relocatable (info))
747 return true;
749 htab = riscv_elf_hash_table (info);
750 symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
751 sym_hashes = elf_sym_hashes (abfd);
753 if (htab->elf.dynobj == NULL)
754 htab->elf.dynobj = abfd;
756 for (rel = relocs; rel < relocs + sec->reloc_count; rel++)
758 unsigned int r_type;
759 unsigned int r_symndx;
760 struct elf_link_hash_entry *h;
761 bool is_abs_symbol = false;
763 r_symndx = ELFNN_R_SYM (rel->r_info);
764 r_type = ELFNN_R_TYPE (rel->r_info);
766 if (r_symndx >= NUM_SHDR_ENTRIES (symtab_hdr))
768 (*_bfd_error_handler) (_("%pB: bad symbol index: %d"),
769 abfd, r_symndx);
770 return false;
773 if (r_symndx < symtab_hdr->sh_info)
775 /* A local symbol. */
776 Elf_Internal_Sym *isym = bfd_sym_from_r_symndx (&htab->elf.sym_cache,
777 abfd, r_symndx);
778 if (isym == NULL)
779 return false;
781 is_abs_symbol = isym->st_shndx == SHN_ABS ? true : false;
783 /* Check relocation against local STT_GNU_IFUNC symbol. */
784 if (ELF_ST_TYPE (isym->st_info) == STT_GNU_IFUNC)
786 h = riscv_elf_get_local_sym_hash (htab, abfd, rel, true);
787 if (h == NULL)
788 return false;
790 /* Fake STT_GNU_IFUNC global symbol. */
791 h->root.root.string = bfd_elf_sym_name (abfd, symtab_hdr,
792 isym, NULL);
793 h->type = STT_GNU_IFUNC;
794 h->def_regular = 1;
795 h->ref_regular = 1;
796 h->forced_local = 1;
797 h->root.type = bfd_link_hash_defined;
799 else
800 h = NULL;
802 else
804 h = sym_hashes[r_symndx - symtab_hdr->sh_info];
805 while (h->root.type == bfd_link_hash_indirect
806 || h->root.type == bfd_link_hash_warning)
807 h = (struct elf_link_hash_entry *) h->root.u.i.link;
809 is_abs_symbol = bfd_is_abs_symbol (&h->root) ? true : false;
812 if (h != NULL)
814 switch (r_type)
816 case R_RISCV_32:
817 case R_RISCV_64:
818 case R_RISCV_CALL:
819 case R_RISCV_CALL_PLT:
820 case R_RISCV_HI20:
821 case R_RISCV_GOT_HI20:
822 case R_RISCV_PCREL_HI20:
823 /* Create the ifunc sections, iplt and ipltgot, for static
824 executables. */
825 if (h->type == STT_GNU_IFUNC
826 && !_bfd_elf_create_ifunc_sections (htab->elf.dynobj, info))
827 return false;
828 break;
830 default:
831 break;
834 /* It is referenced by a non-shared object. */
835 h->ref_regular = 1;
838 switch (r_type)
840 case R_RISCV_TLS_GD_HI20:
841 if (!riscv_elf_record_got_reference (abfd, info, h, r_symndx)
842 || !riscv_elf_record_tls_type (abfd, h, r_symndx, GOT_TLS_GD))
843 return false;
844 break;
846 case R_RISCV_TLS_GOT_HI20:
847 if (bfd_link_dll (info))
848 info->flags |= DF_STATIC_TLS;
849 if (!riscv_elf_record_got_reference (abfd, info, h, r_symndx)
850 || !riscv_elf_record_tls_type (abfd, h, r_symndx, GOT_TLS_IE))
851 return false;
852 break;
854 case R_RISCV_GOT_HI20:
855 if (!riscv_elf_record_got_reference (abfd, info, h, r_symndx)
856 || !riscv_elf_record_tls_type (abfd, h, r_symndx, GOT_NORMAL))
857 return false;
858 break;
860 case R_RISCV_TLSDESC_HI20:
861 if (!riscv_elf_record_got_reference (abfd, info, h, r_symndx)
862 || !riscv_elf_record_tls_type (abfd, h, r_symndx, GOT_TLSDESC))
863 return false;
864 break;
866 case R_RISCV_CALL:
867 case R_RISCV_CALL_PLT:
868 /* These symbol requires a procedure linkage table entry.
869 We actually build the entry in adjust_dynamic_symbol,
870 because these might be a case of linking PIC code without
871 linking in any dynamic objects, in which case we don't
872 need to generate a procedure linkage table after all. */
874 /* If it is a local symbol, then we resolve it directly
875 without creating a PLT entry. */
876 if (h == NULL)
877 continue;
879 h->needs_plt = 1;
880 h->plt.refcount += 1;
881 break;
883 case R_RISCV_PCREL_HI20:
884 if (h != NULL
885 && h->type == STT_GNU_IFUNC)
887 h->non_got_ref = 1;
888 h->pointer_equality_needed = 1;
890 /* We don't use the PCREL_HI20 in the data section,
891 so we always need the plt when it refers to
892 ifunc symbol. */
893 h->plt.refcount += 1;
896 /* The non-preemptible absolute symbol shouldn't be referneced with
897 pc-relative relocation when generating shared object. However,
898 PCREL_HI20/LO12 relocs are always bind locally when generating
899 shared object, so all absolute symbol referenced need to be
900 disallowed, except they are defined in linker script.
902 Maybe we should add this check for all pc-relative relocations,
903 please see pr28789 and pr25749 for details. */
904 if (bfd_link_pic (info)
905 /* (h == NULL || SYMBOL_REFERENCES_LOCAL (info, h)) */
906 && is_abs_symbol)
908 if (h != NULL && (h)->root.ldscript_def)
909 /* Disallow the absolute symbol defined in linker script here
910 will cause the glibc-linux toolchain build failed, so regard
911 them as pc-relative symbols, just like what x86 did. */
913 else
915 const char *name;
916 if (h->root.root.string)
917 name = h->root.root.string;
918 else
920 Elf_Internal_Sym *sym;
921 sym = bfd_sym_from_r_symndx (&htab->elf.sym_cache, abfd,
922 r_symndx);
923 name = bfd_elf_sym_name (abfd, symtab_hdr, sym, NULL);
926 reloc_howto_type *r_t =
927 riscv_elf_rtype_to_howto (abfd, r_type);
928 _bfd_error_handler
929 (_("%pB: relocation %s against absolute symbol `%s' can "
930 "not be used when making a shared object"),
931 abfd, r_t ? r_t->name : _("<unknown>"), name);
932 bfd_set_error (bfd_error_bad_value);
933 return false;
936 /* Fall through. */
938 case R_RISCV_JAL:
939 case R_RISCV_BRANCH:
940 case R_RISCV_RVC_BRANCH:
941 case R_RISCV_RVC_JUMP:
942 /* In shared libraries and pie, these relocs are known
943 to bind locally. */
944 if (bfd_link_pic (info))
945 break;
946 goto static_reloc;
948 case R_RISCV_TPREL_HI20:
949 /* This is not allowed in the pic, but okay in pie. */
950 if (!bfd_link_executable (info))
951 return bad_static_reloc (abfd, r_type, h);
952 if (h != NULL)
953 riscv_elf_record_tls_type (abfd, h, r_symndx, GOT_TLS_LE);
954 break;
956 case R_RISCV_HI20:
957 if (bfd_link_pic (info))
958 return bad_static_reloc (abfd, r_type, h);
959 goto static_reloc;
961 case R_RISCV_32:
962 if (ARCH_SIZE > 32
963 && bfd_link_pic (info)
964 && (sec->flags & SEC_ALLOC) != 0)
966 if (is_abs_symbol)
967 break;
969 reloc_howto_type *r_t = riscv_elf_rtype_to_howto (abfd, r_type);
970 _bfd_error_handler
971 (_("%pB: relocation %s against non-absolute symbol `%s' can "
972 "not be used in RVNN when making a shared object"),
973 abfd, r_t ? r_t->name : _("<unknown>"),
974 h != NULL ? h->root.root.string : "a local symbol");
975 bfd_set_error (bfd_error_bad_value);
976 return false;
978 goto static_reloc;
980 case R_RISCV_COPY:
981 case R_RISCV_JUMP_SLOT:
982 case R_RISCV_RELATIVE:
983 case R_RISCV_64:
984 /* Fall through. */
986 static_reloc:
988 if (h != NULL
989 && (!bfd_link_pic (info)
990 || h->type == STT_GNU_IFUNC))
992 /* This reloc might not bind locally. */
993 h->non_got_ref = 1;
994 h->pointer_equality_needed = 1;
996 if (!h->def_regular
997 || (sec->flags & (SEC_CODE | SEC_READONLY)) != 0)
999 /* We may need a .plt entry if the symbol is a function
1000 defined in a shared lib or is a function referenced
1001 from the code or read-only section. */
1002 h->plt.refcount += 1;
1006 reloc_howto_type *r = riscv_elf_rtype_to_howto (abfd, r_type);
1007 if (RISCV_NEED_DYNAMIC_RELOC (r->pc_relative, info, h, sec))
1009 struct elf_dyn_relocs *p;
1010 struct elf_dyn_relocs **head;
1012 /* When creating a shared object, we must copy these
1013 relocs into the output file. We create a reloc
1014 section in dynobj and make room for the reloc. */
1015 if (sreloc == NULL)
1017 sreloc = _bfd_elf_make_dynamic_reloc_section
1018 (sec, htab->elf.dynobj, RISCV_ELF_LOG_WORD_BYTES,
1019 abfd, /*rela?*/ true);
1021 if (sreloc == NULL)
1022 return false;
1025 /* If this is a global symbol, we count the number of
1026 relocations we need for this symbol. */
1027 if (h != NULL)
1028 head = &h->dyn_relocs;
1029 else
1031 /* Track dynamic relocs needed for local syms too.
1032 We really need local syms available to do this
1033 easily. Oh well. */
1035 asection *s;
1036 void *vpp;
1037 Elf_Internal_Sym *isym;
1039 isym = bfd_sym_from_r_symndx (&htab->elf.sym_cache,
1040 abfd, r_symndx);
1041 if (isym == NULL)
1042 return false;
1044 s = bfd_section_from_elf_index (abfd, isym->st_shndx);
1045 if (s == NULL)
1046 s = sec;
1048 vpp = &elf_section_data (s)->local_dynrel;
1049 head = (struct elf_dyn_relocs **) vpp;
1052 p = *head;
1053 if (p == NULL || p->sec != sec)
1055 size_t amt = sizeof *p;
1056 p = ((struct elf_dyn_relocs *)
1057 bfd_alloc (htab->elf.dynobj, amt));
1058 if (p == NULL)
1059 return false;
1060 p->next = *head;
1061 *head = p;
1062 p->sec = sec;
1063 p->count = 0;
1064 p->pc_count = 0;
1067 p->count += 1;
1068 p->pc_count += r == NULL ? 0 : r->pc_relative;
1071 break;
1073 default:
1074 break;
1078 return true;
1081 /* Adjust a symbol defined by a dynamic object and referenced by a
1082 regular object. The current definition is in some section of the
1083 dynamic object, but we're not including those sections. We have to
1084 change the definition to something the rest of the link can
1085 understand. */
1087 static bool
1088 riscv_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
1089 struct elf_link_hash_entry *h)
1091 struct riscv_elf_link_hash_table *htab;
1092 struct riscv_elf_link_hash_entry * eh;
1093 bfd *dynobj;
1094 asection *s, *srel;
1096 htab = riscv_elf_hash_table (info);
1097 BFD_ASSERT (htab != NULL);
1099 dynobj = htab->elf.dynobj;
1101 /* Make sure we know what is going on here. */
1102 BFD_ASSERT (dynobj != NULL
1103 && (h->needs_plt
1104 || h->type == STT_GNU_IFUNC
1105 || h->is_weakalias
1106 || (h->def_dynamic
1107 && h->ref_regular
1108 && !h->def_regular)));
1110 /* If this is a function, put it in the procedure linkage table. We
1111 will fill in the contents of the procedure linkage table later
1112 (although we could actually do it here). */
1113 if (h->type == STT_FUNC || h->type == STT_GNU_IFUNC || h->needs_plt)
1115 if (h->plt.refcount <= 0
1116 || (h->type != STT_GNU_IFUNC
1117 && (SYMBOL_CALLS_LOCAL (info, h)
1118 || (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1119 && h->root.type == bfd_link_hash_undefweak))))
1121 /* This case can occur if we saw a R_RISCV_CALL_PLT reloc in an
1122 input file, but the symbol was never referred to by a dynamic
1123 object, or if all references were garbage collected. In such
1124 a case, we don't actually need to build a PLT entry. */
1125 h->plt.offset = (bfd_vma) -1;
1126 h->needs_plt = 0;
1129 return true;
1131 else
1132 h->plt.offset = (bfd_vma) -1;
1134 /* If this is a weak symbol, and there is a real definition, the
1135 processor independent code will have arranged for us to see the
1136 real definition first, and we can just use the same value. */
1137 if (h->is_weakalias)
1139 struct elf_link_hash_entry *def = weakdef (h);
1140 BFD_ASSERT (def->root.type == bfd_link_hash_defined);
1141 h->root.u.def.section = def->root.u.def.section;
1142 h->root.u.def.value = def->root.u.def.value;
1143 return true;
1146 /* This is a reference to a symbol defined by a dynamic object which
1147 is not a function. */
1149 /* If we are creating a shared library, we must presume that the
1150 only references to the symbol are via the global offset table.
1151 For such cases we need not do anything here; the relocations will
1152 be handled correctly by relocate_section. */
1153 if (bfd_link_pic (info))
1154 return true;
1156 /* If there are no references to this symbol that do not use the
1157 GOT, we don't need to generate a copy reloc. */
1158 if (!h->non_got_ref)
1159 return true;
1161 /* If -z nocopyreloc was given, we won't generate them either. */
1162 if (info->nocopyreloc)
1164 h->non_got_ref = 0;
1165 return true;
1168 /* If we don't find any dynamic relocs in read-only sections, then
1169 we'll be keeping the dynamic relocs and avoiding the copy reloc. */
1170 if (!_bfd_elf_readonly_dynrelocs (h))
1172 h->non_got_ref = 0;
1173 return true;
1176 /* We must allocate the symbol in our .dynbss section, which will
1177 become part of the .bss section of the executable. There will be
1178 an entry for this symbol in the .dynsym section. The dynamic
1179 object will contain position independent code, so all references
1180 from the dynamic object to this symbol will go through the global
1181 offset table. The dynamic linker will use the .dynsym entry to
1182 determine the address it must put in the global offset table, so
1183 both the dynamic object and the regular object will refer to the
1184 same memory location for the variable. */
1186 /* We must generate a R_RISCV_COPY reloc to tell the dynamic linker
1187 to copy the initial value out of the dynamic object and into the
1188 runtime process image. We need to remember the offset into the
1189 .rel.bss section we are going to use. */
1190 eh = (struct riscv_elf_link_hash_entry *) h;
1191 if (eh->tls_type & ~GOT_NORMAL)
1193 s = htab->sdyntdata;
1194 srel = htab->elf.srelbss;
1196 else if ((h->root.u.def.section->flags & SEC_READONLY) != 0)
1198 s = htab->elf.sdynrelro;
1199 srel = htab->elf.sreldynrelro;
1201 else
1203 s = htab->elf.sdynbss;
1204 srel = htab->elf.srelbss;
1206 if ((h->root.u.def.section->flags & SEC_ALLOC) != 0 && h->size != 0)
1208 srel->size += sizeof (ElfNN_External_Rela);
1209 h->needs_copy = 1;
1212 return _bfd_elf_adjust_dynamic_copy (info, h, s);
1215 /* Allocate space in .plt, .got and associated reloc sections for
1216 dynamic relocs. */
1218 static bool
1219 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
1221 struct bfd_link_info *info;
1222 struct riscv_elf_link_hash_table *htab;
1223 struct elf_dyn_relocs *p;
1225 if (h->root.type == bfd_link_hash_indirect)
1226 return true;
1228 info = (struct bfd_link_info *) inf;
1229 htab = riscv_elf_hash_table (info);
1230 BFD_ASSERT (htab != NULL);
1232 /* When we are generating pde, make sure gp symbol is output as a
1233 dynamic symbol. Then ld.so can set the gp register earlier, before
1234 resolving the ifunc. */
1235 if (!bfd_link_pic (info)
1236 && htab->elf.dynamic_sections_created
1237 && strcmp (h->root.root.string, RISCV_GP_SYMBOL) == 0
1238 && !bfd_elf_link_record_dynamic_symbol (info, h))
1239 return false;
1241 /* Since STT_GNU_IFUNC symbols must go through PLT, we handle them
1242 in the allocate_ifunc_dynrelocs and allocate_local_ifunc_dynrelocs,
1243 if they are defined and referenced in a non-shared object. */
1244 if (h->type == STT_GNU_IFUNC
1245 && h->def_regular)
1246 return true;
1247 else if (htab->elf.dynamic_sections_created
1248 && h->plt.refcount > 0)
1250 /* Make sure this symbol is output as a dynamic symbol.
1251 Undefined weak syms won't yet be marked as dynamic. */
1252 if (h->dynindx == -1
1253 && !h->forced_local)
1255 if (! bfd_elf_link_record_dynamic_symbol (info, h))
1256 return false;
1259 if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (1, bfd_link_pic (info), h))
1261 asection *s = htab->elf.splt;
1263 if (s->size == 0)
1264 s->size = PLT_HEADER_SIZE;
1266 h->plt.offset = s->size;
1268 /* Make room for this entry. */
1269 s->size += PLT_ENTRY_SIZE;
1271 /* We also need to make an entry in the .got.plt section. */
1272 htab->elf.sgotplt->size += GOT_ENTRY_SIZE;
1274 /* We also need to make an entry in the .rela.plt section. */
1275 htab->elf.srelplt->size += sizeof (ElfNN_External_Rela);
1277 /* If this symbol is not defined in a regular file, and we are
1278 not generating a shared library, then set the symbol to this
1279 location in the .plt. This is required to make function
1280 pointers compare as equal between the normal executable and
1281 the shared library. */
1282 if (! bfd_link_pic (info)
1283 && !h->def_regular)
1285 h->root.u.def.section = s;
1286 h->root.u.def.value = h->plt.offset;
1289 /* If the symbol has STO_RISCV_VARIANT_CC flag, then raise the
1290 variant_cc flag of riscv_elf_link_hash_table. */
1291 if (h->other & STO_RISCV_VARIANT_CC)
1292 htab->variant_cc = 1;
1294 else
1296 h->plt.offset = (bfd_vma) -1;
1297 h->needs_plt = 0;
1300 else
1302 h->plt.offset = (bfd_vma) -1;
1303 h->needs_plt = 0;
1306 if (h->got.refcount > 0)
1308 asection *s;
1309 bool dyn;
1310 int tls_type = riscv_elf_hash_entry (h)->tls_type;
1312 /* Make sure this symbol is output as a dynamic symbol.
1313 Undefined weak syms won't yet be marked as dynamic. */
1314 if (h->dynindx == -1
1315 && !h->forced_local)
1317 if (! bfd_elf_link_record_dynamic_symbol (info, h))
1318 return false;
1321 s = htab->elf.sgot;
1322 h->got.offset = s->size;
1323 dyn = htab->elf.dynamic_sections_created;
1324 if (tls_type & (GOT_TLS_GD | GOT_TLS_IE | GOT_TLSDESC))
1326 int indx = 0;
1327 bool need_reloc = false;
1328 RISCV_TLS_GD_IE_NEED_DYN_RELOC(info, dyn, h, indx, need_reloc);
1330 /* TLS_GD needs two dynamic relocs and two GOT slots. */
1331 if (tls_type & GOT_TLS_GD)
1333 s->size += TLS_GD_GOT_ENTRY_SIZE;
1334 if (need_reloc)
1335 htab->elf.srelgot->size += 2 * sizeof (ElfNN_External_Rela);
1338 /* TLS_IE needs one dynamic reloc and one GOT slot. */
1339 if (tls_type & GOT_TLS_IE)
1341 s->size += TLS_IE_GOT_ENTRY_SIZE;
1342 if (need_reloc)
1343 htab->elf.srelgot->size += sizeof (ElfNN_External_Rela);
1346 /* TLSDESC needs one dynamic reloc and two GOT slots. */
1347 if (tls_type & GOT_TLSDESC)
1349 s->size += TLSDESC_GOT_ENTRY_SIZE;
1350 /* TLSDESC always use dynamic relocs. */
1351 htab->elf.srelgot->size += sizeof (ElfNN_External_Rela);
1354 else
1356 s->size += GOT_ENTRY_SIZE;
1357 if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, bfd_link_pic (info), h)
1358 && ! UNDEFWEAK_NO_DYNAMIC_RELOC (info, h))
1359 htab->elf.srelgot->size += sizeof (ElfNN_External_Rela);
1362 else
1363 h->got.offset = (bfd_vma) -1;
1365 if (h->dyn_relocs == NULL)
1366 return true;
1368 /* In the shared -Bsymbolic case, discard space allocated for
1369 dynamic pc-relative relocs against symbols which turn out to be
1370 defined in regular objects. For the normal shared case, discard
1371 space for pc-relative relocs that have become local due to symbol
1372 visibility changes. */
1374 if (bfd_link_pic (info))
1376 if (SYMBOL_CALLS_LOCAL (info, h))
1378 struct elf_dyn_relocs **pp;
1380 for (pp = &h->dyn_relocs; (p = *pp) != NULL; )
1382 p->count -= p->pc_count;
1383 p->pc_count = 0;
1384 if (p->count == 0)
1385 *pp = p->next;
1386 else
1387 pp = &p->next;
1391 /* Also discard relocs on undefined weak syms with non-default
1392 visibility. */
1393 if (h->dyn_relocs != NULL
1394 && h->root.type == bfd_link_hash_undefweak)
1396 if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1397 || UNDEFWEAK_NO_DYNAMIC_RELOC (info, h))
1398 h->dyn_relocs = NULL;
1400 /* Make sure undefined weak symbols are output as a dynamic
1401 symbol in PIEs. */
1402 else if (h->dynindx == -1
1403 && !h->forced_local)
1405 if (! bfd_elf_link_record_dynamic_symbol (info, h))
1406 return false;
1410 else
1412 /* For the non-shared case, discard space for relocs against
1413 symbols which turn out to need copy relocs or are not
1414 dynamic. */
1416 if (!h->non_got_ref
1417 && ((h->def_dynamic
1418 && !h->def_regular)
1419 || (htab->elf.dynamic_sections_created
1420 && (h->root.type == bfd_link_hash_undefweak
1421 || h->root.type == bfd_link_hash_undefined))))
1423 /* Make sure this symbol is output as a dynamic symbol.
1424 Undefined weak syms won't yet be marked as dynamic. */
1425 if (h->dynindx == -1
1426 && !h->forced_local)
1428 if (! bfd_elf_link_record_dynamic_symbol (info, h))
1429 return false;
1432 /* If that succeeded, we know we'll be keeping all the
1433 relocs. */
1434 if (h->dynindx != -1)
1435 goto keep;
1438 h->dyn_relocs = NULL;
1440 keep: ;
1443 /* Finally, allocate space. */
1444 for (p = h->dyn_relocs; p != NULL; p = p->next)
1446 asection *sreloc = elf_section_data (p->sec)->sreloc;
1447 sreloc->size += p->count * sizeof (ElfNN_External_Rela);
1450 return true;
1453 /* Allocate space in .plt, .got and associated reloc sections for
1454 ifunc dynamic relocs. */
1456 static bool
1457 allocate_ifunc_dynrelocs (struct elf_link_hash_entry *h,
1458 void *inf)
1460 struct bfd_link_info *info;
1462 if (h->root.type == bfd_link_hash_indirect)
1463 return true;
1465 if (h->root.type == bfd_link_hash_warning)
1466 h = (struct elf_link_hash_entry *) h->root.u.i.link;
1468 info = (struct bfd_link_info *) inf;
1470 /* Since STT_GNU_IFUNC symbol must go through PLT, we handle it
1471 here if it is defined and referenced in a non-shared object. */
1472 if (h->type == STT_GNU_IFUNC
1473 && h->def_regular)
1474 return _bfd_elf_allocate_ifunc_dyn_relocs (info, h,
1475 &h->dyn_relocs,
1476 PLT_ENTRY_SIZE,
1477 PLT_HEADER_SIZE,
1478 GOT_ENTRY_SIZE,
1479 true);
1480 return true;
1483 /* Allocate space in .plt, .got and associated reloc sections for
1484 local ifunc dynamic relocs. */
1486 static int
1487 allocate_local_ifunc_dynrelocs (void **slot, void *inf)
1489 struct elf_link_hash_entry *h
1490 = (struct elf_link_hash_entry *) *slot;
1492 if (h->type != STT_GNU_IFUNC
1493 || !h->def_regular
1494 || !h->ref_regular
1495 || !h->forced_local
1496 || h->root.type != bfd_link_hash_defined)
1497 abort ();
1499 return allocate_ifunc_dynrelocs (h, inf);
1502 static bool
1503 riscv_elf_size_dynamic_sections (bfd *output_bfd, struct bfd_link_info *info)
1505 struct riscv_elf_link_hash_table *htab;
1506 bfd *dynobj;
1507 asection *s;
1508 bfd *ibfd;
1510 htab = riscv_elf_hash_table (info);
1511 BFD_ASSERT (htab != NULL);
1512 dynobj = htab->elf.dynobj;
1513 BFD_ASSERT (dynobj != NULL);
1515 if (elf_hash_table (info)->dynamic_sections_created)
1517 /* Set the contents of the .interp section to the interpreter. */
1518 if (bfd_link_executable (info) && !info->nointerp)
1520 s = bfd_get_linker_section (dynobj, ".interp");
1521 BFD_ASSERT (s != NULL);
1522 s->size = strlen (ELFNN_DYNAMIC_INTERPRETER) + 1;
1523 s->contents = (unsigned char *) ELFNN_DYNAMIC_INTERPRETER;
1527 /* Set up .got offsets for local syms, and space for local dynamic
1528 relocs. */
1529 for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
1531 bfd_signed_vma *local_got;
1532 bfd_signed_vma *end_local_got;
1533 char *local_tls_type;
1534 bfd_size_type locsymcount;
1535 Elf_Internal_Shdr *symtab_hdr;
1536 asection *srel;
1538 if (! is_riscv_elf (ibfd))
1539 continue;
1541 for (s = ibfd->sections; s != NULL; s = s->next)
1543 struct elf_dyn_relocs *p;
1545 for (p = elf_section_data (s)->local_dynrel; p != NULL; p = p->next)
1547 if (!bfd_is_abs_section (p->sec)
1548 && bfd_is_abs_section (p->sec->output_section))
1550 /* Input section has been discarded, either because
1551 it is a copy of a linkonce section or due to
1552 linker script /DISCARD/, so we'll be discarding
1553 the relocs too. */
1555 else if (p->count != 0)
1557 srel = elf_section_data (p->sec)->sreloc;
1558 srel->size += p->count * sizeof (ElfNN_External_Rela);
1559 if ((p->sec->output_section->flags & SEC_READONLY) != 0)
1560 info->flags |= DF_TEXTREL;
1565 local_got = elf_local_got_refcounts (ibfd);
1566 if (!local_got)
1567 continue;
1569 symtab_hdr = &elf_symtab_hdr (ibfd);
1570 locsymcount = symtab_hdr->sh_info;
1571 end_local_got = local_got + locsymcount;
1572 local_tls_type = _bfd_riscv_elf_local_got_tls_type (ibfd);
1573 s = htab->elf.sgot;
1574 srel = htab->elf.srelgot;
1575 for (; local_got < end_local_got; ++local_got, ++local_tls_type)
1577 if (*local_got > 0)
1579 *local_got = s->size;
1580 if (*local_tls_type & (GOT_TLS_GD | GOT_TLS_IE | GOT_TLSDESC))
1582 if (*local_tls_type & GOT_TLS_GD)
1584 s->size += TLS_GD_GOT_ENTRY_SIZE;
1585 if (bfd_link_dll (info))
1586 srel->size += sizeof (ElfNN_External_Rela);
1588 if (*local_tls_type & GOT_TLS_IE)
1590 s->size += TLS_IE_GOT_ENTRY_SIZE;
1591 if (bfd_link_dll (info))
1592 srel->size += sizeof (ElfNN_External_Rela);
1594 if (*local_tls_type & GOT_TLSDESC)
1596 s->size += TLSDESC_GOT_ENTRY_SIZE;
1597 srel->size += sizeof (ElfNN_External_Rela);
1600 else
1602 s->size += GOT_ENTRY_SIZE;
1603 if (bfd_link_pic (info))
1604 srel->size += sizeof (ElfNN_External_Rela);
1607 else
1608 *local_got = (bfd_vma) -1;
1612 /* Allocate .plt and .got entries and space dynamic relocs for
1613 global symbols. */
1614 elf_link_hash_traverse (&htab->elf, allocate_dynrelocs, info);
1616 /* Allocate .plt and .got entries and space dynamic relocs for
1617 global ifunc symbols. */
1618 elf_link_hash_traverse (&htab->elf, allocate_ifunc_dynrelocs, info);
1620 /* Allocate .plt and .got entries and space dynamic relocs for
1621 local ifunc symbols. */
1622 htab_traverse (htab->loc_hash_table, allocate_local_ifunc_dynrelocs, info);
1624 /* Used to resolve the dynamic relocs overwite problems when
1625 generating static executable. */
1626 if (htab->elf.irelplt)
1627 htab->last_iplt_index = htab->elf.irelplt->reloc_count - 1;
1629 if (htab->elf.sgotplt)
1631 struct elf_link_hash_entry *got;
1632 got = elf_link_hash_lookup (elf_hash_table (info),
1633 "_GLOBAL_OFFSET_TABLE_",
1634 false, false, false);
1636 /* Don't allocate .got.plt section if there are no GOT nor PLT
1637 entries and there is no refeence to _GLOBAL_OFFSET_TABLE_. */
1638 if ((got == NULL
1639 || !got->ref_regular_nonweak)
1640 && (htab->elf.sgotplt->size == GOTPLT_HEADER_SIZE)
1641 && (htab->elf.splt == NULL
1642 || htab->elf.splt->size == 0)
1643 && (htab->elf.sgot == NULL
1644 || (htab->elf.sgot->size
1645 == get_elf_backend_data (output_bfd)->got_header_size)))
1646 htab->elf.sgotplt->size = 0;
1649 /* The check_relocs and adjust_dynamic_symbol entry points have
1650 determined the sizes of the various dynamic sections. Allocate
1651 memory for them. */
1652 for (s = dynobj->sections; s != NULL; s = s->next)
1654 if ((s->flags & SEC_LINKER_CREATED) == 0)
1655 continue;
1657 if (s == htab->elf.splt
1658 || s == htab->elf.sgot
1659 || s == htab->elf.sgotplt
1660 || s == htab->elf.iplt
1661 || s == htab->elf.igotplt
1662 || s == htab->elf.sdynbss
1663 || s == htab->elf.sdynrelro
1664 || s == htab->sdyntdata)
1666 /* Strip this section if we don't need it; see the
1667 comment below. */
1669 else if (startswith (s->name, ".rela"))
1671 if (s->size != 0)
1673 /* We use the reloc_count field as a counter if we need
1674 to copy relocs into the output file. */
1675 s->reloc_count = 0;
1678 else
1680 /* It's not one of our sections. */
1681 continue;
1684 if (s->size == 0)
1686 /* If we don't need this section, strip it from the
1687 output file. This is mostly to handle .rela.bss and
1688 .rela.plt. We must create both sections in
1689 create_dynamic_sections, because they must be created
1690 before the linker maps input sections to output
1691 sections. The linker does that before
1692 adjust_dynamic_symbol is called, and it is that
1693 function which decides whether anything needs to go
1694 into these sections. */
1695 s->flags |= SEC_EXCLUDE;
1696 continue;
1699 if ((s->flags & SEC_HAS_CONTENTS) == 0)
1700 continue;
1702 /* Allocate memory for the section contents. Zero the memory
1703 for the benefit of .rela.plt, which has 4 unused entries
1704 at the beginning, and we don't want garbage. */
1705 s->contents = (bfd_byte *) bfd_zalloc (dynobj, s->size);
1706 if (s->contents == NULL)
1707 return false;
1710 /* Add dynamic entries. */
1711 if (elf_hash_table (info)->dynamic_sections_created)
1713 if (!_bfd_elf_add_dynamic_tags (output_bfd, info, true))
1714 return false;
1716 if (htab->variant_cc
1717 && !_bfd_elf_add_dynamic_entry (info, DT_RISCV_VARIANT_CC, 0))
1718 return false;
1721 return true;
1724 #define TP_OFFSET 0
1725 #define DTP_OFFSET 0x800
1727 /* Return the relocation value for a TLS dtp-relative reloc. */
1729 static bfd_vma
1730 dtpoff (struct bfd_link_info *info, bfd_vma address)
1732 /* If tls_sec is NULL, we should have signalled an error already. */
1733 if (elf_hash_table (info)->tls_sec == NULL)
1734 return 0;
1735 return address - elf_hash_table (info)->tls_sec->vma - DTP_OFFSET;
1738 /* Return the relocation value for a static TLS tp-relative relocation. */
1740 static bfd_vma
1741 tpoff (struct bfd_link_info *info, bfd_vma address)
1743 /* If tls_sec is NULL, we should have signalled an error already. */
1744 if (elf_hash_table (info)->tls_sec == NULL)
1745 return 0;
1746 return address - elf_hash_table (info)->tls_sec->vma - TP_OFFSET;
1749 /* Return the relocation value for a static TLSDESC relocation. */
1751 static bfd_vma
1752 tlsdescoff (struct bfd_link_info *info, bfd_vma address)
1754 /* If tls_sec is NULL, we should have signalled an error already. */
1755 if (elf_hash_table (info)->tls_sec == NULL)
1756 return 0;
1757 return address - elf_hash_table (info)->tls_sec->vma;
1760 /* Return the global pointer's value, or 0 if it is not in use. */
1762 static bfd_vma
1763 riscv_global_pointer_value (struct bfd_link_info *info)
1765 struct bfd_link_hash_entry *h;
1767 h = bfd_link_hash_lookup (info->hash, RISCV_GP_SYMBOL, false, false, true);
1768 if (h == NULL || h->type != bfd_link_hash_defined)
1769 return 0;
1771 return h->u.def.value + sec_addr (h->u.def.section);
1774 /* Emplace a static relocation. */
1776 static bfd_reloc_status_type
1777 perform_relocation (const reloc_howto_type *howto,
1778 const Elf_Internal_Rela *rel,
1779 bfd_vma value,
1780 asection *input_section,
1781 bfd *input_bfd,
1782 bfd_byte *contents)
1784 if (howto->pc_relative)
1785 value -= sec_addr (input_section) + rel->r_offset;
1787 /* PR31179, ignore the non-zero addend of R_RISCV_SUB_ULEB128. */
1788 if (ELFNN_R_TYPE (rel->r_info) != R_RISCV_SUB_ULEB128)
1789 value += rel->r_addend;
1791 switch (ELFNN_R_TYPE (rel->r_info))
1793 case R_RISCV_HI20:
1794 case R_RISCV_TPREL_HI20:
1795 case R_RISCV_PCREL_HI20:
1796 case R_RISCV_GOT_HI20:
1797 case R_RISCV_TLS_GOT_HI20:
1798 case R_RISCV_TLS_GD_HI20:
1799 case R_RISCV_TLSDESC_HI20:
1800 if (ARCH_SIZE > 32 && !VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (value)))
1801 return bfd_reloc_overflow;
1802 value = ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value));
1803 break;
1805 case R_RISCV_LO12_I:
1806 case R_RISCV_GPREL_I:
1807 case R_RISCV_TPREL_LO12_I:
1808 case R_RISCV_TPREL_I:
1809 case R_RISCV_PCREL_LO12_I:
1810 case R_RISCV_TLSDESC_LOAD_LO12:
1811 case R_RISCV_TLSDESC_ADD_LO12:
1812 value = ENCODE_ITYPE_IMM (value);
1813 break;
1815 case R_RISCV_LO12_S:
1816 case R_RISCV_GPREL_S:
1817 case R_RISCV_TPREL_LO12_S:
1818 case R_RISCV_TPREL_S:
1819 case R_RISCV_PCREL_LO12_S:
1820 value = ENCODE_STYPE_IMM (value);
1821 break;
1823 case R_RISCV_CALL:
1824 case R_RISCV_CALL_PLT:
1825 if (ARCH_SIZE > 32 && !VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (value)))
1826 return bfd_reloc_overflow;
1827 value = ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value))
1828 | (ENCODE_ITYPE_IMM (value) << 32);
1829 break;
1831 case R_RISCV_JAL:
1832 if (!VALID_JTYPE_IMM (value))
1833 return bfd_reloc_overflow;
1834 value = ENCODE_JTYPE_IMM (value);
1835 break;
1837 case R_RISCV_BRANCH:
1838 if (!VALID_BTYPE_IMM (value))
1839 return bfd_reloc_overflow;
1840 value = ENCODE_BTYPE_IMM (value);
1841 break;
1843 case R_RISCV_RVC_BRANCH:
1844 if (!VALID_CBTYPE_IMM (value))
1845 return bfd_reloc_overflow;
1846 value = ENCODE_CBTYPE_IMM (value);
1847 break;
1849 case R_RISCV_RVC_JUMP:
1850 if (!VALID_CJTYPE_IMM (value))
1851 return bfd_reloc_overflow;
1852 value = ENCODE_CJTYPE_IMM (value);
1853 break;
1855 case R_RISCV_RVC_LUI:
1856 if (RISCV_CONST_HIGH_PART (value) == 0)
1858 /* Linker relaxation can convert an address equal to or greater than
1859 0x800 to slightly below 0x800. C.LUI does not accept zero as a
1860 valid immediate. We can fix this by converting it to a C.LI. */
1861 bfd_vma insn = riscv_get_insn (howto->bitsize,
1862 contents + rel->r_offset);
1863 insn = (insn & ~MATCH_C_LUI) | MATCH_C_LI;
1864 riscv_put_insn (howto->bitsize, insn, contents + rel->r_offset);
1865 value = ENCODE_CITYPE_IMM (0);
1867 else if (!VALID_CITYPE_LUI_IMM (RISCV_CONST_HIGH_PART (value)))
1868 return bfd_reloc_overflow;
1869 else
1870 value = ENCODE_CITYPE_LUI_IMM (RISCV_CONST_HIGH_PART (value));
1871 break;
1873 /* R_RISCV_SET_ULEB128 won't go into here. */
1874 case R_RISCV_SUB_ULEB128:
1876 unsigned int len = 0;
1877 _bfd_read_unsigned_leb128 (input_bfd, contents + rel->r_offset, &len);
1879 /* Clean the contents value to zero (0x80), but keep the original
1880 length. */
1881 bfd_byte *p = contents + rel->r_offset;
1882 bfd_byte *endp = p + len - 1;
1883 memset (p, 0x80, len - 1);
1884 *(endp) = 0;
1886 /* Make sure the length of the new uleb128 value within the
1887 original (available) length. */
1888 unsigned int new_len = 0;
1889 unsigned int val_t = value;
1892 new_len++;
1893 val_t >>= 7;
1895 while (val_t);
1896 if (new_len > len)
1898 _bfd_error_handler
1899 (_("final size of uleb128 value at offset 0x%lx in %pA from "
1900 "%pB exceeds available space"),
1901 (long) rel->r_offset, input_section, input_bfd);
1902 return bfd_reloc_dangerous;
1904 else
1906 p = _bfd_write_unsigned_leb128 (p, endp, value);
1907 BFD_ASSERT (p);
1909 /* If the length of the value is reduced and shorter than the
1910 original uleb128 length, then _bfd_write_unsigned_leb128 may
1911 clear the 0x80 to 0x0 for the last byte that was written.
1912 So reset it to keep the the original uleb128 length. */
1913 if (--p < endp)
1914 *p |= 0x80;
1916 return bfd_reloc_ok;
1919 case R_RISCV_32:
1920 case R_RISCV_64:
1921 case R_RISCV_ADD8:
1922 case R_RISCV_ADD16:
1923 case R_RISCV_ADD32:
1924 case R_RISCV_ADD64:
1925 case R_RISCV_SUB6:
1926 case R_RISCV_SUB8:
1927 case R_RISCV_SUB16:
1928 case R_RISCV_SUB32:
1929 case R_RISCV_SUB64:
1930 case R_RISCV_SET6:
1931 case R_RISCV_SET8:
1932 case R_RISCV_SET16:
1933 case R_RISCV_SET32:
1934 case R_RISCV_32_PCREL:
1935 case R_RISCV_TLS_DTPREL32:
1936 case R_RISCV_TLS_DTPREL64:
1937 break;
1939 case R_RISCV_DELETE:
1940 return bfd_reloc_ok;
1942 default:
1943 return bfd_reloc_notsupported;
1946 bfd_vma word;
1947 if (riscv_is_insn_reloc (howto))
1948 word = riscv_get_insn (howto->bitsize, contents + rel->r_offset);
1949 else
1950 word = bfd_get (howto->bitsize, input_bfd, contents + rel->r_offset);
1951 word = (word & ~howto->dst_mask) | (value & howto->dst_mask);
1952 if (riscv_is_insn_reloc (howto))
1953 riscv_put_insn (howto->bitsize, word, contents + rel->r_offset);
1954 else
1955 bfd_put (howto->bitsize, input_bfd, word, contents + rel->r_offset);
1957 return bfd_reloc_ok;
1960 /* Remember all PC-relative high-part relocs we've encountered to help us
1961 later resolve the corresponding low-part relocs. */
1963 typedef struct
1965 /* PC value. */
1966 bfd_vma address;
1967 /* Relocation value with addend. */
1968 bfd_vma value;
1969 /* Original reloc type. */
1970 int type;
1971 } riscv_pcrel_hi_reloc;
1973 typedef struct riscv_pcrel_lo_reloc
1975 /* PC value of auipc. */
1976 bfd_vma address;
1977 /* Internal relocation. */
1978 const Elf_Internal_Rela *reloc;
1979 /* Record the following information helps to resolve the %pcrel
1980 which cross different input section. For now we build a hash
1981 for pcrel at the start of riscv_elf_relocate_section, and then
1982 free the hash at the end. But riscv_elf_relocate_section only
1983 handles an input section at a time, so that means we can only
1984 resolve the %pcrel_hi and %pcrel_lo which are in the same input
1985 section. Otherwise, we will report dangerous relocation errors
1986 for those %pcrel which are not in the same input section. */
1987 asection *input_section;
1988 struct bfd_link_info *info;
1989 reloc_howto_type *howto;
1990 bfd_byte *contents;
1991 /* The next riscv_pcrel_lo_reloc. */
1992 struct riscv_pcrel_lo_reloc *next;
1993 } riscv_pcrel_lo_reloc;
1995 typedef struct
1997 /* Hash table for riscv_pcrel_hi_reloc. */
1998 htab_t hi_relocs;
1999 /* Linked list for riscv_pcrel_lo_reloc. */
2000 riscv_pcrel_lo_reloc *lo_relocs;
2001 } riscv_pcrel_relocs;
2003 static hashval_t
2004 riscv_pcrel_reloc_hash (const void *entry)
2006 const riscv_pcrel_hi_reloc *e = entry;
2007 return (hashval_t)(e->address >> 2);
2010 static int
2011 riscv_pcrel_reloc_eq (const void *entry1, const void *entry2)
2013 const riscv_pcrel_hi_reloc *e1 = entry1, *e2 = entry2;
2014 return e1->address == e2->address;
2017 static bool
2018 riscv_init_pcrel_relocs (riscv_pcrel_relocs *p)
2020 p->lo_relocs = NULL;
2021 p->hi_relocs = htab_create (1024, riscv_pcrel_reloc_hash,
2022 riscv_pcrel_reloc_eq, free);
2023 return p->hi_relocs != NULL;
2026 static void
2027 riscv_free_pcrel_relocs (riscv_pcrel_relocs *p)
2029 riscv_pcrel_lo_reloc *cur = p->lo_relocs;
2031 while (cur != NULL)
2033 riscv_pcrel_lo_reloc *next = cur->next;
2034 free (cur);
2035 cur = next;
2038 htab_delete (p->hi_relocs);
2041 static bool
2042 riscv_zero_pcrel_hi_reloc (Elf_Internal_Rela *rel,
2043 struct bfd_link_info *info,
2044 bfd_vma pc,
2045 bfd_vma addr,
2046 bfd_byte *contents,
2047 const reloc_howto_type *howto)
2049 /* We may need to reference low addreses in PC-relative modes even when the
2050 PC is far away from these addresses. For example, undefweak references
2051 need to produce the address 0 when linked. As 0 is far from the arbitrary
2052 addresses that we can link PC-relative programs at, the linker can't
2053 actually relocate references to those symbols. In order to allow these
2054 programs to work we simply convert the PC-relative auipc sequences to
2055 0-relative lui sequences. */
2056 if (bfd_link_pic (info))
2057 return false;
2059 /* If it's possible to reference the symbol using auipc we do so, as that's
2060 more in the spirit of the PC-relative relocations we're processing. */
2061 bfd_vma offset = addr - pc;
2062 if (ARCH_SIZE == 32 || VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (offset)))
2063 return false;
2065 /* If it's impossible to reference this with a LUI-based offset then don't
2066 bother to convert it at all so users still see the PC-relative relocation
2067 in the truncation message. */
2068 if (ARCH_SIZE > 32 && !VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (addr)))
2069 return false;
2071 rel->r_info = ELFNN_R_INFO (addr, R_RISCV_HI20);
2073 bfd_vma insn = riscv_get_insn (howto->bitsize, contents + rel->r_offset);
2074 insn = (insn & ~MASK_AUIPC) | MATCH_LUI;
2075 riscv_put_insn (howto->bitsize, insn, contents + rel->r_offset);
2076 return true;
2079 static bool
2080 riscv_record_pcrel_hi_reloc (riscv_pcrel_relocs *p,
2081 bfd_vma addr,
2082 bfd_vma value,
2083 int type,
2084 bool absolute)
2086 bfd_vma offset = absolute ? value : value - addr;
2087 riscv_pcrel_hi_reloc entry = {addr, offset, type};
2088 riscv_pcrel_hi_reloc **slot =
2089 (riscv_pcrel_hi_reloc **) htab_find_slot (p->hi_relocs, &entry, INSERT);
2091 BFD_ASSERT (*slot == NULL);
2092 *slot = (riscv_pcrel_hi_reloc *) bfd_malloc (sizeof (riscv_pcrel_hi_reloc));
2093 if (*slot == NULL)
2094 return false;
2095 **slot = entry;
2096 return true;
2099 static bool
2100 riscv_record_pcrel_lo_reloc (riscv_pcrel_relocs *p,
2101 bfd_vma addr,
2102 const Elf_Internal_Rela *reloc,
2103 asection *input_section,
2104 struct bfd_link_info *info,
2105 reloc_howto_type *howto,
2106 bfd_byte *contents)
2108 riscv_pcrel_lo_reloc *entry;
2109 entry = (riscv_pcrel_lo_reloc *) bfd_malloc (sizeof (riscv_pcrel_lo_reloc));
2110 if (entry == NULL)
2111 return false;
2112 *entry = (riscv_pcrel_lo_reloc) {addr, reloc, input_section, info,
2113 howto, contents, p->lo_relocs};
2114 p->lo_relocs = entry;
2115 return true;
2118 static bool
2119 riscv_resolve_pcrel_lo_relocs (riscv_pcrel_relocs *p)
2121 riscv_pcrel_lo_reloc *r;
2123 for (r = p->lo_relocs; r != NULL; r = r->next)
2125 bfd *input_bfd = r->input_section->owner;
2127 riscv_pcrel_hi_reloc search = {r->address, 0, 0};
2128 riscv_pcrel_hi_reloc *entry = htab_find (p->hi_relocs, &search);
2129 /* There may be a risk if the %pcrel_lo with addend refers to
2130 an IFUNC symbol. The %pcrel_hi has been relocated to plt,
2131 so the corresponding %pcrel_lo with addend looks wrong. */
2132 char *string = NULL;
2133 if (entry == NULL)
2134 string = _("%pcrel_lo missing matching %pcrel_hi");
2135 else if (entry->type == R_RISCV_GOT_HI20
2136 && r->reloc->r_addend != 0)
2137 string = _("%pcrel_lo with addend isn't allowed for R_RISCV_GOT_HI20");
2138 else if (RISCV_CONST_HIGH_PART (entry->value)
2139 != RISCV_CONST_HIGH_PART (entry->value + r->reloc->r_addend))
2141 /* Check the overflow when adding reloc addend. */
2142 string = bfd_asprintf (_("%%pcrel_lo overflow with an addend,"
2143 " the value of %%pcrel_hi is 0x%" PRIx64
2144 " without any addend, but may be 0x%" PRIx64
2145 " after adding the %%pcrel_lo addend"),
2146 (int64_t) RISCV_CONST_HIGH_PART (entry->value),
2147 (int64_t) RISCV_CONST_HIGH_PART
2148 (entry->value + r->reloc->r_addend));
2149 if (string == NULL)
2150 string = _("%pcrel_lo overflow with an addend");
2153 if (string != NULL)
2155 (*r->info->callbacks->reloc_dangerous)
2156 (r->info, string, input_bfd, r->input_section, r->reloc->r_offset);
2157 return true;
2160 perform_relocation (r->howto, r->reloc, entry->value, r->input_section,
2161 input_bfd, r->contents);
2164 return true;
2167 /* Relocate a RISC-V ELF section.
2169 The RELOCATE_SECTION function is called by the new ELF backend linker
2170 to handle the relocations for a section.
2172 The relocs are always passed as Rela structures.
2174 This function is responsible for adjusting the section contents as
2175 necessary, and (if generating a relocatable output file) adjusting
2176 the reloc addend as necessary.
2178 This function does not have to worry about setting the reloc
2179 address or the reloc symbol index.
2181 LOCAL_SYMS is a pointer to the swapped in local symbols.
2183 LOCAL_SECTIONS is an array giving the section in the input file
2184 corresponding to the st_shndx field of each local symbol.
2186 The global hash table entry for the global symbols can be found
2187 via elf_sym_hashes (input_bfd).
2189 When generating relocatable output, this function must handle
2190 STB_LOCAL/STT_SECTION symbols specially. The output symbol is
2191 going to be the section symbol corresponding to the output
2192 section, which means that the addend must be adjusted
2193 accordingly. */
2195 static int
2196 riscv_elf_relocate_section (bfd *output_bfd,
2197 struct bfd_link_info *info,
2198 bfd *input_bfd,
2199 asection *input_section,
2200 bfd_byte *contents,
2201 Elf_Internal_Rela *relocs,
2202 Elf_Internal_Sym *local_syms,
2203 asection **local_sections)
2205 Elf_Internal_Rela *rel;
2206 Elf_Internal_Rela *relend;
2207 riscv_pcrel_relocs pcrel_relocs;
2208 bool ret = false;
2209 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
2210 Elf_Internal_Shdr *symtab_hdr = &elf_symtab_hdr (input_bfd);
2211 struct elf_link_hash_entry **sym_hashes = elf_sym_hashes (input_bfd);
2212 bfd_vma *local_got_offsets = elf_local_got_offsets (input_bfd);
2213 bfd_vma uleb128_set_vma = 0;
2214 Elf_Internal_Rela *uleb128_set_rel = NULL;
2215 bool absolute;
2217 if (!riscv_init_pcrel_relocs (&pcrel_relocs))
2218 return false;
2220 relend = relocs + input_section->reloc_count;
2221 for (rel = relocs; rel < relend; rel++)
2223 unsigned long r_symndx;
2224 struct elf_link_hash_entry *h;
2225 Elf_Internal_Sym *sym;
2226 asection *sec;
2227 bfd_vma relocation;
2228 bfd_reloc_status_type r = bfd_reloc_ok;
2229 const char *name = NULL;
2230 bfd_vma off, ie_off, desc_off;
2231 bool unresolved_reloc, is_ie = false, is_desc = false;
2232 bfd_vma pc = sec_addr (input_section) + rel->r_offset;
2233 int r_type = ELFNN_R_TYPE (rel->r_info), tls_type;
2234 reloc_howto_type *howto = riscv_elf_rtype_to_howto (input_bfd, r_type);
2235 const char *msg = NULL;
2236 bool resolved_to_zero;
2238 if (howto == NULL)
2239 continue;
2241 /* This is a final link. */
2242 r_symndx = ELFNN_R_SYM (rel->r_info);
2243 h = NULL;
2244 sym = NULL;
2245 sec = NULL;
2246 unresolved_reloc = false;
2247 if (r_symndx < symtab_hdr->sh_info)
2249 sym = local_syms + r_symndx;
2250 sec = local_sections[r_symndx];
2251 relocation = _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
2253 /* Relocate against local STT_GNU_IFUNC symbol. */
2254 if (!bfd_link_relocatable (info)
2255 && ELF_ST_TYPE (sym->st_info) == STT_GNU_IFUNC)
2257 h = riscv_elf_get_local_sym_hash (htab, input_bfd, rel, false);
2258 if (h == NULL)
2259 abort ();
2261 /* Set STT_GNU_IFUNC symbol value. */
2262 h->root.u.def.value = sym->st_value;
2263 h->root.u.def.section = sec;
2266 else
2268 bool warned, ignored;
2270 RELOC_FOR_GLOBAL_SYMBOL (info, input_bfd, input_section, rel,
2271 r_symndx, symtab_hdr, sym_hashes,
2272 h, sec, relocation,
2273 unresolved_reloc, warned, ignored);
2274 if (warned)
2276 /* To avoid generating warning messages about truncated
2277 relocations, set the relocation's address to be the same as
2278 the start of this section. */
2279 if (input_section->output_section != NULL)
2280 relocation = input_section->output_section->vma;
2281 else
2282 relocation = 0;
2286 if (sec != NULL && discarded_section (sec))
2287 RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
2288 rel, 1, relend, howto, 0, contents);
2290 if (bfd_link_relocatable (info))
2291 continue;
2293 /* Since STT_GNU_IFUNC symbol must go through PLT, we handle
2294 it here if it is defined in a non-shared object. */
2295 if (h != NULL
2296 && h->type == STT_GNU_IFUNC
2297 && h->def_regular)
2299 asection *plt, *base_got;
2301 if ((input_section->flags & SEC_ALLOC) == 0)
2303 /* If this is a SHT_NOTE section without SHF_ALLOC, treat
2304 STT_GNU_IFUNC symbol as STT_FUNC. */
2305 if (elf_section_type (input_section) == SHT_NOTE)
2306 goto skip_ifunc;
2308 /* Dynamic relocs are not propagated for SEC_DEBUGGING
2309 sections because such sections are not SEC_ALLOC and
2310 thus ld.so will not process them. */
2311 if ((input_section->flags & SEC_DEBUGGING) != 0)
2312 continue;
2314 abort ();
2316 else if (h->plt.offset == (bfd_vma) -1
2317 /* The following relocation may not need the .plt entries
2318 when all references to a STT_GNU_IFUNC symbols are done
2319 via GOT or static function pointers. */
2320 && r_type != R_RISCV_32
2321 && r_type != R_RISCV_64
2322 && r_type != R_RISCV_HI20
2323 && r_type != R_RISCV_GOT_HI20
2324 && r_type != R_RISCV_LO12_I
2325 && r_type != R_RISCV_LO12_S)
2326 goto bad_ifunc_reloc;
2328 /* STT_GNU_IFUNC symbol must go through PLT. */
2329 plt = htab->elf.splt ? htab->elf.splt : htab->elf.iplt;
2330 relocation = plt->output_section->vma
2331 + plt->output_offset
2332 + h->plt.offset;
2334 switch (r_type)
2336 case R_RISCV_32:
2337 case R_RISCV_64:
2338 if (rel->r_addend != 0)
2340 if (h->root.root.string)
2341 name = h->root.root.string;
2342 else
2343 name = bfd_elf_sym_name (input_bfd, symtab_hdr, sym, NULL);
2345 _bfd_error_handler
2346 /* xgettext:c-format */
2347 (_("%pB: relocation %s against STT_GNU_IFUNC "
2348 "symbol `%s' has non-zero addend: %" PRId64),
2349 input_bfd, howto->name, name, (int64_t) rel->r_addend);
2350 bfd_set_error (bfd_error_bad_value);
2351 return false;
2354 /* Generate dynamic relocation only when there is a non-GOT
2355 reference in a shared object or there is no PLT. */
2356 if ((bfd_link_pic (info) && h->non_got_ref)
2357 || h->plt.offset == (bfd_vma) -1)
2359 Elf_Internal_Rela outrel;
2360 asection *sreloc;
2362 /* Need a dynamic relocation to get the real function
2363 address. */
2364 outrel.r_offset = _bfd_elf_section_offset (output_bfd,
2365 info,
2366 input_section,
2367 rel->r_offset);
2368 if (outrel.r_offset == (bfd_vma) -1
2369 || outrel.r_offset == (bfd_vma) -2)
2370 abort ();
2372 outrel.r_offset += input_section->output_section->vma
2373 + input_section->output_offset;
2375 if (h->dynindx == -1
2376 || h->forced_local
2377 || bfd_link_executable (info))
2379 info->callbacks->minfo
2380 (_("Local IFUNC function `%s' in %pB\n"),
2381 h->root.root.string,
2382 h->root.u.def.section->owner);
2384 /* This symbol is resolved locally. */
2385 outrel.r_info = ELFNN_R_INFO (0, R_RISCV_IRELATIVE);
2386 outrel.r_addend = h->root.u.def.value
2387 + h->root.u.def.section->output_section->vma
2388 + h->root.u.def.section->output_offset;
2390 else
2392 outrel.r_info = ELFNN_R_INFO (h->dynindx, r_type);
2393 outrel.r_addend = 0;
2396 /* Dynamic relocations are stored in
2397 1. .rela.ifunc section in PIC object.
2398 2. .rela.got section in dynamic executable.
2399 3. .rela.iplt section in static executable. */
2400 if (bfd_link_pic (info))
2401 sreloc = htab->elf.irelifunc;
2402 else if (htab->elf.splt != NULL)
2403 sreloc = htab->elf.srelgot;
2404 else
2405 sreloc = htab->elf.irelplt;
2407 riscv_elf_append_rela (output_bfd, sreloc, &outrel);
2409 /* If this reloc is against an external symbol, we
2410 do not want to fiddle with the addend. Otherwise,
2411 we need to include the symbol value so that it
2412 becomes an addend for the dynamic reloc. For an
2413 internal symbol, we have updated addend. */
2414 continue;
2416 goto do_relocation;
2418 case R_RISCV_GOT_HI20:
2419 base_got = htab->elf.sgot;
2420 off = h->got.offset;
2422 if (base_got == NULL)
2423 abort ();
2425 if (off == (bfd_vma) -1)
2427 bfd_vma plt_idx;
2429 /* We can't use h->got.offset here to save state, or
2430 even just remember the offset, as finish_dynamic_symbol
2431 would use that as offset into .got. */
2433 if (htab->elf.splt != NULL)
2435 plt_idx = (h->plt.offset - PLT_HEADER_SIZE)
2436 / PLT_ENTRY_SIZE;
2437 off = GOTPLT_HEADER_SIZE + (plt_idx * GOT_ENTRY_SIZE);
2438 base_got = htab->elf.sgotplt;
2440 else
2442 plt_idx = h->plt.offset / PLT_ENTRY_SIZE;
2443 off = plt_idx * GOT_ENTRY_SIZE;
2444 base_got = htab->elf.igotplt;
2447 if (h->dynindx == -1
2448 || h->forced_local
2449 || info->symbolic)
2451 /* This references the local definition. We must
2452 initialize this entry in the global offset table.
2453 Since the offset must always be a multiple of 8,
2454 we use the least significant bit to record
2455 whether we have initialized it already.
2457 When doing a dynamic link, we create a .rela.got
2458 relocation entry to initialize the value. This
2459 is done in the finish_dynamic_symbol routine. */
2460 if ((off & 1) != 0)
2461 off &= ~1;
2462 else
2464 bfd_put_NN (output_bfd, relocation,
2465 base_got->contents + off);
2466 /* Note that this is harmless for the case,
2467 as -1 | 1 still is -1. */
2468 h->got.offset |= 1;
2473 relocation = base_got->output_section->vma
2474 + base_got->output_offset + off;
2476 if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2477 relocation, r_type,
2478 false))
2479 r = bfd_reloc_overflow;
2480 goto do_relocation;
2482 case R_RISCV_CALL:
2483 case R_RISCV_CALL_PLT:
2484 case R_RISCV_HI20:
2485 case R_RISCV_LO12_I:
2486 case R_RISCV_LO12_S:
2487 goto do_relocation;
2489 case R_RISCV_PCREL_HI20:
2490 if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2491 relocation, r_type,
2492 false))
2493 r = bfd_reloc_overflow;
2494 goto do_relocation;
2496 default:
2497 bad_ifunc_reloc:
2498 if (h->root.root.string)
2499 name = h->root.root.string;
2500 else
2501 /* The entry of local ifunc is fake in global hash table,
2502 we should find the name by the original local symbol. */
2503 name = bfd_elf_sym_name (input_bfd, symtab_hdr, sym, NULL);
2505 _bfd_error_handler
2506 /* xgettext:c-format */
2507 (_("%pB: relocation %s against STT_GNU_IFUNC "
2508 "symbol `%s' isn't supported"), input_bfd,
2509 howto->name, name);
2510 bfd_set_error (bfd_error_bad_value);
2511 return false;
2515 skip_ifunc:
2516 if (h != NULL)
2517 name = h->root.root.string;
2518 else
2520 name = (bfd_elf_string_from_elf_section
2521 (input_bfd, symtab_hdr->sh_link, sym->st_name));
2522 if (name == NULL || *name == '\0')
2523 name = bfd_section_name (sec);
2526 resolved_to_zero = (h != NULL
2527 && UNDEFWEAK_NO_DYNAMIC_RELOC (info, h));
2529 switch (r_type)
2531 case R_RISCV_NONE:
2532 case R_RISCV_RELAX:
2533 case R_RISCV_TPREL_ADD:
2534 case R_RISCV_TLSDESC_CALL:
2535 case R_RISCV_COPY:
2536 case R_RISCV_JUMP_SLOT:
2537 case R_RISCV_RELATIVE:
2538 /* These require nothing of us at all. */
2539 continue;
2541 case R_RISCV_HI20:
2542 case R_RISCV_BRANCH:
2543 case R_RISCV_RVC_BRANCH:
2544 case R_RISCV_RVC_LUI:
2545 case R_RISCV_LO12_I:
2546 case R_RISCV_LO12_S:
2547 case R_RISCV_SET6:
2548 case R_RISCV_SET8:
2549 case R_RISCV_SET16:
2550 case R_RISCV_SET32:
2551 case R_RISCV_32_PCREL:
2552 case R_RISCV_DELETE:
2553 /* These require no special handling beyond perform_relocation. */
2554 break;
2556 case R_RISCV_SET_ULEB128:
2557 if (uleb128_set_rel == NULL)
2559 /* Saved for later usage. */
2560 uleb128_set_vma = relocation;
2561 uleb128_set_rel = rel;
2562 continue;
2564 else
2566 msg = ("Mismatched R_RISCV_SET_ULEB128, it must be paired with"
2567 " and applied before R_RISCV_SUB_ULEB128");
2568 r = bfd_reloc_dangerous;
2570 break;
2572 case R_RISCV_SUB_ULEB128:
2573 if (uleb128_set_rel != NULL
2574 && uleb128_set_rel->r_offset == rel->r_offset)
2576 relocation = uleb128_set_vma - relocation
2577 + uleb128_set_rel->r_addend;
2578 uleb128_set_vma = 0;
2579 uleb128_set_rel = NULL;
2581 /* PR31179, the addend of SUB_ULEB128 should be zero if using
2582 .uleb128, but we make it non-zero by accident in assembler,
2583 so just ignore it in perform_relocation, and make assembler
2584 continue doing the right thing. Don't reset the addend of
2585 SUB_ULEB128 to zero here since it will break the --emit-reloc,
2586 even though the non-zero addend is unexpected.
2588 We encourage people to rebuild their stuff to get the
2589 non-zero addend of SUB_ULEB128, but that might need some
2590 times, so report warnings to inform people need to rebuild
2591 if --check-uleb128 is enabled. However, since the failed
2592 .reloc cases for ADD/SET/SUB/ULEB128 are rarely to use, it
2593 may acceptable that stop supproting them until people rebuld
2594 their stuff, maybe half-year or one year later. I believe
2595 this might be the least harmful option that we should go.
2597 Or maybe we should teach people that don't write the
2598 .reloc R_RISCV_SUB* with non-zero constant, and report
2599 warnings/errors in assembler. */
2600 if (htab->params->check_uleb128
2601 && rel->r_addend != 0)
2602 _bfd_error_handler (_("%pB: warning: R_RISCV_SUB_ULEB128 with"
2603 " non-zero addend, please rebuild by"
2604 " binutils 2.42 or up"), input_bfd);
2606 else
2608 msg = ("Mismatched R_RISCV_SUB_ULEB128, it must be paired with"
2609 " and applied after R_RISCV_SET_ULEB128");
2610 r = bfd_reloc_dangerous;
2612 break;
2614 case R_RISCV_GOT_HI20:
2615 if (h != NULL)
2617 off = h->got.offset;
2618 BFD_ASSERT (off != (bfd_vma) -1);
2620 if (RISCV_RESOLVED_LOCALLY (info, h))
2622 /* We must initialize this entry in the global offset table.
2623 Since the offset must always be a multiple of the word
2624 size, we use the least significant bit to record whether
2625 we have initialized it already.
2627 When doing a dynamic link, we create a .rela.got
2628 relocation entry to initialize the value. This
2629 is done in the finish_dynamic_symbol routine. */
2630 if ((off & 1) != 0)
2631 off &= ~1;
2632 else
2634 bfd_put_NN (output_bfd, relocation,
2635 htab->elf.sgot->contents + off);
2636 h->got.offset |= 1;
2639 else
2640 unresolved_reloc = false;
2642 else
2644 BFD_ASSERT (local_got_offsets != NULL
2645 && local_got_offsets[r_symndx] != (bfd_vma) -1);
2647 off = local_got_offsets[r_symndx];
2649 /* The offset must always be a multiple of the word size.
2650 So, we can use the least significant bit to record
2651 whether we have already processed this entry. */
2652 if ((off & 1) != 0)
2653 off &= ~1;
2654 else
2656 if (bfd_link_pic (info))
2658 asection *s;
2659 Elf_Internal_Rela outrel;
2661 /* We need to generate a R_RISCV_RELATIVE reloc
2662 for the dynamic linker. */
2663 s = htab->elf.srelgot;
2664 BFD_ASSERT (s != NULL);
2666 outrel.r_offset = sec_addr (htab->elf.sgot) + off;
2667 outrel.r_info =
2668 ELFNN_R_INFO (0, R_RISCV_RELATIVE);
2669 outrel.r_addend = relocation;
2670 relocation = 0;
2671 riscv_elf_append_rela (output_bfd, s, &outrel);
2674 bfd_put_NN (output_bfd, relocation,
2675 htab->elf.sgot->contents + off);
2676 local_got_offsets[r_symndx] |= 1;
2680 if (rel->r_addend != 0)
2682 msg = _("The addend isn't allowed for R_RISCV_GOT_HI20");
2683 r = bfd_reloc_dangerous;
2685 else
2687 /* Address of got entry. */
2688 relocation = sec_addr (htab->elf.sgot) + off;
2689 absolute = riscv_zero_pcrel_hi_reloc (rel, info, pc,
2690 relocation, contents,
2691 howto);
2692 /* Update howto if relocation is changed. */
2693 howto = riscv_elf_rtype_to_howto (input_bfd,
2694 ELFNN_R_TYPE (rel->r_info));
2695 if (howto == NULL)
2696 r = bfd_reloc_notsupported;
2697 else if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2698 relocation, r_type,
2699 absolute))
2700 r = bfd_reloc_overflow;
2702 break;
2704 case R_RISCV_ADD8:
2705 case R_RISCV_ADD16:
2706 case R_RISCV_ADD32:
2707 case R_RISCV_ADD64:
2709 bfd_vma old_value = bfd_get (howto->bitsize, input_bfd,
2710 contents + rel->r_offset);
2711 relocation = old_value + relocation;
2713 break;
2715 case R_RISCV_SUB6:
2717 bfd_vma old_value = bfd_get (howto->bitsize, input_bfd,
2718 contents + rel->r_offset);
2719 relocation = (old_value & ~howto->dst_mask)
2720 | (((old_value & howto->dst_mask) - relocation)
2721 & howto->dst_mask);
2723 break;
2725 case R_RISCV_SUB8:
2726 case R_RISCV_SUB16:
2727 case R_RISCV_SUB32:
2728 case R_RISCV_SUB64:
2730 bfd_vma old_value = bfd_get (howto->bitsize, input_bfd,
2731 contents + rel->r_offset);
2732 relocation = old_value - relocation;
2734 break;
2736 case R_RISCV_CALL:
2737 case R_RISCV_CALL_PLT:
2738 /* Handle a call to an undefined weak function. This won't be
2739 relaxed, so we have to handle it here. */
2740 if (h != NULL && h->root.type == bfd_link_hash_undefweak
2741 && (!bfd_link_pic (info) || h->plt.offset == MINUS_ONE))
2743 /* We can use x0 as the base register. */
2744 bfd_vma insn = bfd_getl32 (contents + rel->r_offset + 4);
2745 insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
2746 bfd_putl32 (insn, contents + rel->r_offset + 4);
2747 /* Set the relocation value so that we get 0 after the pc
2748 relative adjustment. */
2749 relocation = sec_addr (input_section) + rel->r_offset;
2751 /* Fall through. */
2753 case R_RISCV_JAL:
2754 case R_RISCV_RVC_JUMP:
2755 if (bfd_link_pic (info) && h != NULL)
2757 if (h->plt.offset != MINUS_ONE)
2759 /* Refer to the PLT entry. This check has to match the
2760 check in _bfd_riscv_relax_section. */
2761 relocation = sec_addr (htab->elf.splt) + h->plt.offset;
2762 unresolved_reloc = false;
2764 else if (!SYMBOL_REFERENCES_LOCAL (info, h)
2765 && (input_section->flags & SEC_ALLOC) != 0
2766 && (input_section->flags & SEC_READONLY) != 0
2767 && ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
2769 /* PR 28509, when generating the shared object, these
2770 referenced symbols may bind externally, which means
2771 they will be exported to the dynamic symbol table,
2772 and are preemptible by default. These symbols cannot
2773 be referenced by the non-pic relocations, like
2774 R_RISCV_JAL and R_RISCV_RVC_JUMP relocations.
2776 However, consider that linker may relax the R_RISCV_CALL
2777 relocations to R_RISCV_JAL or R_RISCV_RVC_JUMP, if
2778 these relocations are relocated to the plt entries,
2779 then we won't report error for them.
2781 Perhaps we also need the similar checks for the
2782 R_RISCV_BRANCH and R_RISCV_RVC_BRANCH relocations. */
2783 msg = bfd_asprintf (_("%%X%%P: relocation %s against `%s'"
2784 " which may bind externally"
2785 " can not be used"
2786 " when making a shared object;"
2787 " recompile with -fPIC\n"),
2788 howto->name, h->root.root.string);
2789 r = bfd_reloc_notsupported;
2792 break;
2794 case R_RISCV_TPREL_HI20:
2795 relocation = tpoff (info, relocation);
2796 break;
2798 case R_RISCV_TPREL_LO12_I:
2799 case R_RISCV_TPREL_LO12_S:
2800 relocation = tpoff (info, relocation);
2801 break;
2803 case R_RISCV_TPREL_I:
2804 case R_RISCV_TPREL_S:
2805 relocation = tpoff (info, relocation);
2806 if (VALID_ITYPE_IMM (relocation + rel->r_addend))
2808 /* We can use tp as the base register. */
2809 bfd_vma insn = bfd_getl32 (contents + rel->r_offset);
2810 insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
2811 insn |= X_TP << OP_SH_RS1;
2812 bfd_putl32 (insn, contents + rel->r_offset);
2814 else
2815 r = bfd_reloc_overflow;
2816 break;
2818 case R_RISCV_GPREL_I:
2819 case R_RISCV_GPREL_S:
2821 bfd_vma gp = riscv_global_pointer_value (info);
2822 bool x0_base = VALID_ITYPE_IMM (relocation + rel->r_addend);
2823 if (x0_base || VALID_ITYPE_IMM (relocation + rel->r_addend - gp))
2825 /* We can use x0 or gp as the base register. */
2826 bfd_vma insn = bfd_getl32 (contents + rel->r_offset);
2827 insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
2828 if (!x0_base)
2830 rel->r_addend -= gp;
2831 insn |= X_GP << OP_SH_RS1;
2833 bfd_putl32 (insn, contents + rel->r_offset);
2835 else
2836 r = bfd_reloc_overflow;
2837 break;
2840 case R_RISCV_PCREL_HI20:
2841 absolute = riscv_zero_pcrel_hi_reloc (rel, info, pc, relocation,
2842 contents, howto);
2843 /* Update howto if relocation is changed. */
2844 howto = riscv_elf_rtype_to_howto (input_bfd,
2845 ELFNN_R_TYPE (rel->r_info));
2846 if (howto == NULL)
2847 r = bfd_reloc_notsupported;
2848 else if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2849 relocation + rel->r_addend,
2850 r_type, absolute))
2851 r = bfd_reloc_overflow;
2852 break;
2854 case R_RISCV_PCREL_LO12_I:
2855 case R_RISCV_PCREL_LO12_S:
2856 /* We don't allow section symbols plus addends as the auipc address,
2857 because then riscv_relax_delete_bytes would have to search through
2858 all relocs to update these addends. This is also ambiguous, as
2859 we do allow offsets to be added to the target address, which are
2860 not to be used to find the auipc address. */
2861 if (((sym != NULL && (ELF_ST_TYPE (sym->st_info) == STT_SECTION))
2862 || (h != NULL && h->type == STT_SECTION))
2863 && rel->r_addend)
2865 msg = _("%pcrel_lo section symbol with an addend");
2866 r = bfd_reloc_dangerous;
2867 break;
2870 if (riscv_record_pcrel_lo_reloc (&pcrel_relocs, relocation, rel,
2871 input_section, info, howto,
2872 contents))
2873 continue;
2874 r = bfd_reloc_overflow;
2875 break;
2877 case R_RISCV_TLS_DTPREL32:
2878 case R_RISCV_TLS_DTPREL64:
2879 relocation = dtpoff (info, relocation);
2880 break;
2882 case R_RISCV_TLSDESC_LOAD_LO12:
2883 case R_RISCV_TLSDESC_ADD_LO12:
2884 if (rel->r_addend)
2886 msg = _("%tlsdesc_lo with addend");
2887 r = bfd_reloc_dangerous;
2888 break;
2891 if (riscv_record_pcrel_lo_reloc (&pcrel_relocs, relocation, rel,
2892 input_section, info, howto,
2893 contents))
2894 continue;
2895 r = bfd_reloc_overflow;
2896 break;
2898 case R_RISCV_32:
2899 /* Non ABS symbol should be blocked in check_relocs. */
2900 if (ARCH_SIZE > 32)
2901 break;
2902 /* Fall through. */
2904 case R_RISCV_64:
2905 if ((input_section->flags & SEC_ALLOC) == 0)
2906 break;
2908 if (RISCV_GENERATE_DYNAMIC_RELOC (howto->pc_relative, info, h,
2909 resolved_to_zero))
2911 Elf_Internal_Rela outrel;
2912 asection *sreloc;
2914 /* When generating a shared object, these relocations
2915 are copied into the output file to be resolved at run
2916 time. */
2918 outrel.r_offset =
2919 _bfd_elf_section_offset (output_bfd, info, input_section,
2920 rel->r_offset);
2921 bool skip = false;
2922 bool relocate = false;
2923 if (outrel.r_offset == (bfd_vma) -1)
2924 skip = true;
2925 else if (outrel.r_offset == (bfd_vma) -2)
2927 skip = true;
2928 relocate = true;
2930 else if (h != NULL && bfd_is_abs_symbol (&h->root))
2932 /* Don't need dynamic reloc when the ABS symbol is
2933 non-dynamic or forced to local. Maybe just use
2934 SYMBOL_REFERENCES_LOCAL to check? */
2935 skip = (h->forced_local || (h->dynindx == -1));
2936 relocate = skip;
2939 outrel.r_offset += sec_addr (input_section);
2941 if (skip)
2942 memset (&outrel, 0, sizeof outrel); /* R_RISCV_NONE. */
2943 else if (RISCV_COPY_INPUT_RELOC (info, h))
2945 /* Maybe just use !SYMBOL_REFERENCES_LOCAL to check? */
2946 outrel.r_info = ELFNN_R_INFO (h->dynindx, r_type);
2947 outrel.r_addend = rel->r_addend;
2949 else
2951 /* This symbol is local, or marked to become local. */
2952 outrel.r_info = ELFNN_R_INFO (0, R_RISCV_RELATIVE);
2953 outrel.r_addend = relocation + rel->r_addend;
2956 sreloc = elf_section_data (input_section)->sreloc;
2957 riscv_elf_append_rela (output_bfd, sreloc, &outrel);
2958 if (!relocate)
2959 continue;
2961 break;
2963 case R_RISCV_TLSDESC_HI20:
2964 is_desc = true;
2965 goto tls;
2967 case R_RISCV_TLS_GOT_HI20:
2968 is_ie = true;
2969 goto tls;
2971 case R_RISCV_TLS_GD_HI20:
2972 tls:
2973 if (h != NULL)
2975 off = h->got.offset;
2976 h->got.offset |= 1;
2978 else
2980 off = local_got_offsets[r_symndx];
2981 local_got_offsets[r_symndx] |= 1;
2984 tls_type = _bfd_riscv_elf_tls_type (input_bfd, h, r_symndx);
2985 BFD_ASSERT (tls_type & (GOT_TLS_IE | GOT_TLS_GD | GOT_TLSDESC));
2986 /* When more than one TLS type is used, the GD slot comes first,
2987 then IE, then finally TLSDESC. */
2988 ie_off = 0;
2989 if (tls_type & GOT_TLS_GD)
2990 ie_off += TLS_GD_GOT_ENTRY_SIZE;
2992 desc_off = ie_off;
2993 if (tls_type & GOT_TLS_IE)
2994 desc_off += TLS_IE_GOT_ENTRY_SIZE;
2996 if ((off & 1) != 0)
2997 off &= ~1;
2998 else
3000 Elf_Internal_Rela outrel;
3001 int indx = 0;
3002 bool need_relocs = false;
3004 if (htab->elf.srelgot == NULL)
3005 abort ();
3007 bool dyn = elf_hash_table (info)->dynamic_sections_created;
3008 RISCV_TLS_GD_IE_NEED_DYN_RELOC (info, dyn, h, indx, need_relocs);
3010 /* The GOT entries have not been initialized yet. Do it
3011 now, and emit any relocations. */
3012 if (tls_type & GOT_TLS_GD)
3014 if (need_relocs)
3016 outrel.r_offset = sec_addr (htab->elf.sgot) + off;
3017 outrel.r_addend = 0;
3018 outrel.r_info = ELFNN_R_INFO (indx, R_RISCV_TLS_DTPMODNN);
3019 bfd_put_NN (output_bfd, 0,
3020 htab->elf.sgot->contents + off);
3021 riscv_elf_append_rela (output_bfd, htab->elf.srelgot, &outrel);
3022 if (indx == 0)
3024 BFD_ASSERT (! unresolved_reloc);
3025 bfd_put_NN (output_bfd,
3026 dtpoff (info, relocation),
3027 (htab->elf.sgot->contents
3028 + off + RISCV_ELF_WORD_BYTES));
3030 else
3032 bfd_put_NN (output_bfd, 0,
3033 (htab->elf.sgot->contents
3034 + off + RISCV_ELF_WORD_BYTES));
3035 outrel.r_info = ELFNN_R_INFO (indx, R_RISCV_TLS_DTPRELNN);
3036 outrel.r_offset += RISCV_ELF_WORD_BYTES;
3037 riscv_elf_append_rela (output_bfd, htab->elf.srelgot, &outrel);
3040 else
3042 /* If we are not emitting relocations for a
3043 general dynamic reference, then we must be in a
3044 static link or an executable link with the
3045 symbol binding locally. Mark it as belonging
3046 to module 1, the executable. */
3047 bfd_put_NN (output_bfd, 1,
3048 htab->elf.sgot->contents + off);
3049 bfd_put_NN (output_bfd,
3050 dtpoff (info, relocation),
3051 (htab->elf.sgot->contents
3052 + off + RISCV_ELF_WORD_BYTES));
3056 if (tls_type & GOT_TLS_IE)
3058 if (need_relocs)
3060 bfd_put_NN (output_bfd, 0,
3061 htab->elf.sgot->contents + off + ie_off);
3062 outrel.r_offset = sec_addr (htab->elf.sgot)
3063 + off + ie_off;
3064 outrel.r_addend = 0;
3065 if (indx == 0)
3066 outrel.r_addend = tpoff (info, relocation);
3067 outrel.r_info = ELFNN_R_INFO (indx, R_RISCV_TLS_TPRELNN);
3068 riscv_elf_append_rela (output_bfd, htab->elf.srelgot, &outrel);
3070 else
3072 bfd_put_NN (output_bfd, tpoff (info, relocation),
3073 htab->elf.sgot->contents + off + ie_off);
3077 if (tls_type & GOT_TLSDESC)
3079 /* TLSDESC is always handled by the dynamic linker and always need
3080 * a relocation. */
3081 bfd_put_NN (output_bfd, 0,
3082 htab->elf.sgot->contents + off + desc_off);
3083 outrel.r_offset = sec_addr (htab->elf.sgot)
3084 + off + desc_off;
3085 outrel.r_addend = 0;
3086 if (indx == 0)
3087 outrel.r_addend = tlsdescoff (info, relocation);
3088 outrel.r_info = ELFNN_R_INFO (indx, R_RISCV_TLSDESC);
3089 riscv_elf_append_rela (output_bfd, htab->elf.srelgot, &outrel);
3093 BFD_ASSERT (off < (bfd_vma) -2);
3094 relocation = sec_addr (htab->elf.sgot) + off;
3095 if (is_ie)
3096 relocation += ie_off;
3097 else if (is_desc)
3098 relocation += desc_off;
3099 if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
3100 relocation, r_type,
3101 false))
3102 r = bfd_reloc_overflow;
3103 unresolved_reloc = false;
3104 break;
3106 default:
3107 r = bfd_reloc_notsupported;
3110 /* Dynamic relocs are not propagated for SEC_DEBUGGING sections
3111 because such sections are not SEC_ALLOC and thus ld.so will
3112 not process them. */
3113 if (unresolved_reloc
3114 && !((input_section->flags & SEC_DEBUGGING) != 0
3115 && h->def_dynamic)
3116 && _bfd_elf_section_offset (output_bfd, info, input_section,
3117 rel->r_offset) != (bfd_vma) -1)
3119 msg = bfd_asprintf (_("%%X%%P: unresolvable %s relocation against "
3120 "symbol `%s'\n"),
3121 howto->name,
3122 h->root.root.string);
3123 r = bfd_reloc_notsupported;
3126 do_relocation:
3127 if (r == bfd_reloc_ok)
3128 r = perform_relocation (howto, rel, relocation, input_section,
3129 input_bfd, contents);
3131 /* We should have already detected the error and set message before.
3132 If the error message isn't set since the linker runs out of memory
3133 or we don't set it before, then we should set the default message
3134 with the "internal error" string here. */
3135 switch (r)
3137 case bfd_reloc_ok:
3138 continue;
3140 case bfd_reloc_overflow:
3141 info->callbacks->reloc_overflow
3142 (info, (h ? &h->root : NULL), name, howto->name,
3143 (bfd_vma) 0, input_bfd, input_section, rel->r_offset);
3144 break;
3146 case bfd_reloc_undefined:
3147 info->callbacks->undefined_symbol
3148 (info, name, input_bfd, input_section, rel->r_offset,
3149 true);
3150 break;
3152 case bfd_reloc_outofrange:
3153 if (msg == NULL)
3154 msg = _("%X%P: internal error: out of range error\n");
3155 break;
3157 case bfd_reloc_notsupported:
3158 if (msg == NULL)
3159 msg = _("%X%P: internal error: unsupported relocation error\n");
3160 break;
3162 case bfd_reloc_dangerous:
3163 /* The error message should already be set. */
3164 if (msg == NULL)
3165 msg = _("dangerous relocation error");
3166 info->callbacks->reloc_dangerous
3167 (info, msg, input_bfd, input_section, rel->r_offset);
3168 break;
3170 default:
3171 msg = _("%X%P: internal error: unknown error\n");
3172 break;
3175 /* Do not report error message for the dangerous relocation again. */
3176 if (msg && r != bfd_reloc_dangerous)
3177 info->callbacks->einfo (msg);
3179 /* We already reported the error via a callback, so don't try to report
3180 it again by returning false. That leads to spurious errors. */
3181 ret = true;
3182 goto out;
3185 ret = riscv_resolve_pcrel_lo_relocs (&pcrel_relocs);
3186 out:
3187 riscv_free_pcrel_relocs (&pcrel_relocs);
3188 return ret;
3191 /* Finish up dynamic symbol handling. We set the contents of various
3192 dynamic sections here. */
3194 static bool
3195 riscv_elf_finish_dynamic_symbol (bfd *output_bfd,
3196 struct bfd_link_info *info,
3197 struct elf_link_hash_entry *h,
3198 Elf_Internal_Sym *sym)
3200 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
3201 const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
3203 if (h->plt.offset != (bfd_vma) -1)
3205 /* We've decided to create a PLT entry for this symbol. */
3206 bfd_byte *loc;
3207 bfd_vma i, header_address, plt_idx, got_offset, got_address;
3208 uint32_t plt_entry[PLT_ENTRY_INSNS];
3209 Elf_Internal_Rela rela;
3210 asection *plt, *gotplt, *relplt;
3212 /* When building a static executable, use .iplt, .igot.plt and
3213 .rela.iplt sections for STT_GNU_IFUNC symbols. */
3214 if (htab->elf.splt != NULL)
3216 plt = htab->elf.splt;
3217 gotplt = htab->elf.sgotplt;
3218 relplt = htab->elf.srelplt;
3220 else
3222 plt = htab->elf.iplt;
3223 gotplt = htab->elf.igotplt;
3224 relplt = htab->elf.irelplt;
3227 /* This symbol has an entry in the procedure linkage table. Set
3228 it up. */
3229 if ((h->dynindx == -1
3230 && !((h->forced_local || bfd_link_executable (info))
3231 && h->def_regular
3232 && h->type == STT_GNU_IFUNC))
3233 || plt == NULL
3234 || gotplt == NULL
3235 || relplt == NULL)
3236 abort ();
3238 /* Calculate the address of the PLT header. */
3239 header_address = sec_addr (plt);
3241 /* Calculate the index of the entry and the offset of .got.plt entry.
3242 For static executables, we don't reserve anything. */
3243 if (plt == htab->elf.splt)
3245 plt_idx = (h->plt.offset - PLT_HEADER_SIZE) / PLT_ENTRY_SIZE;
3246 got_offset = GOTPLT_HEADER_SIZE + (plt_idx * GOT_ENTRY_SIZE);
3248 else
3250 plt_idx = h->plt.offset / PLT_ENTRY_SIZE;
3251 got_offset = plt_idx * GOT_ENTRY_SIZE;
3254 /* Calculate the address of the .got.plt entry. */
3255 got_address = sec_addr (gotplt) + got_offset;
3257 /* Find out where the .plt entry should go. */
3258 loc = plt->contents + h->plt.offset;
3260 /* Fill in the PLT entry itself. */
3261 if (! riscv_make_plt_entry (output_bfd, got_address,
3262 header_address + h->plt.offset,
3263 plt_entry))
3264 return false;
3266 for (i = 0; i < PLT_ENTRY_INSNS; i++)
3267 bfd_putl32 (plt_entry[i], loc + 4*i);
3269 /* Fill in the initial value of the .got.plt entry. */
3270 loc = gotplt->contents + (got_address - sec_addr (gotplt));
3271 bfd_put_NN (output_bfd, sec_addr (plt), loc);
3273 rela.r_offset = got_address;
3275 if (h->dynindx == -1
3276 || ((bfd_link_executable (info)
3277 || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
3278 && h->def_regular
3279 && h->type == STT_GNU_IFUNC))
3281 info->callbacks->minfo (_("Local IFUNC function `%s' in %pB\n"),
3282 h->root.root.string,
3283 h->root.u.def.section->owner);
3285 /* If an STT_GNU_IFUNC symbol is locally defined, generate
3286 R_RISCV_IRELATIVE instead of R_RISCV_JUMP_SLOT. */
3287 asection *sec = h->root.u.def.section;
3288 rela.r_info = ELFNN_R_INFO (0, R_RISCV_IRELATIVE);
3289 rela.r_addend = h->root.u.def.value
3290 + sec->output_section->vma
3291 + sec->output_offset;
3293 else
3295 /* Fill in the entry in the .rela.plt section. */
3296 rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_JUMP_SLOT);
3297 rela.r_addend = 0;
3300 loc = relplt->contents + plt_idx * sizeof (ElfNN_External_Rela);
3301 bed->s->swap_reloca_out (output_bfd, &rela, loc);
3303 if (!h->def_regular)
3305 /* Mark the symbol as undefined, rather than as defined in
3306 the .plt section. Leave the value alone. */
3307 sym->st_shndx = SHN_UNDEF;
3308 /* If the symbol is weak, we do need to clear the value.
3309 Otherwise, the PLT entry would provide a definition for
3310 the symbol even if the symbol wasn't defined anywhere,
3311 and so the symbol would never be NULL. */
3312 if (!h->ref_regular_nonweak)
3313 sym->st_value = 0;
3317 if (h->got.offset != (bfd_vma) -1
3318 && !(riscv_elf_hash_entry (h)->tls_type & (GOT_TLS_GD | GOT_TLS_IE | GOT_TLSDESC))
3319 && !UNDEFWEAK_NO_DYNAMIC_RELOC (info, h))
3321 asection *sgot;
3322 asection *srela;
3323 Elf_Internal_Rela rela;
3324 bool use_elf_append_rela = true;
3326 /* This symbol has an entry in the GOT. Set it up. */
3328 sgot = htab->elf.sgot;
3329 srela = htab->elf.srelgot;
3330 BFD_ASSERT (sgot != NULL && srela != NULL);
3332 rela.r_offset = sec_addr (sgot) + (h->got.offset &~ (bfd_vma) 1);
3334 /* Handle the ifunc symbol in GOT entry. */
3335 if (h->def_regular
3336 && h->type == STT_GNU_IFUNC)
3338 if (h->plt.offset == (bfd_vma) -1)
3340 /* STT_GNU_IFUNC is referenced without PLT. */
3342 if (htab->elf.splt == NULL)
3344 /* Use .rela.iplt section to store .got relocations
3345 in static executable. */
3346 srela = htab->elf.irelplt;
3348 /* Do not use riscv_elf_append_rela to add dynamic
3349 relocs. */
3350 use_elf_append_rela = false;
3353 if (SYMBOL_REFERENCES_LOCAL (info, h))
3355 info->callbacks->minfo (_("Local IFUNC function `%s' in %pB\n"),
3356 h->root.root.string,
3357 h->root.u.def.section->owner);
3359 rela.r_info = ELFNN_R_INFO (0, R_RISCV_IRELATIVE);
3360 rela.r_addend = (h->root.u.def.value
3361 + h->root.u.def.section->output_section->vma
3362 + h->root.u.def.section->output_offset);
3364 else
3366 /* Generate R_RISCV_NN. */
3367 BFD_ASSERT ((h->got.offset & 1) == 0);
3368 BFD_ASSERT (h->dynindx != -1);
3369 rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_NN);
3370 rela.r_addend = 0;
3373 else if (bfd_link_pic (info))
3375 /* Generate R_RISCV_NN. */
3376 BFD_ASSERT ((h->got.offset & 1) == 0);
3377 BFD_ASSERT (h->dynindx != -1);
3378 rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_NN);
3379 rela.r_addend = 0;
3381 else
3383 asection *plt;
3385 if (!h->pointer_equality_needed)
3386 abort ();
3388 /* For non-shared object, we can't use .got.plt, which
3389 contains the real function address if we need pointer
3390 equality. We load the GOT entry with the PLT entry. */
3391 plt = htab->elf.splt ? htab->elf.splt : htab->elf.iplt;
3392 bfd_put_NN (output_bfd, (plt->output_section->vma
3393 + plt->output_offset
3394 + h->plt.offset),
3395 htab->elf.sgot->contents
3396 + (h->got.offset & ~(bfd_vma) 1));
3397 return true;
3400 else if (bfd_link_pic (info)
3401 && SYMBOL_REFERENCES_LOCAL (info, h))
3403 /* If this is a local symbol reference, we just want to emit
3404 a RELATIVE reloc. This can happen if it is a -Bsymbolic link,
3405 or a pie link, or the symbol was forced to be local because
3406 of a version file. The entry in the global offset table will
3407 already have been initialized in the relocate_section function. */
3408 BFD_ASSERT ((h->got.offset & 1) != 0);
3409 asection *sec = h->root.u.def.section;
3410 rela.r_info = ELFNN_R_INFO (0, R_RISCV_RELATIVE);
3411 rela.r_addend = (h->root.u.def.value
3412 + sec->output_section->vma
3413 + sec->output_offset);
3415 else
3417 BFD_ASSERT ((h->got.offset & 1) == 0);
3418 BFD_ASSERT (h->dynindx != -1);
3419 rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_NN);
3420 rela.r_addend = 0;
3423 bfd_put_NN (output_bfd, 0,
3424 sgot->contents + (h->got.offset & ~(bfd_vma) 1));
3426 if (use_elf_append_rela)
3427 riscv_elf_append_rela (output_bfd, srela, &rela);
3428 else
3430 /* Use riscv_elf_append_rela to add the dynamic relocs into
3431 .rela.iplt may cause the overwrite problems. Since we insert
3432 the relocs for PLT didn't handle the reloc_index of .rela.iplt,
3433 but the riscv_elf_append_rela adds the relocs to the place
3434 that are calculated from the reloc_index (in seqential).
3436 One solution is that add these dynamic relocs (GOT IFUNC)
3437 from the last of .rela.iplt section. */
3438 bfd_vma iplt_idx = htab->last_iplt_index--;
3439 bfd_byte *loc = srela->contents
3440 + iplt_idx * sizeof (ElfNN_External_Rela);
3441 bed->s->swap_reloca_out (output_bfd, &rela, loc);
3445 if (h->needs_copy)
3447 Elf_Internal_Rela rela;
3448 asection *s;
3450 /* This symbols needs a copy reloc. Set it up. */
3451 BFD_ASSERT (h->dynindx != -1);
3453 rela.r_offset = sec_addr (h->root.u.def.section) + h->root.u.def.value;
3454 rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_COPY);
3455 rela.r_addend = 0;
3456 if (h->root.u.def.section == htab->elf.sdynrelro)
3457 s = htab->elf.sreldynrelro;
3458 else
3459 s = htab->elf.srelbss;
3460 riscv_elf_append_rela (output_bfd, s, &rela);
3463 /* Mark some specially defined symbols as absolute. */
3464 if (h == htab->elf.hdynamic
3465 || (h == htab->elf.hgot || h == htab->elf.hplt))
3466 sym->st_shndx = SHN_ABS;
3468 return true;
3471 /* Finish up local dynamic symbol handling. We set the contents of
3472 various dynamic sections here. */
3474 static int
3475 riscv_elf_finish_local_dynamic_symbol (void **slot, void *inf)
3477 struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) *slot;
3478 struct bfd_link_info *info = (struct bfd_link_info *) inf;
3480 return riscv_elf_finish_dynamic_symbol (info->output_bfd, info, h, NULL);
3483 /* Finish up the dynamic sections. */
3485 static bool
3486 riscv_finish_dyn (bfd *output_bfd, struct bfd_link_info *info,
3487 bfd *dynobj, asection *sdyn)
3489 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
3490 const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
3491 size_t dynsize = bed->s->sizeof_dyn;
3492 bfd_byte *dyncon, *dynconend;
3494 dynconend = sdyn->contents + sdyn->size;
3495 for (dyncon = sdyn->contents; dyncon < dynconend; dyncon += dynsize)
3497 Elf_Internal_Dyn dyn;
3498 asection *s;
3500 bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
3502 switch (dyn.d_tag)
3504 case DT_PLTGOT:
3505 s = htab->elf.sgotplt;
3506 dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
3507 break;
3508 case DT_JMPREL:
3509 s = htab->elf.srelplt;
3510 dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
3511 break;
3512 case DT_PLTRELSZ:
3513 s = htab->elf.srelplt;
3514 dyn.d_un.d_val = s->size;
3515 break;
3516 default:
3517 continue;
3520 bed->s->swap_dyn_out (output_bfd, &dyn, dyncon);
3522 return true;
3525 static bool
3526 riscv_elf_finish_dynamic_sections (bfd *output_bfd,
3527 struct bfd_link_info *info)
3529 bfd *dynobj;
3530 asection *sdyn;
3531 struct riscv_elf_link_hash_table *htab;
3533 htab = riscv_elf_hash_table (info);
3534 BFD_ASSERT (htab != NULL);
3535 dynobj = htab->elf.dynobj;
3537 sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3539 if (elf_hash_table (info)->dynamic_sections_created)
3541 asection *splt;
3542 bool ret;
3544 splt = htab->elf.splt;
3545 BFD_ASSERT (splt != NULL && sdyn != NULL);
3547 ret = riscv_finish_dyn (output_bfd, info, dynobj, sdyn);
3549 if (!ret)
3550 return ret;
3552 /* Fill in the head and tail entries in the procedure linkage table. */
3553 if (splt->size > 0)
3555 int i;
3556 uint32_t plt_header[PLT_HEADER_INSNS];
3557 ret = riscv_make_plt_header (output_bfd,
3558 sec_addr (htab->elf.sgotplt),
3559 sec_addr (splt), plt_header);
3560 if (!ret)
3561 return ret;
3563 for (i = 0; i < PLT_HEADER_INSNS; i++)
3564 bfd_putl32 (plt_header[i], splt->contents + 4*i);
3566 elf_section_data (splt->output_section)->this_hdr.sh_entsize
3567 = PLT_ENTRY_SIZE;
3571 if (htab->elf.sgotplt)
3573 asection *output_section = htab->elf.sgotplt->output_section;
3575 if (bfd_is_abs_section (output_section))
3577 (*_bfd_error_handler)
3578 (_("discarded output section: `%pA'"), htab->elf.sgotplt);
3579 return false;
3582 if (htab->elf.sgotplt->size > 0)
3584 /* Write the first two entries in .got.plt, needed for the dynamic
3585 linker. */
3586 bfd_put_NN (output_bfd, (bfd_vma) -1, htab->elf.sgotplt->contents);
3587 bfd_put_NN (output_bfd, (bfd_vma) 0,
3588 htab->elf.sgotplt->contents + GOT_ENTRY_SIZE);
3591 elf_section_data (output_section)->this_hdr.sh_entsize = GOT_ENTRY_SIZE;
3594 if (htab->elf.sgot)
3596 asection *output_section = htab->elf.sgot->output_section;
3598 if (htab->elf.sgot->size > 0)
3600 /* Set the first entry in the global offset table to the address of
3601 the dynamic section. */
3602 bfd_vma val = sdyn ? sec_addr (sdyn) : 0;
3603 bfd_put_NN (output_bfd, val, htab->elf.sgot->contents);
3606 elf_section_data (output_section)->this_hdr.sh_entsize = GOT_ENTRY_SIZE;
3609 /* Fill PLT and GOT entries for local STT_GNU_IFUNC symbols. */
3610 htab_traverse (htab->loc_hash_table,
3611 riscv_elf_finish_local_dynamic_symbol,
3612 info);
3614 return true;
3617 /* Return address for Ith PLT stub in section PLT, for relocation REL
3618 or (bfd_vma) -1 if it should not be included. */
3620 static bfd_vma
3621 riscv_elf_plt_sym_val (bfd_vma i, const asection *plt,
3622 const arelent *rel ATTRIBUTE_UNUSED)
3624 return plt->vma + PLT_HEADER_SIZE + i * PLT_ENTRY_SIZE;
3627 static enum elf_reloc_type_class
3628 riscv_reloc_type_class (const struct bfd_link_info *info ATTRIBUTE_UNUSED,
3629 const asection *rel_sec ATTRIBUTE_UNUSED,
3630 const Elf_Internal_Rela *rela)
3632 switch (ELFNN_R_TYPE (rela->r_info))
3634 case R_RISCV_RELATIVE:
3635 return reloc_class_relative;
3636 case R_RISCV_JUMP_SLOT:
3637 return reloc_class_plt;
3638 case R_RISCV_COPY:
3639 return reloc_class_copy;
3640 default:
3641 return reloc_class_normal;
3645 /* Given the ELF header flags in FLAGS, it returns a string that describes the
3646 float ABI. */
3648 static const char *
3649 riscv_float_abi_string (flagword flags)
3651 switch (flags & EF_RISCV_FLOAT_ABI)
3653 case EF_RISCV_FLOAT_ABI_SOFT:
3654 return "soft-float";
3655 break;
3656 case EF_RISCV_FLOAT_ABI_SINGLE:
3657 return "single-float";
3658 break;
3659 case EF_RISCV_FLOAT_ABI_DOUBLE:
3660 return "double-float";
3661 break;
3662 case EF_RISCV_FLOAT_ABI_QUAD:
3663 return "quad-float";
3664 break;
3665 default:
3666 abort ();
3670 /* The information of architecture elf attributes. */
3671 static riscv_subset_list_t in_subsets;
3672 static riscv_subset_list_t out_subsets;
3673 static riscv_subset_list_t merged_subsets;
3675 /* Predicator for standard extension. */
3677 static bool
3678 riscv_std_ext_p (const char *name)
3680 return (strlen (name) == 1) && (name[0] != 'x') && (name[0] != 's');
3683 /* Update the output subset's version to match the input when the input
3684 subset's version is newer. */
3686 static void
3687 riscv_update_subset_version (struct riscv_subset_t *in,
3688 struct riscv_subset_t *out)
3690 if (in == NULL || out == NULL)
3691 return;
3693 /* Update the output ISA versions to the newest ones, but otherwise don't
3694 provide any errors or warnings about mis-matched ISA versions as it's
3695 generally too tricky to check for these at link time. */
3696 if ((in->major_version > out->major_version)
3697 || (in->major_version == out->major_version
3698 && in->minor_version > out->minor_version)
3699 || (out->major_version == RISCV_UNKNOWN_VERSION))
3701 out->major_version = in->major_version;
3702 out->minor_version = in->minor_version;
3706 /* Return true if subset is 'i' or 'e'. */
3708 static bool
3709 riscv_i_or_e_p (bfd *ibfd,
3710 const char *arch,
3711 struct riscv_subset_t *subset)
3713 if ((strcasecmp (subset->name, "e") != 0)
3714 && (strcasecmp (subset->name, "i") != 0))
3716 _bfd_error_handler
3717 (_("error: %pB: corrupted ISA string '%s'. "
3718 "First letter should be 'i' or 'e' but got '%s'"),
3719 ibfd, arch, subset->name);
3720 return false;
3722 return true;
3725 /* Merge standard extensions.
3727 Return Value:
3728 Return FALSE if failed to merge.
3730 Arguments:
3731 `bfd`: bfd handler.
3732 `in_arch`: Raw ISA string for input object.
3733 `out_arch`: Raw ISA string for output object.
3734 `pin`: Subset list for input object.
3735 `pout`: Subset list for output object. */
3737 static bool
3738 riscv_merge_std_ext (bfd *ibfd,
3739 const char *in_arch,
3740 const char *out_arch,
3741 struct riscv_subset_t **pin,
3742 struct riscv_subset_t **pout)
3744 const char *standard_exts = "mafdqlcbjtpvnh";
3745 const char *p;
3746 struct riscv_subset_t *in = *pin;
3747 struct riscv_subset_t *out = *pout;
3749 /* First letter should be 'i' or 'e'. */
3750 if (!riscv_i_or_e_p (ibfd, in_arch, in))
3751 return false;
3753 if (!riscv_i_or_e_p (ibfd, out_arch, out))
3754 return false;
3756 if (strcasecmp (in->name, out->name) != 0)
3758 /* TODO: We might allow merge 'i' with 'e'. */
3759 _bfd_error_handler
3760 (_("error: %pB: mis-matched ISA string to merge '%s' and '%s'"),
3761 ibfd, in->name, out->name);
3762 return false;
3765 riscv_update_subset_version(in, out);
3766 riscv_add_subset (&merged_subsets,
3767 out->name, out->major_version, out->minor_version);
3769 in = in->next;
3770 out = out->next;
3772 /* Handle standard extension first. */
3773 for (p = standard_exts; *p; ++p)
3775 struct riscv_subset_t *ext_in, *ext_out, *ext_merged;
3776 char find_ext[2] = {*p, '\0'};
3777 bool find_in, find_out;
3779 find_in = riscv_lookup_subset (&in_subsets, find_ext, &ext_in);
3780 find_out = riscv_lookup_subset (&out_subsets, find_ext, &ext_out);
3782 if (!find_in && !find_out)
3783 continue;
3785 if (find_in && find_out)
3786 riscv_update_subset_version(ext_in, ext_out);
3788 ext_merged = find_out ? ext_out : ext_in;
3789 riscv_add_subset (&merged_subsets, ext_merged->name,
3790 ext_merged->major_version, ext_merged->minor_version);
3793 /* Skip all standard extensions. */
3794 while ((in != NULL) && riscv_std_ext_p (in->name)) in = in->next;
3795 while ((out != NULL) && riscv_std_ext_p (out->name)) out = out->next;
3797 *pin = in;
3798 *pout = out;
3800 return true;
3803 /* Merge multi letter extensions. PIN is a pointer to the head of the input
3804 object subset list. Likewise for POUT and the output object. Return TRUE
3805 on success and FALSE when a conflict is found. */
3807 static bool
3808 riscv_merge_multi_letter_ext (riscv_subset_t **pin,
3809 riscv_subset_t **pout)
3811 riscv_subset_t *in = *pin;
3812 riscv_subset_t *out = *pout;
3813 riscv_subset_t *tail;
3815 int cmp;
3817 while (in && out)
3819 cmp = riscv_compare_subsets (in->name, out->name);
3821 if (cmp < 0)
3823 /* `in' comes before `out', append `in' and increment. */
3824 riscv_add_subset (&merged_subsets, in->name, in->major_version,
3825 in->minor_version);
3826 in = in->next;
3828 else if (cmp > 0)
3830 /* `out' comes before `in', append `out' and increment. */
3831 riscv_add_subset (&merged_subsets, out->name, out->major_version,
3832 out->minor_version);
3833 out = out->next;
3835 else
3837 /* Both present, check version and increment both. */
3838 riscv_update_subset_version (in, out);
3840 riscv_add_subset (&merged_subsets, out->name, out->major_version,
3841 out->minor_version);
3842 out = out->next;
3843 in = in->next;
3847 if (in || out)
3849 /* If we're here, either `in' or `out' is running longer than
3850 the other. So, we need to append the corresponding tail. */
3851 tail = in ? in : out;
3852 while (tail)
3854 riscv_add_subset (&merged_subsets, tail->name, tail->major_version,
3855 tail->minor_version);
3856 tail = tail->next;
3860 return true;
3863 /* Merge Tag_RISCV_arch attribute. */
3865 static char *
3866 riscv_merge_arch_attr_info (bfd *ibfd, char *in_arch, char *out_arch)
3868 riscv_subset_t *in, *out;
3869 char *merged_arch_str;
3871 unsigned xlen_in, xlen_out;
3872 merged_subsets.head = NULL;
3873 merged_subsets.tail = NULL;
3875 riscv_parse_subset_t riscv_rps_ld_in =
3876 {&in_subsets, _bfd_error_handler, &xlen_in, NULL, false};
3877 riscv_parse_subset_t riscv_rps_ld_out =
3878 {&out_subsets, _bfd_error_handler, &xlen_out, NULL, false};
3880 if (in_arch == NULL && out_arch == NULL)
3881 return NULL;
3882 if (in_arch == NULL && out_arch != NULL)
3883 return out_arch;
3884 if (in_arch != NULL && out_arch == NULL)
3885 return in_arch;
3887 /* Parse subset from ISA string. */
3888 if (!riscv_parse_subset (&riscv_rps_ld_in, in_arch))
3889 return NULL;
3890 if (!riscv_parse_subset (&riscv_rps_ld_out, out_arch))
3891 return NULL;
3893 /* Checking XLEN. */
3894 if (xlen_out != xlen_in)
3896 _bfd_error_handler
3897 (_("error: %pB: ISA string of input (%s) doesn't match "
3898 "output (%s)"), ibfd, in_arch, out_arch);
3899 return NULL;
3902 /* Merge subset list. */
3903 in = in_subsets.head;
3904 out = out_subsets.head;
3906 /* Merge standard extension. */
3907 if (!riscv_merge_std_ext (ibfd, in_arch, out_arch, &in, &out))
3908 return NULL;
3910 /* Merge all non-single letter extensions with single call. */
3911 if (!riscv_merge_multi_letter_ext (&in, &out))
3912 return NULL;
3914 if (xlen_in != xlen_out)
3916 _bfd_error_handler
3917 (_("error: %pB: XLEN of input (%u) doesn't match "
3918 "output (%u)"), ibfd, xlen_in, xlen_out);
3919 return NULL;
3922 if (xlen_in != ARCH_SIZE)
3924 _bfd_error_handler
3925 (_("error: %pB: unsupported XLEN (%u), you might be "
3926 "using wrong emulation"), ibfd, xlen_in);
3927 return NULL;
3930 merged_arch_str = riscv_arch_str (ARCH_SIZE, &merged_subsets);
3932 /* Release the subset lists. */
3933 riscv_release_subset_list (&in_subsets);
3934 riscv_release_subset_list (&out_subsets);
3935 riscv_release_subset_list (&merged_subsets);
3937 return merged_arch_str;
3940 /* Merge object attributes from IBFD into output_bfd of INFO.
3941 Raise an error if there are conflicting attributes. */
3943 static bool
3944 riscv_merge_attributes (bfd *ibfd, struct bfd_link_info *info)
3946 bfd *obfd = info->output_bfd;
3947 obj_attribute *in_attr;
3948 obj_attribute *out_attr;
3949 bool result = true;
3950 bool priv_attrs_merged = false;
3951 const char *sec_name = get_elf_backend_data (ibfd)->obj_attrs_section;
3952 unsigned int i;
3954 /* Skip linker created files. */
3955 if (ibfd->flags & BFD_LINKER_CREATED)
3956 return true;
3958 /* Skip any input that doesn't have an attribute section.
3959 This enables to link object files without attribute section with
3960 any others. */
3961 if (bfd_get_section_by_name (ibfd, sec_name) == NULL)
3962 return true;
3964 if (!elf_known_obj_attributes_proc (obfd)[0].i)
3966 /* This is the first object. Copy the attributes. */
3967 _bfd_elf_copy_obj_attributes (ibfd, obfd);
3969 out_attr = elf_known_obj_attributes_proc (obfd);
3971 /* Use the Tag_null value to indicate the attributes have been
3972 initialized. */
3973 out_attr[0].i = 1;
3975 return true;
3978 in_attr = elf_known_obj_attributes_proc (ibfd);
3979 out_attr = elf_known_obj_attributes_proc (obfd);
3981 for (i = LEAST_KNOWN_OBJ_ATTRIBUTE; i < NUM_KNOWN_OBJ_ATTRIBUTES; i++)
3983 switch (i)
3985 case Tag_RISCV_arch:
3986 if (!out_attr[Tag_RISCV_arch].s)
3987 out_attr[Tag_RISCV_arch].s = in_attr[Tag_RISCV_arch].s;
3988 else if (in_attr[Tag_RISCV_arch].s
3989 && out_attr[Tag_RISCV_arch].s)
3991 /* Check compatible. */
3992 char *merged_arch =
3993 riscv_merge_arch_attr_info (ibfd,
3994 in_attr[Tag_RISCV_arch].s,
3995 out_attr[Tag_RISCV_arch].s);
3996 if (merged_arch == NULL)
3998 result = false;
3999 out_attr[Tag_RISCV_arch].s = "";
4001 else
4002 out_attr[Tag_RISCV_arch].s = merged_arch;
4004 break;
4006 case Tag_RISCV_priv_spec:
4007 case Tag_RISCV_priv_spec_minor:
4008 case Tag_RISCV_priv_spec_revision:
4009 /* If we have handled the privileged elf attributes, then skip it. */
4010 if (!priv_attrs_merged)
4012 unsigned int Tag_a = Tag_RISCV_priv_spec;
4013 unsigned int Tag_b = Tag_RISCV_priv_spec_minor;
4014 unsigned int Tag_c = Tag_RISCV_priv_spec_revision;
4015 enum riscv_spec_class in_priv_spec = PRIV_SPEC_CLASS_NONE;
4016 enum riscv_spec_class out_priv_spec = PRIV_SPEC_CLASS_NONE;
4018 /* Get the privileged spec class from elf attributes. */
4019 riscv_get_priv_spec_class_from_numbers (in_attr[Tag_a].i,
4020 in_attr[Tag_b].i,
4021 in_attr[Tag_c].i,
4022 &in_priv_spec);
4023 riscv_get_priv_spec_class_from_numbers (out_attr[Tag_a].i,
4024 out_attr[Tag_b].i,
4025 out_attr[Tag_c].i,
4026 &out_priv_spec);
4028 /* Allow to link the object without the privileged specs. */
4029 if (out_priv_spec == PRIV_SPEC_CLASS_NONE)
4031 out_attr[Tag_a].i = in_attr[Tag_a].i;
4032 out_attr[Tag_b].i = in_attr[Tag_b].i;
4033 out_attr[Tag_c].i = in_attr[Tag_c].i;
4035 else if (in_priv_spec != PRIV_SPEC_CLASS_NONE
4036 && in_priv_spec != out_priv_spec)
4038 _bfd_error_handler
4039 (_("warning: %pB use privileged spec version %u.%u.%u but "
4040 "the output use version %u.%u.%u"),
4041 ibfd,
4042 in_attr[Tag_a].i,
4043 in_attr[Tag_b].i,
4044 in_attr[Tag_c].i,
4045 out_attr[Tag_a].i,
4046 out_attr[Tag_b].i,
4047 out_attr[Tag_c].i);
4049 /* The privileged spec v1.9.1 can not be linked with others
4050 since the conflicts, so we plan to drop it in a year or
4051 two. */
4052 if (in_priv_spec == PRIV_SPEC_CLASS_1P9P1
4053 || out_priv_spec == PRIV_SPEC_CLASS_1P9P1)
4055 _bfd_error_handler
4056 (_("warning: privileged spec version 1.9.1 can not be "
4057 "linked with other spec versions"));
4060 /* Update the output privileged spec to the newest one. */
4061 if (in_priv_spec > out_priv_spec)
4063 out_attr[Tag_a].i = in_attr[Tag_a].i;
4064 out_attr[Tag_b].i = in_attr[Tag_b].i;
4065 out_attr[Tag_c].i = in_attr[Tag_c].i;
4068 priv_attrs_merged = true;
4070 break;
4072 case Tag_RISCV_unaligned_access:
4073 out_attr[i].i |= in_attr[i].i;
4074 break;
4076 case Tag_RISCV_stack_align:
4077 if (out_attr[i].i == 0)
4078 out_attr[i].i = in_attr[i].i;
4079 else if (in_attr[i].i != 0
4080 && out_attr[i].i != 0
4081 && out_attr[i].i != in_attr[i].i)
4083 _bfd_error_handler
4084 (_("error: %pB use %u-byte stack aligned but the output "
4085 "use %u-byte stack aligned"),
4086 ibfd, in_attr[i].i, out_attr[i].i);
4087 result = false;
4089 break;
4091 default:
4092 result &= _bfd_elf_merge_unknown_attribute_low (ibfd, obfd, i);
4095 /* If out_attr was copied from in_attr then it won't have a type yet. */
4096 if (in_attr[i].type && !out_attr[i].type)
4097 out_attr[i].type = in_attr[i].type;
4100 /* Merge Tag_compatibility attributes and any common GNU ones. */
4101 if (!_bfd_elf_merge_object_attributes (ibfd, info))
4102 return false;
4104 /* Check for any attributes not known on RISC-V. */
4105 result &= _bfd_elf_merge_unknown_attribute_list (ibfd, obfd);
4107 return result;
4110 /* Merge backend specific data from an object file to the output
4111 object file when linking. */
4113 static bool
4114 _bfd_riscv_elf_merge_private_bfd_data (bfd *ibfd, struct bfd_link_info *info)
4116 bfd *obfd = info->output_bfd;
4117 flagword new_flags, old_flags;
4119 if (!is_riscv_elf (ibfd) || !is_riscv_elf (obfd))
4120 return true;
4122 if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
4124 (*_bfd_error_handler)
4125 (_("%pB: ABI is incompatible with that of the selected emulation:\n"
4126 " target emulation `%s' does not match `%s'"),
4127 ibfd, bfd_get_target (ibfd), bfd_get_target (obfd));
4128 return false;
4131 if (!_bfd_elf_merge_object_attributes (ibfd, info))
4132 return false;
4134 if (!riscv_merge_attributes (ibfd, info))
4135 return false;
4137 /* Check to see if the input BFD actually contains any sections. If not,
4138 its flags may not have been initialized either, but it cannot actually
4139 cause any incompatibility. Do not short-circuit dynamic objects; their
4140 section list may be emptied by elf_link_add_object_symbols.
4142 Also check to see if there are no code sections in the input. In this
4143 case, there is no need to check for code specific flags. */
4144 if (!(ibfd->flags & DYNAMIC))
4146 bool null_input_bfd = true;
4147 bool only_data_sections = true;
4148 asection *sec;
4150 for (sec = ibfd->sections; sec != NULL; sec = sec->next)
4152 null_input_bfd = false;
4154 if ((bfd_section_flags (sec)
4155 & (SEC_LOAD | SEC_CODE | SEC_HAS_CONTENTS))
4156 == (SEC_LOAD | SEC_CODE | SEC_HAS_CONTENTS))
4158 only_data_sections = false;
4159 break;
4163 if (null_input_bfd || only_data_sections)
4164 return true;
4167 new_flags = elf_elfheader (ibfd)->e_flags;
4168 old_flags = elf_elfheader (obfd)->e_flags;
4170 if (!elf_flags_init (obfd))
4172 elf_flags_init (obfd) = true;
4173 elf_elfheader (obfd)->e_flags = new_flags;
4174 return true;
4177 /* Disallow linking different float ABIs. */
4178 if ((old_flags ^ new_flags) & EF_RISCV_FLOAT_ABI)
4180 (*_bfd_error_handler)
4181 (_("%pB: can't link %s modules with %s modules"), ibfd,
4182 riscv_float_abi_string (new_flags),
4183 riscv_float_abi_string (old_flags));
4184 goto fail;
4187 /* Disallow linking RVE and non-RVE. */
4188 if ((old_flags ^ new_flags) & EF_RISCV_RVE)
4190 (*_bfd_error_handler)
4191 (_("%pB: can't link RVE with other target"), ibfd);
4192 goto fail;
4195 /* Allow linking RVC and non-RVC, and keep the RVC flag. */
4196 elf_elfheader (obfd)->e_flags |= new_flags & EF_RISCV_RVC;
4198 /* Allow linking TSO and non-TSO, and keep the TSO flag. */
4199 elf_elfheader (obfd)->e_flags |= new_flags & EF_RISCV_TSO;
4201 return true;
4203 fail:
4204 bfd_set_error (bfd_error_bad_value);
4205 return false;
4208 /* A second format for recording PC-relative hi relocations. This stores the
4209 information required to relax them to GP-relative addresses. */
4211 typedef struct riscv_pcgp_hi_reloc riscv_pcgp_hi_reloc;
4212 struct riscv_pcgp_hi_reloc
4214 bfd_vma hi_sec_off;
4215 bfd_vma hi_addend;
4216 bfd_vma hi_addr;
4217 unsigned hi_sym;
4218 asection *sym_sec;
4219 bool undefined_weak;
4220 riscv_pcgp_hi_reloc *next;
4223 typedef struct riscv_pcgp_lo_reloc riscv_pcgp_lo_reloc;
4224 struct riscv_pcgp_lo_reloc
4226 bfd_vma hi_sec_off;
4227 riscv_pcgp_lo_reloc *next;
4230 typedef struct
4232 riscv_pcgp_hi_reloc *hi;
4233 riscv_pcgp_lo_reloc *lo;
4234 } riscv_pcgp_relocs;
4236 /* Initialize the pcgp reloc info in P. */
4238 static bool
4239 riscv_init_pcgp_relocs (riscv_pcgp_relocs *p)
4241 p->hi = NULL;
4242 p->lo = NULL;
4243 return true;
4246 /* Free the pcgp reloc info in P. */
4248 static void
4249 riscv_free_pcgp_relocs (riscv_pcgp_relocs *p,
4250 bfd *abfd ATTRIBUTE_UNUSED,
4251 asection *sec ATTRIBUTE_UNUSED)
4253 riscv_pcgp_hi_reloc *c;
4254 riscv_pcgp_lo_reloc *l;
4256 for (c = p->hi; c != NULL; )
4258 riscv_pcgp_hi_reloc *next = c->next;
4259 free (c);
4260 c = next;
4263 for (l = p->lo; l != NULL; )
4265 riscv_pcgp_lo_reloc *next = l->next;
4266 free (l);
4267 l = next;
4271 /* Record pcgp hi part reloc info in P, using HI_SEC_OFF as the lookup index.
4272 The HI_ADDEND, HI_ADDR, HI_SYM, and SYM_SEC args contain info required to
4273 relax the corresponding lo part reloc. */
4275 static bool
4276 riscv_record_pcgp_hi_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off,
4277 bfd_vma hi_addend, bfd_vma hi_addr,
4278 unsigned hi_sym, asection *sym_sec,
4279 bool undefined_weak)
4281 riscv_pcgp_hi_reloc *new = bfd_malloc (sizeof (*new));
4282 if (!new)
4283 return false;
4284 new->hi_sec_off = hi_sec_off;
4285 new->hi_addend = hi_addend;
4286 new->hi_addr = hi_addr;
4287 new->hi_sym = hi_sym;
4288 new->sym_sec = sym_sec;
4289 new->undefined_weak = undefined_weak;
4290 new->next = p->hi;
4291 p->hi = new;
4292 return true;
4295 /* Look up hi part pcgp reloc info in P, using HI_SEC_OFF as the lookup index.
4296 This is used by a lo part reloc to find the corresponding hi part reloc. */
4298 static riscv_pcgp_hi_reloc *
4299 riscv_find_pcgp_hi_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off)
4301 riscv_pcgp_hi_reloc *c;
4303 for (c = p->hi; c != NULL; c = c->next)
4304 if (c->hi_sec_off == hi_sec_off)
4305 return c;
4306 return NULL;
4309 /* Record pcgp lo part reloc info in P, using HI_SEC_OFF as the lookup info.
4310 This is used to record relocs that can't be relaxed. */
4312 static bool
4313 riscv_record_pcgp_lo_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off)
4315 riscv_pcgp_lo_reloc *new = bfd_malloc (sizeof (*new));
4316 if (!new)
4317 return false;
4318 new->hi_sec_off = hi_sec_off;
4319 new->next = p->lo;
4320 p->lo = new;
4321 return true;
4324 /* Look up lo part pcgp reloc info in P, using HI_SEC_OFF as the lookup index.
4325 This is used by a hi part reloc to find the corresponding lo part reloc. */
4327 static bool
4328 riscv_find_pcgp_lo_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off)
4330 riscv_pcgp_lo_reloc *c;
4332 for (c = p->lo; c != NULL; c = c->next)
4333 if (c->hi_sec_off == hi_sec_off)
4334 return true;
4335 return false;
4338 static void
4339 riscv_update_pcgp_relocs (riscv_pcgp_relocs *p, asection *deleted_sec,
4340 bfd_vma deleted_addr, size_t deleted_count)
4342 /* Bytes have already been deleted and toaddr should match the old section
4343 size for our checks, so adjust it here. */
4344 bfd_vma toaddr = deleted_sec->size + deleted_count;
4345 riscv_pcgp_lo_reloc *l;
4346 riscv_pcgp_hi_reloc *h;
4348 /* Update section offsets of corresponding pcrel_hi relocs for the pcrel_lo
4349 entries where they occur after the deleted bytes. */
4350 for (l = p->lo; l != NULL; l = l->next)
4351 if (l->hi_sec_off > deleted_addr
4352 && l->hi_sec_off < toaddr)
4353 l->hi_sec_off -= deleted_count;
4355 /* Update both section offsets, and symbol values of pcrel_hi relocs where
4356 these values occur after the deleted bytes. */
4357 for (h = p->hi; h != NULL; h = h->next)
4359 if (h->hi_sec_off > deleted_addr
4360 && h->hi_sec_off < toaddr)
4361 h->hi_sec_off -= deleted_count;
4362 if (h->sym_sec == deleted_sec
4363 && h->hi_addr > deleted_addr
4364 && h->hi_addr < toaddr)
4365 h->hi_addr -= deleted_count;
4369 /* Delete some bytes, adjust relcocations and symbol table from a section. */
4371 static bool
4372 _riscv_relax_delete_bytes (bfd *abfd,
4373 asection *sec,
4374 bfd_vma addr,
4375 size_t count,
4376 struct bfd_link_info *link_info,
4377 riscv_pcgp_relocs *p,
4378 bfd_vma delete_total,
4379 bfd_vma toaddr)
4381 unsigned int i, symcount;
4382 struct elf_link_hash_entry **sym_hashes = elf_sym_hashes (abfd);
4383 Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
4384 unsigned int sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
4385 struct bfd_elf_section_data *data = elf_section_data (sec);
4386 bfd_byte *contents = data->this_hdr.contents;
4387 size_t bytes_to_move = toaddr - addr - count;
4389 /* Actually delete the bytes. */
4390 sec->size -= count;
4391 memmove (contents + addr, contents + addr + count + delete_total, bytes_to_move);
4393 /* Still adjust relocations and symbols in non-linear times. */
4394 toaddr = sec->size + count;
4396 /* Adjust the location of all of the relocs. Note that we need not
4397 adjust the addends, since all PC-relative references must be against
4398 symbols, which we will adjust below. */
4399 for (i = 0; i < sec->reloc_count; i++)
4400 if (data->relocs[i].r_offset > addr && data->relocs[i].r_offset < toaddr)
4401 data->relocs[i].r_offset -= count;
4403 /* Adjust the hi_sec_off, and the hi_addr of any entries in the pcgp relocs
4404 table for which these values occur after the deleted bytes. */
4405 if (p)
4406 riscv_update_pcgp_relocs (p, sec, addr, count);
4408 /* Adjust the local symbols defined in this section. */
4409 for (i = 0; i < symtab_hdr->sh_info; i++)
4411 Elf_Internal_Sym *sym = (Elf_Internal_Sym *) symtab_hdr->contents + i;
4412 if (sym->st_shndx == sec_shndx)
4414 /* If the symbol is in the range of memory we just moved, we
4415 have to adjust its value. */
4416 if (sym->st_value > addr && sym->st_value <= toaddr)
4417 sym->st_value -= count;
4419 /* If the symbol *spans* the bytes we just deleted (i.e. its
4420 *end* is in the moved bytes but its *start* isn't), then we
4421 must adjust its size.
4423 This test needs to use the original value of st_value, otherwise
4424 we might accidentally decrease size when deleting bytes right
4425 before the symbol. But since deleted relocs can't span across
4426 symbols, we can't have both a st_value and a st_size decrease,
4427 so it is simpler to just use an else. */
4428 else if (sym->st_value <= addr
4429 && sym->st_value + sym->st_size > addr
4430 && sym->st_value + sym->st_size <= toaddr)
4431 sym->st_size -= count;
4435 /* Now adjust the global symbols defined in this section. */
4436 symcount = ((symtab_hdr->sh_size / sizeof (ElfNN_External_Sym))
4437 - symtab_hdr->sh_info);
4439 for (i = 0; i < symcount; i++)
4441 struct elf_link_hash_entry *sym_hash = sym_hashes[i];
4443 /* The '--wrap SYMBOL' option is causing a pain when the object file,
4444 containing the definition of __wrap_SYMBOL, includes a direct
4445 call to SYMBOL as well. Since both __wrap_SYMBOL and SYMBOL reference
4446 the same symbol (which is __wrap_SYMBOL), but still exist as two
4447 different symbols in 'sym_hashes', we don't want to adjust
4448 the global symbol __wrap_SYMBOL twice.
4450 The same problem occurs with symbols that are versioned_hidden, as
4451 foo becomes an alias for foo@BAR, and hence they need the same
4452 treatment. */
4453 if (link_info->wrap_hash != NULL
4454 || sym_hash->versioned != unversioned)
4456 struct elf_link_hash_entry **cur_sym_hashes;
4458 /* Loop only over the symbols which have already been checked. */
4459 for (cur_sym_hashes = sym_hashes; cur_sym_hashes < &sym_hashes[i];
4460 cur_sym_hashes++)
4462 /* If the current symbol is identical to 'sym_hash', that means
4463 the symbol was already adjusted (or at least checked). */
4464 if (*cur_sym_hashes == sym_hash)
4465 break;
4467 /* Don't adjust the symbol again. */
4468 if (cur_sym_hashes < &sym_hashes[i])
4469 continue;
4472 if ((sym_hash->root.type == bfd_link_hash_defined
4473 || sym_hash->root.type == bfd_link_hash_defweak)
4474 && sym_hash->root.u.def.section == sec)
4476 /* As above, adjust the value if needed. */
4477 if (sym_hash->root.u.def.value > addr
4478 && sym_hash->root.u.def.value <= toaddr)
4479 sym_hash->root.u.def.value -= count;
4481 /* As above, adjust the size if needed. */
4482 else if (sym_hash->root.u.def.value <= addr
4483 && sym_hash->root.u.def.value + sym_hash->size > addr
4484 && sym_hash->root.u.def.value + sym_hash->size <= toaddr)
4485 sym_hash->size -= count;
4489 return true;
4492 typedef bool (*relax_delete_t) (bfd *, asection *,
4493 bfd_vma, size_t,
4494 struct bfd_link_info *,
4495 riscv_pcgp_relocs *,
4496 Elf_Internal_Rela *);
4498 static relax_delete_t riscv_relax_delete_bytes;
4500 /* Do not delete some bytes from a section while relaxing.
4501 Just mark the deleted bytes as R_RISCV_DELETE. */
4503 static bool
4504 _riscv_relax_delete_piecewise (bfd *abfd ATTRIBUTE_UNUSED,
4505 asection *sec ATTRIBUTE_UNUSED,
4506 bfd_vma addr,
4507 size_t count,
4508 struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
4509 riscv_pcgp_relocs *p ATTRIBUTE_UNUSED,
4510 Elf_Internal_Rela *rel)
4512 if (rel == NULL)
4513 return false;
4514 rel->r_info = ELFNN_R_INFO (0, R_RISCV_DELETE);
4515 rel->r_offset = addr;
4516 rel->r_addend = count;
4517 return true;
4520 /* Delete some bytes from a section while relaxing. */
4522 static bool
4523 _riscv_relax_delete_immediate (bfd *abfd,
4524 asection *sec,
4525 bfd_vma addr,
4526 size_t count,
4527 struct bfd_link_info *link_info,
4528 riscv_pcgp_relocs *p,
4529 Elf_Internal_Rela *rel)
4531 if (rel != NULL)
4532 rel->r_info = ELFNN_R_INFO (0, R_RISCV_NONE);
4533 return _riscv_relax_delete_bytes (abfd, sec, addr, count,
4534 link_info, p, 0, sec->size);
4537 /* Delete the bytes for R_RISCV_DELETE relocs. */
4539 static bool
4540 riscv_relax_resolve_delete_relocs (bfd *abfd,
4541 asection *sec,
4542 struct bfd_link_info *link_info,
4543 Elf_Internal_Rela *relocs)
4545 bfd_vma delete_total = 0;
4546 unsigned int i;
4548 for (i = 0; i < sec->reloc_count; i++)
4550 Elf_Internal_Rela *rel = relocs + i;
4551 if (ELFNN_R_TYPE (rel->r_info) != R_RISCV_DELETE)
4552 continue;
4554 /* Find the next R_RISCV_DELETE reloc if possible. */
4555 Elf_Internal_Rela *rel_next = NULL;
4556 unsigned int start = rel - relocs;
4557 for (i = start; i < sec->reloc_count; i++)
4559 /* Since we only replace existing relocs and don't add new relocs, the
4560 relocs are in sequential order. We can skip the relocs prior to this
4561 one, making this search linear time. */
4562 rel_next = relocs + i;
4563 if (ELFNN_R_TYPE ((rel_next)->r_info) == R_RISCV_DELETE
4564 && (rel_next)->r_offset > rel->r_offset)
4566 BFD_ASSERT (rel_next - rel > 0);
4567 break;
4569 else
4570 rel_next = NULL;
4573 bfd_vma toaddr = rel_next == NULL ? sec->size : rel_next->r_offset;
4574 if (!_riscv_relax_delete_bytes (abfd, sec, rel->r_offset, rel->r_addend,
4575 link_info, NULL, delete_total, toaddr))
4576 return false;
4578 delete_total += rel->r_addend;
4579 rel->r_info = ELFNN_R_INFO (0, R_RISCV_NONE);
4581 /* Skip ahead to the next delete reloc. */
4582 i = rel_next != NULL ? (unsigned int) (rel_next - relocs - 1)
4583 : sec->reloc_count;
4586 return true;
4589 typedef bool (*relax_func_t) (bfd *, asection *, asection *,
4590 struct bfd_link_info *,
4591 Elf_Internal_Rela *,
4592 bfd_vma, bfd_vma, bfd_vma, bool *,
4593 riscv_pcgp_relocs *,
4594 bool undefined_weak);
4596 /* Relax AUIPC + JALR into JAL. */
4598 static bool
4599 _bfd_riscv_relax_call (bfd *abfd, asection *sec, asection *sym_sec,
4600 struct bfd_link_info *link_info,
4601 Elf_Internal_Rela *rel,
4602 bfd_vma symval,
4603 bfd_vma max_alignment,
4604 bfd_vma reserve_size ATTRIBUTE_UNUSED,
4605 bool *again,
4606 riscv_pcgp_relocs *pcgp_relocs,
4607 bool undefined_weak ATTRIBUTE_UNUSED)
4609 bfd_byte *contents = elf_section_data (sec)->this_hdr.contents;
4610 bfd_vma foff = symval - (sec_addr (sec) + rel->r_offset);
4611 bool near_zero = (symval + RISCV_IMM_REACH / 2) < RISCV_IMM_REACH;
4612 bfd_vma auipc, jalr;
4613 int rd, r_type, len = 4, rvc = elf_elfheader (abfd)->e_flags & EF_RISCV_RVC;
4615 /* If the call crosses section boundaries, an alignment directive could
4616 cause the PC-relative offset to later increase, so we need to add in the
4617 max alignment of any section inclusive from the call to the target.
4618 Otherwise, we only need to use the alignment of the current section. */
4619 if (VALID_JTYPE_IMM (foff))
4621 if (sym_sec->output_section == sec->output_section
4622 && sym_sec->output_section != bfd_abs_section_ptr)
4623 max_alignment = (bfd_vma) 1 << sym_sec->output_section->alignment_power;
4624 foff += ((bfd_signed_vma) foff < 0 ? -max_alignment : max_alignment);
4627 /* See if this function call can be shortened. */
4628 if (!VALID_JTYPE_IMM (foff) && !(!bfd_link_pic (link_info) && near_zero))
4629 return true;
4631 /* Shorten the function call. */
4632 BFD_ASSERT (rel->r_offset + 8 <= sec->size);
4634 auipc = bfd_getl32 (contents + rel->r_offset);
4635 jalr = bfd_getl32 (contents + rel->r_offset + 4);
4636 rd = (jalr >> OP_SH_RD) & OP_MASK_RD;
4637 rvc = rvc && VALID_CJTYPE_IMM (foff);
4639 /* C.J exists on RV32 and RV64, but C.JAL is RV32-only. */
4640 rvc = rvc && (rd == 0 || (rd == X_RA && ARCH_SIZE == 32));
4642 if (rvc)
4644 /* Relax to C.J[AL] rd, addr. */
4645 r_type = R_RISCV_RVC_JUMP;
4646 auipc = rd == 0 ? MATCH_C_J : MATCH_C_JAL;
4647 len = 2;
4649 else if (VALID_JTYPE_IMM (foff))
4651 /* Relax to JAL rd, addr. */
4652 r_type = R_RISCV_JAL;
4653 auipc = MATCH_JAL | (rd << OP_SH_RD);
4655 else
4657 /* Near zero, relax to JALR rd, x0, addr. */
4658 r_type = R_RISCV_LO12_I;
4659 auipc = MATCH_JALR | (rd << OP_SH_RD);
4662 /* Replace the R_RISCV_CALL reloc. */
4663 rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), r_type);
4664 /* Replace the AUIPC. */
4665 riscv_put_insn (8 * len, auipc, contents + rel->r_offset);
4667 /* Delete unnecessary JALR and reuse the R_RISCV_RELAX reloc. */
4668 *again = true;
4669 return riscv_relax_delete_bytes (abfd, sec, rel->r_offset + len, 8 - len,
4670 link_info, pcgp_relocs, rel + 1);
4673 /* Traverse all output sections and return the max alignment.
4675 If gp is zero, then all the output section alignments are
4676 possible candidates; Otherwise, only the output sections
4677 which are in the [gp-2K, gp+2K) range need to be considered. */
4679 static bfd_vma
4680 _bfd_riscv_get_max_alignment (asection *sec, bfd_vma gp)
4682 unsigned int max_alignment_power = 0;
4683 asection *o;
4685 for (o = sec->output_section->owner->sections; o != NULL; o = o->next)
4687 bool valid = true;
4688 if (gp
4689 && !(VALID_ITYPE_IMM (sec_addr (o) - gp)
4690 || VALID_ITYPE_IMM (sec_addr (o) + o->size - gp)))
4691 valid = false;
4693 if (valid && o->alignment_power > max_alignment_power)
4694 max_alignment_power = o->alignment_power;
4697 return (bfd_vma) 1 << max_alignment_power;
4700 /* Relax non-PIC global variable references to GP-relative references. */
4702 static bool
4703 _bfd_riscv_relax_lui (bfd *abfd,
4704 asection *sec,
4705 asection *sym_sec,
4706 struct bfd_link_info *link_info,
4707 Elf_Internal_Rela *rel,
4708 bfd_vma symval,
4709 bfd_vma max_alignment,
4710 bfd_vma reserve_size,
4711 bool *again,
4712 riscv_pcgp_relocs *pcgp_relocs,
4713 bool undefined_weak)
4715 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (link_info);
4716 bfd_byte *contents = elf_section_data (sec)->this_hdr.contents;
4717 /* Can relax to x0 even when gp relaxation is disabled. */
4718 bfd_vma gp = htab->params->relax_gp
4719 ? riscv_global_pointer_value (link_info)
4720 : 0;
4721 int use_rvc = elf_elfheader (abfd)->e_flags & EF_RISCV_RVC;
4723 BFD_ASSERT (rel->r_offset + 4 <= sec->size);
4725 if (!undefined_weak && gp)
4727 /* If gp and the symbol are in the same output section, which is not the
4728 abs section, then consider only that output section's alignment. */
4729 struct bfd_link_hash_entry *h =
4730 bfd_link_hash_lookup (link_info->hash, RISCV_GP_SYMBOL, false, false,
4731 true);
4732 if (h->u.def.section->output_section == sym_sec->output_section
4733 && sym_sec->output_section != bfd_abs_section_ptr)
4734 max_alignment = (bfd_vma) 1 << sym_sec->output_section->alignment_power;
4735 else
4737 /* Consider output section alignments which are in [gp-2K, gp+2K). */
4738 max_alignment = htab->max_alignment_for_gp;
4739 if (max_alignment == (bfd_vma) -1)
4741 max_alignment = _bfd_riscv_get_max_alignment (sec, gp);
4742 htab->max_alignment_for_gp = max_alignment;
4747 /* Is the reference in range of x0 or gp?
4748 Valid gp range conservatively because of alignment issue.
4750 Should we also consider the alignment issue for x0 base? */
4751 if (undefined_weak
4752 || VALID_ITYPE_IMM (symval)
4753 || (symval >= gp
4754 && VALID_ITYPE_IMM (symval - gp + max_alignment + reserve_size))
4755 || (symval < gp
4756 && VALID_ITYPE_IMM (symval - gp - max_alignment - reserve_size)))
4758 unsigned sym = ELFNN_R_SYM (rel->r_info);
4759 switch (ELFNN_R_TYPE (rel->r_info))
4761 case R_RISCV_LO12_I:
4762 rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_I);
4763 return true;
4765 case R_RISCV_LO12_S:
4766 rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_S);
4767 return true;
4769 case R_RISCV_HI20:
4770 /* Delete unnecessary LUI and reuse the reloc. */
4771 *again = true;
4772 return riscv_relax_delete_bytes (abfd, sec, rel->r_offset, 4,
4773 link_info, pcgp_relocs, rel);
4775 default:
4776 abort ();
4780 /* Can we relax LUI to C.LUI? Alignment might move the section forward;
4781 account for this assuming page alignment at worst. In the presence of
4782 RELRO segment the linker aligns it by one page size, therefore sections
4783 after the segment can be moved more than one page. */
4785 if (use_rvc
4786 && ELFNN_R_TYPE (rel->r_info) == R_RISCV_HI20
4787 && VALID_CITYPE_LUI_IMM (RISCV_CONST_HIGH_PART (symval))
4788 && VALID_CITYPE_LUI_IMM (RISCV_CONST_HIGH_PART (symval)
4789 + (link_info->relro ? 2 * ELF_MAXPAGESIZE
4790 : ELF_MAXPAGESIZE)))
4792 /* Replace LUI with C.LUI if legal (i.e., rd != x0 and rd != x2/sp). */
4793 bfd_vma lui = bfd_getl32 (contents + rel->r_offset);
4794 unsigned rd = ((unsigned)lui >> OP_SH_RD) & OP_MASK_RD;
4795 if (rd == 0 || rd == X_SP)
4796 return true;
4798 lui = (lui & (OP_MASK_RD << OP_SH_RD)) | MATCH_C_LUI;
4799 bfd_putl32 (lui, contents + rel->r_offset);
4801 /* Replace the R_RISCV_HI20 reloc. */
4802 rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), R_RISCV_RVC_LUI);
4804 /* Delete extra bytes and reuse the R_RISCV_RELAX reloc. */
4805 *again = true;
4806 return riscv_relax_delete_bytes (abfd, sec, rel->r_offset + 2, 2,
4807 link_info, pcgp_relocs, rel + 1);
4810 return true;
4813 /* Relax non-PIC TLS references to TP-relative references. */
4815 static bool
4816 _bfd_riscv_relax_tls_le (bfd *abfd,
4817 asection *sec,
4818 asection *sym_sec ATTRIBUTE_UNUSED,
4819 struct bfd_link_info *link_info,
4820 Elf_Internal_Rela *rel,
4821 bfd_vma symval,
4822 bfd_vma max_alignment ATTRIBUTE_UNUSED,
4823 bfd_vma reserve_size ATTRIBUTE_UNUSED,
4824 bool *again,
4825 riscv_pcgp_relocs *pcgp_relocs,
4826 bool undefined_weak ATTRIBUTE_UNUSED)
4828 /* See if this symbol is in range of tp. */
4829 if (RISCV_CONST_HIGH_PART (tpoff (link_info, symval)) != 0)
4830 return true;
4832 BFD_ASSERT (rel->r_offset + 4 <= sec->size);
4833 switch (ELFNN_R_TYPE (rel->r_info))
4835 case R_RISCV_TPREL_LO12_I:
4836 rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), R_RISCV_TPREL_I);
4837 return true;
4839 case R_RISCV_TPREL_LO12_S:
4840 rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), R_RISCV_TPREL_S);
4841 return true;
4843 case R_RISCV_TPREL_HI20:
4844 case R_RISCV_TPREL_ADD:
4845 /* Delete unnecessary instruction and reuse the reloc. */
4846 *again = true;
4847 return riscv_relax_delete_bytes (abfd, sec, rel->r_offset, 4, link_info,
4848 pcgp_relocs, rel);
4850 default:
4851 abort ();
4855 /* Implement R_RISCV_ALIGN by deleting excess alignment NOPs.
4856 Once we've handled an R_RISCV_ALIGN, we can't relax anything else. */
4858 static bool
4859 _bfd_riscv_relax_align (bfd *abfd, asection *sec,
4860 asection *sym_sec,
4861 struct bfd_link_info *link_info,
4862 Elf_Internal_Rela *rel,
4863 bfd_vma symval,
4864 bfd_vma max_alignment ATTRIBUTE_UNUSED,
4865 bfd_vma reserve_size ATTRIBUTE_UNUSED,
4866 bool *again ATTRIBUTE_UNUSED,
4867 riscv_pcgp_relocs *pcgp_relocs ATTRIBUTE_UNUSED,
4868 bool undefined_weak ATTRIBUTE_UNUSED)
4870 bfd_byte *contents = elf_section_data (sec)->this_hdr.contents;
4871 bfd_vma alignment = 1, pos;
4872 while (alignment <= rel->r_addend)
4873 alignment *= 2;
4875 symval -= rel->r_addend;
4876 bfd_vma aligned_addr = ((symval - 1) & ~(alignment - 1)) + alignment;
4877 bfd_vma nop_bytes = aligned_addr - symval;
4879 /* Once we've handled an R_RISCV_ALIGN, we can't relax anything else. */
4880 sec->sec_flg0 = true;
4882 /* Make sure there are enough NOPs to actually achieve the alignment. */
4883 if (rel->r_addend < nop_bytes)
4885 _bfd_error_handler
4886 (_("%pB(%pA+%#" PRIx64 "): %" PRId64 " bytes required for alignment "
4887 "to %" PRId64 "-byte boundary, but only %" PRId64 " present"),
4888 abfd, sym_sec, (uint64_t) rel->r_offset,
4889 (int64_t) nop_bytes, (int64_t) alignment, (int64_t) rel->r_addend);
4890 bfd_set_error (bfd_error_bad_value);
4891 return false;
4894 /* Delete the reloc. */
4895 rel->r_info = ELFNN_R_INFO (0, R_RISCV_NONE);
4897 /* If the number of NOPs is already correct, there's nothing to do. */
4898 if (nop_bytes == rel->r_addend)
4899 return true;
4901 /* Write as many RISC-V NOPs as we need. */
4902 for (pos = 0; pos < (nop_bytes & -4); pos += 4)
4903 bfd_putl32 (RISCV_NOP, contents + rel->r_offset + pos);
4905 /* Write a final RVC NOP if need be. */
4906 if (nop_bytes % 4 != 0)
4907 bfd_putl16 (RVC_NOP, contents + rel->r_offset + pos);
4909 /* Delete excess bytes. */
4910 return riscv_relax_delete_bytes (abfd, sec, rel->r_offset + nop_bytes,
4911 rel->r_addend - nop_bytes, link_info,
4912 NULL, NULL);
4915 /* Relax PC-relative references to GP-relative references. */
4917 static bool
4918 _bfd_riscv_relax_pc (bfd *abfd ATTRIBUTE_UNUSED,
4919 asection *sec,
4920 asection *sym_sec,
4921 struct bfd_link_info *link_info,
4922 Elf_Internal_Rela *rel,
4923 bfd_vma symval,
4924 bfd_vma max_alignment,
4925 bfd_vma reserve_size,
4926 bool *again,
4927 riscv_pcgp_relocs *pcgp_relocs,
4928 bool undefined_weak)
4930 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (link_info);
4931 /* Can relax to x0 even when gp relaxation is disabled. */
4932 bfd_vma gp = htab->params->relax_gp
4933 ? riscv_global_pointer_value (link_info)
4934 : 0;
4936 BFD_ASSERT (rel->r_offset + 4 <= sec->size);
4938 /* Chain the _LO relocs to their cooresponding _HI reloc to compute the
4939 actual target address. */
4940 riscv_pcgp_hi_reloc hi_reloc;
4941 memset (&hi_reloc, 0, sizeof (hi_reloc));
4942 switch (ELFNN_R_TYPE (rel->r_info))
4944 case R_RISCV_PCREL_LO12_I:
4945 case R_RISCV_PCREL_LO12_S:
4947 /* If the %lo has an addend, it isn't for the label pointing at the
4948 hi part instruction, but rather for the symbol pointed at by the
4949 hi part instruction. So we must subtract it here for the lookup.
4950 It is still used below in the final symbol address. */
4951 bfd_vma hi_sec_off = symval - sec_addr (sym_sec) - rel->r_addend;
4952 riscv_pcgp_hi_reloc *hi = riscv_find_pcgp_hi_reloc (pcgp_relocs,
4953 hi_sec_off);
4954 if (hi == NULL)
4956 riscv_record_pcgp_lo_reloc (pcgp_relocs, hi_sec_off);
4957 return true;
4960 hi_reloc = *hi;
4961 symval = hi_reloc.hi_addr;
4962 sym_sec = hi_reloc.sym_sec;
4964 /* We can not know whether the undefined weak symbol is referenced
4965 according to the information of R_RISCV_PCREL_LO12_I/S. Therefore,
4966 we have to record the 'undefined_weak' flag when handling the
4967 corresponding R_RISCV_HI20 reloc in riscv_record_pcgp_hi_reloc. */
4968 undefined_weak = hi_reloc.undefined_weak;
4970 break;
4972 case R_RISCV_PCREL_HI20:
4973 /* Mergeable symbols and code might later move out of range. */
4974 if (! undefined_weak
4975 && sym_sec->flags & (SEC_MERGE | SEC_CODE))
4976 return true;
4978 /* If the cooresponding lo relocation has already been seen then it's not
4979 safe to relax this relocation. */
4980 if (riscv_find_pcgp_lo_reloc (pcgp_relocs, rel->r_offset))
4981 return true;
4983 break;
4985 default:
4986 abort ();
4989 if (!undefined_weak && gp)
4991 /* If gp and the symbol are in the same output section, which is not the
4992 abs section, then consider only that output section's alignment. */
4993 struct bfd_link_hash_entry *h =
4994 bfd_link_hash_lookup (link_info->hash, RISCV_GP_SYMBOL, false, false,
4995 true);
4996 if (h->u.def.section->output_section == sym_sec->output_section
4997 && sym_sec->output_section != bfd_abs_section_ptr)
4998 max_alignment = (bfd_vma) 1 << sym_sec->output_section->alignment_power;
4999 else
5001 /* Consider output section alignments which are in [gp-2K, gp+2K). */
5002 max_alignment = htab->max_alignment_for_gp;
5003 if (max_alignment == (bfd_vma) -1)
5005 max_alignment = _bfd_riscv_get_max_alignment (sec, gp);
5006 htab->max_alignment_for_gp = max_alignment;
5011 /* Is the reference in range of x0 or gp?
5012 Valid gp range conservatively because of alignment issue.
5014 Should we also consider the alignment issue for x0 base? */
5015 if (undefined_weak
5016 || VALID_ITYPE_IMM (symval)
5017 || (symval >= gp
5018 && VALID_ITYPE_IMM (symval - gp + max_alignment + reserve_size))
5019 || (symval < gp
5020 && VALID_ITYPE_IMM (symval - gp - max_alignment - reserve_size)))
5022 unsigned sym = hi_reloc.hi_sym;
5023 switch (ELFNN_R_TYPE (rel->r_info))
5025 case R_RISCV_PCREL_LO12_I:
5026 rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_I);
5027 rel->r_addend += hi_reloc.hi_addend;
5028 return true;
5030 case R_RISCV_PCREL_LO12_S:
5031 rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_S);
5032 rel->r_addend += hi_reloc.hi_addend;
5033 return true;
5035 case R_RISCV_PCREL_HI20:
5036 riscv_record_pcgp_hi_reloc (pcgp_relocs,
5037 rel->r_offset,
5038 rel->r_addend,
5039 symval,
5040 ELFNN_R_SYM(rel->r_info),
5041 sym_sec,
5042 undefined_weak);
5043 /* Delete unnecessary AUIPC and reuse the reloc. */
5044 *again = true;
5045 riscv_relax_delete_bytes (abfd, sec, rel->r_offset, 4, link_info,
5046 pcgp_relocs, rel);
5047 return true;
5049 default:
5050 abort ();
5054 return true;
5057 /* Called by after_allocation to set the information of data segment
5058 before relaxing. */
5060 void
5061 bfd_elfNN_riscv_set_data_segment_info (struct bfd_link_info *info,
5062 int *data_segment_phase)
5064 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
5065 htab->data_segment_phase = data_segment_phase;
5068 /* Relax a section.
5070 Pass 0: Shortens code sequences for LUI/CALL/TPREL/PCREL relocs and
5071 deletes the obsolete bytes.
5072 Pass 1: Which cannot be disabled, handles code alignment directives. */
5074 static bool
5075 _bfd_riscv_relax_section (bfd *abfd, asection *sec,
5076 struct bfd_link_info *info,
5077 bool *again)
5079 Elf_Internal_Shdr *symtab_hdr = &elf_symtab_hdr (abfd);
5080 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
5081 struct bfd_elf_section_data *data = elf_section_data (sec);
5082 Elf_Internal_Rela *relocs;
5083 bool ret = false;
5084 unsigned int i;
5085 bfd_vma max_alignment, reserve_size = 0;
5086 riscv_pcgp_relocs pcgp_relocs;
5087 static asection *first_section = NULL;
5089 *again = false;
5091 if (bfd_link_relocatable (info)
5092 || sec->sec_flg0
5093 || sec->reloc_count == 0
5094 || (sec->flags & SEC_RELOC) == 0
5095 || (sec->flags & SEC_HAS_CONTENTS) == 0
5096 || (info->disable_target_specific_optimizations
5097 && info->relax_pass == 0)
5098 /* The exp_seg_relro_adjust is enum phase_enum (0x4),
5099 and defined in ld/ldexp.h. */
5100 || *(htab->data_segment_phase) == 4)
5101 return true;
5103 /* Record the first relax section, so that we can reset the
5104 max_alignment_for_gp for the repeated relax passes. */
5105 if (first_section == NULL)
5106 first_section = sec;
5107 else if (first_section == sec)
5108 htab->max_alignment_for_gp = -1;
5110 riscv_init_pcgp_relocs (&pcgp_relocs);
5112 /* Read this BFD's relocs if we haven't done so already. */
5113 if (data->relocs)
5114 relocs = data->relocs;
5115 else if (!(relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
5116 info->keep_memory)))
5117 goto fail;
5119 /* Estimate the maximum alignment for all output sections once time
5120 should be enough. */
5121 max_alignment = htab->max_alignment;
5122 if (max_alignment == (bfd_vma) -1)
5124 max_alignment = _bfd_riscv_get_max_alignment (sec, 0/* gp */);
5125 htab->max_alignment = max_alignment;
5128 /* Examine and consider relaxing each reloc. */
5129 for (i = 0; i < sec->reloc_count; i++)
5131 asection *sym_sec;
5132 Elf_Internal_Rela *rel = relocs + i;
5133 relax_func_t relax_func;
5134 int type = ELFNN_R_TYPE (rel->r_info);
5135 bfd_vma symval;
5136 char symtype;
5137 bool undefined_weak = false;
5139 relax_func = NULL;
5140 riscv_relax_delete_bytes = NULL;
5141 if (info->relax_pass == 0)
5143 if (type == R_RISCV_CALL
5144 || type == R_RISCV_CALL_PLT)
5145 relax_func = _bfd_riscv_relax_call;
5146 else if (type == R_RISCV_HI20
5147 || type == R_RISCV_LO12_I
5148 || type == R_RISCV_LO12_S)
5149 relax_func = _bfd_riscv_relax_lui;
5150 else if (type == R_RISCV_TPREL_HI20
5151 || type == R_RISCV_TPREL_ADD
5152 || type == R_RISCV_TPREL_LO12_I
5153 || type == R_RISCV_TPREL_LO12_S)
5154 relax_func = _bfd_riscv_relax_tls_le;
5155 else if (!bfd_link_pic (info)
5156 && (type == R_RISCV_PCREL_HI20
5157 || type == R_RISCV_PCREL_LO12_I
5158 || type == R_RISCV_PCREL_LO12_S))
5159 relax_func = _bfd_riscv_relax_pc;
5160 else
5161 continue;
5162 riscv_relax_delete_bytes = _riscv_relax_delete_piecewise;
5164 /* Only relax this reloc if it is paired with R_RISCV_RELAX. */
5165 if (i == sec->reloc_count - 1
5166 || ELFNN_R_TYPE ((rel + 1)->r_info) != R_RISCV_RELAX
5167 || rel->r_offset != (rel + 1)->r_offset)
5168 continue;
5170 /* Skip over the R_RISCV_RELAX. */
5171 i++;
5173 else if (info->relax_pass == 1 && type == R_RISCV_ALIGN)
5175 relax_func = _bfd_riscv_relax_align;
5176 riscv_relax_delete_bytes = _riscv_relax_delete_immediate;
5178 else
5179 continue;
5181 data->relocs = relocs;
5183 /* Read this BFD's contents if we haven't done so already. */
5184 if (!data->this_hdr.contents
5185 && !bfd_malloc_and_get_section (abfd, sec, &data->this_hdr.contents))
5186 goto fail;
5188 /* Read this BFD's symbols if we haven't done so already. */
5189 if (symtab_hdr->sh_info != 0
5190 && !symtab_hdr->contents
5191 && !(symtab_hdr->contents =
5192 (unsigned char *) bfd_elf_get_elf_syms (abfd, symtab_hdr,
5193 symtab_hdr->sh_info,
5194 0, NULL, NULL, NULL)))
5195 goto fail;
5197 /* Get the value of the symbol referred to by the reloc. */
5198 if (ELFNN_R_SYM (rel->r_info) < symtab_hdr->sh_info)
5200 /* A local symbol. */
5201 Elf_Internal_Sym *isym = ((Elf_Internal_Sym *) symtab_hdr->contents
5202 + ELFNN_R_SYM (rel->r_info));
5203 reserve_size = (isym->st_size - rel->r_addend) > isym->st_size
5204 ? 0 : isym->st_size - rel->r_addend;
5206 /* Relocate against local STT_GNU_IFUNC symbol. we have created
5207 a fake global symbol entry for this, so deal with the local ifunc
5208 as a global. */
5209 if (ELF_ST_TYPE (isym->st_info) == STT_GNU_IFUNC)
5210 continue;
5212 if (isym->st_shndx == SHN_UNDEF)
5213 sym_sec = sec, symval = rel->r_offset;
5214 else
5216 BFD_ASSERT (isym->st_shndx < elf_numsections (abfd));
5217 sym_sec = elf_elfsections (abfd)[isym->st_shndx]->bfd_section;
5218 #if 0
5219 /* The purpose of this code is unknown. It breaks linker scripts
5220 for embedded development that place sections at address zero.
5221 This code is believed to be unnecessary. Disabling it but not
5222 yet removing it, in case something breaks. */
5223 if (sec_addr (sym_sec) == 0)
5224 continue;
5225 #endif
5226 symval = isym->st_value;
5228 symtype = ELF_ST_TYPE (isym->st_info);
5230 else
5232 unsigned long indx;
5233 struct elf_link_hash_entry *h;
5235 indx = ELFNN_R_SYM (rel->r_info) - symtab_hdr->sh_info;
5236 h = elf_sym_hashes (abfd)[indx];
5238 while (h->root.type == bfd_link_hash_indirect
5239 || h->root.type == bfd_link_hash_warning)
5240 h = (struct elf_link_hash_entry *) h->root.u.i.link;
5242 /* Disable the relaxation for ifunc. */
5243 if (h != NULL && h->type == STT_GNU_IFUNC)
5244 continue;
5246 /* Maybe we should check UNDEFWEAK_NO_DYNAMIC_RELOC here? But that
5247 will break the undefweak relaxation testcases, so just make sure
5248 we won't do relaxations for linker_def symbols in short-term. */
5249 if (h->root.type == bfd_link_hash_undefweak
5250 /* The linker_def symbol like __ehdr_start that may be undefweak
5251 for now, but will be guaranteed to be defined later. */
5252 && !h->root.linker_def
5253 && (relax_func == _bfd_riscv_relax_lui
5254 || relax_func == _bfd_riscv_relax_pc))
5256 /* For the lui and auipc relaxations, since the symbol
5257 value of an undefined weak symbol is always be zero,
5258 we can optimize the patterns into a single LI/MV/ADDI
5259 instruction.
5261 Note that, creating shared libraries and pie output may
5262 break the rule above. Fortunately, since we do not relax
5263 pc relocs when creating shared libraries and pie output,
5264 and the absolute address access for R_RISCV_HI20 isn't
5265 allowed when "-fPIC" is set, the problem of creating shared
5266 libraries can not happen currently. Once we support the
5267 auipc relaxations when creating shared libraries, then we will
5268 need the more rigorous checking for this optimization. */
5269 undefined_weak = true;
5272 /* This line has to match the check in riscv_elf_relocate_section
5273 in the R_RISCV_CALL[_PLT] case. */
5274 if (bfd_link_pic (info) && h->plt.offset != MINUS_ONE)
5276 sym_sec = htab->elf.splt;
5277 symval = h->plt.offset;
5279 else if (undefined_weak)
5281 symval = 0;
5282 sym_sec = bfd_und_section_ptr;
5284 else if ((h->root.type == bfd_link_hash_defined
5285 || h->root.type == bfd_link_hash_defweak)
5286 && h->root.u.def.section != NULL
5287 && h->root.u.def.section->output_section != NULL)
5289 symval = h->root.u.def.value;
5290 sym_sec = h->root.u.def.section;
5292 else
5293 continue;
5295 if (h->type != STT_FUNC)
5296 reserve_size =
5297 (h->size - rel->r_addend) > h->size ? 0 : h->size - rel->r_addend;
5298 symtype = h->type;
5301 if (sym_sec->sec_info_type == SEC_INFO_TYPE_MERGE
5302 && (sym_sec->flags & SEC_MERGE))
5304 /* At this stage in linking, no SEC_MERGE symbol has been
5305 adjusted, so all references to such symbols need to be
5306 passed through _bfd_merged_section_offset. (Later, in
5307 relocate_section, all SEC_MERGE symbols *except* for
5308 section symbols have been adjusted.)
5310 gas may reduce relocations against symbols in SEC_MERGE
5311 sections to a relocation against the section symbol when
5312 the original addend was zero. When the reloc is against
5313 a section symbol we should include the addend in the
5314 offset passed to _bfd_merged_section_offset, since the
5315 location of interest is the original symbol. On the
5316 other hand, an access to "sym+addend" where "sym" is not
5317 a section symbol should not include the addend; Such an
5318 access is presumed to be an offset from "sym"; The
5319 location of interest is just "sym". */
5320 if (symtype == STT_SECTION)
5321 symval += rel->r_addend;
5323 symval = _bfd_merged_section_offset (abfd, &sym_sec,
5324 elf_section_data (sym_sec)->sec_info,
5325 symval);
5327 if (symtype != STT_SECTION)
5328 symval += rel->r_addend;
5330 else
5331 symval += rel->r_addend;
5333 symval += sec_addr (sym_sec);
5335 if (!relax_func (abfd, sec, sym_sec, info, rel, symval,
5336 max_alignment, reserve_size, again,
5337 &pcgp_relocs, undefined_weak))
5338 goto fail;
5341 /* Resolve R_RISCV_DELETE relocations. */
5342 if (!riscv_relax_resolve_delete_relocs (abfd, sec, info, relocs))
5343 goto fail;
5345 ret = true;
5347 fail:
5348 if (relocs != data->relocs)
5349 free (relocs);
5350 riscv_free_pcgp_relocs (&pcgp_relocs, abfd, sec);
5352 return ret;
5355 #if ARCH_SIZE == 32
5356 # define PRSTATUS_SIZE 204
5357 # define PRSTATUS_OFFSET_PR_CURSIG 12
5358 # define PRSTATUS_OFFSET_PR_PID 24
5359 # define PRSTATUS_OFFSET_PR_REG 72
5360 # define ELF_GREGSET_T_SIZE 128
5361 # define PRPSINFO_SIZE 128
5362 # define PRPSINFO_OFFSET_PR_PID 16
5363 # define PRPSINFO_OFFSET_PR_FNAME 32
5364 # define PRPSINFO_OFFSET_PR_PSARGS 48
5365 # define PRPSINFO_PR_FNAME_LENGTH 16
5366 # define PRPSINFO_PR_PSARGS_LENGTH 80
5367 #else
5368 # define PRSTATUS_SIZE 376
5369 # define PRSTATUS_OFFSET_PR_CURSIG 12
5370 # define PRSTATUS_OFFSET_PR_PID 32
5371 # define PRSTATUS_OFFSET_PR_REG 112
5372 # define ELF_GREGSET_T_SIZE 256
5373 # define PRPSINFO_SIZE 136
5374 # define PRPSINFO_OFFSET_PR_PID 24
5375 # define PRPSINFO_OFFSET_PR_FNAME 40
5376 # define PRPSINFO_OFFSET_PR_PSARGS 56
5377 # define PRPSINFO_PR_FNAME_LENGTH 16
5378 # define PRPSINFO_PR_PSARGS_LENGTH 80
5379 #endif
5381 /* Write PRSTATUS and PRPSINFO note into core file. This will be called
5382 before the generic code in elf.c. By checking the compiler defines we
5383 only perform any action here if the generic code would otherwise not be
5384 able to help us. The intention is that bare metal core dumps (where the
5385 prstatus_t and/or prpsinfo_t might not be available) will use this code,
5386 while non bare metal tools will use the generic elf code. */
5388 static char *
5389 riscv_write_core_note (bfd *abfd ATTRIBUTE_UNUSED,
5390 char *buf ATTRIBUTE_UNUSED,
5391 int *bufsiz ATTRIBUTE_UNUSED,
5392 int note_type ATTRIBUTE_UNUSED, ...)
5394 switch (note_type)
5396 default:
5397 return NULL;
5399 #if !defined (HAVE_PRPSINFO_T)
5400 case NT_PRPSINFO:
5402 char data[PRPSINFO_SIZE] ATTRIBUTE_NONSTRING;
5403 va_list ap;
5405 va_start (ap, note_type);
5406 memset (data, 0, sizeof (data));
5407 strncpy (data + PRPSINFO_OFFSET_PR_FNAME, va_arg (ap, const char *),
5408 PRPSINFO_PR_FNAME_LENGTH);
5409 #if GCC_VERSION == 8000 || GCC_VERSION == 8001
5410 DIAGNOSTIC_PUSH;
5411 /* GCC 8.0 and 8.1 warn about 80 equals destination size with
5412 -Wstringop-truncation:
5413 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85643
5415 DIAGNOSTIC_IGNORE_STRINGOP_TRUNCATION;
5416 #endif
5417 strncpy (data + PRPSINFO_OFFSET_PR_PSARGS, va_arg (ap, const char *),
5418 PRPSINFO_PR_PSARGS_LENGTH);
5419 #if GCC_VERSION == 8000 || GCC_VERSION == 8001
5420 DIAGNOSTIC_POP;
5421 #endif
5422 va_end (ap);
5423 return elfcore_write_note (abfd, buf, bufsiz,
5424 "CORE", note_type, data, sizeof (data));
5426 #endif /* !HAVE_PRPSINFO_T */
5428 #if !defined (HAVE_PRSTATUS_T)
5429 case NT_PRSTATUS:
5431 char data[PRSTATUS_SIZE];
5432 va_list ap;
5433 long pid;
5434 int cursig;
5435 const void *greg;
5437 va_start (ap, note_type);
5438 memset (data, 0, sizeof(data));
5439 pid = va_arg (ap, long);
5440 bfd_put_32 (abfd, pid, data + PRSTATUS_OFFSET_PR_PID);
5441 cursig = va_arg (ap, int);
5442 bfd_put_16 (abfd, cursig, data + PRSTATUS_OFFSET_PR_CURSIG);
5443 greg = va_arg (ap, const void *);
5444 memcpy (data + PRSTATUS_OFFSET_PR_REG, greg,
5445 PRSTATUS_SIZE - PRSTATUS_OFFSET_PR_REG - ARCH_SIZE / 8);
5446 va_end (ap);
5447 return elfcore_write_note (abfd, buf, bufsiz,
5448 "CORE", note_type, data, sizeof (data));
5450 #endif /* !HAVE_PRSTATUS_T */
5454 /* Support for core dump NOTE sections. */
5456 static bool
5457 riscv_elf_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
5459 switch (note->descsz)
5461 default:
5462 return false;
5464 case PRSTATUS_SIZE: /* sizeof(struct elf_prstatus) on Linux/RISC-V. */
5465 /* pr_cursig */
5466 elf_tdata (abfd)->core->signal
5467 = bfd_get_16 (abfd, note->descdata + PRSTATUS_OFFSET_PR_CURSIG);
5469 /* pr_pid */
5470 elf_tdata (abfd)->core->lwpid
5471 = bfd_get_32 (abfd, note->descdata + PRSTATUS_OFFSET_PR_PID);
5472 break;
5475 /* Make a ".reg/999" section. */
5476 return _bfd_elfcore_make_pseudosection (abfd, ".reg", ELF_GREGSET_T_SIZE,
5477 note->descpos + PRSTATUS_OFFSET_PR_REG);
5480 static bool
5481 riscv_elf_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
5483 switch (note->descsz)
5485 default:
5486 return false;
5488 case PRPSINFO_SIZE: /* sizeof(struct elf_prpsinfo) on Linux/RISC-V. */
5489 /* pr_pid */
5490 elf_tdata (abfd)->core->pid
5491 = bfd_get_32 (abfd, note->descdata + PRPSINFO_OFFSET_PR_PID);
5493 /* pr_fname */
5494 elf_tdata (abfd)->core->program = _bfd_elfcore_strndup
5495 (abfd, note->descdata + PRPSINFO_OFFSET_PR_FNAME,
5496 PRPSINFO_PR_FNAME_LENGTH);
5498 /* pr_psargs */
5499 elf_tdata (abfd)->core->command = _bfd_elfcore_strndup
5500 (abfd, note->descdata + PRPSINFO_OFFSET_PR_PSARGS,
5501 PRPSINFO_PR_PSARGS_LENGTH);
5502 break;
5505 /* Note that for some reason, a spurious space is tacked
5506 onto the end of the args in some (at least one anyway)
5507 implementations, so strip it off if it exists. */
5510 char *command = elf_tdata (abfd)->core->command;
5511 int n = strlen (command);
5513 if (0 < n && command[n - 1] == ' ')
5514 command[n - 1] = '\0';
5517 return true;
5520 /* Set the right mach type. */
5522 static bool
5523 riscv_elf_object_p (bfd *abfd)
5525 /* There are only two mach types in RISCV currently. */
5526 if (strcmp (abfd->xvec->name, "elf32-littleriscv") == 0
5527 || strcmp (abfd->xvec->name, "elf32-bigriscv") == 0)
5528 bfd_default_set_arch_mach (abfd, bfd_arch_riscv, bfd_mach_riscv32);
5529 else
5530 bfd_default_set_arch_mach (abfd, bfd_arch_riscv, bfd_mach_riscv64);
5532 return true;
5535 /* Determine whether an object attribute tag takes an integer, a
5536 string or both. */
5538 static int
5539 riscv_elf_obj_attrs_arg_type (int tag)
5541 return (tag & 1) != 0 ? ATTR_TYPE_FLAG_STR_VAL : ATTR_TYPE_FLAG_INT_VAL;
5544 /* Do not choose mapping symbols as a function name. */
5546 static bfd_size_type
5547 riscv_maybe_function_sym (const asymbol *sym,
5548 asection *sec,
5549 bfd_vma *code_off)
5551 if (sym->flags & BSF_LOCAL
5552 && (riscv_elf_is_mapping_symbols (sym->name)
5553 || _bfd_elf_is_local_label_name (sec->owner, sym->name)))
5554 return 0;
5556 return _bfd_elf_maybe_function_sym (sym, sec, code_off);
5559 /* Treat the following cases as target special symbols, they are
5560 usually omitted. */
5562 static bool
5563 riscv_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
5565 /* PR27584, local and empty symbols. Since they are usually
5566 generated for pcrel relocations. */
5567 return (!strcmp (sym->name, "")
5568 || _bfd_elf_is_local_label_name (abfd, sym->name)
5569 /* PR27916, mapping symbols. */
5570 || riscv_elf_is_mapping_symbols (sym->name));
5573 static int
5574 riscv_elf_additional_program_headers (bfd *abfd,
5575 struct bfd_link_info *info ATTRIBUTE_UNUSED)
5577 int ret = 0;
5579 /* See if we need a PT_RISCV_ATTRIBUTES segment. */
5580 if (bfd_get_section_by_name (abfd, RISCV_ATTRIBUTES_SECTION_NAME))
5581 ++ret;
5583 return ret;
5586 static bool
5587 riscv_elf_modify_segment_map (bfd *abfd,
5588 struct bfd_link_info *info ATTRIBUTE_UNUSED)
5590 asection *s;
5591 struct elf_segment_map *m, **pm;
5592 size_t amt;
5594 /* If there is a .riscv.attributes section, we need a PT_RISCV_ATTRIBUTES
5595 segment. */
5596 s = bfd_get_section_by_name (abfd, RISCV_ATTRIBUTES_SECTION_NAME);
5597 if (s != NULL)
5599 for (m = elf_seg_map (abfd); m != NULL; m = m->next)
5600 if (m->p_type == PT_RISCV_ATTRIBUTES)
5601 break;
5602 /* If there is already a PT_RISCV_ATTRIBUTES header, avoid adding
5603 another. */
5604 if (m == NULL)
5606 amt = sizeof (*m);
5607 m = bfd_zalloc (abfd, amt);
5608 if (m == NULL)
5609 return false;
5611 m->p_type = PT_RISCV_ATTRIBUTES;
5612 m->count = 1;
5613 m->sections[0] = s;
5615 /* We want to put it after the PHDR and INTERP segments. */
5616 pm = &elf_seg_map (abfd);
5617 while (*pm != NULL
5618 && ((*pm)->p_type == PT_PHDR
5619 || (*pm)->p_type == PT_INTERP))
5620 pm = &(*pm)->next;
5622 m->next = *pm;
5623 *pm = m;
5627 return true;
5630 /* Merge non-visibility st_other attributes. */
5632 static void
5633 riscv_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
5634 unsigned int st_other,
5635 bool definition ATTRIBUTE_UNUSED,
5636 bool dynamic ATTRIBUTE_UNUSED)
5638 unsigned int isym_sto = st_other & ~ELF_ST_VISIBILITY (-1);
5639 unsigned int h_sto = h->other & ~ELF_ST_VISIBILITY (-1);
5641 if (isym_sto == h_sto)
5642 return;
5644 if (isym_sto & ~STO_RISCV_VARIANT_CC)
5645 _bfd_error_handler (_("unknown attribute for symbol `%s': 0x%02x"),
5646 h->root.root.string, isym_sto);
5648 if (isym_sto & STO_RISCV_VARIANT_CC)
5649 h->other |= STO_RISCV_VARIANT_CC;
5652 #define TARGET_LITTLE_SYM riscv_elfNN_vec
5653 #define TARGET_LITTLE_NAME "elfNN-littleriscv"
5654 #define TARGET_BIG_SYM riscv_elfNN_be_vec
5655 #define TARGET_BIG_NAME "elfNN-bigriscv"
5657 #define elf_backend_reloc_type_class riscv_reloc_type_class
5659 #define bfd_elfNN_bfd_reloc_name_lookup riscv_reloc_name_lookup
5660 #define bfd_elfNN_bfd_link_hash_table_create riscv_elf_link_hash_table_create
5661 #define bfd_elfNN_bfd_reloc_type_lookup riscv_reloc_type_lookup
5662 #define bfd_elfNN_bfd_merge_private_bfd_data \
5663 _bfd_riscv_elf_merge_private_bfd_data
5664 #define bfd_elfNN_bfd_is_target_special_symbol riscv_elf_is_target_special_symbol
5666 #define elf_backend_copy_indirect_symbol riscv_elf_copy_indirect_symbol
5667 #define elf_backend_create_dynamic_sections riscv_elf_create_dynamic_sections
5668 #define elf_backend_check_relocs riscv_elf_check_relocs
5669 #define elf_backend_adjust_dynamic_symbol riscv_elf_adjust_dynamic_symbol
5670 #define elf_backend_size_dynamic_sections riscv_elf_size_dynamic_sections
5671 #define elf_backend_relocate_section riscv_elf_relocate_section
5672 #define elf_backend_finish_dynamic_symbol riscv_elf_finish_dynamic_symbol
5673 #define elf_backend_finish_dynamic_sections riscv_elf_finish_dynamic_sections
5674 #define elf_backend_plt_sym_val riscv_elf_plt_sym_val
5675 #define elf_backend_grok_prstatus riscv_elf_grok_prstatus
5676 #define elf_backend_grok_psinfo riscv_elf_grok_psinfo
5677 #define elf_backend_object_p riscv_elf_object_p
5678 #define elf_backend_write_core_note riscv_write_core_note
5679 #define elf_backend_maybe_function_sym riscv_maybe_function_sym
5680 #define elf_info_to_howto_rel NULL
5681 #define elf_info_to_howto riscv_info_to_howto_rela
5682 #define bfd_elfNN_bfd_relax_section _bfd_riscv_relax_section
5683 #define bfd_elfNN_mkobject elfNN_riscv_mkobject
5684 #define elf_backend_additional_program_headers \
5685 riscv_elf_additional_program_headers
5686 #define elf_backend_modify_segment_map riscv_elf_modify_segment_map
5687 #define elf_backend_merge_symbol_attribute riscv_elf_merge_symbol_attribute
5689 #define elf_backend_init_index_section _bfd_elf_init_1_index_section
5691 #define elf_backend_can_gc_sections 1
5692 #define elf_backend_can_refcount 1
5693 #define elf_backend_want_got_plt 1
5694 #define elf_backend_plt_readonly 1
5695 #define elf_backend_plt_alignment 4
5696 #define elf_backend_want_plt_sym 1
5697 #define elf_backend_got_header_size (ARCH_SIZE / 8)
5698 #define elf_backend_want_dynrelro 1
5699 #define elf_backend_rela_normal 1
5700 #define elf_backend_default_execstack 0
5702 #undef elf_backend_obj_attrs_vendor
5703 #define elf_backend_obj_attrs_vendor "riscv"
5704 #undef elf_backend_obj_attrs_arg_type
5705 #define elf_backend_obj_attrs_arg_type riscv_elf_obj_attrs_arg_type
5706 #undef elf_backend_obj_attrs_section_type
5707 #define elf_backend_obj_attrs_section_type SHT_RISCV_ATTRIBUTES
5708 #undef elf_backend_obj_attrs_section
5709 #define elf_backend_obj_attrs_section RISCV_ATTRIBUTES_SECTION_NAME
5711 #include "elfNN-target.h"