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