packaging: Enable testing infrastructure
[external/binutils.git] / bfd / elfnn-riscv.c
1 /* RISC-V-specific support for NN-bit ELF.
2    Copyright (C) 2011-2019 Free Software Foundation, Inc.
3
4    Contributed by Andrew Waterman (andrew@sifive.com).
5    Based on TILE-Gx and MIPS targets.
6
7    This file is part of BFD, the Binary File Descriptor library.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; see the file COPYING3. If not,
21    see <http://www.gnu.org/licenses/>.  */
22
23 /* This file handles RISC-V ELF targets.  */
24
25 #include "sysdep.h"
26 #include "bfd.h"
27 #include "libbfd.h"
28 #include "bfdlink.h"
29 #include "genlink.h"
30 #include "elf-bfd.h"
31 #include "elfxx-riscv.h"
32 #include "elf/riscv.h"
33 #include "opcode/riscv.h"
34
35 /* Internal relocations used exclusively by the relaxation pass.  */
36 #define R_RISCV_DELETE (R_RISCV_max + 1)
37
38 #define ARCH_SIZE NN
39
40 #define MINUS_ONE ((bfd_vma)0 - 1)
41
42 #define RISCV_ELF_LOG_WORD_BYTES (ARCH_SIZE == 32 ? 2 : 3)
43
44 #define RISCV_ELF_WORD_BYTES (1 << RISCV_ELF_LOG_WORD_BYTES)
45
46 /* The name of the dynamic interpreter.  This is put in the .interp
47    section.  */
48
49 #define ELF64_DYNAMIC_INTERPRETER "/lib/ld.so.1"
50 #define ELF32_DYNAMIC_INTERPRETER "/lib32/ld.so.1"
51
52 #define ELF_ARCH                        bfd_arch_riscv
53 #define ELF_TARGET_ID                   RISCV_ELF_DATA
54 #define ELF_MACHINE_CODE                EM_RISCV
55 #define ELF_MAXPAGESIZE                 0x1000
56 #define ELF_COMMONPAGESIZE              0x1000
57
58 /* RISC-V ELF linker hash entry.  */
59
60 struct riscv_elf_link_hash_entry
61 {
62   struct elf_link_hash_entry elf;
63
64   /* Track dynamic relocs copied for this symbol.  */
65   struct elf_dyn_relocs *dyn_relocs;
66
67 #define GOT_UNKNOWN     0
68 #define GOT_NORMAL      1
69 #define GOT_TLS_GD      2
70 #define GOT_TLS_IE      4
71 #define GOT_TLS_LE      8
72   char tls_type;
73 };
74
75 #define riscv_elf_hash_entry(ent) \
76   ((struct riscv_elf_link_hash_entry *)(ent))
77
78 struct _bfd_riscv_elf_obj_tdata
79 {
80   struct elf_obj_tdata root;
81
82   /* tls_type for each local got entry.  */
83   char *local_got_tls_type;
84 };
85
86 #define _bfd_riscv_elf_tdata(abfd) \
87   ((struct _bfd_riscv_elf_obj_tdata *) (abfd)->tdata.any)
88
89 #define _bfd_riscv_elf_local_got_tls_type(abfd) \
90   (_bfd_riscv_elf_tdata (abfd)->local_got_tls_type)
91
92 #define _bfd_riscv_elf_tls_type(abfd, h, symndx)                \
93   (*((h) != NULL ? &riscv_elf_hash_entry (h)->tls_type          \
94      : &_bfd_riscv_elf_local_got_tls_type (abfd) [symndx]))
95
96 #define is_riscv_elf(bfd)                               \
97   (bfd_get_flavour (bfd) == bfd_target_elf_flavour      \
98    && elf_tdata (bfd) != NULL                           \
99    && elf_object_id (bfd) == RISCV_ELF_DATA)
100
101 #include "elf/common.h"
102 #include "elf/internal.h"
103
104 struct riscv_elf_link_hash_table
105 {
106   struct elf_link_hash_table elf;
107
108   /* Short-cuts to get to dynamic linker sections.  */
109   asection *sdyntdata;
110
111   /* Small local sym to section mapping cache.  */
112   struct sym_cache sym_cache;
113
114   /* The max alignment of output sections.  */
115   bfd_vma max_alignment;
116 };
117
118
119 /* Get the RISC-V ELF linker hash table from a link_info structure.  */
120 #define riscv_elf_hash_table(p) \
121   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
122   == RISCV_ELF_DATA ? ((struct riscv_elf_link_hash_table *) ((p)->hash)) : NULL)
123
124 static bfd_boolean
125 riscv_info_to_howto_rela (bfd *abfd,
126                           arelent *cache_ptr,
127                           Elf_Internal_Rela *dst)
128 {
129   cache_ptr->howto = riscv_elf_rtype_to_howto (abfd, ELFNN_R_TYPE (dst->r_info));
130   return cache_ptr->howto != NULL;
131 }
132
133 static void
134 riscv_elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
135 {
136   const struct elf_backend_data *bed;
137   bfd_byte *loc;
138
139   bed = get_elf_backend_data (abfd);
140   loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
141   bed->s->swap_reloca_out (abfd, rel, loc);
142 }
143
144 /* PLT/GOT stuff.  */
145
146 #define PLT_HEADER_INSNS 8
147 #define PLT_ENTRY_INSNS 4
148 #define PLT_HEADER_SIZE (PLT_HEADER_INSNS * 4)
149 #define PLT_ENTRY_SIZE (PLT_ENTRY_INSNS * 4)
150
151 #define GOT_ENTRY_SIZE RISCV_ELF_WORD_BYTES
152
153 #define GOTPLT_HEADER_SIZE (2 * GOT_ENTRY_SIZE)
154
155 #define sec_addr(sec) ((sec)->output_section->vma + (sec)->output_offset)
156
157 static bfd_vma
158 riscv_elf_got_plt_val (bfd_vma plt_index, struct bfd_link_info *info)
159 {
160   return sec_addr (riscv_elf_hash_table (info)->elf.sgotplt)
161          + GOTPLT_HEADER_SIZE + (plt_index * GOT_ENTRY_SIZE);
162 }
163
164 #if ARCH_SIZE == 32
165 # define MATCH_LREG MATCH_LW
166 #else
167 # define MATCH_LREG MATCH_LD
168 #endif
169
170 /* Generate a PLT header.  */
171
172 static bfd_boolean
173 riscv_make_plt_header (bfd *output_bfd, bfd_vma gotplt_addr, bfd_vma addr,
174                        uint32_t *entry)
175 {
176   bfd_vma gotplt_offset_high = RISCV_PCREL_HIGH_PART (gotplt_addr, addr);
177   bfd_vma gotplt_offset_low = RISCV_PCREL_LOW_PART (gotplt_addr, addr);
178
179   /* RVE has no t3 register, so this won't work, and is not supported.  */
180   if (elf_elfheader (output_bfd)->e_flags & EF_RISCV_RVE)
181     {
182       _bfd_error_handler (_("%pB: warning: RVE PLT generation not supported"),
183                           output_bfd);
184       return FALSE;
185     }
186
187   /* auipc  t2, %hi(.got.plt)
188      sub    t1, t1, t3               # shifted .got.plt offset + hdr size + 12
189      l[w|d] t3, %lo(.got.plt)(t2)    # _dl_runtime_resolve
190      addi   t1, t1, -(hdr size + 12) # shifted .got.plt offset
191      addi   t0, t2, %lo(.got.plt)    # &.got.plt
192      srli   t1, t1, log2(16/PTRSIZE) # .got.plt offset
193      l[w|d] t0, PTRSIZE(t0)          # link map
194      jr     t3 */
195
196   entry[0] = RISCV_UTYPE (AUIPC, X_T2, gotplt_offset_high);
197   entry[1] = RISCV_RTYPE (SUB, X_T1, X_T1, X_T3);
198   entry[2] = RISCV_ITYPE (LREG, X_T3, X_T2, gotplt_offset_low);
199   entry[3] = RISCV_ITYPE (ADDI, X_T1, X_T1, -(PLT_HEADER_SIZE + 12));
200   entry[4] = RISCV_ITYPE (ADDI, X_T0, X_T2, gotplt_offset_low);
201   entry[5] = RISCV_ITYPE (SRLI, X_T1, X_T1, 4 - RISCV_ELF_LOG_WORD_BYTES);
202   entry[6] = RISCV_ITYPE (LREG, X_T0, X_T0, RISCV_ELF_WORD_BYTES);
203   entry[7] = RISCV_ITYPE (JALR, 0, X_T3, 0);
204
205   return TRUE;
206 }
207
208 /* Generate a PLT entry.  */
209
210 static bfd_boolean
211 riscv_make_plt_entry (bfd *output_bfd, bfd_vma got, bfd_vma addr,
212                       uint32_t *entry)
213 {
214   /* RVE has no t3 register, so this won't work, and is not supported.  */
215   if (elf_elfheader (output_bfd)->e_flags & EF_RISCV_RVE)
216     {
217       _bfd_error_handler (_("%pB: warning: RVE PLT generation not supported"),
218                           output_bfd);
219       return FALSE;
220     }
221
222   /* auipc  t3, %hi(.got.plt entry)
223      l[w|d] t3, %lo(.got.plt entry)(t3)
224      jalr   t1, t3
225      nop */
226
227   entry[0] = RISCV_UTYPE (AUIPC, X_T3, RISCV_PCREL_HIGH_PART (got, addr));
228   entry[1] = RISCV_ITYPE (LREG,  X_T3, X_T3, RISCV_PCREL_LOW_PART (got, addr));
229   entry[2] = RISCV_ITYPE (JALR, X_T1, X_T3, 0);
230   entry[3] = RISCV_NOP;
231
232   return TRUE;
233 }
234
235 /* Create an entry in an RISC-V ELF linker hash table.  */
236
237 static struct bfd_hash_entry *
238 link_hash_newfunc (struct bfd_hash_entry *entry,
239                    struct bfd_hash_table *table, const char *string)
240 {
241   /* Allocate the structure if it has not already been allocated by a
242      subclass.  */
243   if (entry == NULL)
244     {
245       entry =
246         bfd_hash_allocate (table,
247                            sizeof (struct riscv_elf_link_hash_entry));
248       if (entry == NULL)
249         return entry;
250     }
251
252   /* Call the allocation method of the superclass.  */
253   entry = _bfd_elf_link_hash_newfunc (entry, table, string);
254   if (entry != NULL)
255     {
256       struct riscv_elf_link_hash_entry *eh;
257
258       eh = (struct riscv_elf_link_hash_entry *) entry;
259       eh->dyn_relocs = NULL;
260       eh->tls_type = GOT_UNKNOWN;
261     }
262
263   return entry;
264 }
265
266 /* Create a RISC-V ELF linker hash table.  */
267
268 static struct bfd_link_hash_table *
269 riscv_elf_link_hash_table_create (bfd *abfd)
270 {
271   struct riscv_elf_link_hash_table *ret;
272   bfd_size_type amt = sizeof (struct riscv_elf_link_hash_table);
273
274   ret = (struct riscv_elf_link_hash_table *) bfd_zmalloc (amt);
275   if (ret == NULL)
276     return NULL;
277
278   if (!_bfd_elf_link_hash_table_init (&ret->elf, abfd, link_hash_newfunc,
279                                       sizeof (struct riscv_elf_link_hash_entry),
280                                       RISCV_ELF_DATA))
281     {
282       free (ret);
283       return NULL;
284     }
285
286   ret->max_alignment = (bfd_vma) -1;
287   return &ret->elf.root;
288 }
289
290 /* Create the .got section.  */
291
292 static bfd_boolean
293 riscv_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
294 {
295   flagword flags;
296   asection *s, *s_got;
297   struct elf_link_hash_entry *h;
298   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
299   struct elf_link_hash_table *htab = elf_hash_table (info);
300
301   /* This function may be called more than once.  */
302   if (htab->sgot != NULL)
303     return TRUE;
304
305   flags = bed->dynamic_sec_flags;
306
307   s = bfd_make_section_anyway_with_flags (abfd,
308                                           (bed->rela_plts_and_copies_p
309                                            ? ".rela.got" : ".rel.got"),
310                                           (bed->dynamic_sec_flags
311                                            | SEC_READONLY));
312   if (s == NULL
313       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
314     return FALSE;
315   htab->srelgot = s;
316
317   s = s_got = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
318   if (s == NULL
319       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
320     return FALSE;
321   htab->sgot = s;
322
323   /* The first bit of the global offset table is the header.  */
324   s->size += bed->got_header_size;
325
326   if (bed->want_got_plt)
327     {
328       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
329       if (s == NULL
330           || !bfd_set_section_alignment (abfd, s,
331                                          bed->s->log_file_align))
332         return FALSE;
333       htab->sgotplt = s;
334
335       /* Reserve room for the header.  */
336       s->size += GOTPLT_HEADER_SIZE;
337     }
338
339   if (bed->want_got_sym)
340     {
341       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
342          section.  We don't do this in the linker script because we don't want
343          to define the symbol if we are not creating a global offset
344          table.  */
345       h = _bfd_elf_define_linkage_sym (abfd, info, s_got,
346                                        "_GLOBAL_OFFSET_TABLE_");
347       elf_hash_table (info)->hgot = h;
348       if (h == NULL)
349         return FALSE;
350     }
351
352   return TRUE;
353 }
354
355 /* Create .plt, .rela.plt, .got, .got.plt, .rela.got, .dynbss, and
356    .rela.bss sections in DYNOBJ, and set up shortcuts to them in our
357    hash table.  */
358
359 static bfd_boolean
360 riscv_elf_create_dynamic_sections (bfd *dynobj,
361                                    struct bfd_link_info *info)
362 {
363   struct riscv_elf_link_hash_table *htab;
364
365   htab = riscv_elf_hash_table (info);
366   BFD_ASSERT (htab != NULL);
367
368   if (!riscv_elf_create_got_section (dynobj, info))
369     return FALSE;
370
371   if (!_bfd_elf_create_dynamic_sections (dynobj, info))
372     return FALSE;
373
374   if (!bfd_link_pic (info))
375     {
376       /* Technically, this section doesn't have contents.  It is used as the
377          target of TLS copy relocs, to copy TLS data from shared libraries into
378          the executable.  However, if we don't mark it as loadable, then it
379          matches the IS_TBSS test in ldlang.c, and there is no run-time address
380          space allocated for it even though it has SEC_ALLOC.  That test is
381          correct for .tbss, but not correct for this section.  There is also
382          a second problem that having a section with no contents can only work
383          if it comes after all sections with contents in the same segment,
384          but the linker script does not guarantee that.  This is just mixed in
385          with other .tdata.* sections.  We can fix both problems by lying and
386          saying that there are contents.  This section is expected to be small
387          so this should not cause a significant extra program startup cost.  */
388       htab->sdyntdata =
389         bfd_make_section_anyway_with_flags (dynobj, ".tdata.dyn",
390                                             (SEC_ALLOC | SEC_THREAD_LOCAL
391                                              | SEC_LOAD | SEC_DATA
392                                              | SEC_HAS_CONTENTS
393                                              | SEC_LINKER_CREATED));
394     }
395
396   if (!htab->elf.splt || !htab->elf.srelplt || !htab->elf.sdynbss
397       || (!bfd_link_pic (info) && (!htab->elf.srelbss || !htab->sdyntdata)))
398     abort ();
399
400   return TRUE;
401 }
402
403 /* Copy the extra info we tack onto an elf_link_hash_entry.  */
404
405 static void
406 riscv_elf_copy_indirect_symbol (struct bfd_link_info *info,
407                                 struct elf_link_hash_entry *dir,
408                                 struct elf_link_hash_entry *ind)
409 {
410   struct riscv_elf_link_hash_entry *edir, *eind;
411
412   edir = (struct riscv_elf_link_hash_entry *) dir;
413   eind = (struct riscv_elf_link_hash_entry *) ind;
414
415   if (eind->dyn_relocs != NULL)
416     {
417       if (edir->dyn_relocs != NULL)
418         {
419           struct elf_dyn_relocs **pp;
420           struct elf_dyn_relocs *p;
421
422           /* Add reloc counts against the indirect sym to the direct sym
423              list.  Merge any entries against the same section.  */
424           for (pp = &eind->dyn_relocs; (p = *pp) != NULL; )
425             {
426               struct elf_dyn_relocs *q;
427
428               for (q = edir->dyn_relocs; q != NULL; q = q->next)
429                 if (q->sec == p->sec)
430                   {
431                     q->pc_count += p->pc_count;
432                     q->count += p->count;
433                     *pp = p->next;
434                     break;
435                   }
436               if (q == NULL)
437                 pp = &p->next;
438             }
439           *pp = edir->dyn_relocs;
440         }
441
442       edir->dyn_relocs = eind->dyn_relocs;
443       eind->dyn_relocs = NULL;
444     }
445
446   if (ind->root.type == bfd_link_hash_indirect
447       && dir->got.refcount <= 0)
448     {
449       edir->tls_type = eind->tls_type;
450       eind->tls_type = GOT_UNKNOWN;
451     }
452   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
453 }
454
455 static bfd_boolean
456 riscv_elf_record_tls_type (bfd *abfd, struct elf_link_hash_entry *h,
457                            unsigned long symndx, char tls_type)
458 {
459   char *new_tls_type = &_bfd_riscv_elf_tls_type (abfd, h, symndx);
460
461   *new_tls_type |= tls_type;
462   if ((*new_tls_type & GOT_NORMAL) && (*new_tls_type & ~GOT_NORMAL))
463     {
464       (*_bfd_error_handler)
465         (_("%pB: `%s' accessed both as normal and thread local symbol"),
466          abfd, h ? h->root.root.string : "<local>");
467       return FALSE;
468     }
469   return TRUE;
470 }
471
472 static bfd_boolean
473 riscv_elf_record_got_reference (bfd *abfd, struct bfd_link_info *info,
474                                 struct elf_link_hash_entry *h, long symndx)
475 {
476   struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
477   Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
478
479   if (htab->elf.sgot == NULL)
480     {
481       if (!riscv_elf_create_got_section (htab->elf.dynobj, info))
482         return FALSE;
483     }
484
485   if (h != NULL)
486     {
487       h->got.refcount += 1;
488       return TRUE;
489     }
490
491   /* This is a global offset table entry for a local symbol.  */
492   if (elf_local_got_refcounts (abfd) == NULL)
493     {
494       bfd_size_type size = symtab_hdr->sh_info * (sizeof (bfd_vma) + 1);
495       if (!(elf_local_got_refcounts (abfd) = bfd_zalloc (abfd, size)))
496         return FALSE;
497       _bfd_riscv_elf_local_got_tls_type (abfd)
498         = (char *) (elf_local_got_refcounts (abfd) + symtab_hdr->sh_info);
499     }
500   elf_local_got_refcounts (abfd) [symndx] += 1;
501
502   return TRUE;
503 }
504
505 static bfd_boolean
506 bad_static_reloc (bfd *abfd, unsigned r_type, struct elf_link_hash_entry *h)
507 {
508   reloc_howto_type * r = riscv_elf_rtype_to_howto (abfd, r_type);
509
510   (*_bfd_error_handler)
511     (_("%pB: relocation %s against `%s' can not be used when making a shared "
512        "object; recompile with -fPIC"),
513      abfd, r ? r->name : _("<unknown>"),
514      h != NULL ? h->root.root.string : "a local symbol");
515   bfd_set_error (bfd_error_bad_value);
516   return FALSE;
517 }
518 /* Look through the relocs for a section during the first phase, and
519    allocate space in the global offset table or procedure linkage
520    table.  */
521
522 static bfd_boolean
523 riscv_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
524                         asection *sec, const Elf_Internal_Rela *relocs)
525 {
526   struct riscv_elf_link_hash_table *htab;
527   Elf_Internal_Shdr *symtab_hdr;
528   struct elf_link_hash_entry **sym_hashes;
529   const Elf_Internal_Rela *rel;
530   asection *sreloc = NULL;
531
532   if (bfd_link_relocatable (info))
533     return TRUE;
534
535   htab = riscv_elf_hash_table (info);
536   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
537   sym_hashes = elf_sym_hashes (abfd);
538
539   if (htab->elf.dynobj == NULL)
540     htab->elf.dynobj = abfd;
541
542   for (rel = relocs; rel < relocs + sec->reloc_count; rel++)
543     {
544       unsigned int r_type;
545       unsigned int r_symndx;
546       struct elf_link_hash_entry *h;
547
548       r_symndx = ELFNN_R_SYM (rel->r_info);
549       r_type = ELFNN_R_TYPE (rel->r_info);
550
551       if (r_symndx >= NUM_SHDR_ENTRIES (symtab_hdr))
552         {
553           (*_bfd_error_handler) (_("%pB: bad symbol index: %d"),
554                                  abfd, r_symndx);
555           return FALSE;
556         }
557
558       if (r_symndx < symtab_hdr->sh_info)
559         h = NULL;
560       else
561         {
562           h = sym_hashes[r_symndx - symtab_hdr->sh_info];
563           while (h->root.type == bfd_link_hash_indirect
564                  || h->root.type == bfd_link_hash_warning)
565             h = (struct elf_link_hash_entry *) h->root.u.i.link;
566         }
567
568       switch (r_type)
569         {
570         case R_RISCV_TLS_GD_HI20:
571           if (!riscv_elf_record_got_reference (abfd, info, h, r_symndx)
572               || !riscv_elf_record_tls_type (abfd, h, r_symndx, GOT_TLS_GD))
573             return FALSE;
574           break;
575
576         case R_RISCV_TLS_GOT_HI20:
577           if (bfd_link_pic (info))
578             info->flags |= DF_STATIC_TLS;
579           if (!riscv_elf_record_got_reference (abfd, info, h, r_symndx)
580               || !riscv_elf_record_tls_type (abfd, h, r_symndx, GOT_TLS_IE))
581             return FALSE;
582           break;
583
584         case R_RISCV_GOT_HI20:
585           if (!riscv_elf_record_got_reference (abfd, info, h, r_symndx)
586               || !riscv_elf_record_tls_type (abfd, h, r_symndx, GOT_NORMAL))
587             return FALSE;
588           break;
589
590         case R_RISCV_CALL_PLT:
591           /* This symbol requires a procedure linkage table entry.  We
592              actually build the entry in adjust_dynamic_symbol,
593              because this might be a case of linking PIC code without
594              linking in any dynamic objects, in which case we don't
595              need to generate a procedure linkage table after all.  */
596
597           if (h != NULL)
598             {
599               h->needs_plt = 1;
600               h->plt.refcount += 1;
601             }
602           break;
603
604         case R_RISCV_CALL:
605         case R_RISCV_JAL:
606         case R_RISCV_BRANCH:
607         case R_RISCV_RVC_BRANCH:
608         case R_RISCV_RVC_JUMP:
609         case R_RISCV_PCREL_HI20:
610           /* In shared libraries, these relocs are known to bind locally.  */
611           if (bfd_link_pic (info))
612             break;
613           goto static_reloc;
614
615         case R_RISCV_TPREL_HI20:
616           if (!bfd_link_executable (info))
617             return bad_static_reloc (abfd, r_type, h);
618           if (h != NULL)
619             riscv_elf_record_tls_type (abfd, h, r_symndx, GOT_TLS_LE);
620           goto static_reloc;
621
622         case R_RISCV_HI20:
623           if (bfd_link_pic (info))
624             return bad_static_reloc (abfd, r_type, h);
625           /* Fall through.  */
626
627         case R_RISCV_COPY:
628         case R_RISCV_JUMP_SLOT:
629         case R_RISCV_RELATIVE:
630         case R_RISCV_64:
631         case R_RISCV_32:
632           /* Fall through.  */
633
634         static_reloc:
635           /* This reloc might not bind locally.  */
636           if (h != NULL)
637             h->non_got_ref = 1;
638
639           if (h != NULL && !bfd_link_pic (info))
640             {
641               /* We may need a .plt entry if the function this reloc
642                  refers to is in a shared lib.  */
643               h->plt.refcount += 1;
644             }
645
646           /* If we are creating a shared library, and this is a reloc
647              against a global symbol, or a non PC relative reloc
648              against a local symbol, then we need to copy the reloc
649              into the shared library.  However, if we are linking with
650              -Bsymbolic, we do not need to copy a reloc against a
651              global symbol which is defined in an object we are
652              including in the link (i.e., DEF_REGULAR is set).  At
653              this point we have not seen all the input files, so it is
654              possible that DEF_REGULAR is not set now but will be set
655              later (it is never cleared).  In case of a weak definition,
656              DEF_REGULAR may be cleared later by a strong definition in
657              a shared library.  We account for that possibility below by
658              storing information in the relocs_copied field of the hash
659              table entry.  A similar situation occurs when creating
660              shared libraries and symbol visibility changes render the
661              symbol local.
662
663              If on the other hand, we are creating an executable, we
664              may need to keep relocations for symbols satisfied by a
665              dynamic library if we manage to avoid copy relocs for the
666              symbol.  */
667           reloc_howto_type * r = riscv_elf_rtype_to_howto (abfd, r_type);
668
669           if ((bfd_link_pic (info)
670                && (sec->flags & SEC_ALLOC) != 0
671                && ((r != NULL && ! r->pc_relative)
672                    || (h != NULL
673                        && (! info->symbolic
674                            || h->root.type == bfd_link_hash_defweak
675                            || !h->def_regular))))
676               || (!bfd_link_pic (info)
677                   && (sec->flags & SEC_ALLOC) != 0
678                   && h != NULL
679                   && (h->root.type == bfd_link_hash_defweak
680                       || !h->def_regular)))
681             {
682               struct elf_dyn_relocs *p;
683               struct elf_dyn_relocs **head;
684
685               /* When creating a shared object, we must copy these
686                  relocs into the output file.  We create a reloc
687                  section in dynobj and make room for the reloc.  */
688               if (sreloc == NULL)
689                 {
690                   sreloc = _bfd_elf_make_dynamic_reloc_section
691                     (sec, htab->elf.dynobj, RISCV_ELF_LOG_WORD_BYTES,
692                     abfd, /*rela?*/ TRUE);
693
694                   if (sreloc == NULL)
695                     return FALSE;
696                 }
697
698               /* If this is a global symbol, we count the number of
699                  relocations we need for this symbol.  */
700               if (h != NULL)
701                 head = &((struct riscv_elf_link_hash_entry *) h)->dyn_relocs;
702               else
703                 {
704                   /* Track dynamic relocs needed for local syms too.
705                      We really need local syms available to do this
706                      easily.  Oh well.  */
707
708                   asection *s;
709                   void *vpp;
710                   Elf_Internal_Sym *isym;
711
712                   isym = bfd_sym_from_r_symndx (&htab->sym_cache,
713                                                 abfd, r_symndx);
714                   if (isym == NULL)
715                     return FALSE;
716
717                   s = bfd_section_from_elf_index (abfd, isym->st_shndx);
718                   if (s == NULL)
719                     s = sec;
720
721                   vpp = &elf_section_data (s)->local_dynrel;
722                   head = (struct elf_dyn_relocs **) vpp;
723                 }
724
725               p = *head;
726               if (p == NULL || p->sec != sec)
727                 {
728                   bfd_size_type amt = sizeof *p;
729                   p = ((struct elf_dyn_relocs *)
730                        bfd_alloc (htab->elf.dynobj, amt));
731                   if (p == NULL)
732                     return FALSE;
733                   p->next = *head;
734                   *head = p;
735                   p->sec = sec;
736                   p->count = 0;
737                   p->pc_count = 0;
738                 }
739
740               p->count += 1;
741               p->pc_count += r == NULL ? 0 : r->pc_relative;
742             }
743
744           break;
745
746         case R_RISCV_GNU_VTINHERIT:
747           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
748             return FALSE;
749           break;
750
751         case R_RISCV_GNU_VTENTRY:
752           if (!bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_addend))
753             return FALSE;
754           break;
755
756         default:
757           break;
758         }
759     }
760
761   return TRUE;
762 }
763
764 static asection *
765 riscv_elf_gc_mark_hook (asection *sec,
766                         struct bfd_link_info *info,
767                         Elf_Internal_Rela *rel,
768                         struct elf_link_hash_entry *h,
769                         Elf_Internal_Sym *sym)
770 {
771   if (h != NULL)
772     switch (ELFNN_R_TYPE (rel->r_info))
773       {
774       case R_RISCV_GNU_VTINHERIT:
775       case R_RISCV_GNU_VTENTRY:
776         return NULL;
777       }
778
779   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
780 }
781
782 /* Find dynamic relocs for H that apply to read-only sections.  */
783
784 static asection *
785 readonly_dynrelocs (struct elf_link_hash_entry *h)
786 {
787   struct elf_dyn_relocs *p;
788
789   for (p = riscv_elf_hash_entry (h)->dyn_relocs; p != NULL; p = p->next)
790     {
791       asection *s = p->sec->output_section;
792
793       if (s != NULL && (s->flags & SEC_READONLY) != 0)
794         return p->sec;
795     }
796   return NULL;
797 }
798
799 /* Adjust a symbol defined by a dynamic object and referenced by a
800    regular object.  The current definition is in some section of the
801    dynamic object, but we're not including those sections.  We have to
802    change the definition to something the rest of the link can
803    understand.  */
804
805 static bfd_boolean
806 riscv_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
807                                  struct elf_link_hash_entry *h)
808 {
809   struct riscv_elf_link_hash_table *htab;
810   struct riscv_elf_link_hash_entry * eh;
811   bfd *dynobj;
812   asection *s, *srel;
813
814   htab = riscv_elf_hash_table (info);
815   BFD_ASSERT (htab != NULL);
816
817   dynobj = htab->elf.dynobj;
818
819   /* Make sure we know what is going on here.  */
820   BFD_ASSERT (dynobj != NULL
821               && (h->needs_plt
822                   || h->type == STT_GNU_IFUNC
823                   || h->is_weakalias
824                   || (h->def_dynamic
825                       && h->ref_regular
826                       && !h->def_regular)));
827
828   /* If this is a function, put it in the procedure linkage table.  We
829      will fill in the contents of the procedure linkage table later
830      (although we could actually do it here).  */
831   if (h->type == STT_FUNC || h->type == STT_GNU_IFUNC || h->needs_plt)
832     {
833       if (h->plt.refcount <= 0
834           || SYMBOL_CALLS_LOCAL (info, h)
835           || (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
836               && h->root.type == bfd_link_hash_undefweak))
837         {
838           /* This case can occur if we saw a R_RISCV_CALL_PLT reloc in an
839              input file, but the symbol was never referred to by a dynamic
840              object, or if all references were garbage collected.  In such
841              a case, we don't actually need to build a PLT entry.  */
842           h->plt.offset = (bfd_vma) -1;
843           h->needs_plt = 0;
844         }
845
846       return TRUE;
847     }
848   else
849     h->plt.offset = (bfd_vma) -1;
850
851   /* If this is a weak symbol, and there is a real definition, the
852      processor independent code will have arranged for us to see the
853      real definition first, and we can just use the same value.  */
854   if (h->is_weakalias)
855     {
856       struct elf_link_hash_entry *def = weakdef (h);
857       BFD_ASSERT (def->root.type == bfd_link_hash_defined);
858       h->root.u.def.section = def->root.u.def.section;
859       h->root.u.def.value = def->root.u.def.value;
860       return TRUE;
861     }
862
863   /* This is a reference to a symbol defined by a dynamic object which
864      is not a function.  */
865
866   /* If we are creating a shared library, we must presume that the
867      only references to the symbol are via the global offset table.
868      For such cases we need not do anything here; the relocations will
869      be handled correctly by relocate_section.  */
870   if (bfd_link_pic (info))
871     return TRUE;
872
873   /* If there are no references to this symbol that do not use the
874      GOT, we don't need to generate a copy reloc.  */
875   if (!h->non_got_ref)
876     return TRUE;
877
878   /* If -z nocopyreloc was given, we won't generate them either.  */
879   if (info->nocopyreloc)
880     {
881       h->non_got_ref = 0;
882       return TRUE;
883     }
884
885   /* If we don't find any dynamic relocs in read-only sections, then
886      we'll be keeping the dynamic relocs and avoiding the copy reloc.  */
887   if (!readonly_dynrelocs (h))
888     {
889       h->non_got_ref = 0;
890       return TRUE;
891     }
892
893   /* We must allocate the symbol in our .dynbss section, which will
894      become part of the .bss section of the executable.  There will be
895      an entry for this symbol in the .dynsym section.  The dynamic
896      object will contain position independent code, so all references
897      from the dynamic object to this symbol will go through the global
898      offset table.  The dynamic linker will use the .dynsym entry to
899      determine the address it must put in the global offset table, so
900      both the dynamic object and the regular object will refer to the
901      same memory location for the variable.  */
902
903   /* We must generate a R_RISCV_COPY reloc to tell the dynamic linker
904      to copy the initial value out of the dynamic object and into the
905      runtime process image.  We need to remember the offset into the
906      .rel.bss section we are going to use.  */
907   eh = (struct riscv_elf_link_hash_entry *) h;
908   if (eh->tls_type & ~GOT_NORMAL)
909     {
910       s = htab->sdyntdata;
911       srel = htab->elf.srelbss;
912     }
913   else if ((h->root.u.def.section->flags & SEC_READONLY) != 0)
914     {
915       s = htab->elf.sdynrelro;
916       srel = htab->elf.sreldynrelro;
917     }
918   else
919     {
920       s = htab->elf.sdynbss;
921       srel = htab->elf.srelbss;
922     }
923   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0 && h->size != 0)
924     {
925       srel->size += sizeof (ElfNN_External_Rela);
926       h->needs_copy = 1;
927     }
928
929   return _bfd_elf_adjust_dynamic_copy (info, h, s);
930 }
931
932 /* Allocate space in .plt, .got and associated reloc sections for
933    dynamic relocs.  */
934
935 static bfd_boolean
936 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
937 {
938   struct bfd_link_info *info;
939   struct riscv_elf_link_hash_table *htab;
940   struct riscv_elf_link_hash_entry *eh;
941   struct elf_dyn_relocs *p;
942
943   if (h->root.type == bfd_link_hash_indirect)
944     return TRUE;
945
946   info = (struct bfd_link_info *) inf;
947   htab = riscv_elf_hash_table (info);
948   BFD_ASSERT (htab != NULL);
949
950   if (htab->elf.dynamic_sections_created
951       && h->plt.refcount > 0)
952     {
953       /* Make sure this symbol is output as a dynamic symbol.
954          Undefined weak syms won't yet be marked as dynamic.  */
955       if (h->dynindx == -1
956           && !h->forced_local)
957         {
958           if (! bfd_elf_link_record_dynamic_symbol (info, h))
959             return FALSE;
960         }
961
962       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (1, bfd_link_pic (info), h))
963         {
964           asection *s = htab->elf.splt;
965
966           if (s->size == 0)
967             s->size = PLT_HEADER_SIZE;
968
969           h->plt.offset = s->size;
970
971           /* Make room for this entry.  */
972           s->size += PLT_ENTRY_SIZE;
973
974           /* We also need to make an entry in the .got.plt section.  */
975           htab->elf.sgotplt->size += GOT_ENTRY_SIZE;
976
977           /* We also need to make an entry in the .rela.plt section.  */
978           htab->elf.srelplt->size += sizeof (ElfNN_External_Rela);
979
980           /* If this symbol is not defined in a regular file, and we are
981              not generating a shared library, then set the symbol to this
982              location in the .plt.  This is required to make function
983              pointers compare as equal between the normal executable and
984              the shared library.  */
985           if (! bfd_link_pic (info)
986               && !h->def_regular)
987             {
988               h->root.u.def.section = s;
989               h->root.u.def.value = h->plt.offset;
990             }
991         }
992       else
993         {
994           h->plt.offset = (bfd_vma) -1;
995           h->needs_plt = 0;
996         }
997     }
998   else
999     {
1000       h->plt.offset = (bfd_vma) -1;
1001       h->needs_plt = 0;
1002     }
1003
1004   if (h->got.refcount > 0)
1005     {
1006       asection *s;
1007       bfd_boolean dyn;
1008       int tls_type = riscv_elf_hash_entry (h)->tls_type;
1009
1010       /* Make sure this symbol is output as a dynamic symbol.
1011          Undefined weak syms won't yet be marked as dynamic.  */
1012       if (h->dynindx == -1
1013           && !h->forced_local)
1014         {
1015           if (! bfd_elf_link_record_dynamic_symbol (info, h))
1016             return FALSE;
1017         }
1018
1019       s = htab->elf.sgot;
1020       h->got.offset = s->size;
1021       dyn = htab->elf.dynamic_sections_created;
1022       if (tls_type & (GOT_TLS_GD | GOT_TLS_IE))
1023         {
1024           /* TLS_GD needs two dynamic relocs and two GOT slots.  */
1025           if (tls_type & GOT_TLS_GD)
1026             {
1027               s->size += 2 * RISCV_ELF_WORD_BYTES;
1028               htab->elf.srelgot->size += 2 * sizeof (ElfNN_External_Rela);
1029             }
1030
1031           /* TLS_IE needs one dynamic reloc and one GOT slot.  */
1032           if (tls_type & GOT_TLS_IE)
1033             {
1034               s->size += RISCV_ELF_WORD_BYTES;
1035               htab->elf.srelgot->size += sizeof (ElfNN_External_Rela);
1036             }
1037         }
1038       else
1039         {
1040           s->size += RISCV_ELF_WORD_BYTES;
1041           if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, bfd_link_pic (info), h)
1042               && ! UNDEFWEAK_NO_DYNAMIC_RELOC (info, h))
1043             htab->elf.srelgot->size += sizeof (ElfNN_External_Rela);
1044         }
1045     }
1046   else
1047     h->got.offset = (bfd_vma) -1;
1048
1049   eh = (struct riscv_elf_link_hash_entry *) h;
1050   if (eh->dyn_relocs == NULL)
1051     return TRUE;
1052
1053   /* In the shared -Bsymbolic case, discard space allocated for
1054      dynamic pc-relative relocs against symbols which turn out to be
1055      defined in regular objects.  For the normal shared case, discard
1056      space for pc-relative relocs that have become local due to symbol
1057      visibility changes.  */
1058
1059   if (bfd_link_pic (info))
1060     {
1061       if (SYMBOL_CALLS_LOCAL (info, h))
1062         {
1063           struct elf_dyn_relocs **pp;
1064
1065           for (pp = &eh->dyn_relocs; (p = *pp) != NULL; )
1066             {
1067               p->count -= p->pc_count;
1068               p->pc_count = 0;
1069               if (p->count == 0)
1070                 *pp = p->next;
1071               else
1072                 pp = &p->next;
1073             }
1074         }
1075
1076       /* Also discard relocs on undefined weak syms with non-default
1077          visibility.  */
1078       if (eh->dyn_relocs != NULL
1079           && h->root.type == bfd_link_hash_undefweak)
1080         {
1081           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1082               || UNDEFWEAK_NO_DYNAMIC_RELOC (info, h))
1083             eh->dyn_relocs = NULL;
1084
1085           /* Make sure undefined weak symbols are output as a dynamic
1086              symbol in PIEs.  */
1087           else if (h->dynindx == -1
1088                    && !h->forced_local)
1089             {
1090               if (! bfd_elf_link_record_dynamic_symbol (info, h))
1091                 return FALSE;
1092             }
1093         }
1094     }
1095   else
1096     {
1097       /* For the non-shared case, discard space for relocs against
1098          symbols which turn out to need copy relocs or are not
1099          dynamic.  */
1100
1101       if (!h->non_got_ref
1102           && ((h->def_dynamic
1103                && !h->def_regular)
1104               || (htab->elf.dynamic_sections_created
1105                   && (h->root.type == bfd_link_hash_undefweak
1106                       || h->root.type == bfd_link_hash_undefined))))
1107         {
1108           /* Make sure this symbol is output as a dynamic symbol.
1109              Undefined weak syms won't yet be marked as dynamic.  */
1110           if (h->dynindx == -1
1111               && !h->forced_local)
1112             {
1113               if (! bfd_elf_link_record_dynamic_symbol (info, h))
1114                 return FALSE;
1115             }
1116
1117           /* If that succeeded, we know we'll be keeping all the
1118              relocs.  */
1119           if (h->dynindx != -1)
1120             goto keep;
1121         }
1122
1123       eh->dyn_relocs = NULL;
1124
1125     keep: ;
1126     }
1127
1128   /* Finally, allocate space.  */
1129   for (p = eh->dyn_relocs; p != NULL; p = p->next)
1130     {
1131       asection *sreloc = elf_section_data (p->sec)->sreloc;
1132       sreloc->size += p->count * sizeof (ElfNN_External_Rela);
1133     }
1134
1135   return TRUE;
1136 }
1137
1138 /* Set DF_TEXTREL if we find any dynamic relocs that apply to
1139    read-only sections.  */
1140
1141 static bfd_boolean
1142 maybe_set_textrel (struct elf_link_hash_entry *h, void *info_p)
1143 {
1144   asection *sec;
1145
1146   if (h->root.type == bfd_link_hash_indirect)
1147     return TRUE;
1148
1149   sec = readonly_dynrelocs (h);
1150   if (sec != NULL)
1151     {
1152       struct bfd_link_info *info = (struct bfd_link_info *) info_p;
1153
1154       info->flags |= DF_TEXTREL;
1155       info->callbacks->minfo
1156         (_("%pB: dynamic relocation against `%pT' in read-only section `%pA'\n"),
1157          sec->owner, h->root.root.string, sec);
1158
1159       /* Not an error, just cut short the traversal.  */
1160       return FALSE;
1161     }
1162   return TRUE;
1163 }
1164
1165 static bfd_boolean
1166 riscv_elf_size_dynamic_sections (bfd *output_bfd, struct bfd_link_info *info)
1167 {
1168   struct riscv_elf_link_hash_table *htab;
1169   bfd *dynobj;
1170   asection *s;
1171   bfd *ibfd;
1172
1173   htab = riscv_elf_hash_table (info);
1174   BFD_ASSERT (htab != NULL);
1175   dynobj = htab->elf.dynobj;
1176   BFD_ASSERT (dynobj != NULL);
1177
1178   if (elf_hash_table (info)->dynamic_sections_created)
1179     {
1180       /* Set the contents of the .interp section to the interpreter.  */
1181       if (bfd_link_executable (info) && !info->nointerp)
1182         {
1183           s = bfd_get_linker_section (dynobj, ".interp");
1184           BFD_ASSERT (s != NULL);
1185           s->size = strlen (ELFNN_DYNAMIC_INTERPRETER) + 1;
1186           s->contents = (unsigned char *) ELFNN_DYNAMIC_INTERPRETER;
1187         }
1188     }
1189
1190   /* Set up .got offsets for local syms, and space for local dynamic
1191      relocs.  */
1192   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
1193     {
1194       bfd_signed_vma *local_got;
1195       bfd_signed_vma *end_local_got;
1196       char *local_tls_type;
1197       bfd_size_type locsymcount;
1198       Elf_Internal_Shdr *symtab_hdr;
1199       asection *srel;
1200
1201       if (! is_riscv_elf (ibfd))
1202         continue;
1203
1204       for (s = ibfd->sections; s != NULL; s = s->next)
1205         {
1206           struct elf_dyn_relocs *p;
1207
1208           for (p = elf_section_data (s)->local_dynrel; p != NULL; p = p->next)
1209             {
1210               if (!bfd_is_abs_section (p->sec)
1211                   && bfd_is_abs_section (p->sec->output_section))
1212                 {
1213                   /* Input section has been discarded, either because
1214                      it is a copy of a linkonce section or due to
1215                      linker script /DISCARD/, so we'll be discarding
1216                      the relocs too.  */
1217                 }
1218               else if (p->count != 0)
1219                 {
1220                   srel = elf_section_data (p->sec)->sreloc;
1221                   srel->size += p->count * sizeof (ElfNN_External_Rela);
1222                   if ((p->sec->output_section->flags & SEC_READONLY) != 0)
1223                     info->flags |= DF_TEXTREL;
1224                 }
1225             }
1226         }
1227
1228       local_got = elf_local_got_refcounts (ibfd);
1229       if (!local_got)
1230         continue;
1231
1232       symtab_hdr = &elf_symtab_hdr (ibfd);
1233       locsymcount = symtab_hdr->sh_info;
1234       end_local_got = local_got + locsymcount;
1235       local_tls_type = _bfd_riscv_elf_local_got_tls_type (ibfd);
1236       s = htab->elf.sgot;
1237       srel = htab->elf.srelgot;
1238       for (; local_got < end_local_got; ++local_got, ++local_tls_type)
1239         {
1240           if (*local_got > 0)
1241             {
1242               *local_got = s->size;
1243               s->size += RISCV_ELF_WORD_BYTES;
1244               if (*local_tls_type & GOT_TLS_GD)
1245                 s->size += RISCV_ELF_WORD_BYTES;
1246               if (bfd_link_pic (info)
1247                   || (*local_tls_type & (GOT_TLS_GD | GOT_TLS_IE)))
1248                 srel->size += sizeof (ElfNN_External_Rela);
1249             }
1250           else
1251             *local_got = (bfd_vma) -1;
1252         }
1253     }
1254
1255   /* Allocate global sym .plt and .got entries, and space for global
1256      sym dynamic relocs.  */
1257   elf_link_hash_traverse (&htab->elf, allocate_dynrelocs, info);
1258
1259   if (htab->elf.sgotplt)
1260     {
1261       struct elf_link_hash_entry *got;
1262       got = elf_link_hash_lookup (elf_hash_table (info),
1263                                   "_GLOBAL_OFFSET_TABLE_",
1264                                   FALSE, FALSE, FALSE);
1265
1266       /* Don't allocate .got.plt section if there are no GOT nor PLT
1267          entries and there is no refeence to _GLOBAL_OFFSET_TABLE_.  */
1268       if ((got == NULL
1269            || !got->ref_regular_nonweak)
1270           && (htab->elf.sgotplt->size == GOTPLT_HEADER_SIZE)
1271           && (htab->elf.splt == NULL
1272               || htab->elf.splt->size == 0)
1273           && (htab->elf.sgot == NULL
1274               || (htab->elf.sgot->size
1275                   == get_elf_backend_data (output_bfd)->got_header_size)))
1276         htab->elf.sgotplt->size = 0;
1277     }
1278
1279   /* The check_relocs and adjust_dynamic_symbol entry points have
1280      determined the sizes of the various dynamic sections.  Allocate
1281      memory for them.  */
1282   for (s = dynobj->sections; s != NULL; s = s->next)
1283     {
1284       if ((s->flags & SEC_LINKER_CREATED) == 0)
1285         continue;
1286
1287       if (s == htab->elf.splt
1288           || s == htab->elf.sgot
1289           || s == htab->elf.sgotplt
1290           || s == htab->elf.sdynbss
1291           || s == htab->elf.sdynrelro
1292           || s == htab->sdyntdata)
1293         {
1294           /* Strip this section if we don't need it; see the
1295              comment below.  */
1296         }
1297       else if (strncmp (s->name, ".rela", 5) == 0)
1298         {
1299           if (s->size != 0)
1300             {
1301               /* We use the reloc_count field as a counter if we need
1302                  to copy relocs into the output file.  */
1303               s->reloc_count = 0;
1304             }
1305         }
1306       else
1307         {
1308           /* It's not one of our sections.  */
1309           continue;
1310         }
1311
1312       if (s->size == 0)
1313         {
1314           /* If we don't need this section, strip it from the
1315              output file.  This is mostly to handle .rela.bss and
1316              .rela.plt.  We must create both sections in
1317              create_dynamic_sections, because they must be created
1318              before the linker maps input sections to output
1319              sections.  The linker does that before
1320              adjust_dynamic_symbol is called, and it is that
1321              function which decides whether anything needs to go
1322              into these sections.  */
1323           s->flags |= SEC_EXCLUDE;
1324           continue;
1325         }
1326
1327       if ((s->flags & SEC_HAS_CONTENTS) == 0)
1328         continue;
1329
1330       /* Allocate memory for the section contents.  Zero the memory
1331          for the benefit of .rela.plt, which has 4 unused entries
1332          at the beginning, and we don't want garbage.  */
1333       s->contents = (bfd_byte *) bfd_zalloc (dynobj, s->size);
1334       if (s->contents == NULL)
1335         return FALSE;
1336     }
1337
1338   if (elf_hash_table (info)->dynamic_sections_created)
1339     {
1340       /* Add some entries to the .dynamic section.  We fill in the
1341          values later, in riscv_elf_finish_dynamic_sections, but we
1342          must add the entries now so that we get the correct size for
1343          the .dynamic section.  The DT_DEBUG entry is filled in by the
1344          dynamic linker and used by the debugger.  */
1345 #define add_dynamic_entry(TAG, VAL) \
1346   _bfd_elf_add_dynamic_entry (info, TAG, VAL)
1347
1348       if (bfd_link_executable (info))
1349         {
1350           if (!add_dynamic_entry (DT_DEBUG, 0))
1351             return FALSE;
1352         }
1353
1354       if (htab->elf.srelplt->size != 0)
1355         {
1356           if (!add_dynamic_entry (DT_PLTGOT, 0)
1357               || !add_dynamic_entry (DT_PLTRELSZ, 0)
1358               || !add_dynamic_entry (DT_PLTREL, DT_RELA)
1359               || !add_dynamic_entry (DT_JMPREL, 0))
1360             return FALSE;
1361         }
1362
1363       if (!add_dynamic_entry (DT_RELA, 0)
1364           || !add_dynamic_entry (DT_RELASZ, 0)
1365           || !add_dynamic_entry (DT_RELAENT, sizeof (ElfNN_External_Rela)))
1366         return FALSE;
1367
1368       /* If any dynamic relocs apply to a read-only section,
1369          then we need a DT_TEXTREL entry.  */
1370       if ((info->flags & DF_TEXTREL) == 0)
1371         elf_link_hash_traverse (&htab->elf, maybe_set_textrel, info);
1372
1373       if (info->flags & DF_TEXTREL)
1374         {
1375           if (!add_dynamic_entry (DT_TEXTREL, 0))
1376             return FALSE;
1377         }
1378     }
1379 #undef add_dynamic_entry
1380
1381   return TRUE;
1382 }
1383
1384 #define TP_OFFSET 0
1385 #define DTP_OFFSET 0x800
1386
1387 /* Return the relocation value for a TLS dtp-relative reloc.  */
1388
1389 static bfd_vma
1390 dtpoff (struct bfd_link_info *info, bfd_vma address)
1391 {
1392   /* If tls_sec is NULL, we should have signalled an error already.  */
1393   if (elf_hash_table (info)->tls_sec == NULL)
1394     return 0;
1395   return address - elf_hash_table (info)->tls_sec->vma - DTP_OFFSET;
1396 }
1397
1398 /* Return the relocation value for a static TLS tp-relative relocation.  */
1399
1400 static bfd_vma
1401 tpoff (struct bfd_link_info *info, bfd_vma address)
1402 {
1403   /* If tls_sec is NULL, we should have signalled an error already.  */
1404   if (elf_hash_table (info)->tls_sec == NULL)
1405     return 0;
1406   return address - elf_hash_table (info)->tls_sec->vma - TP_OFFSET;
1407 }
1408
1409 /* Return the global pointer's value, or 0 if it is not in use.  */
1410
1411 static bfd_vma
1412 riscv_global_pointer_value (struct bfd_link_info *info)
1413 {
1414   struct bfd_link_hash_entry *h;
1415
1416   h = bfd_link_hash_lookup (info->hash, RISCV_GP_SYMBOL, FALSE, FALSE, TRUE);
1417   if (h == NULL || h->type != bfd_link_hash_defined)
1418     return 0;
1419
1420   return h->u.def.value + sec_addr (h->u.def.section);
1421 }
1422
1423 /* Emplace a static relocation.  */
1424
1425 static bfd_reloc_status_type
1426 perform_relocation (const reloc_howto_type *howto,
1427                     const Elf_Internal_Rela *rel,
1428                     bfd_vma value,
1429                     asection *input_section,
1430                     bfd *input_bfd,
1431                     bfd_byte *contents)
1432 {
1433   if (howto->pc_relative)
1434     value -= sec_addr (input_section) + rel->r_offset;
1435   value += rel->r_addend;
1436
1437   switch (ELFNN_R_TYPE (rel->r_info))
1438     {
1439     case R_RISCV_HI20:
1440     case R_RISCV_TPREL_HI20:
1441     case R_RISCV_PCREL_HI20:
1442     case R_RISCV_GOT_HI20:
1443     case R_RISCV_TLS_GOT_HI20:
1444     case R_RISCV_TLS_GD_HI20:
1445       if (ARCH_SIZE > 32 && !VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (value)))
1446         return bfd_reloc_overflow;
1447       value = ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value));
1448       break;
1449
1450     case R_RISCV_LO12_I:
1451     case R_RISCV_GPREL_I:
1452     case R_RISCV_TPREL_LO12_I:
1453     case R_RISCV_TPREL_I:
1454     case R_RISCV_PCREL_LO12_I:
1455       value = ENCODE_ITYPE_IMM (value);
1456       break;
1457
1458     case R_RISCV_LO12_S:
1459     case R_RISCV_GPREL_S:
1460     case R_RISCV_TPREL_LO12_S:
1461     case R_RISCV_TPREL_S:
1462     case R_RISCV_PCREL_LO12_S:
1463       value = ENCODE_STYPE_IMM (value);
1464       break;
1465
1466     case R_RISCV_CALL:
1467     case R_RISCV_CALL_PLT:
1468       if (ARCH_SIZE > 32 && !VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (value)))
1469         return bfd_reloc_overflow;
1470       value = ENCODE_UTYPE_IMM (RISCV_CONST_HIGH_PART (value))
1471               | (ENCODE_ITYPE_IMM (value) << 32);
1472       break;
1473
1474     case R_RISCV_JAL:
1475       if (!VALID_UJTYPE_IMM (value))
1476         return bfd_reloc_overflow;
1477       value = ENCODE_UJTYPE_IMM (value);
1478       break;
1479
1480     case R_RISCV_BRANCH:
1481       if (!VALID_SBTYPE_IMM (value))
1482         return bfd_reloc_overflow;
1483       value = ENCODE_SBTYPE_IMM (value);
1484       break;
1485
1486     case R_RISCV_RVC_BRANCH:
1487       if (!VALID_RVC_B_IMM (value))
1488         return bfd_reloc_overflow;
1489       value = ENCODE_RVC_B_IMM (value);
1490       break;
1491
1492     case R_RISCV_RVC_JUMP:
1493       if (!VALID_RVC_J_IMM (value))
1494         return bfd_reloc_overflow;
1495       value = ENCODE_RVC_J_IMM (value);
1496       break;
1497
1498     case R_RISCV_RVC_LUI:
1499       if (RISCV_CONST_HIGH_PART (value) == 0)
1500         {
1501           /* Linker relaxation can convert an address equal to or greater than
1502              0x800 to slightly below 0x800.  C.LUI does not accept zero as a
1503              valid immediate.  We can fix this by converting it to a C.LI.  */
1504           bfd_vma insn = bfd_get (howto->bitsize, input_bfd,
1505                                   contents + rel->r_offset);
1506           insn = (insn & ~MATCH_C_LUI) | MATCH_C_LI;
1507           bfd_put (howto->bitsize, input_bfd, insn, contents + rel->r_offset);
1508           value = ENCODE_RVC_IMM (0);
1509         }
1510       else if (!VALID_RVC_LUI_IMM (RISCV_CONST_HIGH_PART (value)))
1511         return bfd_reloc_overflow;
1512       else
1513         value = ENCODE_RVC_LUI_IMM (RISCV_CONST_HIGH_PART (value));
1514       break;
1515
1516     case R_RISCV_32:
1517     case R_RISCV_64:
1518     case R_RISCV_ADD8:
1519     case R_RISCV_ADD16:
1520     case R_RISCV_ADD32:
1521     case R_RISCV_ADD64:
1522     case R_RISCV_SUB6:
1523     case R_RISCV_SUB8:
1524     case R_RISCV_SUB16:
1525     case R_RISCV_SUB32:
1526     case R_RISCV_SUB64:
1527     case R_RISCV_SET6:
1528     case R_RISCV_SET8:
1529     case R_RISCV_SET16:
1530     case R_RISCV_SET32:
1531     case R_RISCV_32_PCREL:
1532     case R_RISCV_TLS_DTPREL32:
1533     case R_RISCV_TLS_DTPREL64:
1534       break;
1535
1536     case R_RISCV_DELETE:
1537       return bfd_reloc_ok;
1538
1539     default:
1540       return bfd_reloc_notsupported;
1541     }
1542
1543   bfd_vma word = bfd_get (howto->bitsize, input_bfd, contents + rel->r_offset);
1544   word = (word & ~howto->dst_mask) | (value & howto->dst_mask);
1545   bfd_put (howto->bitsize, input_bfd, word, contents + rel->r_offset);
1546
1547   return bfd_reloc_ok;
1548 }
1549
1550 /* Remember all PC-relative high-part relocs we've encountered to help us
1551    later resolve the corresponding low-part relocs.  */
1552
1553 typedef struct
1554 {
1555   bfd_vma address;
1556   bfd_vma value;
1557 } riscv_pcrel_hi_reloc;
1558
1559 typedef struct riscv_pcrel_lo_reloc
1560 {
1561   asection *                     input_section;
1562   struct bfd_link_info *         info;
1563   reloc_howto_type *             howto;
1564   const Elf_Internal_Rela *      reloc;
1565   bfd_vma                        addr;
1566   const char *                   name;
1567   bfd_byte *                     contents;
1568   struct riscv_pcrel_lo_reloc *  next;
1569 } riscv_pcrel_lo_reloc;
1570
1571 typedef struct
1572 {
1573   htab_t hi_relocs;
1574   riscv_pcrel_lo_reloc *lo_relocs;
1575 } riscv_pcrel_relocs;
1576
1577 static hashval_t
1578 riscv_pcrel_reloc_hash (const void *entry)
1579 {
1580   const riscv_pcrel_hi_reloc *e = entry;
1581   return (hashval_t)(e->address >> 2);
1582 }
1583
1584 static bfd_boolean
1585 riscv_pcrel_reloc_eq (const void *entry1, const void *entry2)
1586 {
1587   const riscv_pcrel_hi_reloc *e1 = entry1, *e2 = entry2;
1588   return e1->address == e2->address;
1589 }
1590
1591 static bfd_boolean
1592 riscv_init_pcrel_relocs (riscv_pcrel_relocs *p)
1593 {
1594
1595   p->lo_relocs = NULL;
1596   p->hi_relocs = htab_create (1024, riscv_pcrel_reloc_hash,
1597                               riscv_pcrel_reloc_eq, free);
1598   return p->hi_relocs != NULL;
1599 }
1600
1601 static void
1602 riscv_free_pcrel_relocs (riscv_pcrel_relocs *p)
1603 {
1604   riscv_pcrel_lo_reloc *cur = p->lo_relocs;
1605
1606   while (cur != NULL)
1607     {
1608       riscv_pcrel_lo_reloc *next = cur->next;
1609       free (cur);
1610       cur = next;
1611     }
1612
1613   htab_delete (p->hi_relocs);
1614 }
1615
1616 static bfd_boolean
1617 riscv_zero_pcrel_hi_reloc (Elf_Internal_Rela *rel,
1618                            struct bfd_link_info *info,
1619                            bfd_vma pc,
1620                            bfd_vma addr,
1621                            bfd_byte *contents,
1622                            const reloc_howto_type *howto,
1623                            bfd *input_bfd)
1624 {
1625   /* We may need to reference low addreses in PC-relative modes even when the
1626    * PC is far away from these addresses.  For example, undefweak references
1627    * need to produce the address 0 when linked.  As 0 is far from the arbitrary
1628    * addresses that we can link PC-relative programs at, the linker can't
1629    * actually relocate references to those symbols.  In order to allow these
1630    * programs to work we simply convert the PC-relative auipc sequences to
1631    * 0-relative lui sequences.  */
1632   if (bfd_link_pic (info))
1633     return FALSE;
1634
1635   /* If it's possible to reference the symbol using auipc we do so, as that's
1636    * more in the spirit of the PC-relative relocations we're processing.  */
1637   bfd_vma offset = addr - pc;
1638   if (ARCH_SIZE == 32 || VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (offset)))
1639     return FALSE;
1640
1641   /* If it's impossible to reference this with a LUI-based offset then don't
1642    * bother to convert it at all so users still see the PC-relative relocation
1643    * in the truncation message.  */
1644   if (ARCH_SIZE > 32 && !VALID_UTYPE_IMM (RISCV_CONST_HIGH_PART (addr)))
1645     return FALSE;
1646
1647   rel->r_info = ELFNN_R_INFO(addr, R_RISCV_HI20);
1648
1649   bfd_vma insn = bfd_get(howto->bitsize, input_bfd, contents + rel->r_offset);
1650   insn = (insn & ~MASK_AUIPC) | MATCH_LUI;
1651   bfd_put(howto->bitsize, input_bfd, insn, contents + rel->r_offset);
1652   return TRUE;
1653 }
1654
1655 static bfd_boolean
1656 riscv_record_pcrel_hi_reloc (riscv_pcrel_relocs *p, bfd_vma addr,
1657                              bfd_vma value, bfd_boolean absolute)
1658 {
1659   bfd_vma offset = absolute ? value : value - addr;
1660   riscv_pcrel_hi_reloc entry = {addr, offset};
1661   riscv_pcrel_hi_reloc **slot =
1662     (riscv_pcrel_hi_reloc **) htab_find_slot (p->hi_relocs, &entry, INSERT);
1663
1664   BFD_ASSERT (*slot == NULL);
1665   *slot = (riscv_pcrel_hi_reloc *) bfd_malloc (sizeof (riscv_pcrel_hi_reloc));
1666   if (*slot == NULL)
1667     return FALSE;
1668   **slot = entry;
1669   return TRUE;
1670 }
1671
1672 static bfd_boolean
1673 riscv_record_pcrel_lo_reloc (riscv_pcrel_relocs *p,
1674                              asection *input_section,
1675                              struct bfd_link_info *info,
1676                              reloc_howto_type *howto,
1677                              const Elf_Internal_Rela *reloc,
1678                              bfd_vma addr,
1679                              const char *name,
1680                              bfd_byte *contents)
1681 {
1682   riscv_pcrel_lo_reloc *entry;
1683   entry = (riscv_pcrel_lo_reloc *) bfd_malloc (sizeof (riscv_pcrel_lo_reloc));
1684   if (entry == NULL)
1685     return FALSE;
1686   *entry = (riscv_pcrel_lo_reloc) {input_section, info, howto, reloc, addr,
1687                                    name, contents, p->lo_relocs};
1688   p->lo_relocs = entry;
1689   return TRUE;
1690 }
1691
1692 static bfd_boolean
1693 riscv_resolve_pcrel_lo_relocs (riscv_pcrel_relocs *p)
1694 {
1695   riscv_pcrel_lo_reloc *r;
1696
1697   for (r = p->lo_relocs; r != NULL; r = r->next)
1698     {
1699       bfd *input_bfd = r->input_section->owner;
1700
1701       riscv_pcrel_hi_reloc search = {r->addr, 0};
1702       riscv_pcrel_hi_reloc *entry = htab_find (p->hi_relocs, &search);
1703       if (entry == NULL
1704           /* Check for overflow into bit 11 when adding reloc addend.  */
1705           || (! (entry->value & 0x800)
1706               && ((entry->value + r->reloc->r_addend) & 0x800)))
1707         {
1708           char *string = (entry == NULL
1709                           ? "%pcrel_lo missing matching %pcrel_hi"
1710                           : "%pcrel_lo overflow with an addend");
1711           (*r->info->callbacks->reloc_dangerous)
1712             (r->info, string, input_bfd, r->input_section, r->reloc->r_offset);
1713           return TRUE;
1714         }
1715
1716       perform_relocation (r->howto, r->reloc, entry->value, r->input_section,
1717                           input_bfd, r->contents);
1718     }
1719
1720   return TRUE;
1721 }
1722
1723 /* Relocate a RISC-V ELF section.
1724
1725    The RELOCATE_SECTION function is called by the new ELF backend linker
1726    to handle the relocations for a section.
1727
1728    The relocs are always passed as Rela structures.
1729
1730    This function is responsible for adjusting the section contents as
1731    necessary, and (if generating a relocatable output file) adjusting
1732    the reloc addend as necessary.
1733
1734    This function does not have to worry about setting the reloc
1735    address or the reloc symbol index.
1736
1737    LOCAL_SYMS is a pointer to the swapped in local symbols.
1738
1739    LOCAL_SECTIONS is an array giving the section in the input file
1740    corresponding to the st_shndx field of each local symbol.
1741
1742    The global hash table entry for the global symbols can be found
1743    via elf_sym_hashes (input_bfd).
1744
1745    When generating relocatable output, this function must handle
1746    STB_LOCAL/STT_SECTION symbols specially.  The output symbol is
1747    going to be the section symbol corresponding to the output
1748    section, which means that the addend must be adjusted
1749    accordingly.  */
1750
1751 static bfd_boolean
1752 riscv_elf_relocate_section (bfd *output_bfd,
1753                             struct bfd_link_info *info,
1754                             bfd *input_bfd,
1755                             asection *input_section,
1756                             bfd_byte *contents,
1757                             Elf_Internal_Rela *relocs,
1758                             Elf_Internal_Sym *local_syms,
1759                             asection **local_sections)
1760 {
1761   Elf_Internal_Rela *rel;
1762   Elf_Internal_Rela *relend;
1763   riscv_pcrel_relocs pcrel_relocs;
1764   bfd_boolean ret = FALSE;
1765   asection *sreloc = elf_section_data (input_section)->sreloc;
1766   struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
1767   Elf_Internal_Shdr *symtab_hdr = &elf_symtab_hdr (input_bfd);
1768   struct elf_link_hash_entry **sym_hashes = elf_sym_hashes (input_bfd);
1769   bfd_vma *local_got_offsets = elf_local_got_offsets (input_bfd);
1770   bfd_boolean absolute;
1771
1772   if (!riscv_init_pcrel_relocs (&pcrel_relocs))
1773     return FALSE;
1774
1775   relend = relocs + input_section->reloc_count;
1776   for (rel = relocs; rel < relend; rel++)
1777     {
1778       unsigned long r_symndx;
1779       struct elf_link_hash_entry *h;
1780       Elf_Internal_Sym *sym;
1781       asection *sec;
1782       bfd_vma relocation;
1783       bfd_reloc_status_type r = bfd_reloc_ok;
1784       const char *name;
1785       bfd_vma off, ie_off;
1786       bfd_boolean unresolved_reloc, is_ie = FALSE;
1787       bfd_vma pc = sec_addr (input_section) + rel->r_offset;
1788       int r_type = ELFNN_R_TYPE (rel->r_info), tls_type;
1789       reloc_howto_type *howto = riscv_elf_rtype_to_howto (input_bfd, r_type);
1790       const char *msg = NULL;
1791       bfd_boolean resolved_to_zero;
1792
1793       if (howto == NULL
1794           || r_type == R_RISCV_GNU_VTINHERIT || r_type == R_RISCV_GNU_VTENTRY)
1795         continue;
1796
1797       /* This is a final link.  */
1798       r_symndx = ELFNN_R_SYM (rel->r_info);
1799       h = NULL;
1800       sym = NULL;
1801       sec = NULL;
1802       unresolved_reloc = FALSE;
1803       if (r_symndx < symtab_hdr->sh_info)
1804         {
1805           sym = local_syms + r_symndx;
1806           sec = local_sections[r_symndx];
1807           relocation = _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
1808         }
1809       else
1810         {
1811           bfd_boolean warned, ignored;
1812
1813           RELOC_FOR_GLOBAL_SYMBOL (info, input_bfd, input_section, rel,
1814                                    r_symndx, symtab_hdr, sym_hashes,
1815                                    h, sec, relocation,
1816                                    unresolved_reloc, warned, ignored);
1817           if (warned)
1818             {
1819               /* To avoid generating warning messages about truncated
1820                  relocations, set the relocation's address to be the same as
1821                  the start of this section.  */
1822               if (input_section->output_section != NULL)
1823                 relocation = input_section->output_section->vma;
1824               else
1825                 relocation = 0;
1826             }
1827         }
1828
1829       if (sec != NULL && discarded_section (sec))
1830         RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
1831                                          rel, 1, relend, howto, 0, contents);
1832
1833       if (bfd_link_relocatable (info))
1834         continue;
1835
1836       if (h != NULL)
1837         name = h->root.root.string;
1838       else
1839         {
1840           name = (bfd_elf_string_from_elf_section
1841                   (input_bfd, symtab_hdr->sh_link, sym->st_name));
1842           if (name == NULL || *name == '\0')
1843             name = bfd_section_name (input_bfd, sec);
1844         }
1845
1846       resolved_to_zero = (h != NULL
1847                           && UNDEFWEAK_NO_DYNAMIC_RELOC (info, h));
1848
1849       switch (r_type)
1850         {
1851         case R_RISCV_NONE:
1852         case R_RISCV_RELAX:
1853         case R_RISCV_TPREL_ADD:
1854         case R_RISCV_COPY:
1855         case R_RISCV_JUMP_SLOT:
1856         case R_RISCV_RELATIVE:
1857           /* These require nothing of us at all.  */
1858           continue;
1859
1860         case R_RISCV_HI20:
1861         case R_RISCV_BRANCH:
1862         case R_RISCV_RVC_BRANCH:
1863         case R_RISCV_RVC_LUI:
1864         case R_RISCV_LO12_I:
1865         case R_RISCV_LO12_S:
1866         case R_RISCV_SET6:
1867         case R_RISCV_SET8:
1868         case R_RISCV_SET16:
1869         case R_RISCV_SET32:
1870         case R_RISCV_32_PCREL:
1871         case R_RISCV_DELETE:
1872           /* These require no special handling beyond perform_relocation.  */
1873           break;
1874
1875         case R_RISCV_GOT_HI20:
1876           if (h != NULL)
1877             {
1878               bfd_boolean dyn, pic;
1879
1880               off = h->got.offset;
1881               BFD_ASSERT (off != (bfd_vma) -1);
1882               dyn = elf_hash_table (info)->dynamic_sections_created;
1883               pic = bfd_link_pic (info);
1884
1885               if (! WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, pic, h)
1886                   || (pic && SYMBOL_REFERENCES_LOCAL (info, h)))
1887                 {
1888                   /* This is actually a static link, or it is a
1889                      -Bsymbolic link and the symbol is defined
1890                      locally, or the symbol was forced to be local
1891                      because of a version file.  We must initialize
1892                      this entry in the global offset table.  Since the
1893                      offset must always be a multiple of the word size,
1894                      we use the least significant bit to record whether
1895                      we have initialized it already.
1896
1897                      When doing a dynamic link, we create a .rela.got
1898                      relocation entry to initialize the value.  This
1899                      is done in the finish_dynamic_symbol routine.  */
1900                   if ((off & 1) != 0)
1901                     off &= ~1;
1902                   else
1903                     {
1904                       bfd_put_NN (output_bfd, relocation,
1905                                   htab->elf.sgot->contents + off);
1906                       h->got.offset |= 1;
1907                     }
1908                 }
1909               else
1910                 unresolved_reloc = FALSE;
1911             }
1912           else
1913             {
1914               BFD_ASSERT (local_got_offsets != NULL
1915                           && local_got_offsets[r_symndx] != (bfd_vma) -1);
1916
1917               off = local_got_offsets[r_symndx];
1918
1919               /* The offset must always be a multiple of the word size.
1920                  So, we can use the least significant bit to record
1921                  whether we have already processed this entry.  */
1922               if ((off & 1) != 0)
1923                 off &= ~1;
1924               else
1925                 {
1926                   if (bfd_link_pic (info))
1927                     {
1928                       asection *s;
1929                       Elf_Internal_Rela outrel;
1930
1931                       /* We need to generate a R_RISCV_RELATIVE reloc
1932                          for the dynamic linker.  */
1933                       s = htab->elf.srelgot;
1934                       BFD_ASSERT (s != NULL);
1935
1936                       outrel.r_offset = sec_addr (htab->elf.sgot) + off;
1937                       outrel.r_info =
1938                         ELFNN_R_INFO (0, R_RISCV_RELATIVE);
1939                       outrel.r_addend = relocation;
1940                       relocation = 0;
1941                       riscv_elf_append_rela (output_bfd, s, &outrel);
1942                     }
1943
1944                   bfd_put_NN (output_bfd, relocation,
1945                               htab->elf.sgot->contents + off);
1946                   local_got_offsets[r_symndx] |= 1;
1947                 }
1948             }
1949           relocation = sec_addr (htab->elf.sgot) + off;
1950           absolute = riscv_zero_pcrel_hi_reloc (rel,
1951                                                 info,
1952                                                 pc,
1953                                                 relocation,
1954                                                 contents,
1955                                                 howto,
1956                                                 input_bfd);
1957           r_type = ELFNN_R_TYPE (rel->r_info);
1958           howto = riscv_elf_rtype_to_howto (input_bfd, r_type);
1959           if (howto == NULL)
1960             r = bfd_reloc_notsupported;
1961           else if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
1962                                                  relocation, absolute))
1963             r = bfd_reloc_overflow;
1964           break;
1965
1966         case R_RISCV_ADD8:
1967         case R_RISCV_ADD16:
1968         case R_RISCV_ADD32:
1969         case R_RISCV_ADD64:
1970           {
1971             bfd_vma old_value = bfd_get (howto->bitsize, input_bfd,
1972                                          contents + rel->r_offset);
1973             relocation = old_value + relocation;
1974           }
1975           break;
1976
1977         case R_RISCV_SUB6:
1978         case R_RISCV_SUB8:
1979         case R_RISCV_SUB16:
1980         case R_RISCV_SUB32:
1981         case R_RISCV_SUB64:
1982           {
1983             bfd_vma old_value = bfd_get (howto->bitsize, input_bfd,
1984                                          contents + rel->r_offset);
1985             relocation = old_value - relocation;
1986           }
1987           break;
1988
1989         case R_RISCV_CALL:
1990           /* Handle a call to an undefined weak function.  This won't be
1991              relaxed, so we have to handle it here.  */
1992           if (h != NULL && h->root.type == bfd_link_hash_undefweak
1993               && h->plt.offset == MINUS_ONE)
1994             {
1995               /* We can use x0 as the base register.  */
1996               bfd_vma insn = bfd_get_32 (input_bfd,
1997                                          contents + rel->r_offset + 4);
1998               insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
1999               bfd_put_32 (input_bfd, insn, contents + rel->r_offset + 4);
2000               /* Set the relocation value so that we get 0 after the pc
2001                  relative adjustment.  */
2002               relocation = sec_addr (input_section) + rel->r_offset;
2003             }
2004           /* Fall through.  */
2005
2006         case R_RISCV_CALL_PLT:
2007         case R_RISCV_JAL:
2008         case R_RISCV_RVC_JUMP:
2009           if (bfd_link_pic (info) && h != NULL && h->plt.offset != MINUS_ONE)
2010             {
2011               /* Refer to the PLT entry.  */
2012               relocation = sec_addr (htab->elf.splt) + h->plt.offset;
2013               unresolved_reloc = FALSE;
2014             }
2015           break;
2016
2017         case R_RISCV_TPREL_HI20:
2018           relocation = tpoff (info, relocation);
2019           break;
2020
2021         case R_RISCV_TPREL_LO12_I:
2022         case R_RISCV_TPREL_LO12_S:
2023           relocation = tpoff (info, relocation);
2024           break;
2025
2026         case R_RISCV_TPREL_I:
2027         case R_RISCV_TPREL_S:
2028           relocation = tpoff (info, relocation);
2029           if (VALID_ITYPE_IMM (relocation + rel->r_addend))
2030             {
2031               /* We can use tp as the base register.  */
2032               bfd_vma insn = bfd_get_32 (input_bfd, contents + rel->r_offset);
2033               insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
2034               insn |= X_TP << OP_SH_RS1;
2035               bfd_put_32 (input_bfd, insn, contents + rel->r_offset);
2036             }
2037           else
2038             r = bfd_reloc_overflow;
2039           break;
2040
2041         case R_RISCV_GPREL_I:
2042         case R_RISCV_GPREL_S:
2043           {
2044             bfd_vma gp = riscv_global_pointer_value (info);
2045             bfd_boolean x0_base = VALID_ITYPE_IMM (relocation + rel->r_addend);
2046             if (x0_base || VALID_ITYPE_IMM (relocation + rel->r_addend - gp))
2047               {
2048                 /* We can use x0 or gp as the base register.  */
2049                 bfd_vma insn = bfd_get_32 (input_bfd, contents + rel->r_offset);
2050                 insn &= ~(OP_MASK_RS1 << OP_SH_RS1);
2051                 if (!x0_base)
2052                   {
2053                     rel->r_addend -= gp;
2054                     insn |= X_GP << OP_SH_RS1;
2055                   }
2056                 bfd_put_32 (input_bfd, insn, contents + rel->r_offset);
2057               }
2058             else
2059               r = bfd_reloc_overflow;
2060             break;
2061           }
2062
2063         case R_RISCV_PCREL_HI20:
2064           absolute = riscv_zero_pcrel_hi_reloc (rel,
2065                                                 info,
2066                                                 pc,
2067                                                 relocation,
2068                                                 contents,
2069                                                 howto,
2070                                                 input_bfd);
2071           r_type = ELFNN_R_TYPE (rel->r_info);
2072           howto = riscv_elf_rtype_to_howto (input_bfd, r_type);
2073           if (howto == NULL)
2074             r = bfd_reloc_notsupported;
2075           else if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2076                                                  relocation + rel->r_addend,
2077                                                  absolute))
2078             r = bfd_reloc_overflow;
2079           break;
2080
2081         case R_RISCV_PCREL_LO12_I:
2082         case R_RISCV_PCREL_LO12_S:
2083           /* We don't allow section symbols plus addends as the auipc address,
2084              because then riscv_relax_delete_bytes would have to search through
2085              all relocs to update these addends.  This is also ambiguous, as
2086              we do allow offsets to be added to the target address, which are
2087              not to be used to find the auipc address.  */
2088           if (((sym != NULL && (ELF_ST_TYPE (sym->st_info) == STT_SECTION))
2089                || (h != NULL && h->type == STT_SECTION))
2090               && rel->r_addend)
2091             {
2092               r = bfd_reloc_dangerous;
2093               break;
2094             }
2095
2096           if (riscv_record_pcrel_lo_reloc (&pcrel_relocs, input_section, info,
2097                                            howto, rel, relocation, name,
2098                                            contents))
2099             continue;
2100           r = bfd_reloc_overflow;
2101           break;
2102
2103         case R_RISCV_TLS_DTPREL32:
2104         case R_RISCV_TLS_DTPREL64:
2105           relocation = dtpoff (info, relocation);
2106           break;
2107
2108         case R_RISCV_32:
2109         case R_RISCV_64:
2110           if ((input_section->flags & SEC_ALLOC) == 0)
2111             break;
2112
2113           if ((bfd_link_pic (info)
2114                && (h == NULL
2115                    || (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2116                        && !resolved_to_zero)
2117                    || h->root.type != bfd_link_hash_undefweak)
2118                && (! howto->pc_relative
2119                    || !SYMBOL_CALLS_LOCAL (info, h)))
2120               || (!bfd_link_pic (info)
2121                   && h != NULL
2122                   && h->dynindx != -1
2123                   && !h->non_got_ref
2124                   && ((h->def_dynamic
2125                        && !h->def_regular)
2126                       || h->root.type == bfd_link_hash_undefweak
2127                       || h->root.type == bfd_link_hash_undefined)))
2128             {
2129               Elf_Internal_Rela outrel;
2130               bfd_boolean skip_static_relocation, skip_dynamic_relocation;
2131
2132               /* When generating a shared object, these relocations
2133                  are copied into the output file to be resolved at run
2134                  time.  */
2135
2136               outrel.r_offset =
2137                 _bfd_elf_section_offset (output_bfd, info, input_section,
2138                                          rel->r_offset);
2139               skip_static_relocation = outrel.r_offset != (bfd_vma) -2;
2140               skip_dynamic_relocation = outrel.r_offset >= (bfd_vma) -2;
2141               outrel.r_offset += sec_addr (input_section);
2142
2143               if (skip_dynamic_relocation)
2144                 memset (&outrel, 0, sizeof outrel);
2145               else if (h != NULL && h->dynindx != -1
2146                        && !(bfd_link_pic (info)
2147                             && SYMBOLIC_BIND (info, h)
2148                             && h->def_regular))
2149                 {
2150                   outrel.r_info = ELFNN_R_INFO (h->dynindx, r_type);
2151                   outrel.r_addend = rel->r_addend;
2152                 }
2153               else
2154                 {
2155                   outrel.r_info = ELFNN_R_INFO (0, R_RISCV_RELATIVE);
2156                   outrel.r_addend = relocation + rel->r_addend;
2157                 }
2158
2159               riscv_elf_append_rela (output_bfd, sreloc, &outrel);
2160               if (skip_static_relocation)
2161                 continue;
2162             }
2163           break;
2164
2165         case R_RISCV_TLS_GOT_HI20:
2166           is_ie = TRUE;
2167           /* Fall through.  */
2168
2169         case R_RISCV_TLS_GD_HI20:
2170           if (h != NULL)
2171             {
2172               off = h->got.offset;
2173               h->got.offset |= 1;
2174             }
2175           else
2176             {
2177               off = local_got_offsets[r_symndx];
2178               local_got_offsets[r_symndx] |= 1;
2179             }
2180
2181           tls_type = _bfd_riscv_elf_tls_type (input_bfd, h, r_symndx);
2182           BFD_ASSERT (tls_type & (GOT_TLS_IE | GOT_TLS_GD));
2183           /* If this symbol is referenced by both GD and IE TLS, the IE
2184              reference's GOT slot follows the GD reference's slots.  */
2185           ie_off = 0;
2186           if ((tls_type & GOT_TLS_GD) && (tls_type & GOT_TLS_IE))
2187             ie_off = 2 * GOT_ENTRY_SIZE;
2188
2189           if ((off & 1) != 0)
2190             off &= ~1;
2191           else
2192             {
2193               Elf_Internal_Rela outrel;
2194               int indx = 0;
2195               bfd_boolean need_relocs = FALSE;
2196
2197               if (htab->elf.srelgot == NULL)
2198                 abort ();
2199
2200               if (h != NULL)
2201                 {
2202                   bfd_boolean dyn, pic;
2203                   dyn = htab->elf.dynamic_sections_created;
2204                   pic = bfd_link_pic (info);
2205
2206                   if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, pic, h)
2207                       && (!pic || !SYMBOL_REFERENCES_LOCAL (info, h)))
2208                     indx = h->dynindx;
2209                 }
2210
2211               /* The GOT entries have not been initialized yet.  Do it
2212                  now, and emit any relocations.  */
2213               if ((bfd_link_pic (info) || indx != 0)
2214                   && (h == NULL
2215                       || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2216                       || h->root.type != bfd_link_hash_undefweak))
2217                     need_relocs = TRUE;
2218
2219               if (tls_type & GOT_TLS_GD)
2220                 {
2221                   if (need_relocs)
2222                     {
2223                       outrel.r_offset = sec_addr (htab->elf.sgot) + off;
2224                       outrel.r_addend = 0;
2225                       outrel.r_info = ELFNN_R_INFO (indx, R_RISCV_TLS_DTPMODNN);
2226                       bfd_put_NN (output_bfd, 0,
2227                                   htab->elf.sgot->contents + off);
2228                       riscv_elf_append_rela (output_bfd, htab->elf.srelgot, &outrel);
2229                       if (indx == 0)
2230                         {
2231                           BFD_ASSERT (! unresolved_reloc);
2232                           bfd_put_NN (output_bfd,
2233                                       dtpoff (info, relocation),
2234                                       (htab->elf.sgot->contents + off +
2235                                        RISCV_ELF_WORD_BYTES));
2236                         }
2237                       else
2238                         {
2239                           bfd_put_NN (output_bfd, 0,
2240                                       (htab->elf.sgot->contents + off +
2241                                        RISCV_ELF_WORD_BYTES));
2242                           outrel.r_info = ELFNN_R_INFO (indx, R_RISCV_TLS_DTPRELNN);
2243                           outrel.r_offset += RISCV_ELF_WORD_BYTES;
2244                           riscv_elf_append_rela (output_bfd, htab->elf.srelgot, &outrel);
2245                         }
2246                     }
2247                   else
2248                     {
2249                       /* If we are not emitting relocations for a
2250                          general dynamic reference, then we must be in a
2251                          static link or an executable link with the
2252                          symbol binding locally.  Mark it as belonging
2253                          to module 1, the executable.  */
2254                       bfd_put_NN (output_bfd, 1,
2255                                   htab->elf.sgot->contents + off);
2256                       bfd_put_NN (output_bfd,
2257                                   dtpoff (info, relocation),
2258                                   (htab->elf.sgot->contents + off +
2259                                    RISCV_ELF_WORD_BYTES));
2260                    }
2261                 }
2262
2263               if (tls_type & GOT_TLS_IE)
2264                 {
2265                   if (need_relocs)
2266                     {
2267                       bfd_put_NN (output_bfd, 0,
2268                                   htab->elf.sgot->contents + off + ie_off);
2269                       outrel.r_offset = sec_addr (htab->elf.sgot)
2270                                        + off + ie_off;
2271                       outrel.r_addend = 0;
2272                       if (indx == 0)
2273                         outrel.r_addend = tpoff (info, relocation);
2274                       outrel.r_info = ELFNN_R_INFO (indx, R_RISCV_TLS_TPRELNN);
2275                       riscv_elf_append_rela (output_bfd, htab->elf.srelgot, &outrel);
2276                     }
2277                   else
2278                     {
2279                       bfd_put_NN (output_bfd, tpoff (info, relocation),
2280                                   htab->elf.sgot->contents + off + ie_off);
2281                     }
2282                 }
2283             }
2284
2285           BFD_ASSERT (off < (bfd_vma) -2);
2286           relocation = sec_addr (htab->elf.sgot) + off + (is_ie ? ie_off : 0);
2287           if (!riscv_record_pcrel_hi_reloc (&pcrel_relocs, pc,
2288                                             relocation, FALSE))
2289             r = bfd_reloc_overflow;
2290           unresolved_reloc = FALSE;
2291           break;
2292
2293         default:
2294           r = bfd_reloc_notsupported;
2295         }
2296
2297       /* Dynamic relocs are not propagated for SEC_DEBUGGING sections
2298          because such sections are not SEC_ALLOC and thus ld.so will
2299          not process them.  */
2300       if (unresolved_reloc
2301           && !((input_section->flags & SEC_DEBUGGING) != 0
2302                && h->def_dynamic)
2303           && _bfd_elf_section_offset (output_bfd, info, input_section,
2304                                       rel->r_offset) != (bfd_vma) -1)
2305         {
2306           (*_bfd_error_handler)
2307             (_("%pB(%pA+%#" PRIx64 "): "
2308                "unresolvable %s relocation against symbol `%s'"),
2309              input_bfd,
2310              input_section,
2311              (uint64_t) rel->r_offset,
2312              howto->name,
2313              h->root.root.string);
2314
2315           bfd_set_error (bfd_error_bad_value);
2316           ret = FALSE;
2317           goto out;
2318         }
2319
2320       if (r == bfd_reloc_ok)
2321         r = perform_relocation (howto, rel, relocation, input_section,
2322                                 input_bfd, contents);
2323
2324       switch (r)
2325         {
2326         case bfd_reloc_ok:
2327           continue;
2328
2329         case bfd_reloc_overflow:
2330           info->callbacks->reloc_overflow
2331             (info, (h ? &h->root : NULL), name, howto->name,
2332              (bfd_vma) 0, input_bfd, input_section, rel->r_offset);
2333           break;
2334
2335         case bfd_reloc_undefined:
2336           info->callbacks->undefined_symbol
2337             (info, name, input_bfd, input_section, rel->r_offset,
2338              TRUE);
2339           break;
2340
2341         case bfd_reloc_outofrange:
2342           msg = _("%X%P: internal error: out of range error\n");
2343           break;
2344
2345         case bfd_reloc_notsupported:
2346           msg = _("%X%P: internal error: unsupported relocation error\n");
2347           break;
2348
2349         case bfd_reloc_dangerous:
2350           info->callbacks->reloc_dangerous
2351             (info, "%pcrel_lo section symbol with an addend", input_bfd,
2352              input_section, rel->r_offset);
2353           break;
2354
2355         default:
2356           msg = _("%X%P: internal error: unknown error\n");
2357           break;
2358         }
2359
2360       if (msg)
2361         info->callbacks->einfo (msg);
2362
2363       /* We already reported the error via a callback, so don't try to report
2364          it again by returning false.  That leads to spurious errors.  */
2365       ret = TRUE;
2366       goto out;
2367     }
2368
2369   ret = riscv_resolve_pcrel_lo_relocs (&pcrel_relocs);
2370 out:
2371   riscv_free_pcrel_relocs (&pcrel_relocs);
2372   return ret;
2373 }
2374
2375 /* Finish up dynamic symbol handling.  We set the contents of various
2376    dynamic sections here.  */
2377
2378 static bfd_boolean
2379 riscv_elf_finish_dynamic_symbol (bfd *output_bfd,
2380                                  struct bfd_link_info *info,
2381                                  struct elf_link_hash_entry *h,
2382                                  Elf_Internal_Sym *sym)
2383 {
2384   struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
2385   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
2386
2387   if (h->plt.offset != (bfd_vma) -1)
2388     {
2389       /* We've decided to create a PLT entry for this symbol.  */
2390       bfd_byte *loc;
2391       bfd_vma i, header_address, plt_idx, got_address;
2392       uint32_t plt_entry[PLT_ENTRY_INSNS];
2393       Elf_Internal_Rela rela;
2394
2395       BFD_ASSERT (h->dynindx != -1);
2396
2397       /* Calculate the address of the PLT header.  */
2398       header_address = sec_addr (htab->elf.splt);
2399
2400       /* Calculate the index of the entry.  */
2401       plt_idx = (h->plt.offset - PLT_HEADER_SIZE) / PLT_ENTRY_SIZE;
2402
2403       /* Calculate the address of the .got.plt entry.  */
2404       got_address = riscv_elf_got_plt_val (plt_idx, info);
2405
2406       /* Find out where the .plt entry should go.  */
2407       loc = htab->elf.splt->contents + h->plt.offset;
2408
2409       /* Fill in the PLT entry itself.  */
2410       if (! riscv_make_plt_entry (output_bfd, got_address,
2411                                   header_address + h->plt.offset,
2412                                   plt_entry))
2413         return FALSE;
2414
2415       for (i = 0; i < PLT_ENTRY_INSNS; i++)
2416         bfd_put_32 (output_bfd, plt_entry[i], loc + 4*i);
2417
2418       /* Fill in the initial value of the .got.plt entry.  */
2419       loc = htab->elf.sgotplt->contents
2420             + (got_address - sec_addr (htab->elf.sgotplt));
2421       bfd_put_NN (output_bfd, sec_addr (htab->elf.splt), loc);
2422
2423       /* Fill in the entry in the .rela.plt section.  */
2424       rela.r_offset = got_address;
2425       rela.r_addend = 0;
2426       rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_JUMP_SLOT);
2427
2428       loc = htab->elf.srelplt->contents + plt_idx * sizeof (ElfNN_External_Rela);
2429       bed->s->swap_reloca_out (output_bfd, &rela, loc);
2430
2431       if (!h->def_regular)
2432         {
2433           /* Mark the symbol as undefined, rather than as defined in
2434              the .plt section.  Leave the value alone.  */
2435           sym->st_shndx = SHN_UNDEF;
2436           /* If the symbol is weak, we do need to clear the value.
2437              Otherwise, the PLT entry would provide a definition for
2438              the symbol even if the symbol wasn't defined anywhere,
2439              and so the symbol would never be NULL.  */
2440           if (!h->ref_regular_nonweak)
2441             sym->st_value = 0;
2442         }
2443     }
2444
2445   if (h->got.offset != (bfd_vma) -1
2446       && !(riscv_elf_hash_entry (h)->tls_type & (GOT_TLS_GD | GOT_TLS_IE))
2447       && !UNDEFWEAK_NO_DYNAMIC_RELOC (info, h))
2448     {
2449       asection *sgot;
2450       asection *srela;
2451       Elf_Internal_Rela rela;
2452
2453       /* This symbol has an entry in the GOT.  Set it up.  */
2454
2455       sgot = htab->elf.sgot;
2456       srela = htab->elf.srelgot;
2457       BFD_ASSERT (sgot != NULL && srela != NULL);
2458
2459       rela.r_offset = sec_addr (sgot) + (h->got.offset &~ (bfd_vma) 1);
2460
2461       /* If this is a local symbol reference, we just want to emit a RELATIVE
2462          reloc.  This can happen if it is a -Bsymbolic link, or a pie link, or
2463          the symbol was forced to be local because of a version file.
2464          The entry in the global offset table will already have been
2465          initialized in the relocate_section function.  */
2466       if (bfd_link_pic (info)
2467           && SYMBOL_REFERENCES_LOCAL (info, h))
2468         {
2469           BFD_ASSERT((h->got.offset & 1) != 0);
2470           asection *sec = h->root.u.def.section;
2471           rela.r_info = ELFNN_R_INFO (0, R_RISCV_RELATIVE);
2472           rela.r_addend = (h->root.u.def.value
2473                            + sec->output_section->vma
2474                            + sec->output_offset);
2475         }
2476       else
2477         {
2478           BFD_ASSERT((h->got.offset & 1) == 0);
2479           BFD_ASSERT (h->dynindx != -1);
2480           rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_NN);
2481           rela.r_addend = 0;
2482         }
2483
2484       bfd_put_NN (output_bfd, 0,
2485                   sgot->contents + (h->got.offset & ~(bfd_vma) 1));
2486       riscv_elf_append_rela (output_bfd, srela, &rela);
2487     }
2488
2489   if (h->needs_copy)
2490     {
2491       Elf_Internal_Rela rela;
2492       asection *s;
2493
2494       /* This symbols needs a copy reloc.  Set it up.  */
2495       BFD_ASSERT (h->dynindx != -1);
2496
2497       rela.r_offset = sec_addr (h->root.u.def.section) + h->root.u.def.value;
2498       rela.r_info = ELFNN_R_INFO (h->dynindx, R_RISCV_COPY);
2499       rela.r_addend = 0;
2500       if (h->root.u.def.section == htab->elf.sdynrelro)
2501         s = htab->elf.sreldynrelro;
2502       else
2503         s = htab->elf.srelbss;
2504       riscv_elf_append_rela (output_bfd, s, &rela);
2505     }
2506
2507   /* Mark some specially defined symbols as absolute.  */
2508   if (h == htab->elf.hdynamic
2509       || (h == htab->elf.hgot || h == htab->elf.hplt))
2510     sym->st_shndx = SHN_ABS;
2511
2512   return TRUE;
2513 }
2514
2515 /* Finish up the dynamic sections.  */
2516
2517 static bfd_boolean
2518 riscv_finish_dyn (bfd *output_bfd, struct bfd_link_info *info,
2519                   bfd *dynobj, asection *sdyn)
2520 {
2521   struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
2522   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
2523   size_t dynsize = bed->s->sizeof_dyn;
2524   bfd_byte *dyncon, *dynconend;
2525
2526   dynconend = sdyn->contents + sdyn->size;
2527   for (dyncon = sdyn->contents; dyncon < dynconend; dyncon += dynsize)
2528     {
2529       Elf_Internal_Dyn dyn;
2530       asection *s;
2531
2532       bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
2533
2534       switch (dyn.d_tag)
2535         {
2536         case DT_PLTGOT:
2537           s = htab->elf.sgotplt;
2538           dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
2539           break;
2540         case DT_JMPREL:
2541           s = htab->elf.srelplt;
2542           dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
2543           break;
2544         case DT_PLTRELSZ:
2545           s = htab->elf.srelplt;
2546           dyn.d_un.d_val = s->size;
2547           break;
2548         default:
2549           continue;
2550         }
2551
2552       bed->s->swap_dyn_out (output_bfd, &dyn, dyncon);
2553     }
2554   return TRUE;
2555 }
2556
2557 static bfd_boolean
2558 riscv_elf_finish_dynamic_sections (bfd *output_bfd,
2559                                    struct bfd_link_info *info)
2560 {
2561   bfd *dynobj;
2562   asection *sdyn;
2563   struct riscv_elf_link_hash_table *htab;
2564
2565   htab = riscv_elf_hash_table (info);
2566   BFD_ASSERT (htab != NULL);
2567   dynobj = htab->elf.dynobj;
2568
2569   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
2570
2571   if (elf_hash_table (info)->dynamic_sections_created)
2572     {
2573       asection *splt;
2574       bfd_boolean ret;
2575
2576       splt = htab->elf.splt;
2577       BFD_ASSERT (splt != NULL && sdyn != NULL);
2578
2579       ret = riscv_finish_dyn (output_bfd, info, dynobj, sdyn);
2580
2581       if (!ret)
2582         return ret;
2583
2584       /* Fill in the head and tail entries in the procedure linkage table.  */
2585       if (splt->size > 0)
2586         {
2587           int i;
2588           uint32_t plt_header[PLT_HEADER_INSNS];
2589           ret = riscv_make_plt_header (output_bfd,
2590                                        sec_addr (htab->elf.sgotplt),
2591                                        sec_addr (splt), plt_header);
2592           if (!ret)
2593             return ret;
2594
2595           for (i = 0; i < PLT_HEADER_INSNS; i++)
2596             bfd_put_32 (output_bfd, plt_header[i], splt->contents + 4*i);
2597
2598           elf_section_data (splt->output_section)->this_hdr.sh_entsize
2599             = PLT_ENTRY_SIZE;
2600         }
2601     }
2602
2603   if (htab->elf.sgotplt)
2604     {
2605       asection *output_section = htab->elf.sgotplt->output_section;
2606
2607       if (bfd_is_abs_section (output_section))
2608         {
2609           (*_bfd_error_handler)
2610             (_("discarded output section: `%pA'"), htab->elf.sgotplt);
2611           return FALSE;
2612         }
2613
2614       if (htab->elf.sgotplt->size > 0)
2615         {
2616           /* Write the first two entries in .got.plt, needed for the dynamic
2617              linker.  */
2618           bfd_put_NN (output_bfd, (bfd_vma) -1, htab->elf.sgotplt->contents);
2619           bfd_put_NN (output_bfd, (bfd_vma) 0,
2620                       htab->elf.sgotplt->contents + GOT_ENTRY_SIZE);
2621         }
2622
2623       elf_section_data (output_section)->this_hdr.sh_entsize = GOT_ENTRY_SIZE;
2624     }
2625
2626   if (htab->elf.sgot)
2627     {
2628       asection *output_section = htab->elf.sgot->output_section;
2629
2630       if (htab->elf.sgot->size > 0)
2631         {
2632           /* Set the first entry in the global offset table to the address of
2633              the dynamic section.  */
2634           bfd_vma val = sdyn ? sec_addr (sdyn) : 0;
2635           bfd_put_NN (output_bfd, val, htab->elf.sgot->contents);
2636         }
2637
2638       elf_section_data (output_section)->this_hdr.sh_entsize = GOT_ENTRY_SIZE;
2639     }
2640
2641   return TRUE;
2642 }
2643
2644 /* Return address for Ith PLT stub in section PLT, for relocation REL
2645    or (bfd_vma) -1 if it should not be included.  */
2646
2647 static bfd_vma
2648 riscv_elf_plt_sym_val (bfd_vma i, const asection *plt,
2649                        const arelent *rel ATTRIBUTE_UNUSED)
2650 {
2651   return plt->vma + PLT_HEADER_SIZE + i * PLT_ENTRY_SIZE;
2652 }
2653
2654 static enum elf_reloc_type_class
2655 riscv_reloc_type_class (const struct bfd_link_info *info ATTRIBUTE_UNUSED,
2656                         const asection *rel_sec ATTRIBUTE_UNUSED,
2657                         const Elf_Internal_Rela *rela)
2658 {
2659   switch (ELFNN_R_TYPE (rela->r_info))
2660     {
2661     case R_RISCV_RELATIVE:
2662       return reloc_class_relative;
2663     case R_RISCV_JUMP_SLOT:
2664       return reloc_class_plt;
2665     case R_RISCV_COPY:
2666       return reloc_class_copy;
2667     default:
2668       return reloc_class_normal;
2669     }
2670 }
2671
2672 /* Given the ELF header flags in FLAGS, it returns a string that describes the
2673    float ABI.  */
2674
2675 static const char *
2676 riscv_float_abi_string (flagword flags)
2677 {
2678   switch (flags & EF_RISCV_FLOAT_ABI)
2679     {
2680     case EF_RISCV_FLOAT_ABI_SOFT:
2681       return "soft-float";
2682       break;
2683     case EF_RISCV_FLOAT_ABI_SINGLE:
2684       return "single-float";
2685       break;
2686     case EF_RISCV_FLOAT_ABI_DOUBLE:
2687       return "double-float";
2688       break;
2689     case EF_RISCV_FLOAT_ABI_QUAD:
2690       return "quad-float";
2691       break;
2692     default:
2693       abort ();
2694     }
2695 }
2696
2697 /* The information of architecture attribute.  */
2698 static riscv_subset_list_t in_subsets;
2699 static riscv_subset_list_t out_subsets;
2700 static riscv_subset_list_t merged_subsets;
2701
2702 /* Predicator for standard extension.  */
2703
2704 static bfd_boolean
2705 riscv_std_ext_p (const char *name)
2706 {
2707   return (strlen (name) == 1) && (name[0] != 'x') && (name[0] != 's');
2708 }
2709
2710 /* Predicator for non-standard extension.  */
2711
2712 static bfd_boolean
2713 riscv_non_std_ext_p (const char *name)
2714 {
2715   return (strlen (name) >= 2) && (name[0] == 'x');
2716 }
2717
2718 /* Predicator for standard supervisor extension.  */
2719
2720 static bfd_boolean
2721 riscv_std_sv_ext_p (const char *name)
2722 {
2723   return (strlen (name) >= 2) && (name[0] == 's') && (name[1] != 'x');
2724 }
2725
2726 /* Predicator for non-standard supervisor extension.  */
2727
2728 static bfd_boolean
2729 riscv_non_std_sv_ext_p (const char *name)
2730 {
2731   return (strlen (name) >= 3) && (name[0] == 's') && (name[1] == 'x');
2732 }
2733
2734 /* Error handler when version mis-match.  */
2735
2736 static void
2737 riscv_version_mismatch (bfd *ibfd,
2738                         struct riscv_subset_t *in,
2739                         struct riscv_subset_t *out)
2740 {
2741   _bfd_error_handler
2742     (_("error: %pB: Mis-matched ISA version for '%s' extension. "
2743        "%d.%d vs %d.%d"),
2744        ibfd, in->name,
2745        in->major_version, in->minor_version,
2746        out->major_version, out->minor_version);
2747 }
2748
2749 /* Return true if subset is 'i' or 'e'.  */
2750
2751 static bfd_boolean
2752 riscv_i_or_e_p (bfd *ibfd,
2753                 const char *arch,
2754                 struct riscv_subset_t *subset)
2755 {
2756   if ((strcasecmp (subset->name, "e") != 0)
2757       && (strcasecmp (subset->name, "i") != 0))
2758     {
2759       _bfd_error_handler
2760         (_("error: %pB: corrupted ISA string '%s'. "
2761            "First letter should be 'i' or 'e' but got '%s'."),
2762            ibfd, arch, subset->name);
2763       return FALSE;
2764     }
2765   return TRUE;
2766 }
2767
2768 /* Merge standard extensions.
2769
2770    Return Value:
2771      Return FALSE if failed to merge.
2772
2773    Arguments:
2774      `bfd`: bfd handler.
2775      `in_arch`: Raw arch string for input object.
2776      `out_arch`: Raw arch string for output object.
2777      `pin`: subset list for input object, and it'll skip all merged subset after
2778             merge.
2779      `pout`: Like `pin`, but for output object.  */
2780
2781 static bfd_boolean
2782 riscv_merge_std_ext (bfd *ibfd,
2783                      const char *in_arch,
2784                      const char *out_arch,
2785                      struct riscv_subset_t **pin,
2786                      struct riscv_subset_t **pout)
2787 {
2788   const char *standard_exts = riscv_supported_std_ext ();
2789   const char *p;
2790   struct riscv_subset_t *in = *pin;
2791   struct riscv_subset_t *out = *pout;
2792
2793   /* First letter should be 'i' or 'e'.  */
2794   if (!riscv_i_or_e_p (ibfd, in_arch, in))
2795     return FALSE;
2796
2797   if (!riscv_i_or_e_p (ibfd, out_arch, out))
2798     return FALSE;
2799
2800   if (in->name[0] != out->name[0])
2801     {
2802       /* TODO: We might allow merge 'i' with 'e'.  */
2803       _bfd_error_handler
2804         (_("error: %pB: Mis-matched ISA string to merge '%s' and '%s'."),
2805          ibfd, in->name, out->name);
2806       return FALSE;
2807     }
2808   else if ((in->major_version != out->major_version) ||
2809            (in->minor_version != out->minor_version))
2810     {
2811       /* TODO: Allow different merge policy.  */
2812       riscv_version_mismatch (ibfd, in, out);
2813       return FALSE;
2814     }
2815   else
2816     riscv_add_subset (&merged_subsets,
2817                       in->name, in->major_version, in->minor_version);
2818
2819   in = in->next;
2820   out = out->next;
2821
2822   /* Handle standard extension first.  */
2823   for (p = standard_exts; *p; ++p)
2824     {
2825       char find_ext[2] = {*p, '\0'};
2826       struct riscv_subset_t *find_in =
2827         riscv_lookup_subset (&in_subsets, find_ext);
2828       struct riscv_subset_t *find_out =
2829         riscv_lookup_subset (&out_subsets, find_ext);
2830
2831       if (find_in == NULL && find_out == NULL)
2832         continue;
2833
2834       /* Check version is same or not.  */
2835       /* TODO: Allow different merge policy.  */
2836       if ((find_in != NULL && find_out != NULL)
2837           && ((find_in->major_version != find_out->major_version)
2838               || (find_in->minor_version != find_out->minor_version)))
2839         {
2840           riscv_version_mismatch (ibfd, in, out);
2841           return FALSE;
2842         }
2843
2844       struct riscv_subset_t *merged = find_in ? find_in : find_out;
2845       riscv_add_subset (&merged_subsets, merged->name,
2846                         merged->major_version, merged->minor_version);
2847     }
2848
2849   /* Skip all standard extensions.  */
2850   while ((in != NULL) && riscv_std_ext_p (in->name)) in = in->next;
2851   while ((out != NULL) && riscv_std_ext_p (out->name)) out = out->next;
2852
2853   *pin = in;
2854   *pout = out;
2855
2856   return TRUE;
2857 }
2858
2859 /* Merge non-standard and supervisor extensions.
2860    Return Value:
2861      Return FALSE if failed to merge.
2862
2863    Arguments:
2864      `bfd`: bfd handler.
2865      `in_arch`: Raw arch string for input object.
2866      `out_arch`: Raw arch string for output object.
2867      `pin`: subset list for input object, and it'll skip all merged subset after
2868             merge.
2869      `pout`: Like `pin`, but for output object. */
2870
2871 static bfd_boolean
2872 riscv_merge_non_std_and_sv_ext (bfd *ibfd,
2873                                 riscv_subset_t **pin,
2874                                 riscv_subset_t **pout,
2875                                 bfd_boolean (*predicate_func) (const char *))
2876 {
2877   riscv_subset_t *in = *pin;
2878   riscv_subset_t *out = *pout;
2879
2880   for (in = *pin; in != NULL && predicate_func (in->name); in = in->next)
2881     riscv_add_subset (&merged_subsets, in->name, in->major_version,
2882                       in->minor_version);
2883
2884   for (out = *pout; out != NULL && predicate_func (out->name); out = out->next)
2885     {
2886       riscv_subset_t *find_ext =
2887         riscv_lookup_subset (&merged_subsets, out->name);
2888       if (find_ext != NULL)
2889         {
2890           /* Check version is same or not. */
2891           /* TODO: Allow different merge policy.  */
2892           if ((find_ext->major_version != out->major_version)
2893               || (find_ext->minor_version != out->minor_version))
2894             {
2895               riscv_version_mismatch (ibfd, find_ext, out);
2896               return FALSE;
2897             }
2898         }
2899       else
2900         riscv_add_subset (&merged_subsets, out->name,
2901                           out->major_version, out->minor_version);
2902     }
2903
2904   *pin = in;
2905   *pout = out;
2906   return TRUE;
2907 }
2908
2909 /* Merge Tag_RISCV_arch attribute.  */
2910
2911 static char *
2912 riscv_merge_arch_attr_info (bfd *ibfd, char *in_arch, char *out_arch)
2913 {
2914   riscv_subset_t *in, *out;
2915   char *merged_arch_str;
2916
2917   unsigned xlen_in, xlen_out;
2918   merged_subsets.head = NULL;
2919   merged_subsets.tail = NULL;
2920
2921   riscv_parse_subset_t rpe_in;
2922   riscv_parse_subset_t rpe_out;
2923
2924   rpe_in.subset_list = &in_subsets;
2925   rpe_in.error_handler = _bfd_error_handler;
2926   rpe_in.xlen = &xlen_in;
2927
2928   rpe_out.subset_list = &out_subsets;
2929   rpe_out.error_handler = _bfd_error_handler;
2930   rpe_out.xlen = &xlen_out;
2931
2932   if (in_arch == NULL && out_arch == NULL)
2933     return NULL;
2934
2935   if (in_arch == NULL && out_arch != NULL)
2936     return out_arch;
2937
2938   if (in_arch != NULL && out_arch == NULL)
2939     return in_arch;
2940
2941   /* Parse subset from arch string.  */
2942   if (!riscv_parse_subset (&rpe_in, in_arch))
2943     return NULL;
2944
2945   if (!riscv_parse_subset (&rpe_out, out_arch))
2946     return NULL;
2947
2948   /* Checking XLEN.  */
2949   if (xlen_out != xlen_in)
2950     {
2951       _bfd_error_handler
2952         (_("error: %pB: ISA string of input (%s) doesn't match "
2953            "output (%s)."), ibfd, in_arch, out_arch);
2954       return NULL;
2955     }
2956
2957   /* Merge subset list.  */
2958   in = in_subsets.head;
2959   out = out_subsets.head;
2960
2961   /* Merge standard extension.  */
2962   if (!riscv_merge_std_ext (ibfd, in_arch, out_arch, &in, &out))
2963     return NULL;
2964   /* Merge non-standard extension.  */
2965   if (!riscv_merge_non_std_and_sv_ext (ibfd, &in, &out, riscv_non_std_ext_p))
2966     return NULL;
2967   /* Merge standard supervisor extension.  */
2968   if (!riscv_merge_non_std_and_sv_ext (ibfd, &in, &out, riscv_std_sv_ext_p))
2969     return NULL;
2970   /* Merge non-standard supervisor extension.  */
2971   if (!riscv_merge_non_std_and_sv_ext (ibfd, &in, &out, riscv_non_std_sv_ext_p))
2972     return NULL;
2973
2974   if (xlen_in != xlen_out)
2975     {
2976       _bfd_error_handler
2977         (_("error: %pB: XLEN of input (%u) doesn't match "
2978            "output (%u)."), ibfd, xlen_in, xlen_out);
2979       return NULL;
2980     }
2981
2982   if (xlen_in != ARCH_SIZE)
2983     {
2984       _bfd_error_handler
2985         (_("error: %pB: Unsupported XLEN (%u), you might be "
2986            "using wrong emulation."), ibfd, xlen_in);
2987       return NULL;
2988     }
2989
2990   merged_arch_str = riscv_arch_str (ARCH_SIZE, &merged_subsets);
2991
2992   /* Release the subset lists.  */
2993   riscv_release_subset_list (&in_subsets);
2994   riscv_release_subset_list (&out_subsets);
2995   riscv_release_subset_list (&merged_subsets);
2996
2997   return merged_arch_str;
2998 }
2999
3000 /* Merge object attributes from IBFD into output_bfd of INFO.
3001    Raise an error if there are conflicting attributes.  */
3002
3003 static bfd_boolean
3004 riscv_merge_attributes (bfd *ibfd, struct bfd_link_info *info)
3005 {
3006   bfd *obfd = info->output_bfd;
3007   obj_attribute *in_attr;
3008   obj_attribute *out_attr;
3009   bfd_boolean result = TRUE;
3010   const char *sec_name = get_elf_backend_data (ibfd)->obj_attrs_section;
3011   unsigned int i;
3012
3013   /* Skip linker created files.  */
3014   if (ibfd->flags & BFD_LINKER_CREATED)
3015     return TRUE;
3016
3017   /* Skip any input that doesn't have an attribute section.
3018      This enables to link object files without attribute section with
3019      any others.  */
3020   if (bfd_get_section_by_name (ibfd, sec_name) == NULL)
3021     return TRUE;
3022
3023   if (!elf_known_obj_attributes_proc (obfd)[0].i)
3024     {
3025       /* This is the first object.  Copy the attributes.  */
3026       _bfd_elf_copy_obj_attributes (ibfd, obfd);
3027
3028       out_attr = elf_known_obj_attributes_proc (obfd);
3029
3030       /* Use the Tag_null value to indicate the attributes have been
3031          initialized.  */
3032       out_attr[0].i = 1;
3033
3034       return TRUE;
3035     }
3036
3037   in_attr = elf_known_obj_attributes_proc (ibfd);
3038   out_attr = elf_known_obj_attributes_proc (obfd);
3039
3040   for (i = LEAST_KNOWN_OBJ_ATTRIBUTE; i < NUM_KNOWN_OBJ_ATTRIBUTES; i++)
3041     {
3042     switch (i)
3043       {
3044       case Tag_RISCV_arch:
3045         if (!out_attr[Tag_RISCV_arch].s)
3046           out_attr[Tag_RISCV_arch].s = in_attr[Tag_RISCV_arch].s;
3047         else if (in_attr[Tag_RISCV_arch].s
3048                  && out_attr[Tag_RISCV_arch].s)
3049           {
3050             /* Check arch compatible.  */
3051             char *merged_arch =
3052                 riscv_merge_arch_attr_info (ibfd,
3053                                             in_attr[Tag_RISCV_arch].s,
3054                                             out_attr[Tag_RISCV_arch].s);
3055             if (merged_arch == NULL)
3056               {
3057                 result = FALSE;
3058                 out_attr[Tag_RISCV_arch].s = "";
3059               }
3060             else
3061               out_attr[Tag_RISCV_arch].s = merged_arch;
3062           }
3063         break;
3064       case Tag_RISCV_priv_spec:
3065       case Tag_RISCV_priv_spec_minor:
3066       case Tag_RISCV_priv_spec_revision:
3067         if (out_attr[i].i != in_attr[i].i)
3068           {
3069             _bfd_error_handler
3070               (_("error: %pB: conflicting priv spec version "
3071                  "(major/minor/revision)."), ibfd);
3072             result = FALSE;
3073           }
3074         break;
3075       case Tag_RISCV_unaligned_access:
3076         out_attr[i].i |= in_attr[i].i;
3077         break;
3078       case Tag_RISCV_stack_align:
3079         if (out_attr[i].i == 0)
3080           out_attr[i].i = in_attr[i].i;
3081         else if (in_attr[i].i != 0
3082                  && out_attr[i].i != 0
3083                  && out_attr[i].i != in_attr[i].i)
3084           {
3085             _bfd_error_handler
3086               (_("error: %pB use %u-byte stack aligned but the output "
3087                  "use %u-byte stack aligned."),
3088                ibfd, in_attr[i].i, out_attr[i].i);
3089             result = FALSE;
3090           }
3091         break;
3092       default:
3093         result &= _bfd_elf_merge_unknown_attribute_low (ibfd, obfd, i);
3094       }
3095
3096       /* If out_attr was copied from in_attr then it won't have a type yet.  */
3097       if (in_attr[i].type && !out_attr[i].type)
3098         out_attr[i].type = in_attr[i].type;
3099     }
3100
3101   /* Merge Tag_compatibility attributes and any common GNU ones.  */
3102   if (!_bfd_elf_merge_object_attributes (ibfd, info))
3103     return FALSE;
3104
3105   /* Check for any attributes not known on RISC-V.  */
3106   result &= _bfd_elf_merge_unknown_attribute_list (ibfd, obfd);
3107
3108   return result;
3109 }
3110
3111 /* Merge backend specific data from an object file to the output
3112    object file when linking.  */
3113
3114 static bfd_boolean
3115 _bfd_riscv_elf_merge_private_bfd_data (bfd *ibfd, struct bfd_link_info *info)
3116 {
3117   bfd *obfd = info->output_bfd;
3118   flagword new_flags, old_flags;
3119
3120   if (!is_riscv_elf (ibfd) || !is_riscv_elf (obfd))
3121     return TRUE;
3122
3123   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
3124     {
3125       (*_bfd_error_handler)
3126         (_("%pB: ABI is incompatible with that of the selected emulation:\n"
3127            "  target emulation `%s' does not match `%s'"),
3128          ibfd, bfd_get_target (ibfd), bfd_get_target (obfd));
3129       return FALSE;
3130     }
3131
3132   if (!_bfd_elf_merge_object_attributes (ibfd, info))
3133     return FALSE;
3134
3135   if (!riscv_merge_attributes (ibfd, info))
3136     return FALSE;
3137
3138   new_flags = elf_elfheader (ibfd)->e_flags;
3139   old_flags = elf_elfheader (obfd)->e_flags;
3140
3141   if (! elf_flags_init (obfd))
3142     {
3143       elf_flags_init (obfd) = TRUE;
3144       elf_elfheader (obfd)->e_flags = new_flags;
3145       return TRUE;
3146     }
3147
3148   /* Check to see if the input BFD actually contains any sections.  If not,
3149      its flags may not have been initialized either, but it cannot actually
3150      cause any incompatibility.  Do not short-circuit dynamic objects; their
3151      section list may be emptied by elf_link_add_object_symbols.
3152
3153      Also check to see if there are no code sections in the input.  In this
3154      case, there is no need to check for code specific flags.  */
3155   if (!(ibfd->flags & DYNAMIC))
3156     {
3157       bfd_boolean null_input_bfd = TRUE;
3158       bfd_boolean only_data_sections = TRUE;
3159       asection *sec;
3160
3161       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
3162         {
3163           if ((bfd_get_section_flags (ibfd, sec)
3164                & (SEC_LOAD | SEC_CODE | SEC_HAS_CONTENTS))
3165               == (SEC_LOAD | SEC_CODE | SEC_HAS_CONTENTS))
3166             only_data_sections = FALSE;
3167
3168           null_input_bfd = FALSE;
3169           break;
3170         }
3171
3172       if (null_input_bfd || only_data_sections)
3173         return TRUE;
3174     }
3175
3176   /* Disallow linking different float ABIs.  */
3177   if ((old_flags ^ new_flags) & EF_RISCV_FLOAT_ABI)
3178     {
3179       (*_bfd_error_handler)
3180         (_("%pB: can't link %s modules with %s modules"), ibfd,
3181          riscv_float_abi_string (new_flags),
3182          riscv_float_abi_string (old_flags));
3183       goto fail;
3184     }
3185
3186   /* Disallow linking RVE and non-RVE.  */
3187   if ((old_flags ^ new_flags) & EF_RISCV_RVE)
3188     {
3189       (*_bfd_error_handler)
3190        (_("%pB: can't link RVE with other target"), ibfd);
3191       goto fail;
3192     }
3193
3194   /* Allow linking RVC and non-RVC, and keep the RVC flag.  */
3195   elf_elfheader (obfd)->e_flags |= new_flags & EF_RISCV_RVC;
3196
3197   return TRUE;
3198
3199 fail:
3200   bfd_set_error (bfd_error_bad_value);
3201   return FALSE;
3202 }
3203
3204 /* Delete some bytes from a section while relaxing.  */
3205
3206 static bfd_boolean
3207 riscv_relax_delete_bytes (bfd *abfd, asection *sec, bfd_vma addr, size_t count,
3208                           struct bfd_link_info *link_info)
3209 {
3210   unsigned int i, symcount;
3211   bfd_vma toaddr = sec->size;
3212   struct elf_link_hash_entry **sym_hashes = elf_sym_hashes (abfd);
3213   Elf_Internal_Shdr *symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
3214   unsigned int sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
3215   struct bfd_elf_section_data *data = elf_section_data (sec);
3216   bfd_byte *contents = data->this_hdr.contents;
3217
3218   /* Actually delete the bytes.  */
3219   sec->size -= count;
3220   memmove (contents + addr, contents + addr + count, toaddr - addr - count);
3221
3222   /* Adjust the location of all of the relocs.  Note that we need not
3223      adjust the addends, since all PC-relative references must be against
3224      symbols, which we will adjust below.  */
3225   for (i = 0; i < sec->reloc_count; i++)
3226     if (data->relocs[i].r_offset > addr && data->relocs[i].r_offset < toaddr)
3227       data->relocs[i].r_offset -= count;
3228
3229   /* Adjust the local symbols defined in this section.  */
3230   for (i = 0; i < symtab_hdr->sh_info; i++)
3231     {
3232       Elf_Internal_Sym *sym = (Elf_Internal_Sym *) symtab_hdr->contents + i;
3233       if (sym->st_shndx == sec_shndx)
3234         {
3235           /* If the symbol is in the range of memory we just moved, we
3236              have to adjust its value.  */
3237           if (sym->st_value > addr && sym->st_value <= toaddr)
3238             sym->st_value -= count;
3239
3240           /* If the symbol *spans* the bytes we just deleted (i.e. its
3241              *end* is in the moved bytes but its *start* isn't), then we
3242              must adjust its size.
3243
3244              This test needs to use the original value of st_value, otherwise
3245              we might accidentally decrease size when deleting bytes right
3246              before the symbol.  But since deleted relocs can't span across
3247              symbols, we can't have both a st_value and a st_size decrease,
3248              so it is simpler to just use an else.  */
3249           else if (sym->st_value <= addr
3250                    && sym->st_value + sym->st_size > addr
3251                    && sym->st_value + sym->st_size <= toaddr)
3252             sym->st_size -= count;
3253         }
3254     }
3255
3256   /* Now adjust the global symbols defined in this section.  */
3257   symcount = ((symtab_hdr->sh_size / sizeof (ElfNN_External_Sym))
3258               - symtab_hdr->sh_info);
3259
3260   for (i = 0; i < symcount; i++)
3261     {
3262       struct elf_link_hash_entry *sym_hash = sym_hashes[i];
3263
3264       /* The '--wrap SYMBOL' option is causing a pain when the object file,
3265          containing the definition of __wrap_SYMBOL, includes a direct
3266          call to SYMBOL as well. Since both __wrap_SYMBOL and SYMBOL reference
3267          the same symbol (which is __wrap_SYMBOL), but still exist as two
3268          different symbols in 'sym_hashes', we don't want to adjust
3269          the global symbol __wrap_SYMBOL twice.  */
3270       /* The same problem occurs with symbols that are versioned_hidden, as
3271          foo becomes an alias for foo@BAR, and hence they need the same
3272          treatment.  */
3273       if (link_info->wrap_hash != NULL
3274           || sym_hash->versioned == versioned_hidden)
3275         {
3276           struct elf_link_hash_entry **cur_sym_hashes;
3277
3278           /* Loop only over the symbols which have already been checked.  */
3279           for (cur_sym_hashes = sym_hashes; cur_sym_hashes < &sym_hashes[i];
3280                cur_sym_hashes++)
3281             {
3282               /* If the current symbol is identical to 'sym_hash', that means
3283                  the symbol was already adjusted (or at least checked).  */
3284               if (*cur_sym_hashes == sym_hash)
3285                 break;
3286             }
3287           /* Don't adjust the symbol again.  */
3288           if (cur_sym_hashes < &sym_hashes[i])
3289             continue;
3290         }
3291
3292       if ((sym_hash->root.type == bfd_link_hash_defined
3293            || sym_hash->root.type == bfd_link_hash_defweak)
3294           && sym_hash->root.u.def.section == sec)
3295         {
3296           /* As above, adjust the value if needed.  */
3297           if (sym_hash->root.u.def.value > addr
3298               && sym_hash->root.u.def.value <= toaddr)
3299             sym_hash->root.u.def.value -= count;
3300
3301           /* As above, adjust the size if needed.  */
3302           else if (sym_hash->root.u.def.value <= addr
3303                    && sym_hash->root.u.def.value + sym_hash->size > addr
3304                    && sym_hash->root.u.def.value + sym_hash->size <= toaddr)
3305             sym_hash->size -= count;
3306         }
3307     }
3308
3309   return TRUE;
3310 }
3311
3312 /* A second format for recording PC-relative hi relocations.  This stores the
3313    information required to relax them to GP-relative addresses.  */
3314
3315 typedef struct riscv_pcgp_hi_reloc riscv_pcgp_hi_reloc;
3316 struct riscv_pcgp_hi_reloc
3317 {
3318   bfd_vma hi_sec_off;
3319   bfd_vma hi_addend;
3320   bfd_vma hi_addr;
3321   unsigned hi_sym;
3322   asection *sym_sec;
3323   riscv_pcgp_hi_reloc *next;
3324 };
3325
3326 typedef struct riscv_pcgp_lo_reloc riscv_pcgp_lo_reloc;
3327 struct riscv_pcgp_lo_reloc
3328 {
3329   bfd_vma hi_sec_off;
3330   riscv_pcgp_lo_reloc *next;
3331 };
3332
3333 typedef struct
3334 {
3335   riscv_pcgp_hi_reloc *hi;
3336   riscv_pcgp_lo_reloc *lo;
3337 } riscv_pcgp_relocs;
3338
3339 /* Initialize the pcgp reloc info in P.  */
3340
3341 static bfd_boolean
3342 riscv_init_pcgp_relocs (riscv_pcgp_relocs *p)
3343 {
3344   p->hi = NULL;
3345   p->lo = NULL;
3346   return TRUE;
3347 }
3348
3349 /* Free the pcgp reloc info in P.  */
3350
3351 static void
3352 riscv_free_pcgp_relocs (riscv_pcgp_relocs *p,
3353                         bfd *abfd ATTRIBUTE_UNUSED,
3354                         asection *sec ATTRIBUTE_UNUSED)
3355 {
3356   riscv_pcgp_hi_reloc *c;
3357   riscv_pcgp_lo_reloc *l;
3358
3359   for (c = p->hi; c != NULL;)
3360     {
3361       riscv_pcgp_hi_reloc *next = c->next;
3362       free (c);
3363       c = next;
3364     }
3365
3366   for (l = p->lo; l != NULL;)
3367     {
3368       riscv_pcgp_lo_reloc *next = l->next;
3369       free (l);
3370       l = next;
3371     }
3372 }
3373
3374 /* Record pcgp hi part reloc info in P, using HI_SEC_OFF as the lookup index.
3375    The HI_ADDEND, HI_ADDR, HI_SYM, and SYM_SEC args contain info required to
3376    relax the corresponding lo part reloc.  */
3377
3378 static bfd_boolean
3379 riscv_record_pcgp_hi_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off,
3380                             bfd_vma hi_addend, bfd_vma hi_addr,
3381                             unsigned hi_sym, asection *sym_sec)
3382 {
3383   riscv_pcgp_hi_reloc *new = bfd_malloc (sizeof(*new));
3384   if (!new)
3385     return FALSE;
3386   new->hi_sec_off = hi_sec_off;
3387   new->hi_addend = hi_addend;
3388   new->hi_addr = hi_addr;
3389   new->hi_sym = hi_sym;
3390   new->sym_sec = sym_sec;
3391   new->next = p->hi;
3392   p->hi = new;
3393   return TRUE;
3394 }
3395
3396 /* Look up hi part pcgp reloc info in P, using HI_SEC_OFF as the lookup index.
3397    This is used by a lo part reloc to find the corresponding hi part reloc.  */
3398
3399 static riscv_pcgp_hi_reloc *
3400 riscv_find_pcgp_hi_reloc(riscv_pcgp_relocs *p, bfd_vma hi_sec_off)
3401 {
3402   riscv_pcgp_hi_reloc *c;
3403
3404   for (c = p->hi; c != NULL; c = c->next)
3405     if (c->hi_sec_off == hi_sec_off)
3406       return c;
3407   return NULL;
3408 }
3409
3410 /* Record pcgp lo part reloc info in P, using HI_SEC_OFF as the lookup info.
3411    This is used to record relocs that can't be relaxed.  */
3412
3413 static bfd_boolean
3414 riscv_record_pcgp_lo_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off)
3415 {
3416   riscv_pcgp_lo_reloc *new = bfd_malloc (sizeof(*new));
3417   if (!new)
3418     return FALSE;
3419   new->hi_sec_off = hi_sec_off;
3420   new->next = p->lo;
3421   p->lo = new;
3422   return TRUE;
3423 }
3424
3425 /* Look up lo part pcgp reloc info in P, using HI_SEC_OFF as the lookup index.
3426    This is used by a hi part reloc to find the corresponding lo part reloc.  */
3427
3428 static bfd_boolean
3429 riscv_find_pcgp_lo_reloc (riscv_pcgp_relocs *p, bfd_vma hi_sec_off)
3430 {
3431   riscv_pcgp_lo_reloc *c;
3432
3433   for (c = p->lo; c != NULL; c = c->next)
3434     if (c->hi_sec_off == hi_sec_off)
3435       return TRUE;
3436   return FALSE;
3437 }
3438
3439 typedef bfd_boolean (*relax_func_t) (bfd *, asection *, asection *,
3440                                      struct bfd_link_info *,
3441                                      Elf_Internal_Rela *,
3442                                      bfd_vma, bfd_vma, bfd_vma, bfd_boolean *,
3443                                      riscv_pcgp_relocs *);
3444
3445 /* Relax AUIPC + JALR into JAL.  */
3446
3447 static bfd_boolean
3448 _bfd_riscv_relax_call (bfd *abfd, asection *sec, asection *sym_sec,
3449                        struct bfd_link_info *link_info,
3450                        Elf_Internal_Rela *rel,
3451                        bfd_vma symval,
3452                        bfd_vma max_alignment,
3453                        bfd_vma reserve_size ATTRIBUTE_UNUSED,
3454                        bfd_boolean *again,
3455                        riscv_pcgp_relocs *pcgp_relocs ATTRIBUTE_UNUSED)
3456 {
3457   bfd_byte *contents = elf_section_data (sec)->this_hdr.contents;
3458   bfd_signed_vma foff = symval - (sec_addr (sec) + rel->r_offset);
3459   bfd_boolean near_zero = (symval + RISCV_IMM_REACH/2) < RISCV_IMM_REACH;
3460   bfd_vma auipc, jalr;
3461   int rd, r_type, len = 4, rvc = elf_elfheader (abfd)->e_flags & EF_RISCV_RVC;
3462
3463   /* If the call crosses section boundaries, an alignment directive could
3464      cause the PC-relative offset to later increase.  */
3465   if (VALID_UJTYPE_IMM (foff) && sym_sec->output_section != sec->output_section)
3466     foff += (foff < 0 ? -max_alignment : max_alignment);
3467
3468   /* See if this function call can be shortened.  */
3469   if (!VALID_UJTYPE_IMM (foff) && !(!bfd_link_pic (link_info) && near_zero))
3470     return TRUE;
3471
3472   /* Shorten the function call.  */
3473   BFD_ASSERT (rel->r_offset + 8 <= sec->size);
3474
3475   auipc = bfd_get_32 (abfd, contents + rel->r_offset);
3476   jalr = bfd_get_32 (abfd, contents + rel->r_offset + 4);
3477   rd = (jalr >> OP_SH_RD) & OP_MASK_RD;
3478   rvc = rvc && VALID_RVC_J_IMM (foff);
3479
3480   /* C.J exists on RV32 and RV64, but C.JAL is RV32-only.  */
3481   rvc = rvc && (rd == 0 || (rd == X_RA && ARCH_SIZE == 32));
3482
3483   if (rvc)
3484     {
3485       /* Relax to C.J[AL] rd, addr.  */
3486       r_type = R_RISCV_RVC_JUMP;
3487       auipc = rd == 0 ? MATCH_C_J : MATCH_C_JAL;
3488       len = 2;
3489     }
3490   else if (VALID_UJTYPE_IMM (foff))
3491     {
3492       /* Relax to JAL rd, addr.  */
3493       r_type = R_RISCV_JAL;
3494       auipc = MATCH_JAL | (rd << OP_SH_RD);
3495     }
3496   else /* near_zero */
3497     {
3498       /* Relax to JALR rd, x0, addr.  */
3499       r_type = R_RISCV_LO12_I;
3500       auipc = MATCH_JALR | (rd << OP_SH_RD);
3501     }
3502
3503   /* Replace the R_RISCV_CALL reloc.  */
3504   rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), r_type);
3505   /* Replace the AUIPC.  */
3506   bfd_put (8 * len, abfd, auipc, contents + rel->r_offset);
3507
3508   /* Delete unnecessary JALR.  */
3509   *again = TRUE;
3510   return riscv_relax_delete_bytes (abfd, sec, rel->r_offset + len, 8 - len,
3511                                    link_info);
3512 }
3513
3514 /* Traverse all output sections and return the max alignment.  */
3515
3516 static bfd_vma
3517 _bfd_riscv_get_max_alignment (asection *sec)
3518 {
3519   unsigned int max_alignment_power = 0;
3520   asection *o;
3521
3522   for (o = sec->output_section->owner->sections; o != NULL; o = o->next)
3523     {
3524       if (o->alignment_power > max_alignment_power)
3525         max_alignment_power = o->alignment_power;
3526     }
3527
3528   return (bfd_vma) 1 << max_alignment_power;
3529 }
3530
3531 /* Relax non-PIC global variable references.  */
3532
3533 static bfd_boolean
3534 _bfd_riscv_relax_lui (bfd *abfd,
3535                       asection *sec,
3536                       asection *sym_sec,
3537                       struct bfd_link_info *link_info,
3538                       Elf_Internal_Rela *rel,
3539                       bfd_vma symval,
3540                       bfd_vma max_alignment,
3541                       bfd_vma reserve_size,
3542                       bfd_boolean *again,
3543                       riscv_pcgp_relocs *pcgp_relocs ATTRIBUTE_UNUSED)
3544 {
3545   bfd_byte *contents = elf_section_data (sec)->this_hdr.contents;
3546   bfd_vma gp = riscv_global_pointer_value (link_info);
3547   int use_rvc = elf_elfheader (abfd)->e_flags & EF_RISCV_RVC;
3548
3549   BFD_ASSERT (rel->r_offset + 4 <= sec->size);
3550
3551   if (gp)
3552     {
3553       /* If gp and the symbol are in the same output section, which is not the
3554          abs section, then consider only that output section's alignment.  */
3555       struct bfd_link_hash_entry *h =
3556         bfd_link_hash_lookup (link_info->hash, RISCV_GP_SYMBOL, FALSE, FALSE,
3557                               TRUE);
3558       if (h->u.def.section->output_section == sym_sec->output_section
3559           && sym_sec->output_section != bfd_abs_section_ptr)
3560         max_alignment = (bfd_vma) 1 << sym_sec->output_section->alignment_power;
3561     }
3562
3563   /* Is the reference in range of x0 or gp?
3564      Valid gp range conservatively because of alignment issue.  */
3565   if (VALID_ITYPE_IMM (symval)
3566       || (symval >= gp
3567           && VALID_ITYPE_IMM (symval - gp + max_alignment + reserve_size))
3568       || (symval < gp
3569           && VALID_ITYPE_IMM (symval - gp - max_alignment - reserve_size)))
3570     {
3571       unsigned sym = ELFNN_R_SYM (rel->r_info);
3572       switch (ELFNN_R_TYPE (rel->r_info))
3573         {
3574         case R_RISCV_LO12_I:
3575           rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_I);
3576           return TRUE;
3577
3578         case R_RISCV_LO12_S:
3579           rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_S);
3580           return TRUE;
3581
3582         case R_RISCV_HI20:
3583           /* We can delete the unnecessary LUI and reloc.  */
3584           rel->r_info = ELFNN_R_INFO (0, R_RISCV_NONE);
3585           *again = TRUE;
3586           return riscv_relax_delete_bytes (abfd, sec, rel->r_offset, 4,
3587                                            link_info);
3588
3589         default:
3590           abort ();
3591         }
3592     }
3593
3594   /* Can we relax LUI to C.LUI?  Alignment might move the section forward;
3595      account for this assuming page alignment at worst. In the presence of 
3596      RELRO segment the linker aligns it by one page size, therefore sections
3597      after the segment can be moved more than one page. */
3598
3599   if (use_rvc
3600       && ELFNN_R_TYPE (rel->r_info) == R_RISCV_HI20
3601       && VALID_RVC_LUI_IMM (RISCV_CONST_HIGH_PART (symval))
3602       && VALID_RVC_LUI_IMM (RISCV_CONST_HIGH_PART (symval)
3603                             + (link_info->relro ? 2 * ELF_MAXPAGESIZE
3604                                : ELF_MAXPAGESIZE)))
3605     {
3606       /* Replace LUI with C.LUI if legal (i.e., rd != x0 and rd != x2/sp).  */
3607       bfd_vma lui = bfd_get_32 (abfd, contents + rel->r_offset);
3608       unsigned rd = ((unsigned)lui >> OP_SH_RD) & OP_MASK_RD;
3609       if (rd == 0 || rd == X_SP)
3610         return TRUE;
3611
3612       lui = (lui & (OP_MASK_RD << OP_SH_RD)) | MATCH_C_LUI;
3613       bfd_put_32 (abfd, lui, contents + rel->r_offset);
3614
3615       /* Replace the R_RISCV_HI20 reloc.  */
3616       rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), R_RISCV_RVC_LUI);
3617
3618       *again = TRUE;
3619       return riscv_relax_delete_bytes (abfd, sec, rel->r_offset + 2, 2,
3620                                        link_info);
3621     }
3622
3623   return TRUE;
3624 }
3625
3626 /* Relax non-PIC TLS references.  */
3627
3628 static bfd_boolean
3629 _bfd_riscv_relax_tls_le (bfd *abfd,
3630                          asection *sec,
3631                          asection *sym_sec ATTRIBUTE_UNUSED,
3632                          struct bfd_link_info *link_info,
3633                          Elf_Internal_Rela *rel,
3634                          bfd_vma symval,
3635                          bfd_vma max_alignment ATTRIBUTE_UNUSED,
3636                          bfd_vma reserve_size ATTRIBUTE_UNUSED,
3637                          bfd_boolean *again,
3638                          riscv_pcgp_relocs *prcel_relocs ATTRIBUTE_UNUSED)
3639 {
3640   /* See if this symbol is in range of tp.  */
3641   if (RISCV_CONST_HIGH_PART (tpoff (link_info, symval)) != 0)
3642     return TRUE;
3643
3644   BFD_ASSERT (rel->r_offset + 4 <= sec->size);
3645   switch (ELFNN_R_TYPE (rel->r_info))
3646     {
3647     case R_RISCV_TPREL_LO12_I:
3648       rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), R_RISCV_TPREL_I);
3649       return TRUE;
3650
3651     case R_RISCV_TPREL_LO12_S:
3652       rel->r_info = ELFNN_R_INFO (ELFNN_R_SYM (rel->r_info), R_RISCV_TPREL_S);
3653       return TRUE;
3654
3655     case R_RISCV_TPREL_HI20:
3656     case R_RISCV_TPREL_ADD:
3657       /* We can delete the unnecessary instruction and reloc.  */
3658       rel->r_info = ELFNN_R_INFO (0, R_RISCV_NONE);
3659       *again = TRUE;
3660       return riscv_relax_delete_bytes (abfd, sec, rel->r_offset, 4, link_info);
3661
3662     default:
3663       abort ();
3664     }
3665 }
3666
3667 /* Implement R_RISCV_ALIGN by deleting excess alignment NOPs.  */
3668
3669 static bfd_boolean
3670 _bfd_riscv_relax_align (bfd *abfd, asection *sec,
3671                         asection *sym_sec,
3672                         struct bfd_link_info *link_info,
3673                         Elf_Internal_Rela *rel,
3674                         bfd_vma symval,
3675                         bfd_vma max_alignment ATTRIBUTE_UNUSED,
3676                         bfd_vma reserve_size ATTRIBUTE_UNUSED,
3677                         bfd_boolean *again ATTRIBUTE_UNUSED,
3678                         riscv_pcgp_relocs *pcrel_relocs ATTRIBUTE_UNUSED)
3679 {
3680   bfd_byte *contents = elf_section_data (sec)->this_hdr.contents;
3681   bfd_vma alignment = 1, pos;
3682   while (alignment <= rel->r_addend)
3683     alignment *= 2;
3684
3685   symval -= rel->r_addend;
3686   bfd_vma aligned_addr = ((symval - 1) & ~(alignment - 1)) + alignment;
3687   bfd_vma nop_bytes = aligned_addr - symval;
3688
3689   /* Once we've handled an R_RISCV_ALIGN, we can't relax anything else.  */
3690   sec->sec_flg0 = TRUE;
3691
3692   /* Make sure there are enough NOPs to actually achieve the alignment.  */
3693   if (rel->r_addend < nop_bytes)
3694     {
3695       _bfd_error_handler
3696         (_("%pB(%pA+%#" PRIx64 "): %" PRId64 " bytes required for alignment "
3697            "to %" PRId64 "-byte boundary, but only %" PRId64 " present"),
3698          abfd, sym_sec, (uint64_t) rel->r_offset,
3699          (int64_t) nop_bytes, (int64_t) alignment, (int64_t) rel->r_addend);
3700       bfd_set_error (bfd_error_bad_value);
3701       return FALSE;
3702     }
3703
3704   /* Delete the reloc.  */
3705   rel->r_info = ELFNN_R_INFO (0, R_RISCV_NONE);
3706
3707   /* If the number of NOPs is already correct, there's nothing to do.  */
3708   if (nop_bytes == rel->r_addend)
3709     return TRUE;
3710
3711   /* Write as many RISC-V NOPs as we need.  */
3712   for (pos = 0; pos < (nop_bytes & -4); pos += 4)
3713     bfd_put_32 (abfd, RISCV_NOP, contents + rel->r_offset + pos);
3714
3715   /* Write a final RVC NOP if need be.  */
3716   if (nop_bytes % 4 != 0)
3717     bfd_put_16 (abfd, RVC_NOP, contents + rel->r_offset + pos);
3718
3719   /* Delete the excess bytes.  */
3720   return riscv_relax_delete_bytes (abfd, sec, rel->r_offset + nop_bytes,
3721                                    rel->r_addend - nop_bytes, link_info);
3722 }
3723
3724 /* Relax PC-relative references to GP-relative references.  */
3725
3726 static bfd_boolean
3727 _bfd_riscv_relax_pc  (bfd *abfd ATTRIBUTE_UNUSED,
3728                       asection *sec,
3729                       asection *sym_sec,
3730                       struct bfd_link_info *link_info,
3731                       Elf_Internal_Rela *rel,
3732                       bfd_vma symval,
3733                       bfd_vma max_alignment,
3734                       bfd_vma reserve_size,
3735                       bfd_boolean *again ATTRIBUTE_UNUSED,
3736                       riscv_pcgp_relocs *pcgp_relocs)
3737 {
3738   bfd_vma gp = riscv_global_pointer_value (link_info);
3739
3740   BFD_ASSERT (rel->r_offset + 4 <= sec->size);
3741
3742   /* Chain the _LO relocs to their cooresponding _HI reloc to compute the
3743    * actual target address.  */
3744   riscv_pcgp_hi_reloc hi_reloc;
3745   memset (&hi_reloc, 0, sizeof (hi_reloc));
3746   switch (ELFNN_R_TYPE (rel->r_info))
3747     {
3748     case R_RISCV_PCREL_LO12_I:
3749     case R_RISCV_PCREL_LO12_S:
3750       {
3751         /* If the %lo has an addend, it isn't for the label pointing at the
3752            hi part instruction, but rather for the symbol pointed at by the
3753            hi part instruction.  So we must subtract it here for the lookup.
3754            It is still used below in the final symbol address.  */
3755         bfd_vma hi_sec_off = symval - sec_addr (sym_sec) - rel->r_addend;
3756         riscv_pcgp_hi_reloc *hi = riscv_find_pcgp_hi_reloc (pcgp_relocs,
3757                                                             hi_sec_off);
3758         if (hi == NULL)
3759           {
3760             riscv_record_pcgp_lo_reloc (pcgp_relocs, hi_sec_off);
3761             return TRUE;
3762           }
3763
3764         hi_reloc = *hi;
3765         symval = hi_reloc.hi_addr;
3766         sym_sec = hi_reloc.sym_sec;
3767       }
3768       break;
3769
3770     case R_RISCV_PCREL_HI20:
3771       /* Mergeable symbols and code might later move out of range.  */
3772       if (sym_sec->flags & (SEC_MERGE | SEC_CODE))
3773         return TRUE;
3774
3775       /* If the cooresponding lo relocation has already been seen then it's not
3776        * safe to relax this relocation.  */
3777       if (riscv_find_pcgp_lo_reloc (pcgp_relocs, rel->r_offset))
3778         return TRUE;
3779
3780       break;
3781
3782     default:
3783       abort ();
3784     }
3785
3786   if (gp)
3787     {
3788       /* If gp and the symbol are in the same output section, which is not the
3789          abs section, then consider only that output section's alignment.  */
3790       struct bfd_link_hash_entry *h =
3791         bfd_link_hash_lookup (link_info->hash, RISCV_GP_SYMBOL, FALSE, FALSE,
3792                               TRUE);
3793       if (h->u.def.section->output_section == sym_sec->output_section
3794           && sym_sec->output_section != bfd_abs_section_ptr)
3795         max_alignment = (bfd_vma) 1 << sym_sec->output_section->alignment_power;
3796     }
3797
3798   /* Is the reference in range of x0 or gp?
3799      Valid gp range conservatively because of alignment issue.  */
3800   if (VALID_ITYPE_IMM (symval)
3801       || (symval >= gp
3802           && VALID_ITYPE_IMM (symval - gp + max_alignment + reserve_size))
3803       || (symval < gp
3804           && VALID_ITYPE_IMM (symval - gp - max_alignment - reserve_size)))
3805     {
3806       unsigned sym = hi_reloc.hi_sym;
3807       switch (ELFNN_R_TYPE (rel->r_info))
3808         {
3809         case R_RISCV_PCREL_LO12_I:
3810           rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_I);
3811           rel->r_addend += hi_reloc.hi_addend;
3812           return TRUE;
3813
3814         case R_RISCV_PCREL_LO12_S:
3815           rel->r_info = ELFNN_R_INFO (sym, R_RISCV_GPREL_S);
3816           rel->r_addend += hi_reloc.hi_addend;
3817           return TRUE;
3818
3819         case R_RISCV_PCREL_HI20:
3820           riscv_record_pcgp_hi_reloc (pcgp_relocs,
3821                                       rel->r_offset,
3822                                       rel->r_addend,
3823                                       symval,
3824                                       ELFNN_R_SYM(rel->r_info),
3825                                       sym_sec);
3826           /* We can delete the unnecessary AUIPC and reloc.  */
3827           rel->r_info = ELFNN_R_INFO (0, R_RISCV_DELETE);
3828           rel->r_addend = 4;
3829           return TRUE;
3830
3831         default:
3832           abort ();
3833         }
3834     }
3835
3836   return TRUE;
3837 }
3838
3839 /* Relax PC-relative references to GP-relative references.  */
3840
3841 static bfd_boolean
3842 _bfd_riscv_relax_delete (bfd *abfd,
3843                          asection *sec,
3844                          asection *sym_sec ATTRIBUTE_UNUSED,
3845                          struct bfd_link_info *link_info,
3846                          Elf_Internal_Rela *rel,
3847                          bfd_vma symval ATTRIBUTE_UNUSED,
3848                          bfd_vma max_alignment ATTRIBUTE_UNUSED,
3849                          bfd_vma reserve_size ATTRIBUTE_UNUSED,
3850                          bfd_boolean *again ATTRIBUTE_UNUSED,
3851                          riscv_pcgp_relocs *pcgp_relocs ATTRIBUTE_UNUSED)
3852 {
3853   if (!riscv_relax_delete_bytes(abfd, sec, rel->r_offset, rel->r_addend,
3854                                 link_info))
3855     return FALSE;
3856   rel->r_info = ELFNN_R_INFO(0, R_RISCV_NONE);
3857   return TRUE;
3858 }
3859
3860 /* Relax a section.  Pass 0 shortens code sequences unless disabled.  Pass 1
3861    deletes the bytes that pass 0 made obselete.  Pass 2, which cannot be
3862    disabled, handles code alignment directives.  */
3863
3864 static bfd_boolean
3865 _bfd_riscv_relax_section (bfd *abfd, asection *sec,
3866                           struct bfd_link_info *info,
3867                           bfd_boolean *again)
3868 {
3869   Elf_Internal_Shdr *symtab_hdr = &elf_symtab_hdr (abfd);
3870   struct riscv_elf_link_hash_table *htab = riscv_elf_hash_table (info);
3871   struct bfd_elf_section_data *data = elf_section_data (sec);
3872   Elf_Internal_Rela *relocs;
3873   bfd_boolean ret = FALSE;
3874   unsigned int i;
3875   bfd_vma max_alignment, reserve_size = 0;
3876   riscv_pcgp_relocs pcgp_relocs;
3877
3878   *again = FALSE;
3879
3880   if (bfd_link_relocatable (info)
3881       || sec->sec_flg0
3882       || (sec->flags & SEC_RELOC) == 0
3883       || sec->reloc_count == 0
3884       || (info->disable_target_specific_optimizations
3885           && info->relax_pass == 0))
3886     return TRUE;
3887
3888   riscv_init_pcgp_relocs (&pcgp_relocs);
3889
3890   /* Read this BFD's relocs if we haven't done so already.  */
3891   if (data->relocs)
3892     relocs = data->relocs;
3893   else if (!(relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
3894                                                  info->keep_memory)))
3895     goto fail;
3896
3897   if (htab)
3898     {
3899       max_alignment = htab->max_alignment;
3900       if (max_alignment == (bfd_vma) -1)
3901         {
3902           max_alignment = _bfd_riscv_get_max_alignment (sec);
3903           htab->max_alignment = max_alignment;
3904         }
3905     }
3906   else
3907     max_alignment = _bfd_riscv_get_max_alignment (sec);
3908
3909   /* Examine and consider relaxing each reloc.  */
3910   for (i = 0; i < sec->reloc_count; i++)
3911     {
3912       asection *sym_sec;
3913       Elf_Internal_Rela *rel = relocs + i;
3914       relax_func_t relax_func;
3915       int type = ELFNN_R_TYPE (rel->r_info);
3916       bfd_vma symval;
3917       char symtype;
3918
3919       relax_func = NULL;
3920       if (info->relax_pass == 0)
3921         {
3922           if (type == R_RISCV_CALL || type == R_RISCV_CALL_PLT)
3923             relax_func = _bfd_riscv_relax_call;
3924           else if (type == R_RISCV_HI20
3925                    || type == R_RISCV_LO12_I
3926                    || type == R_RISCV_LO12_S)
3927             relax_func = _bfd_riscv_relax_lui;
3928           else if (!bfd_link_pic(info)
3929                    && (type == R_RISCV_PCREL_HI20
3930                    || type == R_RISCV_PCREL_LO12_I
3931                    || type == R_RISCV_PCREL_LO12_S))
3932             relax_func = _bfd_riscv_relax_pc;
3933           else if (type == R_RISCV_TPREL_HI20
3934                    || type == R_RISCV_TPREL_ADD
3935                    || type == R_RISCV_TPREL_LO12_I
3936                    || type == R_RISCV_TPREL_LO12_S)
3937             relax_func = _bfd_riscv_relax_tls_le;
3938           else
3939             continue;
3940
3941           /* Only relax this reloc if it is paired with R_RISCV_RELAX.  */
3942           if (i == sec->reloc_count - 1
3943               || ELFNN_R_TYPE ((rel + 1)->r_info) != R_RISCV_RELAX
3944               || rel->r_offset != (rel + 1)->r_offset)
3945             continue;
3946
3947           /* Skip over the R_RISCV_RELAX.  */
3948           i++;
3949         }
3950       else if (info->relax_pass == 1 && type == R_RISCV_DELETE)
3951         relax_func = _bfd_riscv_relax_delete;
3952       else if (info->relax_pass == 2 && type == R_RISCV_ALIGN)
3953         relax_func = _bfd_riscv_relax_align;
3954       else
3955         continue;
3956
3957       data->relocs = relocs;
3958
3959       /* Read this BFD's contents if we haven't done so already.  */
3960       if (!data->this_hdr.contents
3961           && !bfd_malloc_and_get_section (abfd, sec, &data->this_hdr.contents))
3962         goto fail;
3963
3964       /* Read this BFD's symbols if we haven't done so already.  */
3965       if (symtab_hdr->sh_info != 0
3966           && !symtab_hdr->contents
3967           && !(symtab_hdr->contents =
3968                (unsigned char *) bfd_elf_get_elf_syms (abfd, symtab_hdr,
3969                                                        symtab_hdr->sh_info,
3970                                                        0, NULL, NULL, NULL)))
3971         goto fail;
3972
3973       /* Get the value of the symbol referred to by the reloc.  */
3974       if (ELFNN_R_SYM (rel->r_info) < symtab_hdr->sh_info)
3975         {
3976           /* A local symbol.  */
3977           Elf_Internal_Sym *isym = ((Elf_Internal_Sym *) symtab_hdr->contents
3978                                     + ELFNN_R_SYM (rel->r_info));
3979           reserve_size = (isym->st_size - rel->r_addend) > isym->st_size
3980             ? 0 : isym->st_size - rel->r_addend;
3981
3982           if (isym->st_shndx == SHN_UNDEF)
3983             sym_sec = sec, symval = rel->r_offset;
3984           else
3985             {
3986               BFD_ASSERT (isym->st_shndx < elf_numsections (abfd));
3987               sym_sec = elf_elfsections (abfd)[isym->st_shndx]->bfd_section;
3988 #if 0
3989               /* The purpose of this code is unknown.  It breaks linker scripts
3990                  for embedded development that place sections at address zero.
3991                  This code is believed to be unnecessary.  Disabling it but not
3992                  yet removing it, in case something breaks.  */
3993               if (sec_addr (sym_sec) == 0)
3994                 continue;
3995 #endif
3996               symval = isym->st_value;
3997             }
3998           symtype = ELF_ST_TYPE (isym->st_info);
3999         }
4000       else
4001         {
4002           unsigned long indx;
4003           struct elf_link_hash_entry *h;
4004
4005           indx = ELFNN_R_SYM (rel->r_info) - symtab_hdr->sh_info;
4006           h = elf_sym_hashes (abfd)[indx];
4007
4008           while (h->root.type == bfd_link_hash_indirect
4009                  || h->root.type == bfd_link_hash_warning)
4010             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4011
4012           if (h->plt.offset != MINUS_ONE)
4013             {
4014               sym_sec = htab->elf.splt;
4015               symval = h->plt.offset;
4016             }
4017           else if (h->root.u.def.section->output_section == NULL
4018                    || (h->root.type != bfd_link_hash_defined
4019                        && h->root.type != bfd_link_hash_defweak))
4020             continue;
4021           else
4022             {
4023               symval = h->root.u.def.value;
4024               sym_sec = h->root.u.def.section;
4025             }
4026
4027           if (h->type != STT_FUNC)
4028             reserve_size =
4029               (h->size - rel->r_addend) > h->size ? 0 : h->size - rel->r_addend;
4030           symtype = h->type;
4031         }
4032
4033       if (sym_sec->sec_info_type == SEC_INFO_TYPE_MERGE
4034           && (sym_sec->flags & SEC_MERGE))
4035         {
4036           /* At this stage in linking, no SEC_MERGE symbol has been
4037              adjusted, so all references to such symbols need to be
4038              passed through _bfd_merged_section_offset.  (Later, in
4039              relocate_section, all SEC_MERGE symbols *except* for
4040              section symbols have been adjusted.)
4041
4042              gas may reduce relocations against symbols in SEC_MERGE
4043              sections to a relocation against the section symbol when
4044              the original addend was zero.  When the reloc is against
4045              a section symbol we should include the addend in the
4046              offset passed to _bfd_merged_section_offset, since the
4047              location of interest is the original symbol.  On the
4048              other hand, an access to "sym+addend" where "sym" is not
4049              a section symbol should not include the addend;  Such an
4050              access is presumed to be an offset from "sym";  The
4051              location of interest is just "sym".  */
4052            if (symtype == STT_SECTION)
4053              symval += rel->r_addend;
4054
4055            symval = _bfd_merged_section_offset (abfd, &sym_sec,
4056                                                 elf_section_data (sym_sec)->sec_info,
4057                                                 symval);
4058
4059            if (symtype != STT_SECTION)
4060              symval += rel->r_addend;
4061         }
4062       else
4063         symval += rel->r_addend;
4064
4065       symval += sec_addr (sym_sec);
4066
4067       if (!relax_func (abfd, sec, sym_sec, info, rel, symval,
4068                        max_alignment, reserve_size, again,
4069                        &pcgp_relocs))
4070         goto fail;
4071     }
4072
4073   ret = TRUE;
4074
4075 fail:
4076   if (relocs != data->relocs)
4077     free (relocs);
4078   riscv_free_pcgp_relocs(&pcgp_relocs, abfd, sec);
4079
4080   return ret;
4081 }
4082
4083 #if ARCH_SIZE == 32
4084 # define PRSTATUS_SIZE                  204
4085 # define PRSTATUS_OFFSET_PR_CURSIG      12
4086 # define PRSTATUS_OFFSET_PR_PID         24
4087 # define PRSTATUS_OFFSET_PR_REG         72
4088 # define ELF_GREGSET_T_SIZE             128
4089 # define PRPSINFO_SIZE                  128
4090 # define PRPSINFO_OFFSET_PR_PID         16
4091 # define PRPSINFO_OFFSET_PR_FNAME       32
4092 # define PRPSINFO_OFFSET_PR_PSARGS      48
4093 #else
4094 # define PRSTATUS_SIZE                  376
4095 # define PRSTATUS_OFFSET_PR_CURSIG      12
4096 # define PRSTATUS_OFFSET_PR_PID         32
4097 # define PRSTATUS_OFFSET_PR_REG         112
4098 # define ELF_GREGSET_T_SIZE             256
4099 # define PRPSINFO_SIZE                  136
4100 # define PRPSINFO_OFFSET_PR_PID         24
4101 # define PRPSINFO_OFFSET_PR_FNAME       40
4102 # define PRPSINFO_OFFSET_PR_PSARGS      56
4103 #endif
4104
4105 /* Support for core dump NOTE sections.  */
4106
4107 static bfd_boolean
4108 riscv_elf_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
4109 {
4110   switch (note->descsz)
4111     {
4112       default:
4113         return FALSE;
4114
4115       case PRSTATUS_SIZE:  /* sizeof(struct elf_prstatus) on Linux/RISC-V.  */
4116         /* pr_cursig */
4117         elf_tdata (abfd)->core->signal
4118           = bfd_get_16 (abfd, note->descdata + PRSTATUS_OFFSET_PR_CURSIG);
4119
4120         /* pr_pid */
4121         elf_tdata (abfd)->core->lwpid
4122           = bfd_get_32 (abfd, note->descdata + PRSTATUS_OFFSET_PR_PID);
4123         break;
4124     }
4125
4126   /* Make a ".reg/999" section.  */
4127   return _bfd_elfcore_make_pseudosection (abfd, ".reg", ELF_GREGSET_T_SIZE,
4128                                           note->descpos + PRSTATUS_OFFSET_PR_REG);
4129 }
4130
4131 static bfd_boolean
4132 riscv_elf_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
4133 {
4134   switch (note->descsz)
4135     {
4136       default:
4137         return FALSE;
4138
4139       case PRPSINFO_SIZE: /* sizeof(struct elf_prpsinfo) on Linux/RISC-V.  */
4140         /* pr_pid */
4141         elf_tdata (abfd)->core->pid
4142           = bfd_get_32 (abfd, note->descdata + PRPSINFO_OFFSET_PR_PID);
4143
4144         /* pr_fname */
4145         elf_tdata (abfd)->core->program = _bfd_elfcore_strndup
4146           (abfd, note->descdata + PRPSINFO_OFFSET_PR_FNAME, 16);
4147
4148         /* pr_psargs */
4149         elf_tdata (abfd)->core->command = _bfd_elfcore_strndup
4150           (abfd, note->descdata + PRPSINFO_OFFSET_PR_PSARGS, 80);
4151         break;
4152     }
4153
4154   /* Note that for some reason, a spurious space is tacked
4155      onto the end of the args in some (at least one anyway)
4156      implementations, so strip it off if it exists.  */
4157
4158   {
4159     char *command = elf_tdata (abfd)->core->command;
4160     int n = strlen (command);
4161
4162     if (0 < n && command[n - 1] == ' ')
4163       command[n - 1] = '\0';
4164   }
4165
4166   return TRUE;
4167 }
4168
4169 /* Set the right mach type.  */
4170 static bfd_boolean
4171 riscv_elf_object_p (bfd *abfd)
4172 {
4173   /* There are only two mach types in RISCV currently.  */
4174   if (strcmp (abfd->xvec->name, "elf32-littleriscv") == 0)
4175     bfd_default_set_arch_mach (abfd, bfd_arch_riscv, bfd_mach_riscv32);
4176   else
4177     bfd_default_set_arch_mach (abfd, bfd_arch_riscv, bfd_mach_riscv64);
4178
4179   return TRUE;
4180 }
4181
4182 /* Determine whether an object attribute tag takes an integer, a
4183    string or both.  */
4184
4185 static int
4186 riscv_elf_obj_attrs_arg_type (int tag)
4187 {
4188   return (tag & 1) != 0 ? ATTR_TYPE_FLAG_STR_VAL : ATTR_TYPE_FLAG_INT_VAL;
4189 }
4190
4191 #define TARGET_LITTLE_SYM               riscv_elfNN_vec
4192 #define TARGET_LITTLE_NAME              "elfNN-littleriscv"
4193
4194 #define elf_backend_reloc_type_class         riscv_reloc_type_class
4195
4196 #define bfd_elfNN_bfd_reloc_name_lookup      riscv_reloc_name_lookup
4197 #define bfd_elfNN_bfd_link_hash_table_create riscv_elf_link_hash_table_create
4198 #define bfd_elfNN_bfd_reloc_type_lookup      riscv_reloc_type_lookup
4199 #define bfd_elfNN_bfd_merge_private_bfd_data \
4200   _bfd_riscv_elf_merge_private_bfd_data
4201
4202 #define elf_backend_copy_indirect_symbol     riscv_elf_copy_indirect_symbol
4203 #define elf_backend_create_dynamic_sections  riscv_elf_create_dynamic_sections
4204 #define elf_backend_check_relocs             riscv_elf_check_relocs
4205 #define elf_backend_adjust_dynamic_symbol    riscv_elf_adjust_dynamic_symbol
4206 #define elf_backend_size_dynamic_sections    riscv_elf_size_dynamic_sections
4207 #define elf_backend_relocate_section         riscv_elf_relocate_section
4208 #define elf_backend_finish_dynamic_symbol    riscv_elf_finish_dynamic_symbol
4209 #define elf_backend_finish_dynamic_sections  riscv_elf_finish_dynamic_sections
4210 #define elf_backend_gc_mark_hook             riscv_elf_gc_mark_hook
4211 #define elf_backend_plt_sym_val              riscv_elf_plt_sym_val
4212 #define elf_backend_grok_prstatus            riscv_elf_grok_prstatus
4213 #define elf_backend_grok_psinfo              riscv_elf_grok_psinfo
4214 #define elf_backend_object_p                 riscv_elf_object_p
4215 #define elf_info_to_howto_rel                NULL
4216 #define elf_info_to_howto                    riscv_info_to_howto_rela
4217 #define bfd_elfNN_bfd_relax_section          _bfd_riscv_relax_section
4218
4219 #define elf_backend_init_index_section       _bfd_elf_init_1_index_section
4220
4221 #define elf_backend_can_gc_sections     1
4222 #define elf_backend_can_refcount        1
4223 #define elf_backend_want_got_plt        1
4224 #define elf_backend_plt_readonly        1
4225 #define elf_backend_plt_alignment       4
4226 #define elf_backend_want_plt_sym        1
4227 #define elf_backend_got_header_size     (ARCH_SIZE / 8)
4228 #define elf_backend_want_dynrelro       1
4229 #define elf_backend_rela_normal         1
4230 #define elf_backend_default_execstack   0
4231
4232 #undef  elf_backend_obj_attrs_vendor
4233 #define elf_backend_obj_attrs_vendor            "riscv"
4234 #undef  elf_backend_obj_attrs_arg_type
4235 #define elf_backend_obj_attrs_arg_type          riscv_elf_obj_attrs_arg_type
4236 #undef  elf_backend_obj_attrs_section_type
4237 #define elf_backend_obj_attrs_section_type      SHT_RISCV_ATTRIBUTES
4238 #undef  elf_backend_obj_attrs_section
4239 #define elf_backend_obj_attrs_section           ".riscv.attributes"
4240
4241 #include "elfNN-target.h"