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