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