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