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