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