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