Automatic date update in version.in
[binutils-gdb.git] / bfd / elfnn-riscv.c
blob8bbdd15d5522fc8505182cd3d12a02f786f2b996
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_late_size_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 if (dynobj == NULL)
1514 return true;
1516 if (elf_hash_table (info)->dynamic_sections_created)
1518 /* Set the contents of the .interp section to the interpreter. */
1519 if (bfd_link_executable (info) && !info->nointerp)
1521 s = bfd_get_linker_section (dynobj, ".interp");
1522 BFD_ASSERT (s != NULL);
1523 s->size = strlen (ELFNN_DYNAMIC_INTERPRETER) + 1;
1524 s->contents = (unsigned char *) ELFNN_DYNAMIC_INTERPRETER;
1528 /* Set up .got offsets for local syms, and space for local dynamic
1529 relocs. */
1530 for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
1532 bfd_signed_vma *local_got;
1533 bfd_signed_vma *end_local_got;
1534 char *local_tls_type;
1535 bfd_size_type locsymcount;
1536 Elf_Internal_Shdr *symtab_hdr;
1537 asection *srel;
1539 if (! is_riscv_elf (ibfd))
1540 continue;
1542 for (s = ibfd->sections; s != NULL; s = s->next)
1544 struct elf_dyn_relocs *p;
1546 for (p = elf_section_data (s)->local_dynrel; p != NULL; p = p->next)
1548 if (!bfd_is_abs_section (p->sec)
1549 && bfd_is_abs_section (p->sec->output_section))
1551 /* Input section has been discarded, either because
1552 it is a copy of a linkonce section or due to
1553 linker script /DISCARD/, so we'll be discarding
1554 the relocs too. */
1556 else if (p->count != 0)
1558 srel = elf_section_data (p->sec)->sreloc;
1559 srel->size += p->count * sizeof (ElfNN_External_Rela);
1560 if ((p->sec->output_section->flags & SEC_READONLY) != 0)
1561 info->flags |= DF_TEXTREL;
1566 local_got = elf_local_got_refcounts (ibfd);
1567 if (!local_got)
1568 continue;
1570 symtab_hdr = &elf_symtab_hdr (ibfd);
1571 locsymcount = symtab_hdr->sh_info;
1572 end_local_got = local_got + locsymcount;
1573 local_tls_type = _bfd_riscv_elf_local_got_tls_type (ibfd);
1574 s = htab->elf.sgot;
1575 srel = htab->elf.srelgot;
1576 for (; local_got < end_local_got; ++local_got, ++local_tls_type)
1578 if (*local_got > 0)
1580 *local_got = s->size;
1581 if (*local_tls_type & (GOT_TLS_GD | GOT_TLS_IE | GOT_TLSDESC))
1583 if (*local_tls_type & GOT_TLS_GD)
1585 s->size += TLS_GD_GOT_ENTRY_SIZE;
1586 if (bfd_link_dll (info))
1587 srel->size += sizeof (ElfNN_External_Rela);
1589 if (*local_tls_type & GOT_TLS_IE)
1591 s->size += TLS_IE_GOT_ENTRY_SIZE;
1592 if (bfd_link_dll (info))
1593 srel->size += sizeof (ElfNN_External_Rela);
1595 if (*local_tls_type & GOT_TLSDESC)
1597 s->size += TLSDESC_GOT_ENTRY_SIZE;
1598 srel->size += sizeof (ElfNN_External_Rela);
1601 else
1603 s->size += GOT_ENTRY_SIZE;
1604 if (bfd_link_pic (info))
1605 srel->size += sizeof (ElfNN_External_Rela);
1608 else
1609 *local_got = (bfd_vma) -1;
1613 /* Allocate .plt and .got entries and space dynamic relocs for
1614 global symbols. */
1615 elf_link_hash_traverse (&htab->elf, allocate_dynrelocs, info);
1617 /* Allocate .plt and .got entries and space dynamic relocs for
1618 global ifunc symbols. */
1619 elf_link_hash_traverse (&htab->elf, allocate_ifunc_dynrelocs, info);
1621 /* Allocate .plt and .got entries and space dynamic relocs for
1622 local ifunc symbols. */
1623 htab_traverse (htab->loc_hash_table, allocate_local_ifunc_dynrelocs, info);
1625 /* Used to resolve the dynamic relocs overwite problems when
1626 generating static executable. */
1627 if (htab->elf.irelplt)
1628 htab->last_iplt_index = htab->elf.irelplt->reloc_count - 1;
1630 if (htab->elf.sgotplt)
1632 struct elf_link_hash_entry *got;
1633 got = elf_link_hash_lookup (elf_hash_table (info),
1634 "_GLOBAL_OFFSET_TABLE_",
1635 false, false, false);
1637 /* Don't allocate .got.plt section if there are no GOT nor PLT
1638 entries and there is no refeence to _GLOBAL_OFFSET_TABLE_. */
1639 if ((got == NULL
1640 || !got->ref_regular_nonweak)
1641 && (htab->elf.sgotplt->size == GOTPLT_HEADER_SIZE)
1642 && (htab->elf.splt == NULL
1643 || htab->elf.splt->size == 0)
1644 && (htab->elf.sgot == NULL
1645 || (htab->elf.sgot->size
1646 == get_elf_backend_data (output_bfd)->got_header_size)))
1647 htab->elf.sgotplt->size = 0;
1650 /* The check_relocs and adjust_dynamic_symbol entry points have
1651 determined the sizes of the various dynamic sections. Allocate
1652 memory for them. */
1653 for (s = dynobj->sections; s != NULL; s = s->next)
1655 if ((s->flags & SEC_LINKER_CREATED) == 0)
1656 continue;
1658 if (s == htab->elf.splt
1659 || s == htab->elf.sgot
1660 || s == htab->elf.sgotplt
1661 || s == htab->elf.iplt
1662 || s == htab->elf.igotplt
1663 || s == htab->elf.sdynbss
1664 || s == htab->elf.sdynrelro
1665 || s == htab->sdyntdata)
1667 /* Strip this section if we don't need it; see the
1668 comment below. */
1670 else if (startswith (s->name, ".rela"))
1672 if (s->size != 0)
1674 /* We use the reloc_count field as a counter if we need
1675 to copy relocs into the output file. */
1676 s->reloc_count = 0;
1679 else
1681 /* It's not one of our sections. */
1682 continue;
1685 if (s->size == 0)
1687 /* If we don't need this section, strip it from the
1688 output file. This is mostly to handle .rela.bss and
1689 .rela.plt. We must create both sections in
1690 create_dynamic_sections, because they must be created
1691 before the linker maps input sections to output
1692 sections. The linker does that before
1693 adjust_dynamic_symbol is called, and it is that
1694 function which decides whether anything needs to go
1695 into these sections. */
1696 s->flags |= SEC_EXCLUDE;
1697 continue;
1700 if ((s->flags & SEC_HAS_CONTENTS) == 0)
1701 continue;
1703 /* Allocate memory for the section contents. Zero the memory
1704 for the benefit of .rela.plt, which has 4 unused entries
1705 at the beginning, and we don't want garbage. */
1706 s->contents = (bfd_byte *) bfd_zalloc (dynobj, s->size);
1707 if (s->contents == NULL)
1708 return false;
1711 /* Add dynamic entries. */
1712 if (elf_hash_table (info)->dynamic_sections_created)
1714 if (!_bfd_elf_add_dynamic_tags (output_bfd, info, true))
1715 return false;
1717 if (htab->variant_cc
1718 && !_bfd_elf_add_dynamic_entry (info, DT_RISCV_VARIANT_CC, 0))
1719 return false;
1722 return true;
1725 #define TP_OFFSET 0
1726 #define DTP_OFFSET 0x800
1728 /* Return the relocation value for a TLS dtp-relative reloc. */
1730 static bfd_vma
1731 dtpoff (struct bfd_link_info *info, bfd_vma address)
1733 /* If tls_sec is NULL, we should have signalled an error already. */
1734 if (elf_hash_table (info)->tls_sec == NULL)
1735 return 0;
1736 return address - elf_hash_table (info)->tls_sec->vma - DTP_OFFSET;
1739 /* Return the relocation value for a static TLS tp-relative relocation. */
1741 static bfd_vma
1742 tpoff (struct bfd_link_info *info, bfd_vma address)
1744 /* If tls_sec is NULL, we should have signalled an error already. */
1745 if (elf_hash_table (info)->tls_sec == NULL)
1746 return 0;
1747 return address - elf_hash_table (info)->tls_sec->vma - TP_OFFSET;
1750 /* Return the relocation value for a static TLSDESC relocation. */
1752 static bfd_vma
1753 tlsdescoff (struct bfd_link_info *info, bfd_vma address)
1755 /* If tls_sec is NULL, we should have signalled an error already. */
1756 if (elf_hash_table (info)->tls_sec == NULL)
1757 return 0;
1758 return address - elf_hash_table (info)->tls_sec->vma;
1761 /* Return the global pointer's value, or 0 if it is not in use. */
1763 static bfd_vma
1764 riscv_global_pointer_value (struct bfd_link_info *info)
1766 struct bfd_link_hash_entry *h;
1768 h = bfd_link_hash_lookup (info->hash, RISCV_GP_SYMBOL, false, false, true);
1769 if (h == NULL || h->type != bfd_link_hash_defined)
1770 return 0;
1772 return h->u.def.value + sec_addr (h->u.def.section);
1775 /* Emplace a static relocation. */
1777 static bfd_reloc_status_type
1778 perform_relocation (const reloc_howto_type *howto,
1779 const Elf_Internal_Rela *rel,
1780 bfd_vma value,
1781 asection *input_section,
1782 bfd *input_bfd,
1783 bfd_byte *contents)
1785 if (howto->pc_relative)
1786 value -= sec_addr (input_section) + rel->r_offset;
1788 /* PR31179, ignore the non-zero addend of R_RISCV_SUB_ULEB128. */
1789 if (ELFNN_R_TYPE (rel->r_info) != R_RISCV_SUB_ULEB128)
1790 value += rel->r_addend;
1792 switch (ELFNN_R_TYPE (rel->r_info))
1794 case R_RISCV_HI20:
1795 case R_RISCV_TPREL_HI20:
1796 case R_RISCV_PCREL_HI20:
1797 case R_RISCV_GOT_HI20:
1798 case R_RISCV_TLS_GOT_HI20:
1799 case R_RISCV_TLS_GD_HI20:
1800 case R_RISCV_TLSDESC_HI20:
1801 if (ARCH_SIZE > 32 && !VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (value)))
1802 return bfd_reloc_overflow;
1803 value = ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value));
1804 break;
1806 case R_RISCV_LO12_I:
1807 case R_RISCV_GPREL_I:
1808 case R_RISCV_TPREL_LO12_I:
1809 case R_RISCV_TPREL_I:
1810 case R_RISCV_PCREL_LO12_I:
1811 case R_RISCV_TLSDESC_LOAD_LO12:
1812 case R_RISCV_TLSDESC_ADD_LO12:
1813 value = ENCODE_ITYPE_IMM (value);
1814 break;
1816 case R_RISCV_LO12_S:
1817 case R_RISCV_GPREL_S:
1818 case R_RISCV_TPREL_LO12_S:
1819 case R_RISCV_TPREL_S:
1820 case R_RISCV_PCREL_LO12_S:
1821 value = ENCODE_STYPE_IMM (value);
1822 break;
1824 case R_RISCV_CALL:
1825 case R_RISCV_CALL_PLT:
1826 if (ARCH_SIZE > 32 && !VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (value)))
1827 return bfd_reloc_overflow;
1828 value = ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value))
1829 | (ENCODE_ITYPE_IMM (value) << 32);
1830 break;
1832 case R_RISCV_JAL:
1833 if (!VALID_JTYPE_IMM (value))
1834 return bfd_reloc_overflow;
1835 value = ENCODE_JTYPE_IMM (value);
1836 break;
1838 case R_RISCV_BRANCH:
1839 if (!VALID_BTYPE_IMM (value))
1840 return bfd_reloc_overflow;
1841 value = ENCODE_BTYPE_IMM (value);
1842 break;
1844 case R_RISCV_RVC_BRANCH:
1845 if (!VALID_CBTYPE_IMM (value))
1846 return bfd_reloc_overflow;
1847 value = ENCODE_CBTYPE_IMM (value);
1848 break;
1850 case R_RISCV_RVC_JUMP:
1851 if (!VALID_CJTYPE_IMM (value))
1852 return bfd_reloc_overflow;
1853 value = ENCODE_CJTYPE_IMM (value);
1854 break;
1856 case R_RISCV_RVC_LUI:
1857 if (RISCV_CONST_HIGH_PART (value) == 0)
1859 /* Linker relaxation can convert an address equal to or greater than
1860 0x800 to slightly below 0x800. C.LUI does not accept zero as a
1861 valid immediate. We can fix this by converting it to a C.LI. */
1862 bfd_vma insn = riscv_get_insn (howto->bitsize,
1863 contents + rel->r_offset);
1864 insn = (insn & ~MATCH_C_LUI) | MATCH_C_LI;
1865 riscv_put_insn (howto->bitsize, insn, contents + rel->r_offset);
1866 value = ENCODE_CITYPE_IMM (0);
1868 else if (!VALID_CITYPE_LUI_IMM (RISCV_CONST_HIGH_PART (value)))
1869 return bfd_reloc_overflow;
1870 else
1871 value = ENCODE_CITYPE_LUI_IMM (RISCV_CONST_HIGH_PART (value));
1872 break;
1874 /* R_RISCV_SET_ULEB128 won't go into here. */
1875 case R_RISCV_SUB_ULEB128:
1877 unsigned int len = 0;
1878 _bfd_read_unsigned_leb128 (input_bfd, contents + rel->r_offset, &len);
1880 /* Clean the contents value to zero (0x80), but keep the original
1881 length. */
1882 bfd_byte *p = contents + rel->r_offset;
1883 bfd_byte *endp = p + len - 1;
1884 memset (p, 0x80, len - 1);
1885 *(endp) = 0;
1887 /* Make sure the length of the new uleb128 value within the
1888 original (available) length. */
1889 unsigned int new_len = 0;
1890 unsigned int val_t = value;
1893 new_len++;
1894 val_t >>= 7;
1896 while (val_t);
1897 if (new_len > len)
1899 _bfd_error_handler
1900 (_("final size of uleb128 value at offset 0x%lx in %pA from "
1901 "%pB exceeds available space"),
1902 (long) rel->r_offset, input_section, input_bfd);
1903 return bfd_reloc_dangerous;
1905 else
1907 p = _bfd_write_unsigned_leb128 (p, endp, value);
1908 BFD_ASSERT (p);
1910 /* If the length of the value is reduced and shorter than the
1911 original uleb128 length, then _bfd_write_unsigned_leb128 may
1912 clear the 0x80 to 0x0 for the last byte that was written.
1913 So reset it to keep the the original uleb128 length. */
1914 if (--p < endp)
1915 *p |= 0x80;
1917 return bfd_reloc_ok;
1920 case R_RISCV_32:
1921 case R_RISCV_64:
1922 case R_RISCV_ADD8:
1923 case R_RISCV_ADD16:
1924 case R_RISCV_ADD32:
1925 case R_RISCV_ADD64:
1926 case R_RISCV_SUB6:
1927 case R_RISCV_SUB8:
1928 case R_RISCV_SUB16:
1929 case R_RISCV_SUB32:
1930 case R_RISCV_SUB64:
1931 case R_RISCV_SET6:
1932 case R_RISCV_SET8:
1933 case R_RISCV_SET16:
1934 case R_RISCV_SET32:
1935 case R_RISCV_32_PCREL:
1936 case R_RISCV_TLS_DTPREL32:
1937 case R_RISCV_TLS_DTPREL64:
1938 break;
1940 case R_RISCV_DELETE:
1941 return bfd_reloc_ok;
1943 default:
1944 return bfd_reloc_notsupported;
1947 bfd_vma word;
1948 if (riscv_is_insn_reloc (howto))
1949 word = riscv_get_insn (howto->bitsize, contents + rel->r_offset);
1950 else
1951 word = bfd_get (howto->bitsize, input_bfd, contents + rel->r_offset);
1952 word = (word & ~howto->dst_mask) | (value & howto->dst_mask);
1953 if (riscv_is_insn_reloc (howto))
1954 riscv_put_insn (howto->bitsize, word, contents + rel->r_offset);
1955 else
1956 bfd_put (howto->bitsize, input_bfd, word, contents + rel->r_offset);
1958 return bfd_reloc_ok;
1961 /* Remember all PC-relative high-part relocs we've encountered to help us
1962 later resolve the corresponding low-part relocs. */
1964 typedef struct
1966 /* PC value. */
1967 bfd_vma address;
1968 /* Relocation value with addend. */
1969 bfd_vma value;
1970 /* Original reloc type. */
1971 int type;
1972 /* True if changed to R_RISCV_HI20. */
1973 bool absolute;
1974 } riscv_pcrel_hi_reloc;
1976 typedef struct riscv_pcrel_lo_reloc
1978 /* PC value of auipc. */
1979 bfd_vma address;
1980 /* Internal relocation. */
1981 Elf_Internal_Rela *reloc;
1982 /* Record the following information helps to resolve the %pcrel
1983 which cross different input section. For now we build a hash
1984 for pcrel at the start of riscv_elf_relocate_section, and then
1985 free the hash at the end. But riscv_elf_relocate_section only
1986 handles an input section at a time, so that means we can only
1987 resolve the %pcrel_hi and %pcrel_lo which are in the same input
1988 section. Otherwise, we will report dangerous relocation errors
1989 for those %pcrel which are not in the same input section. */
1990 asection *input_section;
1991 struct bfd_link_info *info;
1992 reloc_howto_type *howto;
1993 bfd_byte *contents;
1994 /* The next riscv_pcrel_lo_reloc. */
1995 struct riscv_pcrel_lo_reloc *next;
1996 } riscv_pcrel_lo_reloc;
1998 typedef struct
2000 /* Hash table for riscv_pcrel_hi_reloc. */
2001 htab_t hi_relocs;
2002 /* Linked list for riscv_pcrel_lo_reloc. */
2003 riscv_pcrel_lo_reloc *lo_relocs;
2004 } riscv_pcrel_relocs;
2006 static hashval_t
2007 riscv_pcrel_reloc_hash (const void *entry)
2009 const riscv_pcrel_hi_reloc *e = entry;
2010 return (hashval_t)(e->address >> 2);
2013 static int
2014 riscv_pcrel_reloc_eq (const void *entry1, const void *entry2)
2016 const riscv_pcrel_hi_reloc *e1 = entry1, *e2 = entry2;
2017 return e1->address == e2->address;
2020 static bool
2021 riscv_init_pcrel_relocs (riscv_pcrel_relocs *p)
2023 p->lo_relocs = NULL;
2024 p->hi_relocs = htab_create (1024, riscv_pcrel_reloc_hash,
2025 riscv_pcrel_reloc_eq, free);
2026 return p->hi_relocs != NULL;
2029 static void
2030 riscv_free_pcrel_relocs (riscv_pcrel_relocs *p)
2032 riscv_pcrel_lo_reloc *cur = p->lo_relocs;
2034 while (cur != NULL)
2036 riscv_pcrel_lo_reloc *next = cur->next;
2037 free (cur);
2038 cur = next;
2041 htab_delete (p->hi_relocs);
2044 static bool
2045 riscv_zero_pcrel_hi_reloc (Elf_Internal_Rela *rel,
2046 struct bfd_link_info *info,
2047 bfd_vma pc,
2048 bfd_vma *addr,
2049 bfd_byte *contents,
2050 const reloc_howto_type *howto)
2052 /* We may need to reference low addreses in PC-relative modes even when the
2053 PC is far away from these addresses. For example, undefweak references
2054 need to produce the address 0 when linked. As 0 is far from the arbitrary
2055 addresses that we can link PC-relative programs at, the linker can't
2056 actually relocate references to those symbols. In order to allow these
2057 programs to work we simply convert the PC-relative auipc sequences to
2058 0-relative lui sequences. */
2059 if (bfd_link_pic (info))
2060 return false;
2062 /* If it's possible to reference the symbol using auipc we do so, as that's
2063 more in the spirit of the PC-relative relocations we're processing. */
2064 bfd_vma offset = *addr - pc;
2065 if (ARCH_SIZE == 32 || VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (offset)))
2066 return false;
2068 /* If it's impossible to reference this with a LUI-based offset then don't
2069 bother to convert it at all so users still see the PC-relative relocation
2070 in the truncation message. */
2071 if (ARCH_SIZE > 32 && !VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (*addr)))
2072 return false;
2074 /* PR27180, encode target absolute address into r_addend rather than
2075 r_sym. Clear the ADDR to avoid duplicate relocate in the
2076 perform_relocation. */
2077 rel->r_info = ELFNN_R_INFO (0, R_RISCV_HI20);
2078 rel->r_addend += *addr;
2079 *addr = 0;
2081 bfd_vma insn = riscv_get_insn (howto->bitsize, contents + rel->r_offset);
2082 insn = (insn & ~MASK_AUIPC) | MATCH_LUI;
2083 riscv_put_insn (howto->bitsize, insn, contents + rel->r_offset);
2084 return true;
2087 static bool
2088 riscv_record_pcrel_hi_reloc (riscv_pcrel_relocs *p,
2089 bfd_vma addr,
2090 bfd_vma value,
2091 int type,
2092 bool absolute)
2094 bfd_vma offset = absolute ? value : value - addr;
2095 riscv_pcrel_hi_reloc entry = {addr, offset, type, absolute};
2096 riscv_pcrel_hi_reloc **slot =
2097 (riscv_pcrel_hi_reloc **) htab_find_slot (p->hi_relocs, &entry, INSERT);
2099 BFD_ASSERT (*slot == NULL);
2100 *slot = (riscv_pcrel_hi_reloc *) bfd_malloc (sizeof (riscv_pcrel_hi_reloc));
2101 if (*slot == NULL)
2102 return false;
2103 **slot = entry;
2104 return true;
2107 static bool
2108 riscv_record_pcrel_lo_reloc (riscv_pcrel_relocs *p,
2109 bfd_vma addr,
2110 Elf_Internal_Rela *reloc,
2111 asection *input_section,
2112 struct bfd_link_info *info,
2113 reloc_howto_type *howto,
2114 bfd_byte *contents)
2116 riscv_pcrel_lo_reloc *entry;
2117 entry = (riscv_pcrel_lo_reloc *) bfd_malloc (sizeof (riscv_pcrel_lo_reloc));
2118 if (entry == NULL)
2119 return false;
2120 *entry = (riscv_pcrel_lo_reloc) {addr, reloc, input_section, info,
2121 howto, contents, p->lo_relocs};
2122 p->lo_relocs = entry;
2123 return true;
2126 static bool
2127 riscv_resolve_pcrel_lo_relocs (riscv_pcrel_relocs *p)
2129 riscv_pcrel_lo_reloc *r;
2131 for (r = p->lo_relocs; r != NULL; r = r->next)
2133 bfd *input_bfd = r->input_section->owner;
2135 riscv_pcrel_hi_reloc search = {r->address, 0, 0, 0};
2136 riscv_pcrel_hi_reloc *entry = htab_find (p->hi_relocs, &search);
2137 /* There may be a risk if the %pcrel_lo with addend refers to
2138 an IFUNC symbol. The %pcrel_hi has been relocated to plt,
2139 so the corresponding %pcrel_lo with addend looks wrong. */
2140 char *string = NULL;
2141 if (entry == NULL)
2142 string = _("%pcrel_lo missing matching %pcrel_hi");
2143 else if (entry->type == R_RISCV_GOT_HI20
2144 && r->reloc->r_addend != 0)
2145 string = _("%pcrel_lo with addend isn't allowed for R_RISCV_GOT_HI20");
2146 else if (RISCV_CONST_HIGH_PART (entry->value)
2147 != RISCV_CONST_HIGH_PART (entry->value + r->reloc->r_addend))
2149 /* Check the overflow when adding reloc addend. */
2150 string = bfd_asprintf (_("%%pcrel_lo overflow with an addend,"
2151 " the value of %%pcrel_hi is 0x%" PRIx64
2152 " without any addend, but may be 0x%" PRIx64
2153 " after adding the %%pcrel_lo addend"),
2154 (int64_t) RISCV_CONST_HIGH_PART (entry->value),
2155 (int64_t) RISCV_CONST_HIGH_PART
2156 (entry->value + r->reloc->r_addend));
2157 if (string == NULL)
2158 string = _("%pcrel_lo overflow with an addend");
2161 if (string != NULL)
2163 (*r->info->callbacks->reloc_dangerous)
2164 (r->info, string, input_bfd, r->input_section, r->reloc->r_offset);
2165 return true;
2168 perform_relocation (r->howto, r->reloc, entry->value, r->input_section,
2169 input_bfd, r->contents);
2171 /* The corresponding R_RISCV_GOT_PCREL_HI20 and R_RISCV_PCREL_HI20 are
2172 converted to R_RISCV_HI20, so try to convert R_RISCV_PCREL_LO12_I/S
2173 to R_RISCV_LO12_I/S. */
2174 if (entry->absolute)
2176 switch (ELFNN_R_TYPE (r->reloc->r_info))
2178 case R_RISCV_PCREL_LO12_I:
2179 r->reloc->r_info = ELFNN_R_INFO (0, R_RISCV_LO12_I);
2180 r->reloc->r_addend += entry->value;
2181 break;
2182 case R_RISCV_PCREL_LO12_S:
2183 r->reloc->r_info = ELFNN_R_INFO (0, R_RISCV_LO12_S);
2184 r->reloc->r_addend += entry->value;
2185 break;
2186 default:
2187 /* This shouldn't happen, so just skip it. */
2188 break;
2193 return true;
2196 /* Relocate a RISC-V ELF section.
2198 The RELOCATE_SECTION function is called by the new ELF backend linker
2199 to handle the relocations for a section.
2201 The relocs are always passed as Rela structures.
2203 This function is responsible for adjusting the section contents as
2204 necessary, and (if generating a relocatable output file) adjusting
2205 the reloc addend as necessary.
2207 This function does not have to worry about setting the reloc
2208 address or the reloc symbol index.
2210 LOCAL_SYMS is a pointer to the swapped in local symbols.
2212 LOCAL_SECTIONS is an array giving the section in the input file
2213 corresponding to the st_shndx field of each local symbol.
2215 The global hash table entry for the global symbols can be found
2216 via elf_sym_hashes (input_bfd).
2218 When generating relocatable output, this function must handle
2219 STB_LOCAL/STT_SECTION symbols specially. The output symbol is
2220 going to be the section symbol corresponding to the output
2221 section, which means that the addend must be adjusted
2222 accordingly. */
2224 static int
2225 riscv_elf_relocate_section (bfd *output_bfd,
2226 struct bfd_link_info *info,
2227 bfd *input_bfd,
2228 asection *input_section,
2229 bfd_byte *contents,
2230 Elf_Internal_Rela *relocs,
2231 Elf_Internal_Sym *local_syms,
2232 asection **local_sections)
2234 Elf_Internal_Rela *rel;
2235 Elf_Internal_Rela *relend;
2236 riscv_pcrel_relocs pcrel_relocs;
2237 bool ret = false;
2238 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
2239 Elf_Internal_Shdr *symtab_hdr = &elf_symtab_hdr (input_bfd);
2240 struct elf_link_hash_entry **sym_hashes = elf_sym_hashes (input_bfd);
2241 bfd_vma *local_got_offsets = elf_local_got_offsets (input_bfd);
2242 bfd_vma uleb128_set_vma = 0;
2243 Elf_Internal_Rela *uleb128_set_rel = NULL;
2244 bool absolute;
2246 if (!riscv_init_pcrel_relocs (&pcrel_relocs))
2247 return false;
2249 relend = relocs + input_section->reloc_count;
2250 for (rel = relocs; rel < relend; rel++)
2252 unsigned long r_symndx;
2253 struct elf_link_hash_entry *h;
2254 Elf_Internal_Sym *sym;
2255 asection *sec;
2256 bfd_vma relocation;
2257 bfd_reloc_status_type r = bfd_reloc_ok;
2258 const char *name = NULL;
2259 bfd_vma off, ie_off, desc_off;
2260 bool unresolved_reloc, is_ie = false, is_desc = false;
2261 bfd_vma pc = sec_addr (input_section) + rel->r_offset;
2262 int r_type = ELFNN_R_TYPE (rel->r_info), tls_type;
2263 reloc_howto_type *howto = riscv_elf_rtype_to_howto (input_bfd, r_type);
2264 const char *msg = NULL;
2265 bool resolved_to_zero;
2267 if (howto == NULL)
2268 continue;
2270 /* This is a final link. */
2271 r_symndx = ELFNN_R_SYM (rel->r_info);
2272 h = NULL;
2273 sym = NULL;
2274 sec = NULL;
2275 unresolved_reloc = false;
2276 if (r_symndx < symtab_hdr->sh_info)
2278 sym = local_syms + r_symndx;
2279 sec = local_sections[r_symndx];
2280 relocation = _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
2282 /* Relocate against local STT_GNU_IFUNC symbol. */
2283 if (!bfd_link_relocatable (info)
2284 && ELF_ST_TYPE (sym->st_info) == STT_GNU_IFUNC)
2286 h = riscv_elf_get_local_sym_hash (htab, input_bfd, rel, false);
2287 if (h == NULL)
2288 abort ();
2290 /* Set STT_GNU_IFUNC symbol value. */
2291 h->root.u.def.value = sym->st_value;
2292 h->root.u.def.section = sec;
2295 else
2297 bool warned, ignored;
2299 RELOC_FOR_GLOBAL_SYMBOL (info, input_bfd, input_section, rel,
2300 r_symndx, symtab_hdr, sym_hashes,
2301 h, sec, relocation,
2302 unresolved_reloc, warned, ignored);
2303 if (warned)
2305 /* To avoid generating warning messages about truncated
2306 relocations, set the relocation's address to be the same as
2307 the start of this section. */
2308 if (input_section->output_section != NULL)
2309 relocation = input_section->output_section->vma;
2310 else
2311 relocation = 0;
2315 if (sec != NULL && discarded_section (sec))
2316 RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
2317 rel, 1, relend, howto, 0, contents);
2319 if (bfd_link_relocatable (info))
2320 continue;
2322 /* Since STT_GNU_IFUNC symbol must go through PLT, we handle
2323 it here if it is defined in a non-shared object. */
2324 if (h != NULL
2325 && h->type == STT_GNU_IFUNC
2326 && h->def_regular)
2328 asection *plt, *base_got;
2330 if ((input_section->flags & SEC_ALLOC) == 0)
2332 /* If this is a SHT_NOTE section without SHF_ALLOC, treat
2333 STT_GNU_IFUNC symbol as STT_FUNC. */
2334 if (elf_section_type (input_section) == SHT_NOTE)
2335 goto skip_ifunc;
2337 /* Dynamic relocs are not propagated for SEC_DEBUGGING
2338 sections because such sections are not SEC_ALLOC and
2339 thus ld.so will not process them. */
2340 if ((input_section->flags & SEC_DEBUGGING) != 0)
2341 continue;
2343 abort ();
2345 else if (h->plt.offset == (bfd_vma) -1
2346 /* The following relocation may not need the .plt entries
2347 when all references to a STT_GNU_IFUNC symbols are done
2348 via GOT or static function pointers. */
2349 && r_type != R_RISCV_32
2350 && r_type != R_RISCV_64
2351 && r_type != R_RISCV_HI20
2352 && r_type != R_RISCV_GOT_HI20
2353 && r_type != R_RISCV_LO12_I
2354 && r_type != R_RISCV_LO12_S)
2355 goto bad_ifunc_reloc;
2357 /* STT_GNU_IFUNC symbol must go through PLT. */
2358 plt = htab->elf.splt ? htab->elf.splt : htab->elf.iplt;
2359 relocation = plt->output_section->vma
2360 + plt->output_offset
2361 + h->plt.offset;
2363 switch (r_type)
2365 case R_RISCV_32:
2366 case R_RISCV_64:
2367 if (rel->r_addend != 0)
2369 if (h->root.root.string)
2370 name = h->root.root.string;
2371 else
2372 name = bfd_elf_sym_name (input_bfd, symtab_hdr, sym, NULL);
2374 _bfd_error_handler
2375 /* xgettext:c-format */
2376 (_("%pB: relocation %s against STT_GNU_IFUNC "
2377 "symbol `%s' has non-zero addend: %" PRId64),
2378 input_bfd, howto->name, name, (int64_t) rel->r_addend);
2379 bfd_set_error (bfd_error_bad_value);
2380 return false;
2383 /* Generate dynamic relocation only when there is a non-GOT
2384 reference in a shared object or there is no PLT. */
2385 if ((bfd_link_pic (info) && h->non_got_ref)
2386 || h->plt.offset == (bfd_vma) -1)
2388 Elf_Internal_Rela outrel;
2390 /* Need a dynamic relocation to get the real function
2391 address. */
2392 outrel.r_offset = _bfd_elf_section_offset (output_bfd,
2393 info,
2394 input_section,
2395 rel->r_offset);
2396 if (outrel.r_offset == (bfd_vma) -1
2397 || outrel.r_offset == (bfd_vma) -2)
2398 abort ();
2400 outrel.r_offset += input_section->output_section->vma
2401 + input_section->output_offset;
2403 if (h->dynindx == -1
2404 || h->forced_local
2405 || bfd_link_executable (info))
2407 info->callbacks->minfo
2408 (_("Local IFUNC function `%s' in %pB\n"),
2409 h->root.root.string,
2410 h->root.u.def.section->owner);
2412 /* This symbol is resolved locally. */
2413 outrel.r_info = ELFNN_R_INFO (0, R_RISCV_IRELATIVE);
2414 outrel.r_addend = h->root.u.def.value
2415 + h->root.u.def.section->output_section->vma
2416 + h->root.u.def.section->output_offset;
2418 else
2420 outrel.r_info = ELFNN_R_INFO (h->dynindx, r_type);
2421 outrel.r_addend = 0;
2424 /* Dynamic relocations are stored in
2425 1. .rela.ifunc section in PIC object.
2426 2. .rela.got section in dynamic executable.
2427 3. .rela.iplt section in static executable. */
2428 if (bfd_link_pic (info))
2429 riscv_elf_append_rela (output_bfd, htab->elf.irelifunc,
2430 &outrel);
2431 else if (htab->elf.splt != NULL)
2432 riscv_elf_append_rela (output_bfd, htab->elf.srelgot,
2433 &outrel);
2434 else
2436 /* Do not use riscv_elf_append_rela to add dynamic
2437 relocs into .rela.iplt, since it may cause the
2438 overwrite problems. This is same as what we did
2439 in the riscv_elf_finish_dynamic_symbol. */
2440 const struct elf_backend_data *bed =
2441 get_elf_backend_data (output_bfd);
2442 bfd_vma iplt_idx = htab->last_iplt_index--;
2443 bfd_byte *loc = htab->elf.irelplt->contents
2444 + iplt_idx * sizeof (ElfNN_External_Rela);
2445 bed->s->swap_reloca_out (output_bfd, &outrel, loc);
2448 /* If this reloc is against an external symbol, we
2449 do not want to fiddle with the addend. Otherwise,
2450 we need to include the symbol value so that it
2451 becomes an addend for the dynamic reloc. For an
2452 internal symbol, we have updated addend. */
2453 continue;
2455 goto do_relocation;
2457 case R_RISCV_GOT_HI20:
2458 base_got = htab->elf.sgot;
2459 off = h->got.offset;
2461 if (base_got == NULL)
2462 abort ();
2464 if (off == (bfd_vma) -1)
2466 bfd_vma plt_idx;
2468 /* We can't use h->got.offset here to save state, or
2469 even just remember the offset, as finish_dynamic_symbol
2470 would use that as offset into .got. */
2472 if (htab->elf.splt != NULL)
2474 plt_idx = (h->plt.offset - PLT_HEADER_SIZE)
2475 / PLT_ENTRY_SIZE;
2476 off = GOTPLT_HEADER_SIZE + (plt_idx * GOT_ENTRY_SIZE);
2477 base_got = htab->elf.sgotplt;
2479 else
2481 plt_idx = h->plt.offset / PLT_ENTRY_SIZE;
2482 off = plt_idx * GOT_ENTRY_SIZE;
2483 base_got = htab->elf.igotplt;
2486 if (h->dynindx == -1
2487 || h->forced_local
2488 || info->symbolic)
2490 /* This references the local definition. We must
2491 initialize this entry in the global offset table.
2492 Since the offset must always be a multiple of 8,
2493 we use the least significant bit to record
2494 whether we have initialized it already.
2496 When doing a dynamic link, we create a .rela.got
2497 relocation entry to initialize the value. This
2498 is done in the finish_dynamic_symbol routine. */
2499 if ((off & 1) != 0)
2500 off &= ~1;
2501 else
2503 bfd_put_NN (output_bfd, relocation,
2504 base_got->contents + off);
2505 /* Note that this is harmless for the case,
2506 as -1 | 1 still is -1. */
2507 h->got.offset |= 1;
2512 relocation = base_got->output_section->vma
2513 + base_got->output_offset + off;
2515 if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2516 relocation, r_type,
2517 false))
2518 r = bfd_reloc_overflow;
2519 goto do_relocation;
2521 case R_RISCV_CALL:
2522 case R_RISCV_CALL_PLT:
2523 case R_RISCV_HI20:
2524 case R_RISCV_LO12_I:
2525 case R_RISCV_LO12_S:
2526 goto do_relocation;
2528 case R_RISCV_PCREL_HI20:
2529 if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2530 relocation, r_type,
2531 false))
2532 r = bfd_reloc_overflow;
2533 goto do_relocation;
2535 default:
2536 bad_ifunc_reloc:
2537 if (h->root.root.string)
2538 name = h->root.root.string;
2539 else
2540 /* The entry of local ifunc is fake in global hash table,
2541 we should find the name by the original local symbol. */
2542 name = bfd_elf_sym_name (input_bfd, symtab_hdr, sym, NULL);
2544 _bfd_error_handler
2545 /* xgettext:c-format */
2546 (_("%pB: relocation %s against STT_GNU_IFUNC "
2547 "symbol `%s' isn't supported"), input_bfd,
2548 howto->name, name);
2549 bfd_set_error (bfd_error_bad_value);
2550 return false;
2554 skip_ifunc:
2555 if (h != NULL)
2556 name = h->root.root.string;
2557 else
2559 name = (bfd_elf_string_from_elf_section
2560 (input_bfd, symtab_hdr->sh_link, sym->st_name));
2561 if (name == NULL || *name == '\0')
2562 name = bfd_section_name (sec);
2565 resolved_to_zero = (h != NULL
2566 && UNDEFWEAK_NO_DYNAMIC_RELOC (info, h));
2568 switch (r_type)
2570 case R_RISCV_NONE:
2571 case R_RISCV_RELAX:
2572 case R_RISCV_TPREL_ADD:
2573 case R_RISCV_TLSDESC_CALL:
2574 case R_RISCV_COPY:
2575 case R_RISCV_JUMP_SLOT:
2576 case R_RISCV_RELATIVE:
2577 /* These require nothing of us at all. */
2578 continue;
2580 case R_RISCV_HI20:
2581 case R_RISCV_BRANCH:
2582 case R_RISCV_RVC_BRANCH:
2583 case R_RISCV_RVC_LUI:
2584 case R_RISCV_LO12_I:
2585 case R_RISCV_LO12_S:
2586 case R_RISCV_SET6:
2587 case R_RISCV_SET8:
2588 case R_RISCV_SET16:
2589 case R_RISCV_SET32:
2590 case R_RISCV_32_PCREL:
2591 case R_RISCV_DELETE:
2592 /* These require no special handling beyond perform_relocation. */
2593 break;
2595 case R_RISCV_SET_ULEB128:
2596 if (uleb128_set_rel == NULL)
2598 /* Saved for later usage. */
2599 uleb128_set_vma = relocation;
2600 uleb128_set_rel = rel;
2601 continue;
2603 else
2605 msg = ("Mismatched R_RISCV_SET_ULEB128, it must be paired with"
2606 " and applied before R_RISCV_SUB_ULEB128");
2607 r = bfd_reloc_dangerous;
2609 break;
2611 case R_RISCV_SUB_ULEB128:
2612 if (uleb128_set_rel != NULL
2613 && uleb128_set_rel->r_offset == rel->r_offset)
2615 relocation = uleb128_set_vma - relocation
2616 + uleb128_set_rel->r_addend;
2617 uleb128_set_vma = 0;
2618 uleb128_set_rel = NULL;
2620 /* PR31179, the addend of SUB_ULEB128 should be zero if using
2621 .uleb128, but we make it non-zero by accident in assembler,
2622 so just ignore it in perform_relocation, and make assembler
2623 continue doing the right thing. Don't reset the addend of
2624 SUB_ULEB128 to zero here since it will break the --emit-reloc,
2625 even though the non-zero addend is unexpected.
2627 We encourage people to rebuild their stuff to get the
2628 non-zero addend of SUB_ULEB128, but that might need some
2629 times, so report warnings to inform people need to rebuild
2630 if --check-uleb128 is enabled. However, since the failed
2631 .reloc cases for ADD/SET/SUB/ULEB128 are rarely to use, it
2632 may acceptable that stop supproting them until people rebuld
2633 their stuff, maybe half-year or one year later. I believe
2634 this might be the least harmful option that we should go.
2636 Or maybe we should teach people that don't write the
2637 .reloc R_RISCV_SUB* with non-zero constant, and report
2638 warnings/errors in assembler. */
2639 if (htab->params->check_uleb128
2640 && rel->r_addend != 0)
2641 _bfd_error_handler (_("%pB: warning: R_RISCV_SUB_ULEB128 with"
2642 " non-zero addend, please rebuild by"
2643 " binutils 2.42 or up"), input_bfd);
2645 else
2647 msg = ("Mismatched R_RISCV_SUB_ULEB128, it must be paired with"
2648 " and applied after R_RISCV_SET_ULEB128");
2649 r = bfd_reloc_dangerous;
2651 break;
2653 case R_RISCV_GOT_HI20:
2654 if (h != NULL)
2656 off = h->got.offset;
2657 BFD_ASSERT (off != (bfd_vma) -1);
2659 if (RISCV_RESOLVED_LOCALLY (info, h))
2661 /* We must initialize this entry in the global offset table.
2662 Since the offset must always be a multiple of the word
2663 size, we use the least significant bit to record whether
2664 we have initialized it already.
2666 When doing a dynamic link, we create a .rela.got
2667 relocation entry to initialize the value. This
2668 is done in the finish_dynamic_symbol routine. */
2669 if ((off & 1) != 0)
2670 off &= ~1;
2671 else
2673 bfd_put_NN (output_bfd, relocation,
2674 htab->elf.sgot->contents + off);
2675 h->got.offset |= 1;
2678 else
2679 unresolved_reloc = false;
2681 else
2683 BFD_ASSERT (local_got_offsets != NULL
2684 && local_got_offsets[r_symndx] != (bfd_vma) -1);
2686 off = local_got_offsets[r_symndx];
2688 /* The offset must always be a multiple of the word size.
2689 So, we can use the least significant bit to record
2690 whether we have already processed this entry. */
2691 if ((off & 1) != 0)
2692 off &= ~1;
2693 else
2695 if (bfd_link_pic (info))
2697 asection *s;
2698 Elf_Internal_Rela outrel;
2700 /* We need to generate a R_RISCV_RELATIVE reloc
2701 for the dynamic linker. */
2702 s = htab->elf.srelgot;
2703 BFD_ASSERT (s != NULL);
2705 outrel.r_offset = sec_addr (htab->elf.sgot) + off;
2706 outrel.r_info =
2707 ELFNN_R_INFO (0, R_RISCV_RELATIVE);
2708 outrel.r_addend = relocation;
2709 relocation = 0;
2710 riscv_elf_append_rela (output_bfd, s, &outrel);
2713 bfd_put_NN (output_bfd, relocation,
2714 htab->elf.sgot->contents + off);
2715 local_got_offsets[r_symndx] |= 1;
2719 if (rel->r_addend != 0)
2721 msg = _("The addend isn't allowed for R_RISCV_GOT_HI20");
2722 r = bfd_reloc_dangerous;
2724 else
2726 /* Address of got entry. */
2727 relocation = sec_addr (htab->elf.sgot) + off;
2728 absolute = riscv_zero_pcrel_hi_reloc (rel, info, pc,
2729 &relocation, contents,
2730 howto);
2731 /* Update howto if relocation is changed. */
2732 howto = riscv_elf_rtype_to_howto (input_bfd,
2733 ELFNN_R_TYPE (rel->r_info));
2734 if (howto == NULL)
2735 r = bfd_reloc_notsupported;
2736 else if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2737 relocation + rel->r_addend,
2738 r_type, absolute))
2739 r = bfd_reloc_overflow;
2741 break;
2743 case R_RISCV_ADD8:
2744 case R_RISCV_ADD16:
2745 case R_RISCV_ADD32:
2746 case R_RISCV_ADD64:
2748 bfd_vma old_value = bfd_get (howto->bitsize, input_bfd,
2749 contents + rel->r_offset);
2750 relocation = old_value + relocation;
2752 break;
2754 case R_RISCV_SUB6:
2756 bfd_vma old_value = bfd_get (howto->bitsize, input_bfd,
2757 contents + rel->r_offset);
2758 relocation = (old_value & ~howto->dst_mask)
2759 | (((old_value & howto->dst_mask) - relocation)
2760 & howto->dst_mask);
2762 break;
2764 case R_RISCV_SUB8:
2765 case R_RISCV_SUB16:
2766 case R_RISCV_SUB32:
2767 case R_RISCV_SUB64:
2769 bfd_vma old_value = bfd_get (howto->bitsize, input_bfd,
2770 contents + rel->r_offset);
2771 relocation = old_value - relocation;
2773 break;
2775 case R_RISCV_CALL:
2776 case R_RISCV_CALL_PLT:
2777 /* Handle a call to an undefined weak function. This won't be
2778 relaxed, so we have to handle it here. */
2779 if (h != NULL && h->root.type == bfd_link_hash_undefweak
2780 && (!bfd_link_pic (info) || h->plt.offset == MINUS_ONE))
2782 /* We can use x0 as the base register. */
2783 bfd_vma insn = bfd_getl32 (contents + rel->r_offset + 4);
2784 insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
2785 bfd_putl32 (insn, contents + rel->r_offset + 4);
2786 /* Set the relocation value so that we get 0 after the pc
2787 relative adjustment. */
2788 relocation = sec_addr (input_section) + rel->r_offset;
2790 /* Fall through. */
2792 case R_RISCV_JAL:
2793 case R_RISCV_RVC_JUMP:
2794 if (bfd_link_pic (info) && h != NULL)
2796 if (h->plt.offset != MINUS_ONE)
2798 /* Refer to the PLT entry. This check has to match the
2799 check in _bfd_riscv_relax_section. */
2800 relocation = sec_addr (htab->elf.splt) + h->plt.offset;
2801 unresolved_reloc = false;
2803 else if (!SYMBOL_REFERENCES_LOCAL (info, h)
2804 && (input_section->flags & SEC_ALLOC) != 0
2805 && (input_section->flags & SEC_READONLY) != 0
2806 && ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
2808 /* PR 28509, when generating the shared object, these
2809 referenced symbols may bind externally, which means
2810 they will be exported to the dynamic symbol table,
2811 and are preemptible by default. These symbols cannot
2812 be referenced by the non-pic relocations, like
2813 R_RISCV_JAL and R_RISCV_RVC_JUMP relocations.
2815 However, consider that linker may relax the R_RISCV_CALL
2816 relocations to R_RISCV_JAL or R_RISCV_RVC_JUMP, if
2817 these relocations are relocated to the plt entries,
2818 then we won't report error for them.
2820 Perhaps we also need the similar checks for the
2821 R_RISCV_BRANCH and R_RISCV_RVC_BRANCH relocations. */
2822 msg = bfd_asprintf (_("%%X%%P: relocation %s against `%s'"
2823 " which may bind externally"
2824 " can not be used"
2825 " when making a shared object;"
2826 " recompile with -fPIC\n"),
2827 howto->name, h->root.root.string);
2828 r = bfd_reloc_notsupported;
2831 break;
2833 case R_RISCV_TPREL_HI20:
2834 relocation = tpoff (info, relocation);
2835 break;
2837 case R_RISCV_TPREL_LO12_I:
2838 case R_RISCV_TPREL_LO12_S:
2839 relocation = tpoff (info, relocation);
2840 break;
2842 case R_RISCV_TPREL_I:
2843 case R_RISCV_TPREL_S:
2844 relocation = tpoff (info, relocation);
2845 if (VALID_ITYPE_IMM (relocation + rel->r_addend))
2847 /* We can use tp as the base register. */
2848 bfd_vma insn = bfd_getl32 (contents + rel->r_offset);
2849 insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
2850 insn |= X_TP << OP_SH_RS1;
2851 bfd_putl32 (insn, contents + rel->r_offset);
2853 else
2854 r = bfd_reloc_overflow;
2855 break;
2857 case R_RISCV_GPREL_I:
2858 case R_RISCV_GPREL_S:
2860 bfd_vma gp = riscv_global_pointer_value (info);
2861 bool x0_base = VALID_ITYPE_IMM (relocation + rel->r_addend);
2862 if (x0_base || VALID_ITYPE_IMM (relocation + rel->r_addend - gp))
2864 /* We can use x0 or gp as the base register. */
2865 bfd_vma insn = bfd_getl32 (contents + rel->r_offset);
2866 insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
2867 if (!x0_base)
2869 rel->r_addend -= gp;
2870 insn |= X_GP << OP_SH_RS1;
2872 bfd_putl32 (insn, contents + rel->r_offset);
2874 else
2875 r = bfd_reloc_overflow;
2876 break;
2879 case R_RISCV_PCREL_HI20:
2880 absolute = riscv_zero_pcrel_hi_reloc (rel, info, pc, &relocation,
2881 contents, howto);
2882 /* Update howto if relocation is changed. */
2883 howto = riscv_elf_rtype_to_howto (input_bfd,
2884 ELFNN_R_TYPE (rel->r_info));
2885 if (howto == NULL)
2886 r = bfd_reloc_notsupported;
2887 else if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2888 relocation + rel->r_addend,
2889 r_type, absolute))
2890 r = bfd_reloc_overflow;
2891 break;
2893 case R_RISCV_PCREL_LO12_I:
2894 case R_RISCV_PCREL_LO12_S:
2895 /* We don't allow section symbols plus addends as the auipc address,
2896 because then riscv_relax_delete_bytes would have to search through
2897 all relocs to update these addends. This is also ambiguous, as
2898 we do allow offsets to be added to the target address, which are
2899 not to be used to find the auipc address. */
2900 if (((sym != NULL && (ELF_ST_TYPE (sym->st_info) == STT_SECTION))
2901 || (h != NULL && h->type == STT_SECTION))
2902 && rel->r_addend)
2904 msg = _("%pcrel_lo section symbol with an addend");
2905 r = bfd_reloc_dangerous;
2906 break;
2909 if (riscv_record_pcrel_lo_reloc (&pcrel_relocs, relocation, rel,
2910 input_section, info, howto,
2911 contents))
2912 continue;
2913 r = bfd_reloc_overflow;
2914 break;
2916 case R_RISCV_TLS_DTPREL32:
2917 case R_RISCV_TLS_DTPREL64:
2918 relocation = dtpoff (info, relocation);
2919 break;
2921 case R_RISCV_TLSDESC_LOAD_LO12:
2922 case R_RISCV_TLSDESC_ADD_LO12:
2923 if (rel->r_addend)
2925 msg = _("%tlsdesc_lo with addend");
2926 r = bfd_reloc_dangerous;
2927 break;
2930 if (riscv_record_pcrel_lo_reloc (&pcrel_relocs, relocation, rel,
2931 input_section, info, howto,
2932 contents))
2933 continue;
2934 r = bfd_reloc_overflow;
2935 break;
2937 case R_RISCV_32:
2938 /* Non ABS symbol should be blocked in check_relocs. */
2939 if (ARCH_SIZE > 32)
2940 break;
2941 /* Fall through. */
2943 case R_RISCV_64:
2944 if ((input_section->flags & SEC_ALLOC) == 0)
2945 break;
2947 if (RISCV_GENERATE_DYNAMIC_RELOC (howto->pc_relative, info, h,
2948 resolved_to_zero))
2950 Elf_Internal_Rela outrel;
2951 asection *sreloc;
2953 /* When generating a shared object, these relocations
2954 are copied into the output file to be resolved at run
2955 time. */
2957 outrel.r_offset =
2958 _bfd_elf_section_offset (output_bfd, info, input_section,
2959 rel->r_offset);
2960 bool skip = false;
2961 bool relocate = false;
2962 if (outrel.r_offset == (bfd_vma) -1)
2963 skip = true;
2964 else if (outrel.r_offset == (bfd_vma) -2)
2966 skip = true;
2967 relocate = true;
2969 else if (h != NULL && bfd_is_abs_symbol (&h->root))
2971 /* Don't need dynamic reloc when the ABS symbol is
2972 non-dynamic or forced to local. Maybe just use
2973 SYMBOL_REFERENCES_LOCAL to check? */
2974 skip = (h->forced_local || (h->dynindx == -1));
2975 relocate = skip;
2978 outrel.r_offset += sec_addr (input_section);
2980 if (skip)
2981 memset (&outrel, 0, sizeof outrel); /* R_RISCV_NONE. */
2982 else if (RISCV_COPY_INPUT_RELOC (info, h))
2984 /* Maybe just use !SYMBOL_REFERENCES_LOCAL to check? */
2985 outrel.r_info = ELFNN_R_INFO (h->dynindx, r_type);
2986 outrel.r_addend = rel->r_addend;
2988 else
2990 /* This symbol is local, or marked to become local. */
2991 outrel.r_info = ELFNN_R_INFO (0, R_RISCV_RELATIVE);
2992 outrel.r_addend = relocation + rel->r_addend;
2995 sreloc = elf_section_data (input_section)->sreloc;
2996 riscv_elf_append_rela (output_bfd, sreloc, &outrel);
2997 if (!relocate)
2998 continue;
3000 break;
3002 case R_RISCV_TLSDESC_HI20:
3003 is_desc = true;
3004 goto tls;
3006 case R_RISCV_TLS_GOT_HI20:
3007 is_ie = true;
3008 goto tls;
3010 case R_RISCV_TLS_GD_HI20:
3011 tls:
3012 if (h != NULL)
3014 off = h->got.offset;
3015 h->got.offset |= 1;
3017 else
3019 off = local_got_offsets[r_symndx];
3020 local_got_offsets[r_symndx] |= 1;
3023 tls_type = _bfd_riscv_elf_tls_type (input_bfd, h, r_symndx);
3024 BFD_ASSERT (tls_type & (GOT_TLS_IE | GOT_TLS_GD | GOT_TLSDESC));
3025 /* When more than one TLS type is used, the GD slot comes first,
3026 then IE, then finally TLSDESC. */
3027 ie_off = 0;
3028 if (tls_type & GOT_TLS_GD)
3029 ie_off += TLS_GD_GOT_ENTRY_SIZE;
3031 desc_off = ie_off;
3032 if (tls_type & GOT_TLS_IE)
3033 desc_off += TLS_IE_GOT_ENTRY_SIZE;
3035 if ((off & 1) != 0)
3036 off &= ~1;
3037 else
3039 Elf_Internal_Rela outrel;
3040 int indx = 0;
3041 bool need_relocs = false;
3043 if (htab->elf.srelgot == NULL)
3044 abort ();
3046 bool dyn = elf_hash_table (info)->dynamic_sections_created;
3047 RISCV_TLS_GD_IE_NEED_DYN_RELOC (info, dyn, h, indx, need_relocs);
3049 /* The GOT entries have not been initialized yet. Do it
3050 now, and emit any relocations. */
3051 if (tls_type & GOT_TLS_GD)
3053 if (need_relocs)
3055 outrel.r_offset = sec_addr (htab->elf.sgot) + off;
3056 outrel.r_addend = 0;
3057 outrel.r_info = ELFNN_R_INFO (indx, R_RISCV_TLS_DTPMODNN);
3058 bfd_put_NN (output_bfd, 0,
3059 htab->elf.sgot->contents + off);
3060 riscv_elf_append_rela (output_bfd, htab->elf.srelgot, &outrel);
3061 if (indx == 0)
3063 BFD_ASSERT (! unresolved_reloc);
3064 bfd_put_NN (output_bfd,
3065 dtpoff (info, relocation),
3066 (htab->elf.sgot->contents
3067 + off + RISCV_ELF_WORD_BYTES));
3069 else
3071 bfd_put_NN (output_bfd, 0,
3072 (htab->elf.sgot->contents
3073 + off + RISCV_ELF_WORD_BYTES));
3074 outrel.r_info = ELFNN_R_INFO (indx, R_RISCV_TLS_DTPRELNN);
3075 outrel.r_offset += RISCV_ELF_WORD_BYTES;
3076 riscv_elf_append_rela (output_bfd, htab->elf.srelgot, &outrel);
3079 else
3081 /* If we are not emitting relocations for a
3082 general dynamic reference, then we must be in a
3083 static link or an executable link with the
3084 symbol binding locally. Mark it as belonging
3085 to module 1, the executable. */
3086 bfd_put_NN (output_bfd, 1,
3087 htab->elf.sgot->contents + off);
3088 bfd_put_NN (output_bfd,
3089 dtpoff (info, relocation),
3090 (htab->elf.sgot->contents
3091 + off + RISCV_ELF_WORD_BYTES));
3095 if (tls_type & GOT_TLS_IE)
3097 if (need_relocs)
3099 bfd_put_NN (output_bfd, 0,
3100 htab->elf.sgot->contents + off + ie_off);
3101 outrel.r_offset = sec_addr (htab->elf.sgot)
3102 + off + ie_off;
3103 outrel.r_addend = 0;
3104 if (indx == 0)
3105 outrel.r_addend = tpoff (info, relocation);
3106 outrel.r_info = ELFNN_R_INFO (indx, R_RISCV_TLS_TPRELNN);
3107 riscv_elf_append_rela (output_bfd, htab->elf.srelgot, &outrel);
3109 else
3111 bfd_put_NN (output_bfd, tpoff (info, relocation),
3112 htab->elf.sgot->contents + off + ie_off);
3116 if (tls_type & GOT_TLSDESC)
3118 /* TLSDESC is always handled by the dynamic linker and always need
3119 * a relocation. */
3120 bfd_put_NN (output_bfd, 0,
3121 htab->elf.sgot->contents + off + desc_off);
3122 outrel.r_offset = sec_addr (htab->elf.sgot)
3123 + off + desc_off;
3124 outrel.r_addend = 0;
3125 if (indx == 0)
3126 outrel.r_addend = tlsdescoff (info, relocation);
3127 outrel.r_info = ELFNN_R_INFO (indx, R_RISCV_TLSDESC);
3128 riscv_elf_append_rela (output_bfd, htab->elf.srelgot, &outrel);
3132 BFD_ASSERT (off < (bfd_vma) -2);
3133 relocation = sec_addr (htab->elf.sgot) + off;
3134 if (is_ie)
3135 relocation += ie_off;
3136 else if (is_desc)
3137 relocation += desc_off;
3138 if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
3139 relocation, r_type,
3140 false))
3141 r = bfd_reloc_overflow;
3142 unresolved_reloc = false;
3143 break;
3145 default:
3146 r = bfd_reloc_notsupported;
3149 /* Dynamic relocs are not propagated for SEC_DEBUGGING sections
3150 because such sections are not SEC_ALLOC and thus ld.so will
3151 not process them. */
3152 if (unresolved_reloc
3153 && !((input_section->flags & SEC_DEBUGGING) != 0
3154 && h->def_dynamic)
3155 && _bfd_elf_section_offset (output_bfd, info, input_section,
3156 rel->r_offset) != (bfd_vma) -1)
3158 msg = bfd_asprintf (_("%%X%%P: unresolvable %s relocation against "
3159 "symbol `%s'\n"),
3160 howto->name,
3161 h->root.root.string);
3162 r = bfd_reloc_notsupported;
3165 do_relocation:
3166 if (r == bfd_reloc_ok)
3167 r = perform_relocation (howto, rel, relocation, input_section,
3168 input_bfd, contents);
3170 /* We should have already detected the error and set message before.
3171 If the error message isn't set since the linker runs out of memory
3172 or we don't set it before, then we should set the default message
3173 with the "internal error" string here. */
3174 switch (r)
3176 case bfd_reloc_ok:
3177 continue;
3179 case bfd_reloc_overflow:
3180 info->callbacks->reloc_overflow
3181 (info, (h ? &h->root : NULL), name, howto->name,
3182 (bfd_vma) 0, input_bfd, input_section, rel->r_offset);
3183 break;
3185 case bfd_reloc_undefined:
3186 info->callbacks->undefined_symbol
3187 (info, name, input_bfd, input_section, rel->r_offset,
3188 true);
3189 break;
3191 case bfd_reloc_outofrange:
3192 if (msg == NULL)
3193 msg = _("%X%P: internal error: out of range error\n");
3194 break;
3196 case bfd_reloc_notsupported:
3197 if (msg == NULL)
3198 msg = _("%X%P: internal error: unsupported relocation error\n");
3199 break;
3201 case bfd_reloc_dangerous:
3202 /* The error message should already be set. */
3203 if (msg == NULL)
3204 msg = _("dangerous relocation error");
3205 info->callbacks->reloc_dangerous
3206 (info, msg, input_bfd, input_section, rel->r_offset);
3207 break;
3209 default:
3210 msg = _("%X%P: internal error: unknown error\n");
3211 break;
3214 /* Do not report error message for the dangerous relocation again. */
3215 if (msg && r != bfd_reloc_dangerous)
3216 info->callbacks->einfo (msg);
3218 /* We already reported the error via a callback, so don't try to report
3219 it again by returning false. That leads to spurious errors. */
3220 ret = true;
3221 goto out;
3224 ret = riscv_resolve_pcrel_lo_relocs (&pcrel_relocs);
3225 out:
3226 riscv_free_pcrel_relocs (&pcrel_relocs);
3227 return ret;
3230 /* Finish up dynamic symbol handling. We set the contents of various
3231 dynamic sections here. */
3233 static bool
3234 riscv_elf_finish_dynamic_symbol (bfd *output_bfd,
3235 struct bfd_link_info *info,
3236 struct elf_link_hash_entry *h,
3237 Elf_Internal_Sym *sym)
3239 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
3240 const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
3242 if (h->plt.offset != (bfd_vma) -1)
3244 /* We've decided to create a PLT entry for this symbol. */
3245 bfd_byte *loc;
3246 bfd_vma i, header_address, plt_idx, got_offset, got_address;
3247 uint32_t plt_entry[PLT_ENTRY_INSNS];
3248 Elf_Internal_Rela rela;
3249 asection *plt, *gotplt, *relplt;
3251 /* When building a static executable, use .iplt, .igot.plt and
3252 .rela.iplt sections for STT_GNU_IFUNC symbols. */
3253 if (htab->elf.splt != NULL)
3255 plt = htab->elf.splt;
3256 gotplt = htab->elf.sgotplt;
3257 relplt = htab->elf.srelplt;
3259 else
3261 plt = htab->elf.iplt;
3262 gotplt = htab->elf.igotplt;
3263 relplt = htab->elf.irelplt;
3266 /* This symbol has an entry in the procedure linkage table. Set
3267 it up. */
3268 if ((h->dynindx == -1
3269 && !((h->forced_local || bfd_link_executable (info))
3270 && h->def_regular
3271 && h->type == STT_GNU_IFUNC))
3272 || plt == NULL
3273 || gotplt == NULL
3274 || relplt == NULL)
3275 abort ();
3277 /* Calculate the address of the PLT header. */
3278 header_address = sec_addr (plt);
3280 /* Calculate the index of the entry and the offset of .got.plt entry.
3281 For static executables, we don't reserve anything. */
3282 if (plt == htab->elf.splt)
3284 plt_idx = (h->plt.offset - PLT_HEADER_SIZE) / PLT_ENTRY_SIZE;
3285 got_offset = GOTPLT_HEADER_SIZE + (plt_idx * GOT_ENTRY_SIZE);
3287 else
3289 plt_idx = h->plt.offset / PLT_ENTRY_SIZE;
3290 got_offset = plt_idx * GOT_ENTRY_SIZE;
3293 /* Calculate the address of the .got.plt entry. */
3294 got_address = sec_addr (gotplt) + got_offset;
3296 /* Find out where the .plt entry should go. */
3297 loc = plt->contents + h->plt.offset;
3299 /* Fill in the PLT entry itself. */
3300 if (! riscv_make_plt_entry (output_bfd, got_address,
3301 header_address + h->plt.offset,
3302 plt_entry))
3303 return false;
3305 for (i = 0; i < PLT_ENTRY_INSNS; i++)
3306 bfd_putl32 (plt_entry[i], loc + 4*i);
3308 /* Fill in the initial value of the .got.plt entry. */
3309 loc = gotplt->contents + (got_address - sec_addr (gotplt));
3310 bfd_put_NN (output_bfd, sec_addr (plt), loc);
3312 rela.r_offset = got_address;
3314 if (h->dynindx == -1
3315 || ((bfd_link_executable (info)
3316 || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
3317 && h->def_regular
3318 && h->type == STT_GNU_IFUNC))
3320 info->callbacks->minfo (_("Local IFUNC function `%s' in %pB\n"),
3321 h->root.root.string,
3322 h->root.u.def.section->owner);
3324 /* If an STT_GNU_IFUNC symbol is locally defined, generate
3325 R_RISCV_IRELATIVE instead of R_RISCV_JUMP_SLOT. */
3326 asection *sec = h->root.u.def.section;
3327 rela.r_info = ELFNN_R_INFO (0, R_RISCV_IRELATIVE);
3328 rela.r_addend = h->root.u.def.value
3329 + sec->output_section->vma
3330 + sec->output_offset;
3332 else
3334 /* Fill in the entry in the .rela.plt section. */
3335 rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_JUMP_SLOT);
3336 rela.r_addend = 0;
3339 loc = relplt->contents + plt_idx * sizeof (ElfNN_External_Rela);
3340 bed->s->swap_reloca_out (output_bfd, &rela, loc);
3342 if (!h->def_regular)
3344 /* Mark the symbol as undefined, rather than as defined in
3345 the .plt section. Leave the value alone. */
3346 sym->st_shndx = SHN_UNDEF;
3347 /* If the symbol is weak, we do need to clear the value.
3348 Otherwise, the PLT entry would provide a definition for
3349 the symbol even if the symbol wasn't defined anywhere,
3350 and so the symbol would never be NULL. */
3351 if (!h->ref_regular_nonweak)
3352 sym->st_value = 0;
3356 if (h->got.offset != (bfd_vma) -1
3357 && !(riscv_elf_hash_entry (h)->tls_type & (GOT_TLS_GD | GOT_TLS_IE | GOT_TLSDESC))
3358 && !UNDEFWEAK_NO_DYNAMIC_RELOC (info, h))
3360 asection *sgot;
3361 asection *srela;
3362 Elf_Internal_Rela rela;
3363 bool use_elf_append_rela = true;
3365 /* This symbol has an entry in the GOT. Set it up. */
3367 sgot = htab->elf.sgot;
3368 srela = htab->elf.srelgot;
3369 BFD_ASSERT (sgot != NULL && srela != NULL);
3371 rela.r_offset = sec_addr (sgot) + (h->got.offset &~ (bfd_vma) 1);
3373 /* Handle the ifunc symbol in GOT entry. */
3374 if (h->def_regular
3375 && h->type == STT_GNU_IFUNC)
3377 if (h->plt.offset == (bfd_vma) -1)
3379 /* STT_GNU_IFUNC is referenced without PLT. */
3381 if (htab->elf.splt == NULL)
3383 /* Use .rela.iplt section to store .got relocations
3384 in static executable. */
3385 srela = htab->elf.irelplt;
3387 /* Do not use riscv_elf_append_rela to add dynamic
3388 relocs. */
3389 use_elf_append_rela = false;
3392 if (SYMBOL_REFERENCES_LOCAL (info, h))
3394 info->callbacks->minfo (_("Local IFUNC function `%s' in %pB\n"),
3395 h->root.root.string,
3396 h->root.u.def.section->owner);
3398 rela.r_info = ELFNN_R_INFO (0, R_RISCV_IRELATIVE);
3399 rela.r_addend = (h->root.u.def.value
3400 + h->root.u.def.section->output_section->vma
3401 + h->root.u.def.section->output_offset);
3403 else
3405 /* Generate R_RISCV_NN. */
3406 BFD_ASSERT ((h->got.offset & 1) == 0);
3407 BFD_ASSERT (h->dynindx != -1);
3408 rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_NN);
3409 rela.r_addend = 0;
3412 else if (bfd_link_pic (info))
3414 /* Generate R_RISCV_NN. */
3415 BFD_ASSERT ((h->got.offset & 1) == 0);
3416 BFD_ASSERT (h->dynindx != -1);
3417 rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_NN);
3418 rela.r_addend = 0;
3420 else
3422 asection *plt;
3424 if (!h->pointer_equality_needed)
3425 abort ();
3427 /* For non-shared object, we can't use .got.plt, which
3428 contains the real function address if we need pointer
3429 equality. We load the GOT entry with the PLT entry. */
3430 plt = htab->elf.splt ? htab->elf.splt : htab->elf.iplt;
3431 bfd_put_NN (output_bfd, (plt->output_section->vma
3432 + plt->output_offset
3433 + h->plt.offset),
3434 htab->elf.sgot->contents
3435 + (h->got.offset & ~(bfd_vma) 1));
3436 return true;
3439 else if (bfd_link_pic (info)
3440 && SYMBOL_REFERENCES_LOCAL (info, h))
3442 /* If this is a local symbol reference, we just want to emit
3443 a RELATIVE reloc. This can happen if it is a -Bsymbolic link,
3444 or a pie link, or the symbol was forced to be local because
3445 of a version file. The entry in the global offset table will
3446 already have been initialized in the relocate_section function. */
3447 BFD_ASSERT ((h->got.offset & 1) != 0);
3448 asection *sec = h->root.u.def.section;
3449 rela.r_info = ELFNN_R_INFO (0, R_RISCV_RELATIVE);
3450 rela.r_addend = (h->root.u.def.value
3451 + sec->output_section->vma
3452 + sec->output_offset);
3454 else
3456 BFD_ASSERT ((h->got.offset & 1) == 0);
3457 BFD_ASSERT (h->dynindx != -1);
3458 rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_NN);
3459 rela.r_addend = 0;
3462 bfd_put_NN (output_bfd, 0,
3463 sgot->contents + (h->got.offset & ~(bfd_vma) 1));
3465 if (use_elf_append_rela)
3466 riscv_elf_append_rela (output_bfd, srela, &rela);
3467 else
3469 /* Use riscv_elf_append_rela to add the dynamic relocs into
3470 .rela.iplt may cause the overwrite problems. Since we insert
3471 the relocs for PLT didn't handle the reloc_index of .rela.iplt,
3472 but the riscv_elf_append_rela adds the relocs to the place
3473 that are calculated from the reloc_index (in seqential).
3475 One solution is that add these dynamic relocs (GOT IFUNC)
3476 from the last of .rela.iplt section. */
3477 bfd_vma iplt_idx = htab->last_iplt_index--;
3478 bfd_byte *loc = srela->contents
3479 + iplt_idx * sizeof (ElfNN_External_Rela);
3480 bed->s->swap_reloca_out (output_bfd, &rela, loc);
3484 if (h->needs_copy)
3486 Elf_Internal_Rela rela;
3487 asection *s;
3489 /* This symbols needs a copy reloc. Set it up. */
3490 BFD_ASSERT (h->dynindx != -1);
3492 rela.r_offset = sec_addr (h->root.u.def.section) + h->root.u.def.value;
3493 rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_COPY);
3494 rela.r_addend = 0;
3495 if (h->root.u.def.section == htab->elf.sdynrelro)
3496 s = htab->elf.sreldynrelro;
3497 else
3498 s = htab->elf.srelbss;
3499 riscv_elf_append_rela (output_bfd, s, &rela);
3502 /* Mark some specially defined symbols as absolute. */
3503 if (h == htab->elf.hdynamic
3504 || (h == htab->elf.hgot || h == htab->elf.hplt))
3505 sym->st_shndx = SHN_ABS;
3507 return true;
3510 /* Finish up local dynamic symbol handling. We set the contents of
3511 various dynamic sections here. */
3513 static int
3514 riscv_elf_finish_local_dynamic_symbol (void **slot, void *inf)
3516 struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) *slot;
3517 struct bfd_link_info *info = (struct bfd_link_info *) inf;
3519 return riscv_elf_finish_dynamic_symbol (info->output_bfd, info, h, NULL);
3522 /* Finish up the dynamic sections. */
3524 static bool
3525 riscv_finish_dyn (bfd *output_bfd, struct bfd_link_info *info,
3526 bfd *dynobj, asection *sdyn)
3528 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
3529 const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
3530 size_t dynsize = bed->s->sizeof_dyn;
3531 bfd_byte *dyncon, *dynconend;
3533 dynconend = sdyn->contents + sdyn->size;
3534 for (dyncon = sdyn->contents; dyncon < dynconend; dyncon += dynsize)
3536 Elf_Internal_Dyn dyn;
3537 asection *s;
3539 bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
3541 switch (dyn.d_tag)
3543 case DT_PLTGOT:
3544 s = htab->elf.sgotplt;
3545 dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
3546 break;
3547 case DT_JMPREL:
3548 s = htab->elf.srelplt;
3549 dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
3550 break;
3551 case DT_PLTRELSZ:
3552 s = htab->elf.srelplt;
3553 dyn.d_un.d_val = s->size;
3554 break;
3555 default:
3556 continue;
3559 bed->s->swap_dyn_out (output_bfd, &dyn, dyncon);
3561 return true;
3564 static bool
3565 riscv_elf_finish_dynamic_sections (bfd *output_bfd,
3566 struct bfd_link_info *info)
3568 bfd *dynobj;
3569 asection *sdyn;
3570 struct riscv_elf_link_hash_table *htab;
3572 htab = riscv_elf_hash_table (info);
3573 BFD_ASSERT (htab != NULL);
3574 dynobj = htab->elf.dynobj;
3576 sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3578 if (elf_hash_table (info)->dynamic_sections_created)
3580 asection *splt;
3581 bool ret;
3583 splt = htab->elf.splt;
3584 BFD_ASSERT (splt != NULL && sdyn != NULL);
3586 ret = riscv_finish_dyn (output_bfd, info, dynobj, sdyn);
3588 if (!ret)
3589 return ret;
3591 /* Fill in the head and tail entries in the procedure linkage table. */
3592 if (splt->size > 0)
3594 int i;
3595 uint32_t plt_header[PLT_HEADER_INSNS];
3596 ret = riscv_make_plt_header (output_bfd,
3597 sec_addr (htab->elf.sgotplt),
3598 sec_addr (splt), plt_header);
3599 if (!ret)
3600 return ret;
3602 for (i = 0; i < PLT_HEADER_INSNS; i++)
3603 bfd_putl32 (plt_header[i], splt->contents + 4*i);
3605 elf_section_data (splt->output_section)->this_hdr.sh_entsize
3606 = PLT_ENTRY_SIZE;
3610 if (htab->elf.sgotplt && htab->elf.sgotplt->size > 0)
3612 asection *output_section = htab->elf.sgotplt->output_section;
3614 if (bfd_is_abs_section (output_section))
3616 (*_bfd_error_handler)
3617 (_("discarded output section: `%pA'"), htab->elf.sgotplt);
3618 return false;
3621 /* Write the first two entries in .got.plt, needed for the dynamic
3622 linker. */
3623 bfd_put_NN (output_bfd, (bfd_vma) -1, htab->elf.sgotplt->contents);
3624 bfd_put_NN (output_bfd, (bfd_vma) 0,
3625 htab->elf.sgotplt->contents + GOT_ENTRY_SIZE);
3627 elf_section_data (output_section)->this_hdr.sh_entsize = GOT_ENTRY_SIZE;
3630 if (htab->elf.sgot && htab->elf.sgot->size > 0)
3632 asection *output_section = htab->elf.sgot->output_section;
3634 if (!bfd_is_abs_section (output_section))
3636 /* Set the first entry in the global offset table to the address of
3637 the dynamic section. */
3638 bfd_vma val = sdyn ? sec_addr (sdyn) : 0;
3639 bfd_put_NN (output_bfd, val, htab->elf.sgot->contents);
3641 elf_section_data (output_section)->this_hdr.sh_entsize = GOT_ENTRY_SIZE;
3645 /* Fill PLT and GOT entries for local STT_GNU_IFUNC symbols. */
3646 htab_traverse (htab->loc_hash_table,
3647 riscv_elf_finish_local_dynamic_symbol,
3648 info);
3650 return true;
3653 /* Return address for Ith PLT stub in section PLT, for relocation REL
3654 or (bfd_vma) -1 if it should not be included. */
3656 static bfd_vma
3657 riscv_elf_plt_sym_val (bfd_vma i, const asection *plt,
3658 const arelent *rel ATTRIBUTE_UNUSED)
3660 return plt->vma + PLT_HEADER_SIZE + i * PLT_ENTRY_SIZE;
3663 static enum elf_reloc_type_class
3664 riscv_reloc_type_class (const struct bfd_link_info *info ATTRIBUTE_UNUSED,
3665 const asection *rel_sec ATTRIBUTE_UNUSED,
3666 const Elf_Internal_Rela *rela)
3668 switch (ELFNN_R_TYPE (rela->r_info))
3670 case R_RISCV_RELATIVE:
3671 return reloc_class_relative;
3672 case R_RISCV_JUMP_SLOT:
3673 return reloc_class_plt;
3674 case R_RISCV_COPY:
3675 return reloc_class_copy;
3676 default:
3677 return reloc_class_normal;
3681 /* Given the ELF header flags in FLAGS, it returns a string that describes the
3682 float ABI. */
3684 static const char *
3685 riscv_float_abi_string (flagword flags)
3687 switch (flags & EF_RISCV_FLOAT_ABI)
3689 case EF_RISCV_FLOAT_ABI_SOFT:
3690 return "soft-float";
3691 break;
3692 case EF_RISCV_FLOAT_ABI_SINGLE:
3693 return "single-float";
3694 break;
3695 case EF_RISCV_FLOAT_ABI_DOUBLE:
3696 return "double-float";
3697 break;
3698 case EF_RISCV_FLOAT_ABI_QUAD:
3699 return "quad-float";
3700 break;
3701 default:
3702 abort ();
3706 /* The information of architecture elf attributes. */
3707 static riscv_subset_list_t in_subsets;
3708 static riscv_subset_list_t out_subsets;
3709 static riscv_subset_list_t merged_subsets;
3711 /* Predicator for standard extension. */
3713 static bool
3714 riscv_std_ext_p (const char *name)
3716 return (strlen (name) == 1) && (name[0] != 'x') && (name[0] != 's');
3719 /* Update the output subset's version to match the input when the input
3720 subset's version is newer. */
3722 static void
3723 riscv_update_subset_version (struct riscv_subset_t *in,
3724 struct riscv_subset_t *out)
3726 if (in == NULL || out == NULL)
3727 return;
3729 /* Update the output ISA versions to the newest ones, but otherwise don't
3730 provide any errors or warnings about mis-matched ISA versions as it's
3731 generally too tricky to check for these at link time. */
3732 if ((in->major_version > out->major_version)
3733 || (in->major_version == out->major_version
3734 && in->minor_version > out->minor_version)
3735 || (out->major_version == RISCV_UNKNOWN_VERSION))
3737 out->major_version = in->major_version;
3738 out->minor_version = in->minor_version;
3742 /* Return true if subset is 'i' or 'e'. */
3744 static bool
3745 riscv_i_or_e_p (bfd *ibfd,
3746 const char *arch,
3747 struct riscv_subset_t *subset)
3749 if ((strcasecmp (subset->name, "e") != 0)
3750 && (strcasecmp (subset->name, "i") != 0))
3752 _bfd_error_handler
3753 (_("error: %pB: corrupted ISA string '%s'. "
3754 "First letter should be 'i' or 'e' but got '%s'"),
3755 ibfd, arch, subset->name);
3756 return false;
3758 return true;
3761 /* Merge standard extensions.
3763 Return Value:
3764 Return FALSE if failed to merge.
3766 Arguments:
3767 `bfd`: bfd handler.
3768 `in_arch`: Raw ISA string for input object.
3769 `out_arch`: Raw ISA string for output object.
3770 `pin`: Subset list for input object.
3771 `pout`: Subset list for output object. */
3773 static bool
3774 riscv_merge_std_ext (bfd *ibfd,
3775 const char *in_arch,
3776 const char *out_arch,
3777 struct riscv_subset_t **pin,
3778 struct riscv_subset_t **pout)
3780 const char *standard_exts = "mafdqlcbjtpvnh";
3781 const char *p;
3782 struct riscv_subset_t *in = *pin;
3783 struct riscv_subset_t *out = *pout;
3785 /* First letter should be 'i' or 'e'. */
3786 if (!riscv_i_or_e_p (ibfd, in_arch, in))
3787 return false;
3789 if (!riscv_i_or_e_p (ibfd, out_arch, out))
3790 return false;
3792 if (strcasecmp (in->name, out->name) != 0)
3794 /* TODO: We might allow merge 'i' with 'e'. */
3795 _bfd_error_handler
3796 (_("error: %pB: mis-matched ISA string to merge '%s' and '%s'"),
3797 ibfd, in->name, out->name);
3798 return false;
3801 riscv_update_subset_version(in, out);
3802 riscv_add_subset (&merged_subsets,
3803 out->name, out->major_version, out->minor_version);
3805 in = in->next;
3806 out = out->next;
3808 /* Handle standard extension first. */
3809 for (p = standard_exts; *p; ++p)
3811 struct riscv_subset_t *ext_in, *ext_out, *ext_merged;
3812 char find_ext[2] = {*p, '\0'};
3813 bool find_in, find_out;
3815 find_in = riscv_lookup_subset (&in_subsets, find_ext, &ext_in);
3816 find_out = riscv_lookup_subset (&out_subsets, find_ext, &ext_out);
3818 if (!find_in && !find_out)
3819 continue;
3821 if (find_in && find_out)
3822 riscv_update_subset_version(ext_in, ext_out);
3824 ext_merged = find_out ? ext_out : ext_in;
3825 riscv_add_subset (&merged_subsets, ext_merged->name,
3826 ext_merged->major_version, ext_merged->minor_version);
3829 /* Skip all standard extensions. */
3830 while ((in != NULL) && riscv_std_ext_p (in->name)) in = in->next;
3831 while ((out != NULL) && riscv_std_ext_p (out->name)) out = out->next;
3833 *pin = in;
3834 *pout = out;
3836 return true;
3839 /* Merge multi letter extensions. PIN is a pointer to the head of the input
3840 object subset list. Likewise for POUT and the output object. Return TRUE
3841 on success and FALSE when a conflict is found. */
3843 static bool
3844 riscv_merge_multi_letter_ext (riscv_subset_t **pin,
3845 riscv_subset_t **pout)
3847 riscv_subset_t *in = *pin;
3848 riscv_subset_t *out = *pout;
3849 riscv_subset_t *tail;
3851 int cmp;
3853 while (in && out)
3855 cmp = riscv_compare_subsets (in->name, out->name);
3857 if (cmp < 0)
3859 /* `in' comes before `out', append `in' and increment. */
3860 riscv_add_subset (&merged_subsets, in->name, in->major_version,
3861 in->minor_version);
3862 in = in->next;
3864 else if (cmp > 0)
3866 /* `out' comes before `in', append `out' and increment. */
3867 riscv_add_subset (&merged_subsets, out->name, out->major_version,
3868 out->minor_version);
3869 out = out->next;
3871 else
3873 /* Both present, check version and increment both. */
3874 riscv_update_subset_version (in, out);
3876 riscv_add_subset (&merged_subsets, out->name, out->major_version,
3877 out->minor_version);
3878 out = out->next;
3879 in = in->next;
3883 if (in || out)
3885 /* If we're here, either `in' or `out' is running longer than
3886 the other. So, we need to append the corresponding tail. */
3887 tail = in ? in : out;
3888 while (tail)
3890 riscv_add_subset (&merged_subsets, tail->name, tail->major_version,
3891 tail->minor_version);
3892 tail = tail->next;
3896 return true;
3899 /* Merge Tag_RISCV_arch attribute. */
3901 static char *
3902 riscv_merge_arch_attr_info (bfd *ibfd, char *in_arch, char *out_arch)
3904 riscv_subset_t *in, *out;
3905 char *merged_arch_str;
3907 unsigned xlen_in, xlen_out;
3908 merged_subsets.head = NULL;
3909 merged_subsets.tail = NULL;
3911 riscv_parse_subset_t riscv_rps_ld_in =
3912 {&in_subsets, _bfd_error_handler, &xlen_in, NULL, false};
3913 riscv_parse_subset_t riscv_rps_ld_out =
3914 {&out_subsets, _bfd_error_handler, &xlen_out, NULL, false};
3916 if (in_arch == NULL && out_arch == NULL)
3917 return NULL;
3918 if (in_arch == NULL && out_arch != NULL)
3919 return out_arch;
3920 if (in_arch != NULL && out_arch == NULL)
3921 return in_arch;
3923 /* Parse subset from ISA string. */
3924 if (!riscv_parse_subset (&riscv_rps_ld_in, in_arch))
3925 return NULL;
3926 if (!riscv_parse_subset (&riscv_rps_ld_out, out_arch))
3927 return NULL;
3929 /* Checking XLEN. */
3930 if (xlen_out != xlen_in)
3932 _bfd_error_handler
3933 (_("error: %pB: ISA string of input (%s) doesn't match "
3934 "output (%s)"), ibfd, in_arch, out_arch);
3935 return NULL;
3938 /* Merge subset list. */
3939 in = in_subsets.head;
3940 out = out_subsets.head;
3942 /* Merge standard extension. */
3943 if (!riscv_merge_std_ext (ibfd, in_arch, out_arch, &in, &out))
3944 return NULL;
3946 /* Merge all non-single letter extensions with single call. */
3947 if (!riscv_merge_multi_letter_ext (&in, &out))
3948 return NULL;
3950 if (xlen_in != xlen_out)
3952 _bfd_error_handler
3953 (_("error: %pB: XLEN of input (%u) doesn't match "
3954 "output (%u)"), ibfd, xlen_in, xlen_out);
3955 return NULL;
3958 if (xlen_in != ARCH_SIZE)
3960 _bfd_error_handler
3961 (_("error: %pB: unsupported XLEN (%u), you might be "
3962 "using wrong emulation"), ibfd, xlen_in);
3963 return NULL;
3966 merged_arch_str = riscv_arch_str (ARCH_SIZE, &merged_subsets);
3968 /* Release the subset lists. */
3969 riscv_release_subset_list (&in_subsets);
3970 riscv_release_subset_list (&out_subsets);
3971 riscv_release_subset_list (&merged_subsets);
3973 return merged_arch_str;
3976 /* Merge object attributes from IBFD into output_bfd of INFO.
3977 Raise an error if there are conflicting attributes. */
3979 static bool
3980 riscv_merge_attributes (bfd *ibfd, struct bfd_link_info *info)
3982 bfd *obfd = info->output_bfd;
3983 obj_attribute *in_attr;
3984 obj_attribute *out_attr;
3985 bool result = true;
3986 bool priv_attrs_merged = false;
3987 const char *sec_name = get_elf_backend_data (ibfd)->obj_attrs_section;
3988 unsigned int i;
3990 /* Skip linker created files. */
3991 if (ibfd->flags & BFD_LINKER_CREATED)
3992 return true;
3994 /* Skip any input that doesn't have an attribute section.
3995 This enables to link object files without attribute section with
3996 any others. */
3997 if (bfd_get_section_by_name (ibfd, sec_name) == NULL)
3998 return true;
4000 if (!elf_known_obj_attributes_proc (obfd)[0].i)
4002 /* This is the first object. Copy the attributes. */
4003 _bfd_elf_copy_obj_attributes (ibfd, obfd);
4005 out_attr = elf_known_obj_attributes_proc (obfd);
4007 /* Use the Tag_null value to indicate the attributes have been
4008 initialized. */
4009 out_attr[0].i = 1;
4011 return true;
4014 in_attr = elf_known_obj_attributes_proc (ibfd);
4015 out_attr = elf_known_obj_attributes_proc (obfd);
4017 for (i = LEAST_KNOWN_OBJ_ATTRIBUTE; i < NUM_KNOWN_OBJ_ATTRIBUTES; i++)
4019 switch (i)
4021 case Tag_RISCV_arch:
4022 if (!out_attr[Tag_RISCV_arch].s)
4023 out_attr[Tag_RISCV_arch].s = in_attr[Tag_RISCV_arch].s;
4024 else if (in_attr[Tag_RISCV_arch].s
4025 && out_attr[Tag_RISCV_arch].s)
4027 /* Check compatible. */
4028 char *merged_arch =
4029 riscv_merge_arch_attr_info (ibfd,
4030 in_attr[Tag_RISCV_arch].s,
4031 out_attr[Tag_RISCV_arch].s);
4032 if (merged_arch == NULL)
4034 result = false;
4035 out_attr[Tag_RISCV_arch].s = "";
4037 else
4038 out_attr[Tag_RISCV_arch].s = merged_arch;
4040 break;
4042 case Tag_RISCV_priv_spec:
4043 case Tag_RISCV_priv_spec_minor:
4044 case Tag_RISCV_priv_spec_revision:
4045 /* If we have handled the privileged elf attributes, then skip it. */
4046 if (!priv_attrs_merged)
4048 unsigned int Tag_a = Tag_RISCV_priv_spec;
4049 unsigned int Tag_b = Tag_RISCV_priv_spec_minor;
4050 unsigned int Tag_c = Tag_RISCV_priv_spec_revision;
4051 enum riscv_spec_class in_priv_spec = PRIV_SPEC_CLASS_NONE;
4052 enum riscv_spec_class out_priv_spec = PRIV_SPEC_CLASS_NONE;
4054 /* Get the privileged spec class from elf attributes. */
4055 riscv_get_priv_spec_class_from_numbers (in_attr[Tag_a].i,
4056 in_attr[Tag_b].i,
4057 in_attr[Tag_c].i,
4058 &in_priv_spec);
4059 riscv_get_priv_spec_class_from_numbers (out_attr[Tag_a].i,
4060 out_attr[Tag_b].i,
4061 out_attr[Tag_c].i,
4062 &out_priv_spec);
4064 /* Allow to link the object without the privileged specs. */
4065 if (out_priv_spec == PRIV_SPEC_CLASS_NONE)
4067 out_attr[Tag_a].i = in_attr[Tag_a].i;
4068 out_attr[Tag_b].i = in_attr[Tag_b].i;
4069 out_attr[Tag_c].i = in_attr[Tag_c].i;
4071 else if (in_priv_spec != PRIV_SPEC_CLASS_NONE
4072 && in_priv_spec != out_priv_spec)
4074 /* The abandoned privileged spec v1.9.1 can not be linked with
4075 others since the conflicts. Keep the check since compatible
4076 issue. */
4077 if (in_priv_spec == PRIV_SPEC_CLASS_1P9P1
4078 || out_priv_spec == PRIV_SPEC_CLASS_1P9P1)
4080 _bfd_error_handler
4081 (_("warning: privileged spec version 1.9.1 can not be "
4082 "linked with other spec versions"));
4085 /* Update the output privileged spec to the newest one. */
4086 if (in_priv_spec > out_priv_spec)
4088 out_attr[Tag_a].i = in_attr[Tag_a].i;
4089 out_attr[Tag_b].i = in_attr[Tag_b].i;
4090 out_attr[Tag_c].i = in_attr[Tag_c].i;
4093 priv_attrs_merged = true;
4095 break;
4097 case Tag_RISCV_unaligned_access:
4098 out_attr[i].i |= in_attr[i].i;
4099 break;
4101 case Tag_RISCV_stack_align:
4102 if (out_attr[i].i == 0)
4103 out_attr[i].i = in_attr[i].i;
4104 else if (in_attr[i].i != 0
4105 && out_attr[i].i != 0
4106 && out_attr[i].i != in_attr[i].i)
4108 _bfd_error_handler
4109 (_("error: %pB use %u-byte stack aligned but the output "
4110 "use %u-byte stack aligned"),
4111 ibfd, in_attr[i].i, out_attr[i].i);
4112 result = false;
4114 break;
4116 default:
4117 result &= _bfd_elf_merge_unknown_attribute_low (ibfd, obfd, i);
4120 /* If out_attr was copied from in_attr then it won't have a type yet. */
4121 if (in_attr[i].type && !out_attr[i].type)
4122 out_attr[i].type = in_attr[i].type;
4125 /* Merge Tag_compatibility attributes and any common GNU ones. */
4126 if (!_bfd_elf_merge_object_attributes (ibfd, info))
4127 return false;
4129 /* Check for any attributes not known on RISC-V. */
4130 result &= _bfd_elf_merge_unknown_attribute_list (ibfd, obfd);
4132 return result;
4135 /* Merge backend specific data from an object file to the output
4136 object file when linking. */
4138 static bool
4139 _bfd_riscv_elf_merge_private_bfd_data (bfd *ibfd, struct bfd_link_info *info)
4141 bfd *obfd = info->output_bfd;
4142 flagword new_flags, old_flags;
4144 if (!is_riscv_elf (ibfd) || !is_riscv_elf (obfd))
4145 return true;
4147 if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
4149 (*_bfd_error_handler)
4150 (_("%pB: ABI is incompatible with that of the selected emulation:\n"
4151 " target emulation `%s' does not match `%s'"),
4152 ibfd, bfd_get_target (ibfd), bfd_get_target (obfd));
4153 return false;
4156 if (!_bfd_elf_merge_object_attributes (ibfd, info))
4157 return false;
4159 if (!riscv_merge_attributes (ibfd, info))
4160 return false;
4162 /* Check to see if the input BFD actually contains any sections. If not,
4163 its flags may not have been initialized either, but it cannot actually
4164 cause any incompatibility. Do not short-circuit dynamic objects; their
4165 section list may be emptied by elf_link_add_object_symbols.
4167 Also check to see if there are no code sections in the input. In this
4168 case, there is no need to check for code specific flags. */
4169 if (!(ibfd->flags & DYNAMIC))
4171 bool null_input_bfd = true;
4172 bool only_data_sections = true;
4173 asection *sec;
4175 for (sec = ibfd->sections; sec != NULL; sec = sec->next)
4177 null_input_bfd = false;
4179 if ((bfd_section_flags (sec)
4180 & (SEC_LOAD | SEC_CODE | SEC_HAS_CONTENTS))
4181 == (SEC_LOAD | SEC_CODE | SEC_HAS_CONTENTS))
4183 only_data_sections = false;
4184 break;
4188 if (null_input_bfd || only_data_sections)
4189 return true;
4192 new_flags = elf_elfheader (ibfd)->e_flags;
4193 old_flags = elf_elfheader (obfd)->e_flags;
4195 if (!elf_flags_init (obfd))
4197 elf_flags_init (obfd) = true;
4198 elf_elfheader (obfd)->e_flags = new_flags;
4199 return true;
4202 /* Disallow linking different float ABIs. */
4203 if ((old_flags ^ new_flags) & EF_RISCV_FLOAT_ABI)
4205 (*_bfd_error_handler)
4206 (_("%pB: can't link %s modules with %s modules"), ibfd,
4207 riscv_float_abi_string (new_flags),
4208 riscv_float_abi_string (old_flags));
4209 goto fail;
4212 /* Disallow linking RVE and non-RVE. */
4213 if ((old_flags ^ new_flags) & EF_RISCV_RVE)
4215 (*_bfd_error_handler)
4216 (_("%pB: can't link RVE with other target"), ibfd);
4217 goto fail;
4220 /* Allow linking RVC and non-RVC, and keep the RVC flag. */
4221 elf_elfheader (obfd)->e_flags |= new_flags & EF_RISCV_RVC;
4223 /* Allow linking TSO and non-TSO, and keep the TSO flag. */
4224 elf_elfheader (obfd)->e_flags |= new_flags & EF_RISCV_TSO;
4226 return true;
4228 fail:
4229 bfd_set_error (bfd_error_bad_value);
4230 return false;
4233 /* Ignore and report warning for the unknwon elf attribute. */
4235 static bool
4236 riscv_elf_obj_attrs_handle_unknown (bfd *abfd, int tag)
4238 _bfd_error_handler
4239 /* xgettext:c-format */
4240 (_("warning: %pB: unknown RISCV ABI object attribute %d"),
4241 abfd, tag);
4242 return true;
4245 /* A second format for recording PC-relative hi relocations. This stores the
4246 information required to relax them to GP-relative addresses. */
4248 typedef struct riscv_pcgp_hi_reloc riscv_pcgp_hi_reloc;
4249 struct riscv_pcgp_hi_reloc
4251 bfd_vma hi_sec_off;
4252 bfd_vma hi_addend;
4253 bfd_vma hi_addr;
4254 unsigned hi_sym;
4255 asection *sym_sec;
4256 bool undefined_weak;
4257 riscv_pcgp_hi_reloc *next;
4260 typedef struct riscv_pcgp_lo_reloc riscv_pcgp_lo_reloc;
4261 struct riscv_pcgp_lo_reloc
4263 bfd_vma hi_sec_off;
4264 riscv_pcgp_lo_reloc *next;
4267 typedef struct
4269 riscv_pcgp_hi_reloc *hi;
4270 riscv_pcgp_lo_reloc *lo;
4271 } riscv_pcgp_relocs;
4273 /* Initialize the pcgp reloc info in P. */
4275 static bool
4276 riscv_init_pcgp_relocs (riscv_pcgp_relocs *p)
4278 p->hi = NULL;
4279 p->lo = NULL;
4280 return true;
4283 /* Free the pcgp reloc info in P. */
4285 static void
4286 riscv_free_pcgp_relocs (riscv_pcgp_relocs *p,
4287 bfd *abfd ATTRIBUTE_UNUSED,
4288 asection *sec ATTRIBUTE_UNUSED)
4290 riscv_pcgp_hi_reloc *c;
4291 riscv_pcgp_lo_reloc *l;
4293 for (c = p->hi; c != NULL; )
4295 riscv_pcgp_hi_reloc *next = c->next;
4296 free (c);
4297 c = next;
4300 for (l = p->lo; l != NULL; )
4302 riscv_pcgp_lo_reloc *next = l->next;
4303 free (l);
4304 l = next;
4308 /* Record pcgp hi part reloc info in P, using HI_SEC_OFF as the lookup index.
4309 The HI_ADDEND, HI_ADDR, HI_SYM, and SYM_SEC args contain info required to
4310 relax the corresponding lo part reloc. */
4312 static bool
4313 riscv_record_pcgp_hi_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off,
4314 bfd_vma hi_addend, bfd_vma hi_addr,
4315 unsigned hi_sym, asection *sym_sec,
4316 bool undefined_weak)
4318 riscv_pcgp_hi_reloc *new = bfd_malloc (sizeof (*new));
4319 if (!new)
4320 return false;
4321 new->hi_sec_off = hi_sec_off;
4322 new->hi_addend = hi_addend;
4323 new->hi_addr = hi_addr;
4324 new->hi_sym = hi_sym;
4325 new->sym_sec = sym_sec;
4326 new->undefined_weak = undefined_weak;
4327 new->next = p->hi;
4328 p->hi = new;
4329 return true;
4332 /* Look up hi part pcgp reloc info in P, using HI_SEC_OFF as the lookup index.
4333 This is used by a lo part reloc to find the corresponding hi part reloc. */
4335 static riscv_pcgp_hi_reloc *
4336 riscv_find_pcgp_hi_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off)
4338 riscv_pcgp_hi_reloc *c;
4340 for (c = p->hi; c != NULL; c = c->next)
4341 if (c->hi_sec_off == hi_sec_off)
4342 return c;
4343 return NULL;
4346 /* Record pcgp lo part reloc info in P, using HI_SEC_OFF as the lookup info.
4347 This is used to record relocs that can't be relaxed. */
4349 static bool
4350 riscv_record_pcgp_lo_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off)
4352 riscv_pcgp_lo_reloc *new = bfd_malloc (sizeof (*new));
4353 if (!new)
4354 return false;
4355 new->hi_sec_off = hi_sec_off;
4356 new->next = p->lo;
4357 p->lo = new;
4358 return true;
4361 /* Look up lo part pcgp reloc info in P, using HI_SEC_OFF as the lookup index.
4362 This is used by a hi part reloc to find the corresponding lo part reloc. */
4364 static bool
4365 riscv_find_pcgp_lo_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off)
4367 riscv_pcgp_lo_reloc *c;
4369 for (c = p->lo; c != NULL; c = c->next)
4370 if (c->hi_sec_off == hi_sec_off)
4371 return true;
4372 return false;
4375 static void
4376 riscv_update_pcgp_relocs (riscv_pcgp_relocs *p, asection *deleted_sec,
4377 bfd_vma deleted_addr, size_t deleted_count)
4379 /* Bytes have already been deleted and toaddr should match the old section
4380 size for our checks, so adjust it here. */
4381 bfd_vma toaddr = deleted_sec->size + deleted_count;
4382 riscv_pcgp_lo_reloc *l;
4383 riscv_pcgp_hi_reloc *h;
4385 /* Update section offsets of corresponding pcrel_hi relocs for the pcrel_lo
4386 entries where they occur after the deleted bytes. */
4387 for (l = p->lo; l != NULL; l = l->next)
4388 if (l->hi_sec_off > deleted_addr
4389 && l->hi_sec_off < toaddr)
4390 l->hi_sec_off -= deleted_count;
4392 /* Update both section offsets, and symbol values of pcrel_hi relocs where
4393 these values occur after the deleted bytes. */
4394 for (h = p->hi; h != NULL; h = h->next)
4396 if (h->hi_sec_off > deleted_addr
4397 && h->hi_sec_off < toaddr)
4398 h->hi_sec_off -= deleted_count;
4399 if (h->sym_sec == deleted_sec
4400 && h->hi_addr > deleted_addr
4401 && h->hi_addr < toaddr)
4402 h->hi_addr -= deleted_count;
4406 /* Delete some bytes, adjust relcocations and symbol table from a section. */
4408 static bool
4409 _riscv_relax_delete_bytes (bfd *abfd,
4410 asection *sec,
4411 bfd_vma addr,
4412 size_t count,
4413 struct bfd_link_info *link_info,
4414 riscv_pcgp_relocs *p,
4415 bfd_vma delete_total,
4416 bfd_vma toaddr)
4418 unsigned int i, symcount;
4419 struct elf_link_hash_entry **sym_hashes = elf_sym_hashes (abfd);
4420 Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
4421 unsigned int sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
4422 struct bfd_elf_section_data *data = elf_section_data (sec);
4423 bfd_byte *contents = data->this_hdr.contents;
4424 size_t bytes_to_move = toaddr - addr - count;
4426 /* Actually delete the bytes. */
4427 sec->size -= count;
4428 memmove (contents + addr, contents + addr + count + delete_total, bytes_to_move);
4430 /* Still adjust relocations and symbols in non-linear times. */
4431 toaddr = sec->size + count;
4433 /* Adjust the location of all of the relocs. Note that we need not
4434 adjust the addends, since all PC-relative references must be against
4435 symbols, which we will adjust below. */
4436 for (i = 0; i < sec->reloc_count; i++)
4437 if (data->relocs[i].r_offset > addr && data->relocs[i].r_offset < toaddr)
4438 data->relocs[i].r_offset -= count;
4440 /* Adjust the hi_sec_off, and the hi_addr of any entries in the pcgp relocs
4441 table for which these values occur after the deleted bytes. */
4442 if (p)
4443 riscv_update_pcgp_relocs (p, sec, addr, count);
4445 /* Adjust the local symbols defined in this section. */
4446 for (i = 0; i < symtab_hdr->sh_info; i++)
4448 Elf_Internal_Sym *sym = (Elf_Internal_Sym *) symtab_hdr->contents + i;
4449 if (sym->st_shndx == sec_shndx)
4451 /* If the symbol is in the range of memory we just moved, we
4452 have to adjust its value. */
4453 if (sym->st_value > addr && sym->st_value <= toaddr)
4454 sym->st_value -= count;
4456 /* If the symbol *spans* the bytes we just deleted (i.e. its
4457 *end* is in the moved bytes but its *start* isn't), then we
4458 must adjust its size.
4460 This test needs to use the original value of st_value, otherwise
4461 we might accidentally decrease size when deleting bytes right
4462 before the symbol. But since deleted relocs can't span across
4463 symbols, we can't have both a st_value and a st_size decrease,
4464 so it is simpler to just use an else. */
4465 else if (sym->st_value <= addr
4466 && sym->st_value + sym->st_size > addr
4467 && sym->st_value + sym->st_size <= toaddr)
4468 sym->st_size -= count;
4472 /* Now adjust the global symbols defined in this section. */
4473 symcount = ((symtab_hdr->sh_size / sizeof (ElfNN_External_Sym))
4474 - symtab_hdr->sh_info);
4476 for (i = 0; i < symcount; i++)
4478 struct elf_link_hash_entry *sym_hash = sym_hashes[i];
4480 /* The '--wrap SYMBOL' option is causing a pain when the object file,
4481 containing the definition of __wrap_SYMBOL, includes a direct
4482 call to SYMBOL as well. Since both __wrap_SYMBOL and SYMBOL reference
4483 the same symbol (which is __wrap_SYMBOL), but still exist as two
4484 different symbols in 'sym_hashes', we don't want to adjust
4485 the global symbol __wrap_SYMBOL twice.
4487 The same problem occurs with symbols that are versioned_hidden, as
4488 foo becomes an alias for foo@BAR, and hence they need the same
4489 treatment. */
4490 if (link_info->wrap_hash != NULL
4491 || sym_hash->versioned != unversioned)
4493 struct elf_link_hash_entry **cur_sym_hashes;
4495 /* Loop only over the symbols which have already been checked. */
4496 for (cur_sym_hashes = sym_hashes; cur_sym_hashes < &sym_hashes[i];
4497 cur_sym_hashes++)
4499 /* If the current symbol is identical to 'sym_hash', that means
4500 the symbol was already adjusted (or at least checked). */
4501 if (*cur_sym_hashes == sym_hash)
4502 break;
4504 /* Don't adjust the symbol again. */
4505 if (cur_sym_hashes < &sym_hashes[i])
4506 continue;
4509 if ((sym_hash->root.type == bfd_link_hash_defined
4510 || sym_hash->root.type == bfd_link_hash_defweak)
4511 && sym_hash->root.u.def.section == sec)
4513 /* As above, adjust the value if needed. */
4514 if (sym_hash->root.u.def.value > addr
4515 && sym_hash->root.u.def.value <= toaddr)
4516 sym_hash->root.u.def.value -= count;
4518 /* As above, adjust the size if needed. */
4519 else if (sym_hash->root.u.def.value <= addr
4520 && sym_hash->root.u.def.value + sym_hash->size > addr
4521 && sym_hash->root.u.def.value + sym_hash->size <= toaddr)
4522 sym_hash->size -= count;
4526 return true;
4529 typedef bool (*relax_delete_t) (bfd *, asection *,
4530 bfd_vma, size_t,
4531 struct bfd_link_info *,
4532 riscv_pcgp_relocs *,
4533 Elf_Internal_Rela *);
4535 static relax_delete_t riscv_relax_delete_bytes;
4537 /* Do not delete some bytes from a section while relaxing.
4538 Just mark the deleted bytes as R_RISCV_DELETE. */
4540 static bool
4541 _riscv_relax_delete_piecewise (bfd *abfd ATTRIBUTE_UNUSED,
4542 asection *sec ATTRIBUTE_UNUSED,
4543 bfd_vma addr,
4544 size_t count,
4545 struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
4546 riscv_pcgp_relocs *p ATTRIBUTE_UNUSED,
4547 Elf_Internal_Rela *rel)
4549 if (rel == NULL)
4550 return false;
4551 rel->r_info = ELFNN_R_INFO (0, R_RISCV_DELETE);
4552 rel->r_offset = addr;
4553 rel->r_addend = count;
4554 return true;
4557 /* Delete some bytes from a section while relaxing. */
4559 static bool
4560 _riscv_relax_delete_immediate (bfd *abfd,
4561 asection *sec,
4562 bfd_vma addr,
4563 size_t count,
4564 struct bfd_link_info *link_info,
4565 riscv_pcgp_relocs *p,
4566 Elf_Internal_Rela *rel)
4568 if (rel != NULL)
4569 rel->r_info = ELFNN_R_INFO (0, R_RISCV_NONE);
4570 return _riscv_relax_delete_bytes (abfd, sec, addr, count,
4571 link_info, p, 0, sec->size);
4574 /* Delete the bytes for R_RISCV_DELETE relocs. */
4576 static bool
4577 riscv_relax_resolve_delete_relocs (bfd *abfd,
4578 asection *sec,
4579 struct bfd_link_info *link_info,
4580 Elf_Internal_Rela *relocs)
4582 bfd_vma delete_total = 0;
4583 unsigned int i;
4585 for (i = 0; i < sec->reloc_count; i++)
4587 Elf_Internal_Rela *rel = relocs + i;
4588 if (ELFNN_R_TYPE (rel->r_info) != R_RISCV_DELETE)
4589 continue;
4591 /* Find the next R_RISCV_DELETE reloc if possible. */
4592 Elf_Internal_Rela *rel_next = NULL;
4593 unsigned int start = rel - relocs;
4594 for (i = start; i < sec->reloc_count; i++)
4596 /* Since we only replace existing relocs and don't add new relocs, the
4597 relocs are in sequential order. We can skip the relocs prior to this
4598 one, making this search linear time. */
4599 rel_next = relocs + i;
4600 if (ELFNN_R_TYPE ((rel_next)->r_info) == R_RISCV_DELETE
4601 && (rel_next)->r_offset > rel->r_offset)
4603 BFD_ASSERT (rel_next - rel > 0);
4604 break;
4606 else
4607 rel_next = NULL;
4610 bfd_vma toaddr = rel_next == NULL ? sec->size : rel_next->r_offset;
4611 if (!_riscv_relax_delete_bytes (abfd, sec, rel->r_offset, rel->r_addend,
4612 link_info, NULL, delete_total, toaddr))
4613 return false;
4615 delete_total += rel->r_addend;
4616 rel->r_info = ELFNN_R_INFO (0, R_RISCV_NONE);
4618 /* Skip ahead to the next delete reloc. */
4619 i = rel_next != NULL ? (unsigned int) (rel_next - relocs - 1)
4620 : sec->reloc_count;
4623 return true;
4626 typedef bool (*relax_func_t) (bfd *, asection *, asection *,
4627 struct bfd_link_info *,
4628 Elf_Internal_Rela *,
4629 bfd_vma, bfd_vma, bfd_vma, bool *,
4630 riscv_pcgp_relocs *,
4631 bool undefined_weak);
4633 /* Relax AUIPC + JALR into JAL. */
4635 static bool
4636 _bfd_riscv_relax_call (bfd *abfd, asection *sec, asection *sym_sec,
4637 struct bfd_link_info *link_info,
4638 Elf_Internal_Rela *rel,
4639 bfd_vma symval,
4640 bfd_vma max_alignment,
4641 bfd_vma reserve_size ATTRIBUTE_UNUSED,
4642 bool *again,
4643 riscv_pcgp_relocs *pcgp_relocs,
4644 bool undefined_weak ATTRIBUTE_UNUSED)
4646 bfd_byte *contents = elf_section_data (sec)->this_hdr.contents;
4647 bfd_vma foff = symval - (sec_addr (sec) + rel->r_offset);
4648 bool near_zero = (symval + RISCV_IMM_REACH / 2) < RISCV_IMM_REACH;
4649 bfd_vma auipc, jalr;
4650 int rd, r_type, len = 4, rvc = elf_elfheader (abfd)->e_flags & EF_RISCV_RVC;
4652 /* If the call crosses section boundaries, an alignment directive could
4653 cause the PC-relative offset to later increase, so we need to add in the
4654 max alignment of any section inclusive from the call to the target.
4655 Otherwise, we only need to use the alignment of the current section. */
4656 if (VALID_JTYPE_IMM (foff))
4658 if (sym_sec->output_section == sec->output_section
4659 && sym_sec->output_section != bfd_abs_section_ptr)
4660 max_alignment = (bfd_vma) 1 << sym_sec->output_section->alignment_power;
4661 foff += ((bfd_signed_vma) foff < 0 ? -max_alignment : max_alignment);
4664 /* See if this function call can be shortened. */
4665 if (!VALID_JTYPE_IMM (foff) && !(!bfd_link_pic (link_info) && near_zero))
4666 return true;
4668 /* Shorten the function call. */
4669 BFD_ASSERT (rel->r_offset + 8 <= sec->size);
4671 auipc = bfd_getl32 (contents + rel->r_offset);
4672 jalr = bfd_getl32 (contents + rel->r_offset + 4);
4673 rd = (jalr >> OP_SH_RD) & OP_MASK_RD;
4674 rvc = rvc && VALID_CJTYPE_IMM (foff);
4676 /* C.J exists on RV32 and RV64, but C.JAL is RV32-only. */
4677 rvc = rvc && (rd == 0 || (rd == X_RA && ARCH_SIZE == 32));
4679 if (rvc)
4681 /* Relax to C.J[AL] rd, addr. */
4682 r_type = R_RISCV_RVC_JUMP;
4683 auipc = rd == 0 ? MATCH_C_J : MATCH_C_JAL;
4684 len = 2;
4686 else if (VALID_JTYPE_IMM (foff))
4688 /* Relax to JAL rd, addr. */
4689 r_type = R_RISCV_JAL;
4690 auipc = MATCH_JAL | (rd << OP_SH_RD);
4692 else
4694 /* Near zero, relax to JALR rd, x0, addr. */
4695 r_type = R_RISCV_LO12_I;
4696 auipc = MATCH_JALR | (rd << OP_SH_RD);
4699 /* Replace the R_RISCV_CALL reloc. */
4700 rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), r_type);
4701 /* Replace the AUIPC. */
4702 riscv_put_insn (8 * len, auipc, contents + rel->r_offset);
4704 /* Delete unnecessary JALR and reuse the R_RISCV_RELAX reloc. */
4705 *again = true;
4706 return riscv_relax_delete_bytes (abfd, sec, rel->r_offset + len, 8 - len,
4707 link_info, pcgp_relocs, rel + 1);
4710 /* Traverse all output sections and return the max alignment.
4712 If gp is zero, then all the output section alignments are
4713 possible candidates; Otherwise, only the output sections
4714 which are in the [gp-2K, gp+2K) range need to be considered. */
4716 static bfd_vma
4717 _bfd_riscv_get_max_alignment (asection *sec, bfd_vma gp)
4719 unsigned int max_alignment_power = 0;
4720 asection *o;
4722 for (o = sec->output_section->owner->sections; o != NULL; o = o->next)
4724 bool valid = true;
4725 if (gp
4726 && !(VALID_ITYPE_IMM (sec_addr (o) - gp)
4727 || VALID_ITYPE_IMM (sec_addr (o) + o->size - gp)))
4728 valid = false;
4730 if (valid && o->alignment_power > max_alignment_power)
4731 max_alignment_power = o->alignment_power;
4734 return (bfd_vma) 1 << max_alignment_power;
4737 /* Relax non-PIC global variable references to GP-relative references. */
4739 static bool
4740 _bfd_riscv_relax_lui (bfd *abfd,
4741 asection *sec,
4742 asection *sym_sec,
4743 struct bfd_link_info *link_info,
4744 Elf_Internal_Rela *rel,
4745 bfd_vma symval,
4746 bfd_vma max_alignment,
4747 bfd_vma reserve_size,
4748 bool *again,
4749 riscv_pcgp_relocs *pcgp_relocs,
4750 bool undefined_weak)
4752 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (link_info);
4753 bfd_byte *contents = elf_section_data (sec)->this_hdr.contents;
4754 /* Can relax to x0 even when gp relaxation is disabled. */
4755 bfd_vma gp = htab->params->relax_gp
4756 ? riscv_global_pointer_value (link_info)
4757 : 0;
4758 bfd_vma data_segment_alignment = link_info->relro
4759 ? ELF_MAXPAGESIZE + ELF_COMMONPAGESIZE
4760 : ELF_MAXPAGESIZE;
4761 int use_rvc = elf_elfheader (abfd)->e_flags & EF_RISCV_RVC;
4763 BFD_ASSERT (rel->r_offset + 4 <= sec->size);
4765 if (!undefined_weak && gp)
4767 /* If gp and the symbol are in the same output section, which is not the
4768 abs section, then consider only that output section's alignment. */
4769 struct bfd_link_hash_entry *h =
4770 bfd_link_hash_lookup (link_info->hash, RISCV_GP_SYMBOL, false, false,
4771 true);
4772 if (h->u.def.section->output_section == sym_sec->output_section
4773 && sym_sec->output_section != bfd_abs_section_ptr)
4774 max_alignment = (bfd_vma) 1 << sym_sec->output_section->alignment_power;
4775 else
4777 /* Consider output section alignments which are in [gp-2K, gp+2K). */
4778 max_alignment = htab->max_alignment_for_gp;
4779 if (max_alignment == (bfd_vma) -1)
4781 max_alignment = _bfd_riscv_get_max_alignment (sec, gp);
4782 htab->max_alignment_for_gp = max_alignment;
4786 /* PR27566, for default linker script, if a symbol's value outsides the
4787 bounds of the defined section, then it may cross the data segment
4788 alignment, so we should reserve more size about MAXPAGESIZE and
4789 COMMONPAGESIZE, since the data segment alignment might move the
4790 section forward. */
4791 if (symval < sec_addr (sym_sec)
4792 || symval > (sec_addr (sym_sec) + sym_sec->size))
4793 max_alignment = data_segment_alignment > max_alignment
4794 ? data_segment_alignment : max_alignment;
4797 /* Is the reference in range of x0 or gp?
4798 Valid gp range conservatively because of alignment issue.
4800 Should we also consider the alignment issue for x0 base? */
4801 if (undefined_weak
4802 || VALID_ITYPE_IMM (symval)
4803 || (symval >= gp
4804 && VALID_ITYPE_IMM (symval - gp + max_alignment + reserve_size))
4805 || (symval < gp
4806 && VALID_ITYPE_IMM (symval - gp - max_alignment - reserve_size)))
4808 unsigned sym = ELFNN_R_SYM (rel->r_info);
4809 switch (ELFNN_R_TYPE (rel->r_info))
4811 case R_RISCV_LO12_I:
4812 rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_I);
4813 return true;
4815 case R_RISCV_LO12_S:
4816 rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_S);
4817 return true;
4819 case R_RISCV_HI20:
4820 /* Delete unnecessary LUI and reuse the reloc. */
4821 *again = true;
4822 return riscv_relax_delete_bytes (abfd, sec, rel->r_offset, 4,
4823 link_info, pcgp_relocs, rel);
4825 default:
4826 abort ();
4830 /* Can we relax LUI to C.LUI? Alignment might move the section forward;
4831 account for this assuming page alignment at worst. In the presence of
4832 RELRO segment the linker aligns it by one page size, therefore sections
4833 after the segment can be moved more than one page. */
4835 if (use_rvc
4836 && ELFNN_R_TYPE (rel->r_info) == R_RISCV_HI20
4837 && VALID_CITYPE_LUI_IMM (RISCV_CONST_HIGH_PART (symval))
4838 && VALID_CITYPE_LUI_IMM (RISCV_CONST_HIGH_PART (symval)
4839 + data_segment_alignment))
4841 /* Replace LUI with C.LUI if legal (i.e., rd != x0 and rd != x2/sp). */
4842 bfd_vma lui = bfd_getl32 (contents + rel->r_offset);
4843 unsigned rd = ((unsigned)lui >> OP_SH_RD) & OP_MASK_RD;
4844 if (rd == 0 || rd == X_SP)
4845 return true;
4847 lui = (lui & (OP_MASK_RD << OP_SH_RD)) | MATCH_C_LUI;
4848 bfd_putl32 (lui, contents + rel->r_offset);
4850 /* Replace the R_RISCV_HI20 reloc. */
4851 rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), R_RISCV_RVC_LUI);
4853 /* Delete extra bytes and reuse the R_RISCV_RELAX reloc. */
4854 *again = true;
4855 return riscv_relax_delete_bytes (abfd, sec, rel->r_offset + 2, 2,
4856 link_info, pcgp_relocs, rel + 1);
4859 return true;
4862 /* Relax non-PIC TLS references to TP-relative references. */
4864 static bool
4865 _bfd_riscv_relax_tls_le (bfd *abfd,
4866 asection *sec,
4867 asection *sym_sec ATTRIBUTE_UNUSED,
4868 struct bfd_link_info *link_info,
4869 Elf_Internal_Rela *rel,
4870 bfd_vma symval,
4871 bfd_vma max_alignment ATTRIBUTE_UNUSED,
4872 bfd_vma reserve_size ATTRIBUTE_UNUSED,
4873 bool *again,
4874 riscv_pcgp_relocs *pcgp_relocs,
4875 bool undefined_weak ATTRIBUTE_UNUSED)
4877 /* See if this symbol is in range of tp. */
4878 if (RISCV_CONST_HIGH_PART (tpoff (link_info, symval)) != 0)
4879 return true;
4881 BFD_ASSERT (rel->r_offset + 4 <= sec->size);
4882 switch (ELFNN_R_TYPE (rel->r_info))
4884 case R_RISCV_TPREL_LO12_I:
4885 rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), R_RISCV_TPREL_I);
4886 return true;
4888 case R_RISCV_TPREL_LO12_S:
4889 rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), R_RISCV_TPREL_S);
4890 return true;
4892 case R_RISCV_TPREL_HI20:
4893 case R_RISCV_TPREL_ADD:
4894 /* Delete unnecessary instruction and reuse the reloc. */
4895 *again = true;
4896 return riscv_relax_delete_bytes (abfd, sec, rel->r_offset, 4, link_info,
4897 pcgp_relocs, rel);
4899 default:
4900 abort ();
4904 /* Implement R_RISCV_ALIGN by deleting excess alignment NOPs.
4905 Once we've handled an R_RISCV_ALIGN, we can't relax anything else. */
4907 static bool
4908 _bfd_riscv_relax_align (bfd *abfd, asection *sec,
4909 asection *sym_sec,
4910 struct bfd_link_info *link_info,
4911 Elf_Internal_Rela *rel,
4912 bfd_vma symval,
4913 bfd_vma max_alignment ATTRIBUTE_UNUSED,
4914 bfd_vma reserve_size ATTRIBUTE_UNUSED,
4915 bool *again ATTRIBUTE_UNUSED,
4916 riscv_pcgp_relocs *pcgp_relocs ATTRIBUTE_UNUSED,
4917 bool undefined_weak ATTRIBUTE_UNUSED)
4919 bfd_byte *contents = elf_section_data (sec)->this_hdr.contents;
4920 bfd_vma alignment = 1, pos;
4921 while (alignment <= rel->r_addend)
4922 alignment *= 2;
4924 symval -= rel->r_addend;
4925 bfd_vma aligned_addr = ((symval - 1) & ~(alignment - 1)) + alignment;
4926 bfd_vma nop_bytes = aligned_addr - symval;
4928 /* Once we've handled an R_RISCV_ALIGN, we can't relax anything else. */
4929 sec->sec_flg0 = true;
4931 /* Make sure there are enough NOPs to actually achieve the alignment. */
4932 if (rel->r_addend < nop_bytes)
4934 _bfd_error_handler
4935 (_("%pB(%pA+%#" PRIx64 "): %" PRId64 " bytes required for alignment "
4936 "to %" PRId64 "-byte boundary, but only %" PRId64 " present"),
4937 abfd, sym_sec, (uint64_t) rel->r_offset,
4938 (int64_t) nop_bytes, (int64_t) alignment, (int64_t) rel->r_addend);
4939 bfd_set_error (bfd_error_bad_value);
4940 return false;
4943 /* Delete the reloc. */
4944 rel->r_info = ELFNN_R_INFO (0, R_RISCV_NONE);
4946 /* If the number of NOPs is already correct, there's nothing to do. */
4947 if (nop_bytes == rel->r_addend)
4948 return true;
4950 /* Write as many RISC-V NOPs as we need. */
4951 for (pos = 0; pos < (nop_bytes & -4); pos += 4)
4952 bfd_putl32 (RISCV_NOP, contents + rel->r_offset + pos);
4954 /* Write a final RVC NOP if need be. */
4955 if (nop_bytes % 4 != 0)
4956 bfd_putl16 (RVC_NOP, contents + rel->r_offset + pos);
4958 /* Delete excess bytes. */
4959 return riscv_relax_delete_bytes (abfd, sec, rel->r_offset + nop_bytes,
4960 rel->r_addend - nop_bytes, link_info,
4961 NULL, NULL);
4964 /* Relax PC-relative references to GP-relative references. */
4966 static bool
4967 _bfd_riscv_relax_pc (bfd *abfd ATTRIBUTE_UNUSED,
4968 asection *sec,
4969 asection *sym_sec,
4970 struct bfd_link_info *link_info,
4971 Elf_Internal_Rela *rel,
4972 bfd_vma symval,
4973 bfd_vma max_alignment,
4974 bfd_vma reserve_size,
4975 bool *again,
4976 riscv_pcgp_relocs *pcgp_relocs,
4977 bool undefined_weak)
4979 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (link_info);
4980 /* Can relax to x0 even when gp relaxation is disabled. */
4981 bfd_vma gp = htab->params->relax_gp
4982 ? riscv_global_pointer_value (link_info)
4983 : 0;
4984 bfd_vma data_segment_alignment = link_info->relro
4985 ? ELF_MAXPAGESIZE + ELF_COMMONPAGESIZE
4986 : ELF_MAXPAGESIZE;
4988 BFD_ASSERT (rel->r_offset + 4 <= sec->size);
4990 /* Chain the _LO relocs to their cooresponding _HI reloc to compute the
4991 actual target address. */
4992 riscv_pcgp_hi_reloc hi_reloc;
4993 memset (&hi_reloc, 0, sizeof (hi_reloc));
4994 switch (ELFNN_R_TYPE (rel->r_info))
4996 case R_RISCV_PCREL_LO12_I:
4997 case R_RISCV_PCREL_LO12_S:
4999 /* If the %lo has an addend, it isn't for the label pointing at the
5000 hi part instruction, but rather for the symbol pointed at by the
5001 hi part instruction. So we must subtract it here for the lookup.
5002 It is still used below in the final symbol address. */
5003 bfd_vma hi_sec_off = symval - sec_addr (sym_sec) - rel->r_addend;
5004 riscv_pcgp_hi_reloc *hi = riscv_find_pcgp_hi_reloc (pcgp_relocs,
5005 hi_sec_off);
5006 if (hi == NULL)
5008 riscv_record_pcgp_lo_reloc (pcgp_relocs, hi_sec_off);
5009 return true;
5012 hi_reloc = *hi;
5013 symval = hi_reloc.hi_addr;
5014 sym_sec = hi_reloc.sym_sec;
5016 /* We can not know whether the undefined weak symbol is referenced
5017 according to the information of R_RISCV_PCREL_LO12_I/S. Therefore,
5018 we have to record the 'undefined_weak' flag when handling the
5019 corresponding R_RISCV_HI20 reloc in riscv_record_pcgp_hi_reloc. */
5020 undefined_weak = hi_reloc.undefined_weak;
5022 break;
5024 case R_RISCV_PCREL_HI20:
5025 /* Mergeable symbols and code might later move out of range. */
5026 if (! undefined_weak
5027 && sym_sec->flags & (SEC_MERGE | SEC_CODE))
5028 return true;
5030 /* If the cooresponding lo relocation has already been seen then it's not
5031 safe to relax this relocation. */
5032 if (riscv_find_pcgp_lo_reloc (pcgp_relocs, rel->r_offset))
5033 return true;
5035 break;
5037 default:
5038 abort ();
5041 if (!undefined_weak && gp)
5043 /* If gp and the symbol are in the same output section, which is not the
5044 abs section, then consider only that output section's alignment. */
5045 struct bfd_link_hash_entry *h =
5046 bfd_link_hash_lookup (link_info->hash, RISCV_GP_SYMBOL, false, false,
5047 true);
5048 if (h->u.def.section->output_section == sym_sec->output_section
5049 && sym_sec->output_section != bfd_abs_section_ptr)
5050 max_alignment = (bfd_vma) 1 << sym_sec->output_section->alignment_power;
5051 else
5053 /* Consider output section alignments which are in [gp-2K, gp+2K). */
5054 max_alignment = htab->max_alignment_for_gp;
5055 if (max_alignment == (bfd_vma) -1)
5057 max_alignment = _bfd_riscv_get_max_alignment (sec, gp);
5058 htab->max_alignment_for_gp = max_alignment;
5062 /* PR27566, for default linker script, if a symbol's value outsides the
5063 bounds of the defined section, then it may cross the data segment
5064 alignment, so we should reserve more size about MAXPAGESIZE and
5065 COMMONPAGESIZE, since the data segment alignment might move the
5066 section forward. */
5067 if (symval < sec_addr (sym_sec)
5068 || symval > (sec_addr (sym_sec) + sym_sec->size))
5069 max_alignment = data_segment_alignment > max_alignment
5070 ? data_segment_alignment : max_alignment;
5073 /* Is the reference in range of x0 or gp?
5074 Valid gp range conservatively because of alignment issue.
5076 Should we also consider the alignment issue for x0 base? */
5077 if (undefined_weak
5078 || VALID_ITYPE_IMM (symval)
5079 || (symval >= gp
5080 && VALID_ITYPE_IMM (symval - gp + max_alignment + reserve_size))
5081 || (symval < gp
5082 && VALID_ITYPE_IMM (symval - gp - max_alignment - reserve_size)))
5084 unsigned sym = hi_reloc.hi_sym;
5085 switch (ELFNN_R_TYPE (rel->r_info))
5087 case R_RISCV_PCREL_LO12_I:
5088 rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_I);
5089 rel->r_addend += hi_reloc.hi_addend;
5090 return true;
5092 case R_RISCV_PCREL_LO12_S:
5093 rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_S);
5094 rel->r_addend += hi_reloc.hi_addend;
5095 return true;
5097 case R_RISCV_PCREL_HI20:
5098 riscv_record_pcgp_hi_reloc (pcgp_relocs,
5099 rel->r_offset,
5100 rel->r_addend,
5101 symval,
5102 ELFNN_R_SYM(rel->r_info),
5103 sym_sec,
5104 undefined_weak);
5105 /* Delete unnecessary AUIPC and reuse the reloc. */
5106 *again = true;
5107 riscv_relax_delete_bytes (abfd, sec, rel->r_offset, 4, link_info,
5108 pcgp_relocs, rel);
5109 return true;
5111 default:
5112 abort ();
5116 return true;
5119 /* Called by after_allocation to set the information of data segment
5120 before relaxing. */
5122 void
5123 bfd_elfNN_riscv_set_data_segment_info (struct bfd_link_info *info,
5124 int *data_segment_phase)
5126 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
5127 htab->data_segment_phase = data_segment_phase;
5130 /* Relax a section.
5132 Pass 0: Shortens code sequences for LUI/CALL/TPREL/PCREL relocs and
5133 deletes the obsolete bytes.
5134 Pass 1: Which cannot be disabled, handles code alignment directives. */
5136 static bool
5137 _bfd_riscv_relax_section (bfd *abfd, asection *sec,
5138 struct bfd_link_info *info,
5139 bool *again)
5141 Elf_Internal_Shdr *symtab_hdr = &elf_symtab_hdr (abfd);
5142 struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
5143 struct bfd_elf_section_data *data = elf_section_data (sec);
5144 Elf_Internal_Rela *relocs;
5145 bool ret = false;
5146 unsigned int i;
5147 bfd_vma max_alignment, reserve_size = 0;
5148 riscv_pcgp_relocs pcgp_relocs;
5149 static asection *first_section = NULL;
5151 *again = false;
5153 if (bfd_link_relocatable (info)
5154 || sec->sec_flg0
5155 || sec->reloc_count == 0
5156 || (sec->flags & SEC_RELOC) == 0
5157 || (sec->flags & SEC_HAS_CONTENTS) == 0
5158 || (info->disable_target_specific_optimizations
5159 && info->relax_pass == 0)
5160 /* The exp_seg_relro_adjust is enum phase_enum (0x4),
5161 and defined in ld/ldexp.h. */
5162 || *(htab->data_segment_phase) == 4)
5163 return true;
5165 /* Record the first relax section, so that we can reset the
5166 max_alignment_for_gp for the repeated relax passes. */
5167 if (first_section == NULL)
5168 first_section = sec;
5169 else if (first_section == sec)
5170 htab->max_alignment_for_gp = -1;
5172 riscv_init_pcgp_relocs (&pcgp_relocs);
5174 /* Read this BFD's relocs if we haven't done so already. */
5175 if (data->relocs)
5176 relocs = data->relocs;
5177 else if (!(relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
5178 info->keep_memory)))
5179 goto fail;
5181 /* Estimate the maximum alignment for all output sections once time
5182 should be enough. */
5183 max_alignment = htab->max_alignment;
5184 if (max_alignment == (bfd_vma) -1)
5186 max_alignment = _bfd_riscv_get_max_alignment (sec, 0/* gp */);
5187 htab->max_alignment = max_alignment;
5190 /* Examine and consider relaxing each reloc. */
5191 for (i = 0; i < sec->reloc_count; i++)
5193 asection *sym_sec;
5194 Elf_Internal_Rela *rel = relocs + i;
5195 relax_func_t relax_func;
5196 int type = ELFNN_R_TYPE (rel->r_info);
5197 bfd_vma symval;
5198 char symtype;
5199 bool undefined_weak = false;
5201 relax_func = NULL;
5202 riscv_relax_delete_bytes = NULL;
5203 if (info->relax_pass == 0)
5205 if (type == R_RISCV_CALL
5206 || type == R_RISCV_CALL_PLT)
5207 relax_func = _bfd_riscv_relax_call;
5208 else if (type == R_RISCV_HI20
5209 || type == R_RISCV_LO12_I
5210 || type == R_RISCV_LO12_S)
5211 relax_func = _bfd_riscv_relax_lui;
5212 else if (type == R_RISCV_TPREL_HI20
5213 || type == R_RISCV_TPREL_ADD
5214 || type == R_RISCV_TPREL_LO12_I
5215 || type == R_RISCV_TPREL_LO12_S)
5216 relax_func = _bfd_riscv_relax_tls_le;
5217 else if (!bfd_link_pic (info)
5218 && (type == R_RISCV_PCREL_HI20
5219 || type == R_RISCV_PCREL_LO12_I
5220 || type == R_RISCV_PCREL_LO12_S))
5221 relax_func = _bfd_riscv_relax_pc;
5222 else
5223 continue;
5224 riscv_relax_delete_bytes = _riscv_relax_delete_piecewise;
5226 /* Only relax this reloc if it is paired with R_RISCV_RELAX. */
5227 if (i == sec->reloc_count - 1
5228 || ELFNN_R_TYPE ((rel + 1)->r_info) != R_RISCV_RELAX
5229 || rel->r_offset != (rel + 1)->r_offset)
5230 continue;
5232 /* Skip over the R_RISCV_RELAX. */
5233 i++;
5235 else if (info->relax_pass == 1 && type == R_RISCV_ALIGN)
5237 relax_func = _bfd_riscv_relax_align;
5238 riscv_relax_delete_bytes = _riscv_relax_delete_immediate;
5240 else
5241 continue;
5243 data->relocs = relocs;
5245 /* Read this BFD's contents if we haven't done so already. */
5246 if (!data->this_hdr.contents
5247 && !bfd_malloc_and_get_section (abfd, sec, &data->this_hdr.contents))
5248 goto fail;
5250 /* Read this BFD's symbols if we haven't done so already. */
5251 if (symtab_hdr->sh_info != 0
5252 && !symtab_hdr->contents
5253 && !(symtab_hdr->contents =
5254 (unsigned char *) bfd_elf_get_elf_syms (abfd, symtab_hdr,
5255 symtab_hdr->sh_info,
5256 0, NULL, NULL, NULL)))
5257 goto fail;
5259 /* Get the value of the symbol referred to by the reloc. */
5260 if (ELFNN_R_SYM (rel->r_info) < symtab_hdr->sh_info)
5262 /* A local symbol. */
5263 Elf_Internal_Sym *isym = ((Elf_Internal_Sym *) symtab_hdr->contents
5264 + ELFNN_R_SYM (rel->r_info));
5265 reserve_size = (isym->st_size - rel->r_addend) > isym->st_size
5266 ? 0 : isym->st_size - rel->r_addend;
5268 /* Relocate against local STT_GNU_IFUNC symbol. we have created
5269 a fake global symbol entry for this, so deal with the local ifunc
5270 as a global. */
5271 if (ELF_ST_TYPE (isym->st_info) == STT_GNU_IFUNC)
5272 continue;
5274 if (isym->st_shndx == SHN_UNDEF)
5275 sym_sec = sec, symval = rel->r_offset;
5276 else
5278 BFD_ASSERT (isym->st_shndx < elf_numsections (abfd));
5279 sym_sec = elf_elfsections (abfd)[isym->st_shndx]->bfd_section;
5280 #if 0
5281 /* The purpose of this code is unknown. It breaks linker scripts
5282 for embedded development that place sections at address zero.
5283 This code is believed to be unnecessary. Disabling it but not
5284 yet removing it, in case something breaks. */
5285 if (sec_addr (sym_sec) == 0)
5286 continue;
5287 #endif
5288 symval = isym->st_value;
5290 symtype = ELF_ST_TYPE (isym->st_info);
5292 else
5294 unsigned long indx;
5295 struct elf_link_hash_entry *h;
5297 indx = ELFNN_R_SYM (rel->r_info) - symtab_hdr->sh_info;
5298 h = elf_sym_hashes (abfd)[indx];
5300 while (h->root.type == bfd_link_hash_indirect
5301 || h->root.type == bfd_link_hash_warning)
5302 h = (struct elf_link_hash_entry *) h->root.u.i.link;
5304 /* Disable the relaxation for ifunc. */
5305 if (h != NULL && h->type == STT_GNU_IFUNC)
5306 continue;
5308 /* Maybe we should check UNDEFWEAK_NO_DYNAMIC_RELOC here? But that
5309 will break the undefweak relaxation testcases, so just make sure
5310 we won't do relaxations for linker_def symbols in short-term. */
5311 if (h->root.type == bfd_link_hash_undefweak
5312 /* The linker_def symbol like __ehdr_start that may be undefweak
5313 for now, but will be guaranteed to be defined later. */
5314 && !h->root.linker_def
5315 && (relax_func == _bfd_riscv_relax_lui
5316 || relax_func == _bfd_riscv_relax_pc))
5318 /* For the lui and auipc relaxations, since the symbol
5319 value of an undefined weak symbol is always be zero,
5320 we can optimize the patterns into a single LI/MV/ADDI
5321 instruction.
5323 Note that, creating shared libraries and pie output may
5324 break the rule above. Fortunately, since we do not relax
5325 pc relocs when creating shared libraries and pie output,
5326 and the absolute address access for R_RISCV_HI20 isn't
5327 allowed when "-fPIC" is set, the problem of creating shared
5328 libraries can not happen currently. Once we support the
5329 auipc relaxations when creating shared libraries, then we will
5330 need the more rigorous checking for this optimization. */
5331 undefined_weak = true;
5334 /* This line has to match the check in riscv_elf_relocate_section
5335 in the R_RISCV_CALL[_PLT] case. */
5336 if (bfd_link_pic (info) && h->plt.offset != MINUS_ONE)
5338 sym_sec = htab->elf.splt;
5339 symval = h->plt.offset;
5341 else if (undefined_weak)
5343 symval = 0;
5344 sym_sec = bfd_und_section_ptr;
5346 else if ((h->root.type == bfd_link_hash_defined
5347 || h->root.type == bfd_link_hash_defweak)
5348 && h->root.u.def.section != NULL
5349 && h->root.u.def.section->output_section != NULL)
5351 symval = h->root.u.def.value;
5352 sym_sec = h->root.u.def.section;
5354 else
5355 continue;
5357 if (h->type != STT_FUNC)
5358 reserve_size =
5359 (h->size - rel->r_addend) > h->size ? 0 : h->size - rel->r_addend;
5360 symtype = h->type;
5363 if (sym_sec->sec_info_type == SEC_INFO_TYPE_MERGE
5364 && (sym_sec->flags & SEC_MERGE))
5366 /* At this stage in linking, no SEC_MERGE symbol has been
5367 adjusted, so all references to such symbols need to be
5368 passed through _bfd_merged_section_offset. (Later, in
5369 relocate_section, all SEC_MERGE symbols *except* for
5370 section symbols have been adjusted.)
5372 gas may reduce relocations against symbols in SEC_MERGE
5373 sections to a relocation against the section symbol when
5374 the original addend was zero. When the reloc is against
5375 a section symbol we should include the addend in the
5376 offset passed to _bfd_merged_section_offset, since the
5377 location of interest is the original symbol. On the
5378 other hand, an access to "sym+addend" where "sym" is not
5379 a section symbol should not include the addend; Such an
5380 access is presumed to be an offset from "sym"; The
5381 location of interest is just "sym". */
5382 if (symtype == STT_SECTION)
5383 symval += rel->r_addend;
5385 symval = _bfd_merged_section_offset (abfd, &sym_sec,
5386 elf_section_data (sym_sec)->sec_info,
5387 symval);
5389 if (symtype != STT_SECTION)
5390 symval += rel->r_addend;
5392 else
5393 symval += rel->r_addend;
5395 symval += sec_addr (sym_sec);
5397 if (!relax_func (abfd, sec, sym_sec, info, rel, symval,
5398 max_alignment, reserve_size, again,
5399 &pcgp_relocs, undefined_weak))
5400 goto fail;
5403 /* Resolve R_RISCV_DELETE relocations. */
5404 if (!riscv_relax_resolve_delete_relocs (abfd, sec, info, relocs))
5405 goto fail;
5407 ret = true;
5409 fail:
5410 if (relocs != data->relocs)
5411 free (relocs);
5412 riscv_free_pcgp_relocs (&pcgp_relocs, abfd, sec);
5414 return ret;
5417 #if ARCH_SIZE == 32
5418 # define PRSTATUS_SIZE 204
5419 # define PRSTATUS_OFFSET_PR_CURSIG 12
5420 # define PRSTATUS_OFFSET_PR_PID 24
5421 # define PRSTATUS_OFFSET_PR_REG 72
5422 # define ELF_GREGSET_T_SIZE 128
5423 # define PRPSINFO_SIZE 128
5424 # define PRPSINFO_OFFSET_PR_PID 16
5425 # define PRPSINFO_OFFSET_PR_FNAME 32
5426 # define PRPSINFO_OFFSET_PR_PSARGS 48
5427 # define PRPSINFO_PR_FNAME_LENGTH 16
5428 # define PRPSINFO_PR_PSARGS_LENGTH 80
5429 #else
5430 # define PRSTATUS_SIZE 376
5431 # define PRSTATUS_OFFSET_PR_CURSIG 12
5432 # define PRSTATUS_OFFSET_PR_PID 32
5433 # define PRSTATUS_OFFSET_PR_REG 112
5434 # define ELF_GREGSET_T_SIZE 256
5435 # define PRPSINFO_SIZE 136
5436 # define PRPSINFO_OFFSET_PR_PID 24
5437 # define PRPSINFO_OFFSET_PR_FNAME 40
5438 # define PRPSINFO_OFFSET_PR_PSARGS 56
5439 # define PRPSINFO_PR_FNAME_LENGTH 16
5440 # define PRPSINFO_PR_PSARGS_LENGTH 80
5441 #endif
5443 /* Write PRSTATUS and PRPSINFO note into core file. This will be called
5444 before the generic code in elf.c. By checking the compiler defines we
5445 only perform any action here if the generic code would otherwise not be
5446 able to help us. The intention is that bare metal core dumps (where the
5447 prstatus_t and/or prpsinfo_t might not be available) will use this code,
5448 while non bare metal tools will use the generic elf code. */
5450 static char *
5451 riscv_write_core_note (bfd *abfd ATTRIBUTE_UNUSED,
5452 char *buf ATTRIBUTE_UNUSED,
5453 int *bufsiz ATTRIBUTE_UNUSED,
5454 int note_type ATTRIBUTE_UNUSED, ...)
5456 switch (note_type)
5458 default:
5459 return NULL;
5461 #if !defined (HAVE_PRPSINFO_T)
5462 case NT_PRPSINFO:
5464 char data[PRPSINFO_SIZE] ATTRIBUTE_NONSTRING;
5465 va_list ap;
5467 va_start (ap, note_type);
5468 memset (data, 0, sizeof (data));
5469 strncpy (data + PRPSINFO_OFFSET_PR_FNAME, va_arg (ap, const char *),
5470 PRPSINFO_PR_FNAME_LENGTH);
5471 #if GCC_VERSION == 8000 || GCC_VERSION == 8001
5472 DIAGNOSTIC_PUSH;
5473 /* GCC 8.0 and 8.1 warn about 80 equals destination size with
5474 -Wstringop-truncation:
5475 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85643
5477 DIAGNOSTIC_IGNORE_STRINGOP_TRUNCATION;
5478 #endif
5479 strncpy (data + PRPSINFO_OFFSET_PR_PSARGS, va_arg (ap, const char *),
5480 PRPSINFO_PR_PSARGS_LENGTH);
5481 #if GCC_VERSION == 8000 || GCC_VERSION == 8001
5482 DIAGNOSTIC_POP;
5483 #endif
5484 va_end (ap);
5485 return elfcore_write_note (abfd, buf, bufsiz,
5486 "CORE", note_type, data, sizeof (data));
5488 #endif /* !HAVE_PRPSINFO_T */
5490 #if !defined (HAVE_PRSTATUS_T)
5491 case NT_PRSTATUS:
5493 char data[PRSTATUS_SIZE];
5494 va_list ap;
5495 long pid;
5496 int cursig;
5497 const void *greg;
5499 va_start (ap, note_type);
5500 memset (data, 0, sizeof(data));
5501 pid = va_arg (ap, long);
5502 bfd_put_32 (abfd, pid, data + PRSTATUS_OFFSET_PR_PID);
5503 cursig = va_arg (ap, int);
5504 bfd_put_16 (abfd, cursig, data + PRSTATUS_OFFSET_PR_CURSIG);
5505 greg = va_arg (ap, const void *);
5506 memcpy (data + PRSTATUS_OFFSET_PR_REG, greg,
5507 PRSTATUS_SIZE - PRSTATUS_OFFSET_PR_REG - ARCH_SIZE / 8);
5508 va_end (ap);
5509 return elfcore_write_note (abfd, buf, bufsiz,
5510 "CORE", note_type, data, sizeof (data));
5512 #endif /* !HAVE_PRSTATUS_T */
5516 /* Support for core dump NOTE sections. */
5518 static bool
5519 riscv_elf_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
5521 switch (note->descsz)
5523 default:
5524 return false;
5526 case PRSTATUS_SIZE: /* sizeof(struct elf_prstatus) on Linux/RISC-V. */
5527 /* pr_cursig */
5528 elf_tdata (abfd)->core->signal
5529 = bfd_get_16 (abfd, note->descdata + PRSTATUS_OFFSET_PR_CURSIG);
5531 /* pr_pid */
5532 elf_tdata (abfd)->core->lwpid
5533 = bfd_get_32 (abfd, note->descdata + PRSTATUS_OFFSET_PR_PID);
5534 break;
5537 /* Make a ".reg/999" section. */
5538 return _bfd_elfcore_make_pseudosection (abfd, ".reg", ELF_GREGSET_T_SIZE,
5539 note->descpos + PRSTATUS_OFFSET_PR_REG);
5542 static bool
5543 riscv_elf_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
5545 switch (note->descsz)
5547 default:
5548 return false;
5550 case PRPSINFO_SIZE: /* sizeof(struct elf_prpsinfo) on Linux/RISC-V. */
5551 /* pr_pid */
5552 elf_tdata (abfd)->core->pid
5553 = bfd_get_32 (abfd, note->descdata + PRPSINFO_OFFSET_PR_PID);
5555 /* pr_fname */
5556 elf_tdata (abfd)->core->program = _bfd_elfcore_strndup
5557 (abfd, note->descdata + PRPSINFO_OFFSET_PR_FNAME,
5558 PRPSINFO_PR_FNAME_LENGTH);
5560 /* pr_psargs */
5561 elf_tdata (abfd)->core->command = _bfd_elfcore_strndup
5562 (abfd, note->descdata + PRPSINFO_OFFSET_PR_PSARGS,
5563 PRPSINFO_PR_PSARGS_LENGTH);
5564 break;
5567 /* Note that for some reason, a spurious space is tacked
5568 onto the end of the args in some (at least one anyway)
5569 implementations, so strip it off if it exists. */
5572 char *command = elf_tdata (abfd)->core->command;
5573 int n = strlen (command);
5575 if (0 < n && command[n - 1] == ' ')
5576 command[n - 1] = '\0';
5579 return true;
5582 /* Set the right mach type. */
5584 static bool
5585 riscv_elf_object_p (bfd *abfd)
5587 /* There are only two mach types in RISCV currently. */
5588 if (strcmp (abfd->xvec->name, "elf32-littleriscv") == 0
5589 || strcmp (abfd->xvec->name, "elf32-bigriscv") == 0)
5590 bfd_default_set_arch_mach (abfd, bfd_arch_riscv, bfd_mach_riscv32);
5591 else
5592 bfd_default_set_arch_mach (abfd, bfd_arch_riscv, bfd_mach_riscv64);
5594 return true;
5597 /* Determine whether an object attribute tag takes an integer, a
5598 string or both. */
5600 static int
5601 riscv_elf_obj_attrs_arg_type (int tag)
5603 return (tag & 1) != 0 ? ATTR_TYPE_FLAG_STR_VAL : ATTR_TYPE_FLAG_INT_VAL;
5606 /* Do not choose mapping symbols as a function name. */
5608 static bfd_size_type
5609 riscv_maybe_function_sym (const asymbol *sym,
5610 asection *sec,
5611 bfd_vma *code_off)
5613 if (sym->flags & BSF_LOCAL
5614 && (riscv_elf_is_mapping_symbols (sym->name)
5615 || _bfd_elf_is_local_label_name (sec->owner, sym->name)))
5616 return 0;
5618 return _bfd_elf_maybe_function_sym (sym, sec, code_off);
5621 /* Treat the following cases as target special symbols, they are
5622 usually omitted. */
5624 static bool
5625 riscv_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
5627 /* PR27584, local and empty symbols. Since they are usually
5628 generated for pcrel relocations. */
5629 return (!sym->name[0]
5630 || _bfd_elf_is_local_label_name (abfd, sym->name)
5631 /* PR27916, mapping symbols. */
5632 || riscv_elf_is_mapping_symbols (sym->name));
5635 static int
5636 riscv_elf_additional_program_headers (bfd *abfd,
5637 struct bfd_link_info *info ATTRIBUTE_UNUSED)
5639 int ret = 0;
5641 /* See if we need a PT_RISCV_ATTRIBUTES segment. */
5642 if (bfd_get_section_by_name (abfd, RISCV_ATTRIBUTES_SECTION_NAME))
5643 ++ret;
5645 return ret;
5648 static bool
5649 riscv_elf_modify_segment_map (bfd *abfd,
5650 struct bfd_link_info *info ATTRIBUTE_UNUSED)
5652 asection *s;
5653 struct elf_segment_map *m, **pm;
5654 size_t amt;
5656 /* If there is a .riscv.attributes section, we need a PT_RISCV_ATTRIBUTES
5657 segment. */
5658 s = bfd_get_section_by_name (abfd, RISCV_ATTRIBUTES_SECTION_NAME);
5659 if (s != NULL)
5661 for (m = elf_seg_map (abfd); m != NULL; m = m->next)
5662 if (m->p_type == PT_RISCV_ATTRIBUTES)
5663 break;
5664 /* If there is already a PT_RISCV_ATTRIBUTES header, avoid adding
5665 another. */
5666 if (m == NULL)
5668 amt = sizeof (*m);
5669 m = bfd_zalloc (abfd, amt);
5670 if (m == NULL)
5671 return false;
5673 m->p_type = PT_RISCV_ATTRIBUTES;
5674 m->count = 1;
5675 m->sections[0] = s;
5677 /* We want to put it after the PHDR and INTERP segments. */
5678 pm = &elf_seg_map (abfd);
5679 while (*pm != NULL
5680 && ((*pm)->p_type == PT_PHDR
5681 || (*pm)->p_type == PT_INTERP))
5682 pm = &(*pm)->next;
5684 m->next = *pm;
5685 *pm = m;
5689 return true;
5692 /* Merge non-visibility st_other attributes. */
5694 static void
5695 riscv_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
5696 unsigned int st_other,
5697 bool definition ATTRIBUTE_UNUSED,
5698 bool dynamic ATTRIBUTE_UNUSED)
5700 unsigned int isym_sto = st_other & ~ELF_ST_VISIBILITY (-1);
5701 unsigned int h_sto = h->other & ~ELF_ST_VISIBILITY (-1);
5703 if (isym_sto == h_sto)
5704 return;
5706 if (isym_sto & ~STO_RISCV_VARIANT_CC)
5707 _bfd_error_handler (_("unknown attribute for symbol `%s': 0x%02x"),
5708 h->root.root.string, isym_sto);
5710 if (isym_sto & STO_RISCV_VARIANT_CC)
5711 h->other |= STO_RISCV_VARIANT_CC;
5714 #define TARGET_LITTLE_SYM riscv_elfNN_vec
5715 #define TARGET_LITTLE_NAME "elfNN-littleriscv"
5716 #define TARGET_BIG_SYM riscv_elfNN_be_vec
5717 #define TARGET_BIG_NAME "elfNN-bigriscv"
5719 #define elf_backend_reloc_type_class riscv_reloc_type_class
5721 #define bfd_elfNN_bfd_reloc_name_lookup riscv_reloc_name_lookup
5722 #define bfd_elfNN_bfd_link_hash_table_create riscv_elf_link_hash_table_create
5723 #define bfd_elfNN_bfd_reloc_type_lookup riscv_reloc_type_lookup
5724 #define bfd_elfNN_bfd_merge_private_bfd_data \
5725 _bfd_riscv_elf_merge_private_bfd_data
5726 #define bfd_elfNN_bfd_is_target_special_symbol riscv_elf_is_target_special_symbol
5728 #define elf_backend_copy_indirect_symbol riscv_elf_copy_indirect_symbol
5729 #define elf_backend_create_dynamic_sections riscv_elf_create_dynamic_sections
5730 #define elf_backend_check_relocs riscv_elf_check_relocs
5731 #define elf_backend_adjust_dynamic_symbol riscv_elf_adjust_dynamic_symbol
5732 #define elf_backend_late_size_sections riscv_elf_late_size_sections
5733 #define elf_backend_relocate_section riscv_elf_relocate_section
5734 #define elf_backend_finish_dynamic_symbol riscv_elf_finish_dynamic_symbol
5735 #define elf_backend_finish_dynamic_sections riscv_elf_finish_dynamic_sections
5736 #define elf_backend_plt_sym_val riscv_elf_plt_sym_val
5737 #define elf_backend_grok_prstatus riscv_elf_grok_prstatus
5738 #define elf_backend_grok_psinfo riscv_elf_grok_psinfo
5739 #define elf_backend_object_p riscv_elf_object_p
5740 #define elf_backend_write_core_note riscv_write_core_note
5741 #define elf_backend_maybe_function_sym riscv_maybe_function_sym
5742 #define elf_info_to_howto_rel NULL
5743 #define elf_info_to_howto riscv_info_to_howto_rela
5744 #define bfd_elfNN_bfd_relax_section _bfd_riscv_relax_section
5745 #define bfd_elfNN_mkobject elfNN_riscv_mkobject
5746 #define elf_backend_additional_program_headers \
5747 riscv_elf_additional_program_headers
5748 #define elf_backend_modify_segment_map riscv_elf_modify_segment_map
5749 #define elf_backend_merge_symbol_attribute riscv_elf_merge_symbol_attribute
5751 #define elf_backend_init_index_section _bfd_elf_init_1_index_section
5753 #define elf_backend_can_gc_sections 1
5754 #define elf_backend_can_refcount 1
5755 #define elf_backend_want_got_plt 1
5756 #define elf_backend_plt_readonly 1
5757 #define elf_backend_plt_alignment 4
5758 #define elf_backend_want_plt_sym 1
5759 #define elf_backend_got_header_size (ARCH_SIZE / 8)
5760 #define elf_backend_want_dynrelro 1
5761 #define elf_backend_rela_normal 1
5762 #define elf_backend_default_execstack 0
5764 #undef elf_backend_obj_attrs_vendor
5765 #define elf_backend_obj_attrs_vendor "riscv"
5766 #undef elf_backend_obj_attrs_arg_type
5767 #define elf_backend_obj_attrs_arg_type riscv_elf_obj_attrs_arg_type
5768 #undef elf_backend_obj_attrs_section_type
5769 #define elf_backend_obj_attrs_section_type SHT_RISCV_ATTRIBUTES
5770 #undef elf_backend_obj_attrs_section
5771 #define elf_backend_obj_attrs_section RISCV_ATTRIBUTES_SECTION_NAME
5772 #define elf_backend_obj_attrs_handle_unknown riscv_elf_obj_attrs_handle_unknown
5774 #include "elfNN-target.h"