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