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