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