Patch for PR gold/19042 - unsupported reloc 311/312.
[external/binutils.git] / gold / aarch64.cc
1 // aarch64.cc -- aarch64 target support for gold.
2
3 // Copyright (C) 2014-2015 Free Software Foundation, Inc.
4 // Written by Jing Yu <jingyu@google.com> and Han Shen <shenhan@google.com>.
5
6 // This file is part of gold.
7
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 3 of the License, or
11 // (at your option) any later version.
12
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 // MA 02110-1301, USA.
22
23 #include "gold.h"
24
25 #include <cstring>
26 #include <map>
27 #include <set>
28
29 #include "elfcpp.h"
30 #include "dwarf.h"
31 #include "parameters.h"
32 #include "reloc.h"
33 #include "aarch64.h"
34 #include "object.h"
35 #include "symtab.h"
36 #include "layout.h"
37 #include "output.h"
38 #include "copy-relocs.h"
39 #include "target.h"
40 #include "target-reloc.h"
41 #include "target-select.h"
42 #include "tls.h"
43 #include "freebsd.h"
44 #include "nacl.h"
45 #include "gc.h"
46 #include "icf.h"
47 #include "aarch64-reloc-property.h"
48
49 // The first three .got.plt entries are reserved.
50 const int32_t AARCH64_GOTPLT_RESERVE_COUNT = 3;
51
52
53 namespace
54 {
55
56 using namespace gold;
57
58 template<int size, bool big_endian>
59 class Output_data_plt_aarch64;
60
61 template<int size, bool big_endian>
62 class Output_data_plt_aarch64_standard;
63
64 template<int size, bool big_endian>
65 class Target_aarch64;
66
67 template<int size, bool big_endian>
68 class AArch64_relocate_functions;
69
70 // Utility class dealing with insns. This is ported from macros in
71 // bfd/elfnn-aarch64.cc, but wrapped inside a class as static members. This
72 // class is used in erratum sequence scanning.
73
74 template<bool big_endian>
75 class AArch64_insn_utilities
76 {
77 public:
78   typedef typename elfcpp::Swap<32, big_endian>::Valtype Insntype;
79
80   static const int BYTES_PER_INSN;
81
82   // Zero register encoding - 31.
83   static const unsigned int AARCH64_ZR;
84
85   static unsigned int
86   aarch64_bit(Insntype insn, int pos)
87   { return ((1 << pos)  & insn) >> pos; }
88
89   static unsigned int
90   aarch64_bits(Insntype insn, int pos, int l)
91   { return (insn >> pos) & ((1 << l) - 1); }
92
93   // Get the encoding field "op31" of 3-source data processing insns. "op31" is
94   // the name defined in armv8 insn manual C3.5.9.
95   static unsigned int
96   aarch64_op31(Insntype insn)
97   { return aarch64_bits(insn, 21, 3); }
98
99   // Get the encoding field "ra" of 3-source data processing insns. "ra" is the
100   // third source register. See armv8 insn manual C3.5.9.
101   static unsigned int
102   aarch64_ra(Insntype insn)
103   { return aarch64_bits(insn, 10, 5); }
104
105   static bool
106   is_adr(const Insntype insn)
107   { return (insn & 0x9F000000) == 0x10000000; }
108
109   static bool
110   is_adrp(const Insntype insn)
111   { return (insn & 0x9F000000) == 0x90000000; }
112
113   static unsigned int
114   aarch64_rm(const Insntype insn)
115   { return aarch64_bits(insn, 16, 5); }
116
117   static unsigned int
118   aarch64_rn(const Insntype insn)
119   { return aarch64_bits(insn, 5, 5); }
120
121   static unsigned int
122   aarch64_rd(const Insntype insn)
123   { return aarch64_bits(insn, 0, 5); }
124
125   static unsigned int
126   aarch64_rt(const Insntype insn)
127   { return aarch64_bits(insn, 0, 5); }
128
129   static unsigned int
130   aarch64_rt2(const Insntype insn)
131   { return aarch64_bits(insn, 10, 5); }
132
133   // Encode imm21 into adr. Signed imm21 is in the range of [-1M, 1M).
134   static Insntype
135   aarch64_adr_encode_imm(Insntype adr, int imm21)
136   {
137     gold_assert(is_adr(adr));
138     gold_assert(-(1 << 20) <= imm21 && imm21 < (1 << 20));
139     const int mask19 = (1 << 19) - 1;
140     const int mask2 = 3;
141     adr &= ~((mask19 << 5) | (mask2 << 29));
142     adr |= ((imm21 & mask2) << 29) | (((imm21 >> 2) & mask19) << 5);
143     return adr;
144   }
145
146   // Retrieve encoded adrp 33-bit signed imm value. This value is obtained by
147   // 21-bit signed imm encoded in the insn multiplied by 4k (page size) and
148   // 64-bit sign-extended, resulting in [-4G, 4G) with 12-lsb being 0.
149   static int64_t
150   aarch64_adrp_decode_imm(const Insntype adrp)
151   {
152     const int mask19 = (1 << 19) - 1;
153     const int mask2 = 3;
154     gold_assert(is_adrp(adrp));
155     // 21-bit imm encoded in adrp.
156     uint64_t imm = ((adrp >> 29) & mask2) | (((adrp >> 5) & mask19) << 2);
157     // Retrieve msb of 21-bit-signed imm for sign extension.
158     uint64_t msbt = (imm >> 20) & 1;
159     // Real value is imm multipled by 4k. Value now has 33-bit information.
160     int64_t value = imm << 12;
161     // Sign extend to 64-bit by repeating msbt 31 (64-33) times and merge it
162     // with value.
163     return ((((uint64_t)(1) << 32) - msbt) << 33) | value;
164   }
165
166   static bool
167   aarch64_b(const Insntype insn)
168   { return (insn & 0xFC000000) == 0x14000000; }
169
170   static bool
171   aarch64_bl(const Insntype insn)
172   { return (insn & 0xFC000000) == 0x94000000; }
173
174   static bool
175   aarch64_blr(const Insntype insn)
176   { return (insn & 0xFFFFFC1F) == 0xD63F0000; }
177
178   static bool
179   aarch64_br(const Insntype insn)
180   { return (insn & 0xFFFFFC1F) == 0xD61F0000; }
181
182   // All ld/st ops.  See C4-182 of the ARM ARM.  The encoding space for
183   // LD_PCREL, LDST_RO, LDST_UI and LDST_UIMM cover prefetch ops.
184   static bool
185   aarch64_ld(Insntype insn) { return aarch64_bit(insn, 22) == 1; }
186
187   static bool
188   aarch64_ldst(Insntype insn)
189   { return (insn & 0x0a000000) == 0x08000000; }
190
191   static bool
192   aarch64_ldst_ex(Insntype insn)
193   { return (insn & 0x3f000000) == 0x08000000; }
194
195   static bool
196   aarch64_ldst_pcrel(Insntype insn)
197   { return (insn & 0x3b000000) == 0x18000000; }
198
199   static bool
200   aarch64_ldst_nap(Insntype insn)
201   { return (insn & 0x3b800000) == 0x28000000; }
202
203   static bool
204   aarch64_ldstp_pi(Insntype insn)
205   { return (insn & 0x3b800000) == 0x28800000; }
206
207   static bool
208   aarch64_ldstp_o(Insntype insn)
209   { return (insn & 0x3b800000) == 0x29000000; }
210
211   static bool
212   aarch64_ldstp_pre(Insntype insn)
213   { return (insn & 0x3b800000) == 0x29800000; }
214
215   static bool
216   aarch64_ldst_ui(Insntype insn)
217   { return (insn & 0x3b200c00) == 0x38000000; }
218
219   static bool
220   aarch64_ldst_piimm(Insntype insn)
221   { return (insn & 0x3b200c00) == 0x38000400; }
222
223   static bool
224   aarch64_ldst_u(Insntype insn)
225   { return (insn & 0x3b200c00) == 0x38000800; }
226
227   static bool
228   aarch64_ldst_preimm(Insntype insn)
229   { return (insn & 0x3b200c00) == 0x38000c00; }
230
231   static bool
232   aarch64_ldst_ro(Insntype insn)
233   { return (insn & 0x3b200c00) == 0x38200800; }
234
235   static bool
236   aarch64_ldst_uimm(Insntype insn)
237   { return (insn & 0x3b000000) == 0x39000000; }
238
239   static bool
240   aarch64_ldst_simd_m(Insntype insn)
241   { return (insn & 0xbfbf0000) == 0x0c000000; }
242
243   static bool
244   aarch64_ldst_simd_m_pi(Insntype insn)
245   { return (insn & 0xbfa00000) == 0x0c800000; }
246
247   static bool
248   aarch64_ldst_simd_s(Insntype insn)
249   { return (insn & 0xbf9f0000) == 0x0d000000; }
250
251   static bool
252   aarch64_ldst_simd_s_pi(Insntype insn)
253   { return (insn & 0xbf800000) == 0x0d800000; }
254
255   // Classify an INSN if it is indeed a load/store. Return true if INSN is a
256   // LD/ST instruction otherwise return false. For scalar LD/ST instructions
257   // PAIR is FALSE, RT is returned and RT2 is set equal to RT. For LD/ST pair
258   // instructions PAIR is TRUE, RT and RT2 are returned.
259   static bool
260   aarch64_mem_op_p(Insntype insn, unsigned int *rt, unsigned int *rt2,
261                    bool *pair, bool *load)
262   {
263     uint32_t opcode;
264     unsigned int r;
265     uint32_t opc = 0;
266     uint32_t v = 0;
267     uint32_t opc_v = 0;
268
269     /* Bail out quickly if INSN doesn't fall into the the load-store
270        encoding space.  */
271     if (!aarch64_ldst (insn))
272       return false;
273
274     *pair = false;
275     *load = false;
276     if (aarch64_ldst_ex (insn))
277       {
278         *rt = aarch64_rt (insn);
279         *rt2 = *rt;
280         if (aarch64_bit (insn, 21) == 1)
281           {
282             *pair = true;
283             *rt2 = aarch64_rt2 (insn);
284           }
285         *load = aarch64_ld (insn);
286         return true;
287       }
288     else if (aarch64_ldst_nap (insn)
289              || aarch64_ldstp_pi (insn)
290              || aarch64_ldstp_o (insn)
291              || aarch64_ldstp_pre (insn))
292       {
293         *pair = true;
294         *rt = aarch64_rt (insn);
295         *rt2 = aarch64_rt2 (insn);
296         *load = aarch64_ld (insn);
297         return true;
298       }
299     else if (aarch64_ldst_pcrel (insn)
300              || aarch64_ldst_ui (insn)
301              || aarch64_ldst_piimm (insn)
302              || aarch64_ldst_u (insn)
303              || aarch64_ldst_preimm (insn)
304              || aarch64_ldst_ro (insn)
305              || aarch64_ldst_uimm (insn))
306       {
307         *rt = aarch64_rt (insn);
308         *rt2 = *rt;
309         if (aarch64_ldst_pcrel (insn))
310           *load = true;
311         opc = aarch64_bits (insn, 22, 2);
312         v = aarch64_bit (insn, 26);
313         opc_v = opc | (v << 2);
314         *load =  (opc_v == 1 || opc_v == 2 || opc_v == 3
315                   || opc_v == 5 || opc_v == 7);
316         return true;
317       }
318     else if (aarch64_ldst_simd_m (insn)
319              || aarch64_ldst_simd_m_pi (insn))
320       {
321         *rt = aarch64_rt (insn);
322         *load = aarch64_bit (insn, 22);
323         opcode = (insn >> 12) & 0xf;
324         switch (opcode)
325           {
326           case 0:
327           case 2:
328             *rt2 = *rt + 3;
329             break;
330
331           case 4:
332           case 6:
333             *rt2 = *rt + 2;
334             break;
335
336           case 7:
337             *rt2 = *rt;
338             break;
339
340           case 8:
341           case 10:
342             *rt2 = *rt + 1;
343             break;
344
345           default:
346             return false;
347           }
348         return true;
349       }
350     else if (aarch64_ldst_simd_s (insn)
351              || aarch64_ldst_simd_s_pi (insn))
352       {
353         *rt = aarch64_rt (insn);
354         r = (insn >> 21) & 1;
355         *load = aarch64_bit (insn, 22);
356         opcode = (insn >> 13) & 0x7;
357         switch (opcode)
358           {
359           case 0:
360           case 2:
361           case 4:
362             *rt2 = *rt + r;
363             break;
364
365           case 1:
366           case 3:
367           case 5:
368             *rt2 = *rt + (r == 0 ? 2 : 3);
369             break;
370
371           case 6:
372             *rt2 = *rt + r;
373             break;
374
375           case 7:
376             *rt2 = *rt + (r == 0 ? 2 : 3);
377             break;
378
379           default:
380             return false;
381           }
382         return true;
383       }
384     return false;
385   }  // End of "aarch64_mem_op_p".
386
387   // Return true if INSN is mac insn.
388   static bool
389   aarch64_mac(Insntype insn)
390   { return (insn & 0xff000000) == 0x9b000000; }
391
392   // Return true if INSN is multiply-accumulate.
393   // (This is similar to implementaton in elfnn-aarch64.c.)
394   static bool
395   aarch64_mlxl(Insntype insn)
396   {
397     uint32_t op31 = aarch64_op31(insn);
398     if (aarch64_mac(insn)
399         && (op31 == 0 || op31 == 1 || op31 == 5)
400         /* Exclude MUL instructions which are encoded as a multiple-accumulate
401            with RA = XZR.  */
402         && aarch64_ra(insn) != AARCH64_ZR)
403       {
404         return true;
405       }
406     return false;
407   }
408 };  // End of "AArch64_insn_utilities".
409
410
411 // Insn length in byte.
412
413 template<bool big_endian>
414 const int AArch64_insn_utilities<big_endian>::BYTES_PER_INSN = 4;
415
416
417 // Zero register encoding - 31.
418
419 template<bool big_endian>
420 const unsigned int AArch64_insn_utilities<big_endian>::AARCH64_ZR = 0x1f;
421
422
423 // Output_data_got_aarch64 class.
424
425 template<int size, bool big_endian>
426 class Output_data_got_aarch64 : public Output_data_got<size, big_endian>
427 {
428  public:
429   typedef typename elfcpp::Elf_types<size>::Elf_Addr Valtype;
430   Output_data_got_aarch64(Symbol_table* symtab, Layout* layout)
431     : Output_data_got<size, big_endian>(),
432       symbol_table_(symtab), layout_(layout)
433   { }
434
435   // Add a static entry for the GOT entry at OFFSET.  GSYM is a global
436   // symbol and R_TYPE is the code of a dynamic relocation that needs to be
437   // applied in a static link.
438   void
439   add_static_reloc(unsigned int got_offset, unsigned int r_type, Symbol* gsym)
440   { this->static_relocs_.push_back(Static_reloc(got_offset, r_type, gsym)); }
441
442
443   // Add a static reloc for the GOT entry at OFFSET.  RELOBJ is an object
444   // defining a local symbol with INDEX.  R_TYPE is the code of a dynamic
445   // relocation that needs to be applied in a static link.
446   void
447   add_static_reloc(unsigned int got_offset, unsigned int r_type,
448                    Sized_relobj_file<size, big_endian>* relobj,
449                    unsigned int index)
450   {
451     this->static_relocs_.push_back(Static_reloc(got_offset, r_type, relobj,
452                                                 index));
453   }
454
455
456  protected:
457   // Write out the GOT table.
458   void
459   do_write(Output_file* of) {
460     // The first entry in the GOT is the address of the .dynamic section.
461     gold_assert(this->data_size() >= size / 8);
462     Output_section* dynamic = this->layout_->dynamic_section();
463     Valtype dynamic_addr = dynamic == NULL ? 0 : dynamic->address();
464     this->replace_constant(0, dynamic_addr);
465     Output_data_got<size, big_endian>::do_write(of);
466
467     // Handling static relocs
468     if (this->static_relocs_.empty())
469       return;
470
471     typedef typename elfcpp::Elf_types<size>::Elf_Addr AArch64_address;
472
473     gold_assert(parameters->doing_static_link());
474     const off_t offset = this->offset();
475     const section_size_type oview_size =
476       convert_to_section_size_type(this->data_size());
477     unsigned char* const oview = of->get_output_view(offset, oview_size);
478
479     Output_segment* tls_segment = this->layout_->tls_segment();
480     gold_assert(tls_segment != NULL);
481
482     AArch64_address aligned_tcb_address =
483       align_address(Target_aarch64<size, big_endian>::TCB_SIZE,
484                     tls_segment->maximum_alignment());
485
486     for (size_t i = 0; i < this->static_relocs_.size(); ++i)
487       {
488         Static_reloc& reloc(this->static_relocs_[i]);
489         AArch64_address value;
490
491         if (!reloc.symbol_is_global())
492           {
493             Sized_relobj_file<size, big_endian>* object = reloc.relobj();
494             const Symbol_value<size>* psymval =
495               reloc.relobj()->local_symbol(reloc.index());
496
497             // We are doing static linking.  Issue an error and skip this
498             // relocation if the symbol is undefined or in a discarded_section.
499             bool is_ordinary;
500             unsigned int shndx = psymval->input_shndx(&is_ordinary);
501             if ((shndx == elfcpp::SHN_UNDEF)
502                 || (is_ordinary
503                     && shndx != elfcpp::SHN_UNDEF
504                     && !object->is_section_included(shndx)
505                     && !this->symbol_table_->is_section_folded(object, shndx)))
506               {
507                 gold_error(_("undefined or discarded local symbol %u from "
508                              " object %s in GOT"),
509                            reloc.index(), reloc.relobj()->name().c_str());
510                 continue;
511               }
512             value = psymval->value(object, 0);
513           }
514         else
515           {
516             const Symbol* gsym = reloc.symbol();
517             gold_assert(gsym != NULL);
518             if (gsym->is_forwarder())
519               gsym = this->symbol_table_->resolve_forwards(gsym);
520
521             // We are doing static linking.  Issue an error and skip this
522             // relocation if the symbol is undefined or in a discarded_section
523             // unless it is a weakly_undefined symbol.
524             if ((gsym->is_defined_in_discarded_section()
525                  || gsym->is_undefined())
526                 && !gsym->is_weak_undefined())
527               {
528                 gold_error(_("undefined or discarded symbol %s in GOT"),
529                            gsym->name());
530                 continue;
531               }
532
533             if (!gsym->is_weak_undefined())
534               {
535                 const Sized_symbol<size>* sym =
536                   static_cast<const Sized_symbol<size>*>(gsym);
537                 value = sym->value();
538               }
539             else
540               value = 0;
541           }
542
543         unsigned got_offset = reloc.got_offset();
544         gold_assert(got_offset < oview_size);
545
546         typedef typename elfcpp::Swap<size, big_endian>::Valtype Valtype;
547         Valtype* wv = reinterpret_cast<Valtype*>(oview + got_offset);
548         Valtype x;
549         switch (reloc.r_type())
550           {
551           case elfcpp::R_AARCH64_TLS_DTPREL64:
552             x = value;
553             break;
554           case elfcpp::R_AARCH64_TLS_TPREL64:
555             x = value + aligned_tcb_address;
556             break;
557           default:
558             gold_unreachable();
559           }
560         elfcpp::Swap<size, big_endian>::writeval(wv, x);
561       }
562
563     of->write_output_view(offset, oview_size, oview);
564   }
565
566  private:
567   // Symbol table of the output object.
568   Symbol_table* symbol_table_;
569   // A pointer to the Layout class, so that we can find the .dynamic
570   // section when we write out the GOT section.
571   Layout* layout_;
572
573   // This class represent dynamic relocations that need to be applied by
574   // gold because we are using TLS relocations in a static link.
575   class Static_reloc
576   {
577    public:
578     Static_reloc(unsigned int got_offset, unsigned int r_type, Symbol* gsym)
579       : got_offset_(got_offset), r_type_(r_type), symbol_is_global_(true)
580     { this->u_.global.symbol = gsym; }
581
582     Static_reloc(unsigned int got_offset, unsigned int r_type,
583           Sized_relobj_file<size, big_endian>* relobj, unsigned int index)
584       : got_offset_(got_offset), r_type_(r_type), symbol_is_global_(false)
585     {
586       this->u_.local.relobj = relobj;
587       this->u_.local.index = index;
588     }
589
590     // Return the GOT offset.
591     unsigned int
592     got_offset() const
593     { return this->got_offset_; }
594
595     // Relocation type.
596     unsigned int
597     r_type() const
598     { return this->r_type_; }
599
600     // Whether the symbol is global or not.
601     bool
602     symbol_is_global() const
603     { return this->symbol_is_global_; }
604
605     // For a relocation against a global symbol, the global symbol.
606     Symbol*
607     symbol() const
608     {
609       gold_assert(this->symbol_is_global_);
610       return this->u_.global.symbol;
611     }
612
613     // For a relocation against a local symbol, the defining object.
614     Sized_relobj_file<size, big_endian>*
615     relobj() const
616     {
617       gold_assert(!this->symbol_is_global_);
618       return this->u_.local.relobj;
619     }
620
621     // For a relocation against a local symbol, the local symbol index.
622     unsigned int
623     index() const
624     {
625       gold_assert(!this->symbol_is_global_);
626       return this->u_.local.index;
627     }
628
629    private:
630     // GOT offset of the entry to which this relocation is applied.
631     unsigned int got_offset_;
632     // Type of relocation.
633     unsigned int r_type_;
634     // Whether this relocation is against a global symbol.
635     bool symbol_is_global_;
636     // A global or local symbol.
637     union
638     {
639       struct
640       {
641         // For a global symbol, the symbol itself.
642         Symbol* symbol;
643       } global;
644       struct
645       {
646         // For a local symbol, the object defining the symbol.
647         Sized_relobj_file<size, big_endian>* relobj;
648         // For a local symbol, the symbol index.
649         unsigned int index;
650       } local;
651     } u_;
652   };  // End of inner class Static_reloc
653
654   std::vector<Static_reloc> static_relocs_;
655 };  // End of Output_data_got_aarch64
656
657
658 template<int size, bool big_endian>
659 class AArch64_input_section;
660
661
662 template<int size, bool big_endian>
663 class AArch64_output_section;
664
665
666 template<int size, bool big_endian>
667 class AArch64_relobj;
668
669
670 // Stub type enum constants.
671
672 enum
673 {
674   ST_NONE = 0,
675
676   // Using adrp/add pair, 4 insns (including alignment) without mem access,
677   // the fastest stub. This has a limited jump distance, which is tested by
678   // aarch64_valid_for_adrp_p.
679   ST_ADRP_BRANCH = 1,
680
681   // Using ldr-absolute-address/br-register, 4 insns with 1 mem access,
682   // unlimited in jump distance.
683   ST_LONG_BRANCH_ABS = 2,
684
685   // Using ldr/calculate-pcrel/jump, 8 insns (including alignment) with 1
686   // mem access, slowest one. Only used in position independent executables.
687   ST_LONG_BRANCH_PCREL = 3,
688
689   // Stub for erratum 843419 handling.
690   ST_E_843419 = 4,
691
692   // Stub for erratum 835769 handling.
693   ST_E_835769 = 5,
694
695   // Number of total stub types.
696   ST_NUMBER = 6
697 };
698
699
700 // Struct that wraps insns for a particular stub. All stub templates are
701 // created/initialized as constants by Stub_template_repertoire.
702
703 template<bool big_endian>
704 struct Stub_template
705 {
706   const typename AArch64_insn_utilities<big_endian>::Insntype* insns;
707   const int insn_num;
708 };
709
710
711 // Simple singleton class that creates/initializes/stores all types of stub
712 // templates.
713
714 template<bool big_endian>
715 class Stub_template_repertoire
716 {
717 public:
718   typedef typename AArch64_insn_utilities<big_endian>::Insntype Insntype;
719
720   // Single static method to get stub template for a given stub type.
721   static const Stub_template<big_endian>*
722   get_stub_template(int type)
723   {
724     static Stub_template_repertoire<big_endian> singleton;
725     return singleton.stub_templates_[type];
726   }
727
728 private:
729   // Constructor - creates/initializes all stub templates.
730   Stub_template_repertoire();
731   ~Stub_template_repertoire()
732   { }
733
734   // Disallowing copy ctor and copy assignment operator.
735   Stub_template_repertoire(Stub_template_repertoire&);
736   Stub_template_repertoire& operator=(Stub_template_repertoire&);
737
738   // Data that stores all insn templates.
739   const Stub_template<big_endian>* stub_templates_[ST_NUMBER];
740 };  // End of "class Stub_template_repertoire".
741
742
743 // Constructor - creates/initilizes all stub templates.
744
745 template<bool big_endian>
746 Stub_template_repertoire<big_endian>::Stub_template_repertoire()
747 {
748   // Insn array definitions.
749   const static Insntype ST_NONE_INSNS[] = {};
750
751   const static Insntype ST_ADRP_BRANCH_INSNS[] =
752     {
753       0x90000010,       /*      adrp    ip0, X             */
754                         /*        ADR_PREL_PG_HI21(X)      */
755       0x91000210,       /*      add     ip0, ip0, :lo12:X  */
756                         /*        ADD_ABS_LO12_NC(X)       */
757       0xd61f0200,       /*      br      ip0                */
758       0x00000000,       /*      alignment padding          */
759     };
760
761   const static Insntype ST_LONG_BRANCH_ABS_INSNS[] =
762     {
763       0x58000050,       /*      ldr   ip0, 0x8             */
764       0xd61f0200,       /*      br    ip0                  */
765       0x00000000,       /*      address field              */
766       0x00000000,       /*      address fields             */
767     };
768
769   const static Insntype ST_LONG_BRANCH_PCREL_INSNS[] =
770     {
771       0x58000090,       /*      ldr   ip0, 0x10            */
772       0x10000011,       /*      adr   ip1, #0              */
773       0x8b110210,       /*      add   ip0, ip0, ip1        */
774       0xd61f0200,       /*      br    ip0                  */
775       0x00000000,       /*      address field              */
776       0x00000000,       /*      address field              */
777       0x00000000,       /*      alignment padding          */
778       0x00000000,       /*      alignment padding          */
779     };
780
781   const static Insntype ST_E_843419_INSNS[] =
782     {
783       0x00000000,    /* Placeholder for erratum insn. */
784       0x14000000,    /* b <label> */
785     };
786
787   // ST_E_835769 has the same stub template as ST_E_843419.
788   const static Insntype* ST_E_835769_INSNS = ST_E_843419_INSNS;
789
790 #define install_insn_template(T) \
791   const static Stub_template<big_endian> template_##T = {  \
792     T##_INSNS, sizeof(T##_INSNS) / sizeof(T##_INSNS[0]) }; \
793   this->stub_templates_[T] = &template_##T
794
795   install_insn_template(ST_NONE);
796   install_insn_template(ST_ADRP_BRANCH);
797   install_insn_template(ST_LONG_BRANCH_ABS);
798   install_insn_template(ST_LONG_BRANCH_PCREL);
799   install_insn_template(ST_E_843419);
800   install_insn_template(ST_E_835769);
801
802 #undef install_insn_template
803 }
804
805
806 // Base class for stubs.
807
808 template<int size, bool big_endian>
809 class Stub_base
810 {
811 public:
812   typedef typename elfcpp::Elf_types<size>::Elf_Addr AArch64_address;
813   typedef typename AArch64_insn_utilities<big_endian>::Insntype Insntype;
814
815   static const AArch64_address invalid_address =
816     static_cast<AArch64_address>(-1);
817
818   static const section_offset_type invalid_offset =
819     static_cast<section_offset_type>(-1);
820
821   Stub_base(int type)
822     : destination_address_(invalid_address),
823       offset_(invalid_offset),
824       type_(type)
825   {}
826
827   ~Stub_base()
828   {}
829
830   // Get stub type.
831   int
832   type() const
833   { return this->type_; }
834
835   // Get stub template that provides stub insn information.
836   const Stub_template<big_endian>*
837   stub_template() const
838   {
839     return Stub_template_repertoire<big_endian>::
840       get_stub_template(this->type());
841   }
842
843   // Get destination address.
844   AArch64_address
845   destination_address() const
846   {
847     gold_assert(this->destination_address_ != this->invalid_address);
848     return this->destination_address_;
849   }
850
851   // Set destination address.
852   void
853   set_destination_address(AArch64_address address)
854   {
855     gold_assert(address != this->invalid_address);
856     this->destination_address_ = address;
857   }
858
859   // Reset the destination address.
860   void
861   reset_destination_address()
862   { this->destination_address_ = this->invalid_address; }
863
864   // Get offset of code stub. For Reloc_stub, it is the offset from the
865   // beginning of its containing stub table; for Erratum_stub, it is the offset
866   // from the end of reloc_stubs.
867   section_offset_type
868   offset() const
869   {
870     gold_assert(this->offset_ != this->invalid_offset);
871     return this->offset_;
872   }
873
874   // Set stub offset.
875   void
876   set_offset(section_offset_type offset)
877   { this->offset_ = offset; }
878
879   // Return the stub insn.
880   const Insntype*
881   insns() const
882   { return this->stub_template()->insns; }
883
884   // Return num of stub insns.
885   unsigned int
886   insn_num() const
887   { return this->stub_template()->insn_num; }
888
889   // Get size of the stub.
890   int
891   stub_size() const
892   {
893     return this->insn_num() *
894       AArch64_insn_utilities<big_endian>::BYTES_PER_INSN;
895   }
896
897   // Write stub to output file.
898   void
899   write(unsigned char* view, section_size_type view_size)
900   { this->do_write(view, view_size); }
901
902 protected:
903   // Abstract method to be implemented by sub-classes.
904   virtual void
905   do_write(unsigned char*, section_size_type) = 0;
906
907 private:
908   // The last insn of a stub is a jump to destination insn. This field records
909   // the destination address.
910   AArch64_address destination_address_;
911   // The stub offset. Note this has difference interpretations between an
912   // Reloc_stub and an Erratum_stub. For Reloc_stub this is the offset from the
913   // beginning of the containing stub_table, whereas for Erratum_stub, this is
914   // the offset from the end of reloc_stubs.
915   section_offset_type offset_;
916   // Stub type.
917   const int type_;
918 };  // End of "Stub_base".
919
920
921 // Erratum stub class. An erratum stub differs from a reloc stub in that for
922 // each erratum occurrence, we generate an erratum stub. We never share erratum
923 // stubs, whereas for reloc stubs, different branches insns share a single reloc
924 // stub as long as the branch targets are the same. (More to the point, reloc
925 // stubs can be shared because they're used to reach a specific target, whereas
926 // erratum stubs branch back to the original control flow.)
927
928 template<int size, bool big_endian>
929 class Erratum_stub : public Stub_base<size, big_endian>
930 {
931 public:
932   typedef AArch64_relobj<size, big_endian> The_aarch64_relobj;
933   typedef typename elfcpp::Elf_types<size>::Elf_Addr AArch64_address;
934   typedef AArch64_insn_utilities<big_endian> Insn_utilities;
935   typedef typename AArch64_insn_utilities<big_endian>::Insntype Insntype;
936
937   static const int STUB_ADDR_ALIGN;
938
939   static const Insntype invalid_insn = static_cast<Insntype>(-1);
940
941   Erratum_stub(The_aarch64_relobj* relobj, int type,
942                unsigned shndx, unsigned int sh_offset)
943     : Stub_base<size, big_endian>(type), relobj_(relobj),
944       shndx_(shndx), sh_offset_(sh_offset),
945       erratum_insn_(invalid_insn),
946       erratum_address_(this->invalid_address)
947   {}
948
949   ~Erratum_stub() {}
950
951   // Return the object that contains the erratum.
952   The_aarch64_relobj*
953   relobj()
954   { return this->relobj_; }
955
956   // Get section index of the erratum.
957   unsigned int
958   shndx() const
959   { return this->shndx_; }
960
961   // Get section offset of the erratum.
962   unsigned int
963   sh_offset() const
964   { return this->sh_offset_; }
965
966   // Get the erratum insn. This is the insn located at erratum_insn_address.
967   Insntype
968   erratum_insn() const
969   {
970     gold_assert(this->erratum_insn_ != this->invalid_insn);
971     return this->erratum_insn_;
972   }
973
974   // Set the insn that the erratum happens to.
975   void
976   set_erratum_insn(Insntype insn)
977   { this->erratum_insn_ = insn; }
978
979   // For 843419, the erratum insn is ld/st xt, [xn, #uimm], which may be a
980   // relocation spot, in this case, the erratum_insn_ recorded at scanning phase
981   // is no longer the one we want to write out to the stub, update erratum_insn_
982   // with relocated version. Also note that in this case xn must not be "PC", so
983   // it is safe to move the erratum insn from the origin place to the stub. For
984   // 835769, the erratum insn is multiply-accumulate insn, which could not be a
985   // relocation spot (assertion added though).
986   void
987   update_erratum_insn(Insntype insn)
988   {
989     gold_assert(this->erratum_insn_ != this->invalid_insn);
990     switch (this->type())
991       {
992       case ST_E_843419:
993         gold_assert(Insn_utilities::aarch64_ldst_uimm(insn));
994         gold_assert(Insn_utilities::aarch64_ldst_uimm(this->erratum_insn()));
995         gold_assert(Insn_utilities::aarch64_rd(insn) ==
996                     Insn_utilities::aarch64_rd(this->erratum_insn()));
997         gold_assert(Insn_utilities::aarch64_rn(insn) ==
998                     Insn_utilities::aarch64_rn(this->erratum_insn()));
999         // Update plain ld/st insn with relocated insn.
1000         this->erratum_insn_ = insn;
1001         break;
1002       case ST_E_835769:
1003         gold_assert(insn == this->erratum_insn());
1004         break;
1005       default:
1006         gold_unreachable();
1007       }
1008   }
1009
1010
1011   // Return the address where an erratum must be done.
1012   AArch64_address
1013   erratum_address() const
1014   {
1015     gold_assert(this->erratum_address_ != this->invalid_address);
1016     return this->erratum_address_;
1017   }
1018
1019   // Set the address where an erratum must be done.
1020   void
1021   set_erratum_address(AArch64_address addr)
1022   { this->erratum_address_ = addr; }
1023
1024   // Comparator used to group Erratum_stubs in a set by (obj, shndx,
1025   // sh_offset). We do not include 'type' in the calculation, becuase there is
1026   // at most one stub type at (obj, shndx, sh_offset).
1027   bool
1028   operator<(const Erratum_stub<size, big_endian>& k) const
1029   {
1030     if (this == &k)
1031       return false;
1032     // We group stubs by relobj.
1033     if (this->relobj_ != k.relobj_)
1034       return this->relobj_ < k.relobj_;
1035     // Then by section index.
1036     if (this->shndx_ != k.shndx_)
1037       return this->shndx_ < k.shndx_;
1038     // Lastly by section offset.
1039     return this->sh_offset_ < k.sh_offset_;
1040   }
1041
1042 protected:
1043   virtual void
1044   do_write(unsigned char*, section_size_type);
1045
1046 private:
1047   // The object that needs to be fixed.
1048   The_aarch64_relobj* relobj_;
1049   // The shndx in the object that needs to be fixed.
1050   const unsigned int shndx_;
1051   // The section offset in the obejct that needs to be fixed.
1052   const unsigned int sh_offset_;
1053   // The insn to be fixed.
1054   Insntype erratum_insn_;
1055   // The address of the above insn.
1056   AArch64_address erratum_address_;
1057 };  // End of "Erratum_stub".
1058
1059
1060 // Erratum sub class to wrap additional info needed by 843419.  In fixing this
1061 // erratum, we may choose to replace 'adrp' with 'adr', in this case, we need
1062 // adrp's code position (two or three insns before erratum insn itself).
1063
1064 template<int size, bool big_endian>
1065 class E843419_stub : public Erratum_stub<size, big_endian>
1066 {
1067 public:
1068   typedef typename AArch64_insn_utilities<big_endian>::Insntype Insntype;
1069
1070   E843419_stub(AArch64_relobj<size, big_endian>* relobj,
1071                       unsigned int shndx, unsigned int sh_offset,
1072                       unsigned int adrp_sh_offset)
1073     : Erratum_stub<size, big_endian>(relobj, ST_E_843419, shndx, sh_offset),
1074       adrp_sh_offset_(adrp_sh_offset)
1075   {}
1076
1077   unsigned int
1078   adrp_sh_offset() const
1079   { return this->adrp_sh_offset_; }
1080
1081 private:
1082   // Section offset of "adrp". (We do not need a "adrp_shndx_" field, because we
1083   // can can obtain it from its parent.)
1084   const unsigned int adrp_sh_offset_;
1085 };
1086
1087
1088 template<int size, bool big_endian>
1089 const int Erratum_stub<size, big_endian>::STUB_ADDR_ALIGN = 4;
1090
1091 // Comparator used in set definition.
1092 template<int size, bool big_endian>
1093 struct Erratum_stub_less
1094 {
1095   bool
1096   operator()(const Erratum_stub<size, big_endian>* s1,
1097              const Erratum_stub<size, big_endian>* s2) const
1098   { return *s1 < *s2; }
1099 };
1100
1101 // Erratum_stub implementation for writing stub to output file.
1102
1103 template<int size, bool big_endian>
1104 void
1105 Erratum_stub<size, big_endian>::do_write(unsigned char* view, section_size_type)
1106 {
1107   typedef typename elfcpp::Swap<32, big_endian>::Valtype Insntype;
1108   const Insntype* insns = this->insns();
1109   uint32_t num_insns = this->insn_num();
1110   Insntype* ip = reinterpret_cast<Insntype*>(view);
1111   // For current implemented erratum 843419 and 835769, the first insn in the
1112   // stub is always a copy of the problematic insn (in 843419, the mem access
1113   // insn, in 835769, the mac insn), followed by a jump-back.
1114   elfcpp::Swap<32, big_endian>::writeval(ip, this->erratum_insn());
1115   for (uint32_t i = 1; i < num_insns; ++i)
1116     elfcpp::Swap<32, big_endian>::writeval(ip + i, insns[i]);
1117 }
1118
1119
1120 // Reloc stub class.
1121
1122 template<int size, bool big_endian>
1123 class Reloc_stub : public Stub_base<size, big_endian>
1124 {
1125  public:
1126   typedef Reloc_stub<size, big_endian> This;
1127   typedef typename elfcpp::Elf_types<size>::Elf_Addr AArch64_address;
1128
1129   // Branch range. This is used to calculate the section group size, as well as
1130   // determine whether a stub is needed.
1131   static const int MAX_BRANCH_OFFSET = ((1 << 25) - 1) << 2;
1132   static const int MIN_BRANCH_OFFSET = -((1 << 25) << 2);
1133
1134   // Constant used to determine if an offset fits in the adrp instruction
1135   // encoding.
1136   static const int MAX_ADRP_IMM = (1 << 20) - 1;
1137   static const int MIN_ADRP_IMM = -(1 << 20);
1138
1139   static const int BYTES_PER_INSN = 4;
1140   static const int STUB_ADDR_ALIGN;
1141
1142   // Determine whether the offset fits in the jump/branch instruction.
1143   static bool
1144   aarch64_valid_branch_offset_p(int64_t offset)
1145   { return offset >= MIN_BRANCH_OFFSET && offset <= MAX_BRANCH_OFFSET; }
1146
1147   // Determine whether the offset fits in the adrp immediate field.
1148   static bool
1149   aarch64_valid_for_adrp_p(AArch64_address location, AArch64_address dest)
1150   {
1151     typedef AArch64_relocate_functions<size, big_endian> Reloc;
1152     int64_t adrp_imm = (Reloc::Page(dest) - Reloc::Page(location)) >> 12;
1153     return adrp_imm >= MIN_ADRP_IMM && adrp_imm <= MAX_ADRP_IMM;
1154   }
1155
1156   // Determine the stub type for a certain relocation or ST_NONE, if no stub is
1157   // needed.
1158   static int
1159   stub_type_for_reloc(unsigned int r_type, AArch64_address address,
1160                       AArch64_address target);
1161
1162   Reloc_stub(int type)
1163     : Stub_base<size, big_endian>(type)
1164   { }
1165
1166   ~Reloc_stub()
1167   { }
1168
1169   // The key class used to index the stub instance in the stub table's stub map.
1170   class Key
1171   {
1172    public:
1173     Key(int type, const Symbol* symbol, const Relobj* relobj,
1174         unsigned int r_sym, int32_t addend)
1175       : type_(type), addend_(addend)
1176     {
1177       if (symbol != NULL)
1178         {
1179           this->r_sym_ = Reloc_stub::invalid_index;
1180           this->u_.symbol = symbol;
1181         }
1182       else
1183         {
1184           gold_assert(relobj != NULL && r_sym != invalid_index);
1185           this->r_sym_ = r_sym;
1186           this->u_.relobj = relobj;
1187         }
1188     }
1189
1190     ~Key()
1191     { }
1192
1193     // Return stub type.
1194     int
1195     type() const
1196     { return this->type_; }
1197
1198     // Return the local symbol index or invalid_index.
1199     unsigned int
1200     r_sym() const
1201     { return this->r_sym_; }
1202
1203     // Return the symbol if there is one.
1204     const Symbol*
1205     symbol() const
1206     { return this->r_sym_ == invalid_index ? this->u_.symbol : NULL; }
1207
1208     // Return the relobj if there is one.
1209     const Relobj*
1210     relobj() const
1211     { return this->r_sym_ != invalid_index ? this->u_.relobj : NULL; }
1212
1213     // Whether this equals to another key k.
1214     bool
1215     eq(const Key& k) const
1216     {
1217       return ((this->type_ == k.type_)
1218               && (this->r_sym_ == k.r_sym_)
1219               && ((this->r_sym_ != Reloc_stub::invalid_index)
1220                   ? (this->u_.relobj == k.u_.relobj)
1221                   : (this->u_.symbol == k.u_.symbol))
1222               && (this->addend_ == k.addend_));
1223     }
1224
1225     // Return a hash value.
1226     size_t
1227     hash_value() const
1228     {
1229       size_t name_hash_value = gold::string_hash<char>(
1230           (this->r_sym_ != Reloc_stub::invalid_index)
1231           ? this->u_.relobj->name().c_str()
1232           : this->u_.symbol->name());
1233       // We only have 4 stub types.
1234       size_t stub_type_hash_value = 0x03 & this->type_;
1235       return (name_hash_value
1236               ^ stub_type_hash_value
1237               ^ ((this->r_sym_ & 0x3fff) << 2)
1238               ^ ((this->addend_ & 0xffff) << 16));
1239     }
1240
1241     // Functors for STL associative containers.
1242     struct hash
1243     {
1244       size_t
1245       operator()(const Key& k) const
1246       { return k.hash_value(); }
1247     };
1248
1249     struct equal_to
1250     {
1251       bool
1252       operator()(const Key& k1, const Key& k2) const
1253       { return k1.eq(k2); }
1254     };
1255
1256    private:
1257     // Stub type.
1258     const int type_;
1259     // If this is a local symbol, this is the index in the defining object.
1260     // Otherwise, it is invalid_index for a global symbol.
1261     unsigned int r_sym_;
1262     // If r_sym_ is an invalid index, this points to a global symbol.
1263     // Otherwise, it points to a relobj.  We used the unsized and target
1264     // independent Symbol and Relobj classes instead of Sized_symbol<32> and
1265     // Arm_relobj, in order to avoid making the stub class a template
1266     // as most of the stub machinery is endianness-neutral.  However, it
1267     // may require a bit of casting done by users of this class.
1268     union
1269     {
1270       const Symbol* symbol;
1271       const Relobj* relobj;
1272     } u_;
1273     // Addend associated with a reloc.
1274     int32_t addend_;
1275   };  // End of inner class Reloc_stub::Key
1276
1277  protected:
1278   // This may be overridden in the child class.
1279   virtual void
1280   do_write(unsigned char*, section_size_type);
1281
1282  private:
1283   static const unsigned int invalid_index = static_cast<unsigned int>(-1);
1284 };  // End of Reloc_stub
1285
1286 template<int size, bool big_endian>
1287 const int Reloc_stub<size, big_endian>::STUB_ADDR_ALIGN = 4;
1288
1289 // Write data to output file.
1290
1291 template<int size, bool big_endian>
1292 void
1293 Reloc_stub<size, big_endian>::
1294 do_write(unsigned char* view, section_size_type)
1295 {
1296   typedef typename elfcpp::Swap<32, big_endian>::Valtype Insntype;
1297   const uint32_t* insns = this->insns();
1298   uint32_t num_insns = this->insn_num();
1299   Insntype* ip = reinterpret_cast<Insntype*>(view);
1300   for (uint32_t i = 0; i < num_insns; ++i)
1301     elfcpp::Swap<32, big_endian>::writeval(ip + i, insns[i]);
1302 }
1303
1304
1305 // Determine the stub type for a certain relocation or ST_NONE, if no stub is
1306 // needed.
1307
1308 template<int size, bool big_endian>
1309 inline int
1310 Reloc_stub<size, big_endian>::stub_type_for_reloc(
1311     unsigned int r_type, AArch64_address location, AArch64_address dest)
1312 {
1313   int64_t branch_offset = 0;
1314   switch(r_type)
1315     {
1316     case elfcpp::R_AARCH64_CALL26:
1317     case elfcpp::R_AARCH64_JUMP26:
1318       branch_offset = dest - location;
1319       break;
1320     default:
1321       gold_unreachable();
1322     }
1323
1324   if (aarch64_valid_branch_offset_p(branch_offset))
1325     return ST_NONE;
1326
1327   if (aarch64_valid_for_adrp_p(location, dest))
1328     return ST_ADRP_BRANCH;
1329
1330   if (parameters->options().output_is_position_independent()
1331       && parameters->options().output_is_executable())
1332     return ST_LONG_BRANCH_PCREL;
1333
1334   return ST_LONG_BRANCH_ABS;
1335 }
1336
1337 // A class to hold stubs for the ARM target.
1338
1339 template<int size, bool big_endian>
1340 class Stub_table : public Output_data
1341 {
1342  public:
1343   typedef Target_aarch64<size, big_endian> The_target_aarch64;
1344   typedef typename elfcpp::Elf_types<size>::Elf_Addr AArch64_address;
1345   typedef AArch64_relobj<size, big_endian> The_aarch64_relobj;
1346   typedef AArch64_input_section<size, big_endian> The_aarch64_input_section;
1347   typedef Reloc_stub<size, big_endian> The_reloc_stub;
1348   typedef typename The_reloc_stub::Key The_reloc_stub_key;
1349   typedef Erratum_stub<size, big_endian> The_erratum_stub;
1350   typedef Erratum_stub_less<size, big_endian> The_erratum_stub_less;
1351   typedef typename The_reloc_stub_key::hash The_reloc_stub_key_hash;
1352   typedef typename The_reloc_stub_key::equal_to The_reloc_stub_key_equal_to;
1353   typedef Stub_table<size, big_endian> The_stub_table;
1354   typedef Unordered_map<The_reloc_stub_key, The_reloc_stub*,
1355                         The_reloc_stub_key_hash, The_reloc_stub_key_equal_to>
1356                         Reloc_stub_map;
1357   typedef typename Reloc_stub_map::const_iterator Reloc_stub_map_const_iter;
1358   typedef Relocate_info<size, big_endian> The_relocate_info;
1359
1360   typedef std::set<The_erratum_stub*, The_erratum_stub_less> Erratum_stub_set;
1361   typedef typename Erratum_stub_set::iterator Erratum_stub_set_iter;
1362
1363   Stub_table(The_aarch64_input_section* owner)
1364     : Output_data(), owner_(owner), reloc_stubs_size_(0),
1365       erratum_stubs_size_(0), prev_data_size_(0)
1366   { }
1367
1368   ~Stub_table()
1369   { }
1370
1371   The_aarch64_input_section*
1372   owner() const
1373   { return owner_; }
1374
1375   // Whether this stub table is empty.
1376   bool
1377   empty() const
1378   { return reloc_stubs_.empty() && erratum_stubs_.empty(); }
1379
1380   // Return the current data size.
1381   off_t
1382   current_data_size() const
1383   { return this->current_data_size_for_child(); }
1384
1385   // Add a STUB using KEY.  The caller is responsible for avoiding addition
1386   // if a STUB with the same key has already been added.
1387   void
1388   add_reloc_stub(The_reloc_stub* stub, const The_reloc_stub_key& key);
1389
1390   // Add an erratum stub into the erratum stub set. The set is ordered by
1391   // (relobj, shndx, sh_offset).
1392   void
1393   add_erratum_stub(The_erratum_stub* stub);
1394
1395   // Find if such erratum exists for any given (obj, shndx, sh_offset).
1396   The_erratum_stub*
1397   find_erratum_stub(The_aarch64_relobj* a64relobj,
1398                     unsigned int shndx, unsigned int sh_offset);
1399
1400   // Find all the erratums for a given input section. The return value is a pair
1401   // of iterators [begin, end).
1402   std::pair<Erratum_stub_set_iter, Erratum_stub_set_iter>
1403   find_erratum_stubs_for_input_section(The_aarch64_relobj* a64relobj,
1404                                        unsigned int shndx);
1405
1406   // Compute the erratum stub address.
1407   AArch64_address
1408   erratum_stub_address(The_erratum_stub* stub) const
1409   {
1410     AArch64_address r = align_address(this->address() + this->reloc_stubs_size_,
1411                                       The_erratum_stub::STUB_ADDR_ALIGN);
1412     r += stub->offset();
1413     return r;
1414   }
1415
1416   // Finalize stubs. No-op here, just for completeness.
1417   void
1418   finalize_stubs()
1419   { }
1420
1421   // Look up a relocation stub using KEY. Return NULL if there is none.
1422   The_reloc_stub*
1423   find_reloc_stub(The_reloc_stub_key& key)
1424   {
1425     Reloc_stub_map_const_iter p = this->reloc_stubs_.find(key);
1426     return (p != this->reloc_stubs_.end()) ? p->second : NULL;
1427   }
1428
1429   // Relocate stubs in this stub table.
1430   void
1431   relocate_stubs(const The_relocate_info*,
1432                  The_target_aarch64*,
1433                  Output_section*,
1434                  unsigned char*,
1435                  AArch64_address,
1436                  section_size_type);
1437
1438   // Update data size at the end of a relaxation pass.  Return true if data size
1439   // is different from that of the previous relaxation pass.
1440   bool
1441   update_data_size_changed_p()
1442   {
1443     // No addralign changed here.
1444     off_t s = align_address(this->reloc_stubs_size_,
1445                             The_erratum_stub::STUB_ADDR_ALIGN)
1446               + this->erratum_stubs_size_;
1447     bool changed = (s != this->prev_data_size_);
1448     this->prev_data_size_ = s;
1449     return changed;
1450   }
1451
1452  protected:
1453   // Write out section contents.
1454   void
1455   do_write(Output_file*);
1456
1457   // Return the required alignment.
1458   uint64_t
1459   do_addralign() const
1460   {
1461     return std::max(The_reloc_stub::STUB_ADDR_ALIGN,
1462                     The_erratum_stub::STUB_ADDR_ALIGN);
1463   }
1464
1465   // Reset address and file offset.
1466   void
1467   do_reset_address_and_file_offset()
1468   { this->set_current_data_size_for_child(this->prev_data_size_); }
1469
1470   // Set final data size.
1471   void
1472   set_final_data_size()
1473   { this->set_data_size(this->current_data_size()); }
1474
1475  private:
1476   // Relocate one stub.
1477   void
1478   relocate_stub(The_reloc_stub*,
1479                 const The_relocate_info*,
1480                 The_target_aarch64*,
1481                 Output_section*,
1482                 unsigned char*,
1483                 AArch64_address,
1484                 section_size_type);
1485
1486  private:
1487   // Owner of this stub table.
1488   The_aarch64_input_section* owner_;
1489   // The relocation stubs.
1490   Reloc_stub_map reloc_stubs_;
1491   // The erratum stubs.
1492   Erratum_stub_set erratum_stubs_;
1493   // Size of reloc stubs.
1494   off_t reloc_stubs_size_;
1495   // Size of erratum stubs.
1496   off_t erratum_stubs_size_;
1497   // data size of this in the previous pass.
1498   off_t prev_data_size_;
1499 };  // End of Stub_table
1500
1501
1502 // Add an erratum stub into the erratum stub set. The set is ordered by
1503 // (relobj, shndx, sh_offset).
1504
1505 template<int size, bool big_endian>
1506 void
1507 Stub_table<size, big_endian>::add_erratum_stub(The_erratum_stub* stub)
1508 {
1509   std::pair<Erratum_stub_set_iter, bool> ret =
1510     this->erratum_stubs_.insert(stub);
1511   gold_assert(ret.second);
1512   this->erratum_stubs_size_ = align_address(
1513         this->erratum_stubs_size_, The_erratum_stub::STUB_ADDR_ALIGN);
1514   stub->set_offset(this->erratum_stubs_size_);
1515   this->erratum_stubs_size_ += stub->stub_size();
1516 }
1517
1518
1519 // Find if such erratum exists for given (obj, shndx, sh_offset).
1520
1521 template<int size, bool big_endian>
1522 Erratum_stub<size, big_endian>*
1523 Stub_table<size, big_endian>::find_erratum_stub(
1524     The_aarch64_relobj* a64relobj, unsigned int shndx, unsigned int sh_offset)
1525 {
1526   // A dummy object used as key to search in the set.
1527   The_erratum_stub key(a64relobj, ST_NONE,
1528                          shndx, sh_offset);
1529   Erratum_stub_set_iter i = this->erratum_stubs_.find(&key);
1530   if (i != this->erratum_stubs_.end())
1531     {
1532         The_erratum_stub* stub(*i);
1533         gold_assert(stub->erratum_insn() != 0);
1534         return stub;
1535     }
1536   return NULL;
1537 }
1538
1539
1540 // Find all the errata for a given input section. The return value is a pair of
1541 // iterators [begin, end).
1542
1543 template<int size, bool big_endian>
1544 std::pair<typename Stub_table<size, big_endian>::Erratum_stub_set_iter,
1545           typename Stub_table<size, big_endian>::Erratum_stub_set_iter>
1546 Stub_table<size, big_endian>::find_erratum_stubs_for_input_section(
1547     The_aarch64_relobj* a64relobj, unsigned int shndx)
1548 {
1549   typedef std::pair<Erratum_stub_set_iter, Erratum_stub_set_iter> Result_pair;
1550   Erratum_stub_set_iter start, end;
1551   The_erratum_stub low_key(a64relobj, ST_NONE, shndx, 0);
1552   start = this->erratum_stubs_.lower_bound(&low_key);
1553   if (start == this->erratum_stubs_.end())
1554     return Result_pair(this->erratum_stubs_.end(),
1555                        this->erratum_stubs_.end());
1556   end = start;
1557   while (end != this->erratum_stubs_.end() &&
1558          (*end)->relobj() == a64relobj && (*end)->shndx() == shndx)
1559     ++end;
1560   return Result_pair(start, end);
1561 }
1562
1563
1564 // Add a STUB using KEY.  The caller is responsible for avoiding addition
1565 // if a STUB with the same key has already been added.
1566
1567 template<int size, bool big_endian>
1568 void
1569 Stub_table<size, big_endian>::add_reloc_stub(
1570     The_reloc_stub* stub, const The_reloc_stub_key& key)
1571 {
1572   gold_assert(stub->type() == key.type());
1573   this->reloc_stubs_[key] = stub;
1574
1575   // Assign stub offset early.  We can do this because we never remove
1576   // reloc stubs and they are in the beginning of the stub table.
1577   this->reloc_stubs_size_ = align_address(this->reloc_stubs_size_,
1578                                           The_reloc_stub::STUB_ADDR_ALIGN);
1579   stub->set_offset(this->reloc_stubs_size_);
1580   this->reloc_stubs_size_ += stub->stub_size();
1581 }
1582
1583
1584 // Relocate all stubs in this stub table.
1585
1586 template<int size, bool big_endian>
1587 void
1588 Stub_table<size, big_endian>::
1589 relocate_stubs(const The_relocate_info* relinfo,
1590                The_target_aarch64* target_aarch64,
1591                Output_section* output_section,
1592                unsigned char* view,
1593                AArch64_address address,
1594                section_size_type view_size)
1595 {
1596   // "view_size" is the total size of the stub_table.
1597   gold_assert(address == this->address() &&
1598               view_size == static_cast<section_size_type>(this->data_size()));
1599   for(Reloc_stub_map_const_iter p = this->reloc_stubs_.begin();
1600       p != this->reloc_stubs_.end(); ++p)
1601     relocate_stub(p->second, relinfo, target_aarch64, output_section,
1602                   view, address, view_size);
1603
1604   // Just for convenience.
1605   const int BPI = AArch64_insn_utilities<big_endian>::BYTES_PER_INSN;
1606
1607   // Now 'relocate' erratum stubs.
1608   for(Erratum_stub_set_iter i = this->erratum_stubs_.begin();
1609       i != this->erratum_stubs_.end(); ++i)
1610     {
1611       AArch64_address stub_address = this->erratum_stub_address(*i);
1612       // The address of "b" in the stub that is to be "relocated".
1613       AArch64_address stub_b_insn_address;
1614       // Branch offset that is to be filled in "b" insn.
1615       int b_offset = 0;
1616       switch ((*i)->type())
1617         {
1618         case ST_E_843419:
1619         case ST_E_835769:
1620           // The 1st insn of the erratum could be a relocation spot,
1621           // in this case we need to fix it with
1622           // "(*i)->erratum_insn()".
1623           elfcpp::Swap<32, big_endian>::writeval(
1624               view + (stub_address - this->address()),
1625               (*i)->erratum_insn());
1626           // For the erratum, the 2nd insn is a b-insn to be patched
1627           // (relocated).
1628           stub_b_insn_address = stub_address + 1 * BPI;
1629           b_offset = (*i)->destination_address() - stub_b_insn_address;
1630           AArch64_relocate_functions<size, big_endian>::construct_b(
1631               view + (stub_b_insn_address - this->address()),
1632               ((unsigned int)(b_offset)) & 0xfffffff);
1633           break;
1634         default:
1635           gold_unreachable();
1636           break;
1637         }
1638     }
1639 }
1640
1641
1642 // Relocate one stub.  This is a helper for Stub_table::relocate_stubs().
1643
1644 template<int size, bool big_endian>
1645 void
1646 Stub_table<size, big_endian>::
1647 relocate_stub(The_reloc_stub* stub,
1648               const The_relocate_info* relinfo,
1649               The_target_aarch64* target_aarch64,
1650               Output_section* output_section,
1651               unsigned char* view,
1652               AArch64_address address,
1653               section_size_type view_size)
1654 {
1655   // "offset" is the offset from the beginning of the stub_table.
1656   section_size_type offset = stub->offset();
1657   section_size_type stub_size = stub->stub_size();
1658   // "view_size" is the total size of the stub_table.
1659   gold_assert(offset + stub_size <= view_size);
1660
1661   target_aarch64->relocate_stub(stub, relinfo, output_section,
1662                                 view + offset, address + offset, view_size);
1663 }
1664
1665
1666 // Write out the stubs to file.
1667
1668 template<int size, bool big_endian>
1669 void
1670 Stub_table<size, big_endian>::do_write(Output_file* of)
1671 {
1672   off_t offset = this->offset();
1673   const section_size_type oview_size =
1674     convert_to_section_size_type(this->data_size());
1675   unsigned char* const oview = of->get_output_view(offset, oview_size);
1676
1677   // Write relocation stubs.
1678   for (typename Reloc_stub_map::const_iterator p = this->reloc_stubs_.begin();
1679       p != this->reloc_stubs_.end(); ++p)
1680     {
1681       The_reloc_stub* stub = p->second;
1682       AArch64_address address = this->address() + stub->offset();
1683       gold_assert(address ==
1684                   align_address(address, The_reloc_stub::STUB_ADDR_ALIGN));
1685       stub->write(oview + stub->offset(), stub->stub_size());
1686     }
1687
1688   // Write erratum stubs.
1689   unsigned int erratum_stub_start_offset =
1690     align_address(this->reloc_stubs_size_, The_erratum_stub::STUB_ADDR_ALIGN);
1691   for (typename Erratum_stub_set::iterator p = this->erratum_stubs_.begin();
1692        p != this->erratum_stubs_.end(); ++p)
1693     {
1694       The_erratum_stub* stub(*p);
1695       stub->write(oview + erratum_stub_start_offset + stub->offset(),
1696                   stub->stub_size());
1697     }
1698
1699   of->write_output_view(this->offset(), oview_size, oview);
1700 }
1701
1702
1703 // AArch64_relobj class.
1704
1705 template<int size, bool big_endian>
1706 class AArch64_relobj : public Sized_relobj_file<size, big_endian>
1707 {
1708  public:
1709   typedef AArch64_relobj<size, big_endian> This;
1710   typedef Target_aarch64<size, big_endian> The_target_aarch64;
1711   typedef AArch64_input_section<size, big_endian> The_aarch64_input_section;
1712   typedef typename elfcpp::Elf_types<size>::Elf_Addr AArch64_address;
1713   typedef Stub_table<size, big_endian> The_stub_table;
1714   typedef Erratum_stub<size, big_endian> The_erratum_stub;
1715   typedef typename The_stub_table::Erratum_stub_set_iter Erratum_stub_set_iter;
1716   typedef std::vector<The_stub_table*> Stub_table_list;
1717   static const AArch64_address invalid_address =
1718       static_cast<AArch64_address>(-1);
1719
1720   AArch64_relobj(const std::string& name, Input_file* input_file, off_t offset,
1721                  const typename elfcpp::Ehdr<size, big_endian>& ehdr)
1722     : Sized_relobj_file<size, big_endian>(name, input_file, offset, ehdr),
1723       stub_tables_()
1724   { }
1725
1726   ~AArch64_relobj()
1727   { }
1728
1729   // Return the stub table of the SHNDX-th section if there is one.
1730   The_stub_table*
1731   stub_table(unsigned int shndx) const
1732   {
1733     gold_assert(shndx < this->stub_tables_.size());
1734     return this->stub_tables_[shndx];
1735   }
1736
1737   // Set STUB_TABLE to be the stub_table of the SHNDX-th section.
1738   void
1739   set_stub_table(unsigned int shndx, The_stub_table* stub_table)
1740   {
1741     gold_assert(shndx < this->stub_tables_.size());
1742     this->stub_tables_[shndx] = stub_table;
1743   }
1744
1745   // Entrance to errata scanning.
1746   void
1747   scan_errata(unsigned int shndx,
1748               const elfcpp::Shdr<size, big_endian>&,
1749               Output_section*, const Symbol_table*,
1750               The_target_aarch64*);
1751
1752   // Scan all relocation sections for stub generation.
1753   void
1754   scan_sections_for_stubs(The_target_aarch64*, const Symbol_table*,
1755                           const Layout*);
1756
1757   // Whether a section is a scannable text section.
1758   bool
1759   text_section_is_scannable(const elfcpp::Shdr<size, big_endian>&, unsigned int,
1760                             const Output_section*, const Symbol_table*);
1761
1762   // Convert regular input section with index SHNDX to a relaxed section.
1763   void
1764   convert_input_section_to_relaxed_section(unsigned /* shndx */)
1765   {
1766     // The stubs have relocations and we need to process them after writing
1767     // out the stubs.  So relocation now must follow section write.
1768     this->set_relocs_must_follow_section_writes();
1769   }
1770
1771   // Structure for mapping symbol position.
1772   struct Mapping_symbol_position
1773   {
1774     Mapping_symbol_position(unsigned int shndx, AArch64_address offset):
1775       shndx_(shndx), offset_(offset)
1776     {}
1777
1778     // "<" comparator used in ordered_map container.
1779     bool
1780     operator<(const Mapping_symbol_position& p) const
1781     {
1782       return (this->shndx_ < p.shndx_
1783               || (this->shndx_ == p.shndx_ && this->offset_ < p.offset_));
1784     }
1785
1786     // Section index.
1787     unsigned int shndx_;
1788
1789     // Section offset.
1790     AArch64_address offset_;
1791   };
1792
1793   typedef std::map<Mapping_symbol_position, char> Mapping_symbol_info;
1794
1795  protected:
1796   // Post constructor setup.
1797   void
1798   do_setup()
1799   {
1800     // Call parent's setup method.
1801     Sized_relobj_file<size, big_endian>::do_setup();
1802
1803     // Initialize look-up tables.
1804     this->stub_tables_.resize(this->shnum());
1805   }
1806
1807   virtual void
1808   do_relocate_sections(
1809       const Symbol_table* symtab, const Layout* layout,
1810       const unsigned char* pshdrs, Output_file* of,
1811       typename Sized_relobj_file<size, big_endian>::Views* pviews);
1812
1813   // Count local symbols and (optionally) record mapping info.
1814   virtual void
1815   do_count_local_symbols(Stringpool_template<char>*,
1816                          Stringpool_template<char>*);
1817
1818  private:
1819   // Fix all errata in the object.
1820   void
1821   fix_errata(typename Sized_relobj_file<size, big_endian>::Views* pviews);
1822
1823   // Try to fix erratum 843419 in an optimized way. Return true if patch is
1824   // applied.
1825   bool
1826   try_fix_erratum_843419_optimized(
1827       The_erratum_stub*,
1828       typename Sized_relobj_file<size, big_endian>::View_size&);
1829
1830   // Whether a section needs to be scanned for relocation stubs.
1831   bool
1832   section_needs_reloc_stub_scanning(const elfcpp::Shdr<size, big_endian>&,
1833                                     const Relobj::Output_sections&,
1834                                     const Symbol_table*, const unsigned char*);
1835
1836   // List of stub tables.
1837   Stub_table_list stub_tables_;
1838
1839   // Mapping symbol information sorted by (section index, section_offset).
1840   Mapping_symbol_info mapping_symbol_info_;
1841 };  // End of AArch64_relobj
1842
1843
1844 // Override to record mapping symbol information.
1845 template<int size, bool big_endian>
1846 void
1847 AArch64_relobj<size, big_endian>::do_count_local_symbols(
1848     Stringpool_template<char>* pool, Stringpool_template<char>* dynpool)
1849 {
1850   Sized_relobj_file<size, big_endian>::do_count_local_symbols(pool, dynpool);
1851
1852   // Only erratum-fixing work needs mapping symbols, so skip this time consuming
1853   // processing if not fixing erratum.
1854   if (!parameters->options().fix_cortex_a53_843419()
1855       && !parameters->options().fix_cortex_a53_835769())
1856     return;
1857
1858   const unsigned int loccount = this->local_symbol_count();
1859   if (loccount == 0)
1860     return;
1861
1862   // Read the symbol table section header.
1863   const unsigned int symtab_shndx = this->symtab_shndx();
1864   elfcpp::Shdr<size, big_endian>
1865       symtabshdr(this, this->elf_file()->section_header(symtab_shndx));
1866   gold_assert(symtabshdr.get_sh_type() == elfcpp::SHT_SYMTAB);
1867
1868   // Read the local symbols.
1869   const int sym_size =elfcpp::Elf_sizes<size>::sym_size;
1870   gold_assert(loccount == symtabshdr.get_sh_info());
1871   off_t locsize = loccount * sym_size;
1872   const unsigned char* psyms = this->get_view(symtabshdr.get_sh_offset(),
1873                                               locsize, true, true);
1874
1875   // For mapping symbol processing, we need to read the symbol names.
1876   unsigned int strtab_shndx = this->adjust_shndx(symtabshdr.get_sh_link());
1877   if (strtab_shndx >= this->shnum())
1878     {
1879       this->error(_("invalid symbol table name index: %u"), strtab_shndx);
1880       return;
1881     }
1882
1883   elfcpp::Shdr<size, big_endian>
1884     strtabshdr(this, this->elf_file()->section_header(strtab_shndx));
1885   if (strtabshdr.get_sh_type() != elfcpp::SHT_STRTAB)
1886     {
1887       this->error(_("symbol table name section has wrong type: %u"),
1888                   static_cast<unsigned int>(strtabshdr.get_sh_type()));
1889       return;
1890     }
1891
1892   const char* pnames =
1893     reinterpret_cast<const char*>(this->get_view(strtabshdr.get_sh_offset(),
1894                                                  strtabshdr.get_sh_size(),
1895                                                  false, false));
1896
1897   // Skip the first dummy symbol.
1898   psyms += sym_size;
1899   typename Sized_relobj_file<size, big_endian>::Local_values*
1900     plocal_values = this->local_values();
1901   for (unsigned int i = 1; i < loccount; ++i, psyms += sym_size)
1902     {
1903       elfcpp::Sym<size, big_endian> sym(psyms);
1904       Symbol_value<size>& lv((*plocal_values)[i]);
1905       AArch64_address input_value = lv.input_value();
1906
1907       // Check to see if this is a mapping symbol. AArch64 mapping symbols are
1908       // defined in "ELF for the ARM 64-bit Architecture", Table 4-4, Mapping
1909       // symbols.
1910       // Mapping symbols could be one of the following 4 forms -
1911       //   a) $x
1912       //   b) $x.<any...>
1913       //   c) $d
1914       //   d) $d.<any...>
1915       const char* sym_name = pnames + sym.get_st_name();
1916       if (sym_name[0] == '$' && (sym_name[1] == 'x' || sym_name[1] == 'd')
1917           && (sym_name[2] == '\0' || sym_name[2] == '.'))
1918         {
1919           bool is_ordinary;
1920           unsigned int input_shndx =
1921             this->adjust_sym_shndx(i, sym.get_st_shndx(), &is_ordinary);
1922           gold_assert(is_ordinary);
1923
1924           Mapping_symbol_position msp(input_shndx, input_value);
1925           // Insert mapping_symbol_info into map whose ordering is defined by
1926           // (shndx, offset_within_section).
1927           this->mapping_symbol_info_[msp] = sym_name[1];
1928         }
1929    }
1930 }
1931
1932
1933 // Fix all errata in the object.
1934
1935 template<int size, bool big_endian>
1936 void
1937 AArch64_relobj<size, big_endian>::fix_errata(
1938     typename Sized_relobj_file<size, big_endian>::Views* pviews)
1939 {
1940   typedef typename elfcpp::Swap<32,big_endian>::Valtype Insntype;
1941   unsigned int shnum = this->shnum();
1942   for (unsigned int i = 1; i < shnum; ++i)
1943     {
1944       The_stub_table* stub_table = this->stub_table(i);
1945       if (!stub_table)
1946         continue;
1947       std::pair<Erratum_stub_set_iter, Erratum_stub_set_iter>
1948         ipair(stub_table->find_erratum_stubs_for_input_section(this, i));
1949       Erratum_stub_set_iter p = ipair.first, end = ipair.second;
1950       while (p != end)
1951         {
1952           The_erratum_stub* stub = *p;
1953           typename Sized_relobj_file<size, big_endian>::View_size&
1954             pview((*pviews)[i]);
1955
1956           // Double check data before fix.
1957           gold_assert(pview.address + stub->sh_offset()
1958                       == stub->erratum_address());
1959
1960           // Update previously recorded erratum insn with relocated
1961           // version.
1962           Insntype* ip =
1963             reinterpret_cast<Insntype*>(pview.view + stub->sh_offset());
1964           Insntype insn_to_fix = ip[0];
1965           stub->update_erratum_insn(insn_to_fix);
1966
1967           // First try to see if erratum is 843419 and if it can be fixed
1968           // without using branch-to-stub.
1969           if (!try_fix_erratum_843419_optimized(stub, pview))
1970             {
1971               // Replace the erratum insn with a branch-to-stub.
1972               AArch64_address stub_address =
1973                 stub_table->erratum_stub_address(stub);
1974               unsigned int b_offset = stub_address - stub->erratum_address();
1975               AArch64_relocate_functions<size, big_endian>::construct_b(
1976                 pview.view + stub->sh_offset(), b_offset & 0xfffffff);
1977             }
1978           ++p;
1979         }
1980     }
1981 }
1982
1983
1984 // This is an optimization for 843419. This erratum requires the sequence begin
1985 // with 'adrp', when final value calculated by adrp fits in adr, we can just
1986 // replace 'adrp' with 'adr', so we save 2 jumps per occurrence. (Note, however,
1987 // in this case, we do not delete the erratum stub (too late to do so), it is
1988 // merely generated without ever being called.)
1989
1990 template<int size, bool big_endian>
1991 bool
1992 AArch64_relobj<size, big_endian>::try_fix_erratum_843419_optimized(
1993     The_erratum_stub* stub,
1994     typename Sized_relobj_file<size, big_endian>::View_size& pview)
1995 {
1996   if (stub->type() != ST_E_843419)
1997     return false;
1998
1999   typedef AArch64_insn_utilities<big_endian> Insn_utilities;
2000   typedef typename elfcpp::Swap<32,big_endian>::Valtype Insntype;
2001   E843419_stub<size, big_endian>* e843419_stub =
2002     reinterpret_cast<E843419_stub<size, big_endian>*>(stub);
2003   AArch64_address pc = pview.address + e843419_stub->adrp_sh_offset();
2004   Insntype* adrp_view = reinterpret_cast<Insntype*>(
2005     pview.view + e843419_stub->adrp_sh_offset());
2006   Insntype adrp_insn = adrp_view[0];
2007   gold_assert(Insn_utilities::is_adrp(adrp_insn));
2008   // Get adrp 33-bit signed imm value.
2009   int64_t adrp_imm = Insn_utilities::
2010     aarch64_adrp_decode_imm(adrp_insn);
2011   // adrp - final value transferred to target register is calculated as:
2012   //     PC[11:0] = Zeros(12)
2013   //     adrp_dest_value = PC + adrp_imm;
2014   int64_t adrp_dest_value = (pc & ~((1 << 12) - 1)) + adrp_imm;
2015   // adr -final value transferred to target register is calucalted as:
2016   //     PC + adr_imm
2017   // So we have:
2018   //     PC + adr_imm = adrp_dest_value
2019   //   ==>
2020   //     adr_imm = adrp_dest_value - PC
2021   int64_t adr_imm = adrp_dest_value - pc;
2022   // Check if imm fits in adr (21-bit signed).
2023   if (-(1 << 20) <= adr_imm && adr_imm < (1 << 20))
2024     {
2025       // Convert 'adrp' into 'adr'.
2026       Insntype adr_insn = adrp_insn & ((1u << 31) - 1);
2027       adr_insn = Insn_utilities::
2028         aarch64_adr_encode_imm(adr_insn, adr_imm);
2029       elfcpp::Swap<32, big_endian>::writeval(adrp_view, adr_insn);
2030       return true;
2031     }
2032   return false;
2033 }
2034
2035
2036 // Relocate sections.
2037
2038 template<int size, bool big_endian>
2039 void
2040 AArch64_relobj<size, big_endian>::do_relocate_sections(
2041     const Symbol_table* symtab, const Layout* layout,
2042     const unsigned char* pshdrs, Output_file* of,
2043     typename Sized_relobj_file<size, big_endian>::Views* pviews)
2044 {
2045   // Call parent to relocate sections.
2046   Sized_relobj_file<size, big_endian>::do_relocate_sections(symtab, layout,
2047                                                             pshdrs, of, pviews);
2048
2049   // We do not generate stubs if doing a relocatable link.
2050   if (parameters->options().relocatable())
2051     return;
2052
2053   if (parameters->options().fix_cortex_a53_843419()
2054       || parameters->options().fix_cortex_a53_835769())
2055     this->fix_errata(pviews);
2056
2057   Relocate_info<size, big_endian> relinfo;
2058   relinfo.symtab = symtab;
2059   relinfo.layout = layout;
2060   relinfo.object = this;
2061
2062   // Relocate stub tables.
2063   unsigned int shnum = this->shnum();
2064   The_target_aarch64* target = The_target_aarch64::current_target();
2065
2066   for (unsigned int i = 1; i < shnum; ++i)
2067     {
2068       The_aarch64_input_section* aarch64_input_section =
2069           target->find_aarch64_input_section(this, i);
2070       if (aarch64_input_section != NULL
2071           && aarch64_input_section->is_stub_table_owner()
2072           && !aarch64_input_section->stub_table()->empty())
2073         {
2074           Output_section* os = this->output_section(i);
2075           gold_assert(os != NULL);
2076
2077           relinfo.reloc_shndx = elfcpp::SHN_UNDEF;
2078           relinfo.reloc_shdr = NULL;
2079           relinfo.data_shndx = i;
2080           relinfo.data_shdr = pshdrs + i * elfcpp::Elf_sizes<size>::shdr_size;
2081
2082           typename Sized_relobj_file<size, big_endian>::View_size&
2083               view_struct = (*pviews)[i];
2084           gold_assert(view_struct.view != NULL);
2085
2086           The_stub_table* stub_table = aarch64_input_section->stub_table();
2087           off_t offset = stub_table->address() - view_struct.address;
2088           unsigned char* view = view_struct.view + offset;
2089           AArch64_address address = stub_table->address();
2090           section_size_type view_size = stub_table->data_size();
2091           stub_table->relocate_stubs(&relinfo, target, os, view, address,
2092                                      view_size);
2093         }
2094     }
2095 }
2096
2097
2098 // Determine if an input section is scannable for stub processing.  SHDR is
2099 // the header of the section and SHNDX is the section index.  OS is the output
2100 // section for the input section and SYMTAB is the global symbol table used to
2101 // look up ICF information.
2102
2103 template<int size, bool big_endian>
2104 bool
2105 AArch64_relobj<size, big_endian>::text_section_is_scannable(
2106     const elfcpp::Shdr<size, big_endian>& text_shdr,
2107     unsigned int text_shndx,
2108     const Output_section* os,
2109     const Symbol_table* symtab)
2110 {
2111   // Skip any empty sections, unallocated sections or sections whose
2112   // type are not SHT_PROGBITS.
2113   if (text_shdr.get_sh_size() == 0
2114       || (text_shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0
2115       || text_shdr.get_sh_type() != elfcpp::SHT_PROGBITS)
2116     return false;
2117
2118   // Skip any discarded or ICF'ed sections.
2119   if (os == NULL || symtab->is_section_folded(this, text_shndx))
2120     return false;
2121
2122   // Skip exception frame.
2123   if (strcmp(os->name(), ".eh_frame") == 0)
2124     return false ;
2125
2126   gold_assert(!this->is_output_section_offset_invalid(text_shndx) ||
2127               os->find_relaxed_input_section(this, text_shndx) != NULL);
2128
2129   return true;
2130 }
2131
2132
2133 // Determine if we want to scan the SHNDX-th section for relocation stubs.
2134 // This is a helper for AArch64_relobj::scan_sections_for_stubs().
2135
2136 template<int size, bool big_endian>
2137 bool
2138 AArch64_relobj<size, big_endian>::section_needs_reloc_stub_scanning(
2139     const elfcpp::Shdr<size, big_endian>& shdr,
2140     const Relobj::Output_sections& out_sections,
2141     const Symbol_table* symtab,
2142     const unsigned char* pshdrs)
2143 {
2144   unsigned int sh_type = shdr.get_sh_type();
2145   if (sh_type != elfcpp::SHT_RELA)
2146     return false;
2147
2148   // Ignore empty section.
2149   off_t sh_size = shdr.get_sh_size();
2150   if (sh_size == 0)
2151     return false;
2152
2153   // Ignore reloc section with unexpected symbol table.  The
2154   // error will be reported in the final link.
2155   if (this->adjust_shndx(shdr.get_sh_link()) != this->symtab_shndx())
2156     return false;
2157
2158   gold_assert(sh_type == elfcpp::SHT_RELA);
2159   unsigned int reloc_size = elfcpp::Elf_sizes<size>::rela_size;
2160
2161   // Ignore reloc section with unexpected entsize or uneven size.
2162   // The error will be reported in the final link.
2163   if (reloc_size != shdr.get_sh_entsize() || sh_size % reloc_size != 0)
2164     return false;
2165
2166   // Ignore reloc section with bad info.  This error will be
2167   // reported in the final link.
2168   unsigned int text_shndx = this->adjust_shndx(shdr.get_sh_info());
2169   if (text_shndx >= this->shnum())
2170     return false;
2171
2172   const unsigned int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
2173   const elfcpp::Shdr<size, big_endian> text_shdr(pshdrs +
2174                                                  text_shndx * shdr_size);
2175   return this->text_section_is_scannable(text_shdr, text_shndx,
2176                                          out_sections[text_shndx], symtab);
2177 }
2178
2179
2180 // Scan section SHNDX for erratum 843419 and 835769.
2181
2182 template<int size, bool big_endian>
2183 void
2184 AArch64_relobj<size, big_endian>::scan_errata(
2185     unsigned int shndx, const elfcpp::Shdr<size, big_endian>& shdr,
2186     Output_section* os, const Symbol_table* symtab,
2187     The_target_aarch64* target)
2188 {
2189   if (shdr.get_sh_size() == 0
2190       || (shdr.get_sh_flags() &
2191           (elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR)) == 0
2192       || shdr.get_sh_type() != elfcpp::SHT_PROGBITS)
2193     return;
2194
2195   if (!os || symtab->is_section_folded(this, shndx)) return;
2196
2197   AArch64_address output_offset = this->get_output_section_offset(shndx);
2198   AArch64_address output_address;
2199   if (output_offset != invalid_address)
2200     output_address = os->address() + output_offset;
2201   else
2202     {
2203       const Output_relaxed_input_section* poris =
2204         os->find_relaxed_input_section(this, shndx);
2205       if (!poris) return;
2206       output_address = poris->address();
2207     }
2208
2209   section_size_type input_view_size = 0;
2210   const unsigned char* input_view =
2211     this->section_contents(shndx, &input_view_size, false);
2212
2213   Mapping_symbol_position section_start(shndx, 0);
2214   // Find the first mapping symbol record within section shndx.
2215   typename Mapping_symbol_info::const_iterator p =
2216     this->mapping_symbol_info_.lower_bound(section_start);
2217   while (p != this->mapping_symbol_info_.end() &&
2218          p->first.shndx_ == shndx)
2219     {
2220       typename Mapping_symbol_info::const_iterator prev = p;
2221       ++p;
2222       if (prev->second == 'x')
2223         {
2224           section_size_type span_start =
2225             convert_to_section_size_type(prev->first.offset_);
2226           section_size_type span_end;
2227           if (p != this->mapping_symbol_info_.end()
2228               && p->first.shndx_ == shndx)
2229             span_end = convert_to_section_size_type(p->first.offset_);
2230           else
2231             span_end = convert_to_section_size_type(shdr.get_sh_size());
2232
2233           // Here we do not share the scanning code of both errata. For 843419,
2234           // only the last few insns of each page are examined, which is fast,
2235           // whereas, for 835769, every insn pair needs to be checked.
2236
2237           if (parameters->options().fix_cortex_a53_843419())
2238             target->scan_erratum_843419_span(
2239               this, shndx, span_start, span_end,
2240               const_cast<unsigned char*>(input_view), output_address);
2241
2242           if (parameters->options().fix_cortex_a53_835769())
2243             target->scan_erratum_835769_span(
2244               this, shndx, span_start, span_end,
2245               const_cast<unsigned char*>(input_view), output_address);
2246         }
2247     }
2248 }
2249
2250
2251 // Scan relocations for stub generation.
2252
2253 template<int size, bool big_endian>
2254 void
2255 AArch64_relobj<size, big_endian>::scan_sections_for_stubs(
2256     The_target_aarch64* target,
2257     const Symbol_table* symtab,
2258     const Layout* layout)
2259 {
2260   unsigned int shnum = this->shnum();
2261   const unsigned int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
2262
2263   // Read the section headers.
2264   const unsigned char* pshdrs = this->get_view(this->elf_file()->shoff(),
2265                                                shnum * shdr_size,
2266                                                true, true);
2267
2268   // To speed up processing, we set up hash tables for fast lookup of
2269   // input offsets to output addresses.
2270   this->initialize_input_to_output_maps();
2271
2272   const Relobj::Output_sections& out_sections(this->output_sections());
2273
2274   Relocate_info<size, big_endian> relinfo;
2275   relinfo.symtab = symtab;
2276   relinfo.layout = layout;
2277   relinfo.object = this;
2278
2279   // Do relocation stubs scanning.
2280   const unsigned char* p = pshdrs + shdr_size;
2281   for (unsigned int i = 1; i < shnum; ++i, p += shdr_size)
2282     {
2283       const elfcpp::Shdr<size, big_endian> shdr(p);
2284       if (parameters->options().fix_cortex_a53_843419()
2285           || parameters->options().fix_cortex_a53_835769())
2286         scan_errata(i, shdr, out_sections[i], symtab, target);
2287       if (this->section_needs_reloc_stub_scanning(shdr, out_sections, symtab,
2288                                                   pshdrs))
2289         {
2290           unsigned int index = this->adjust_shndx(shdr.get_sh_info());
2291           AArch64_address output_offset =
2292               this->get_output_section_offset(index);
2293           AArch64_address output_address;
2294           if (output_offset != invalid_address)
2295             {
2296               output_address = out_sections[index]->address() + output_offset;
2297             }
2298           else
2299             {
2300               // Currently this only happens for a relaxed section.
2301               const Output_relaxed_input_section* poris =
2302                   out_sections[index]->find_relaxed_input_section(this, index);
2303               gold_assert(poris != NULL);
2304               output_address = poris->address();
2305             }
2306
2307           // Get the relocations.
2308           const unsigned char* prelocs = this->get_view(shdr.get_sh_offset(),
2309                                                         shdr.get_sh_size(),
2310                                                         true, false);
2311
2312           // Get the section contents.
2313           section_size_type input_view_size = 0;
2314           const unsigned char* input_view =
2315               this->section_contents(index, &input_view_size, false);
2316
2317           relinfo.reloc_shndx = i;
2318           relinfo.data_shndx = index;
2319           unsigned int sh_type = shdr.get_sh_type();
2320           unsigned int reloc_size;
2321           gold_assert (sh_type == elfcpp::SHT_RELA);
2322           reloc_size = elfcpp::Elf_sizes<size>::rela_size;
2323
2324           Output_section* os = out_sections[index];
2325           target->scan_section_for_stubs(&relinfo, sh_type, prelocs,
2326                                          shdr.get_sh_size() / reloc_size,
2327                                          os,
2328                                          output_offset == invalid_address,
2329                                          input_view, output_address,
2330                                          input_view_size);
2331         }
2332     }
2333 }
2334
2335
2336 // A class to wrap an ordinary input section containing executable code.
2337
2338 template<int size, bool big_endian>
2339 class AArch64_input_section : public Output_relaxed_input_section
2340 {
2341  public:
2342   typedef Stub_table<size, big_endian> The_stub_table;
2343
2344   AArch64_input_section(Relobj* relobj, unsigned int shndx)
2345     : Output_relaxed_input_section(relobj, shndx, 1),
2346       stub_table_(NULL),
2347       original_contents_(NULL), original_size_(0),
2348       original_addralign_(1)
2349   { }
2350
2351   ~AArch64_input_section()
2352   { delete[] this->original_contents_; }
2353
2354   // Initialize.
2355   void
2356   init();
2357
2358   // Set the stub_table.
2359   void
2360   set_stub_table(The_stub_table* st)
2361   { this->stub_table_ = st; }
2362
2363   // Whether this is a stub table owner.
2364   bool
2365   is_stub_table_owner() const
2366   { return this->stub_table_ != NULL && this->stub_table_->owner() == this; }
2367
2368   // Return the original size of the section.
2369   uint32_t
2370   original_size() const
2371   { return this->original_size_; }
2372
2373   // Return the stub table.
2374   The_stub_table*
2375   stub_table()
2376   { return stub_table_; }
2377
2378  protected:
2379   // Write out this input section.
2380   void
2381   do_write(Output_file*);
2382
2383   // Return required alignment of this.
2384   uint64_t
2385   do_addralign() const
2386   {
2387     if (this->is_stub_table_owner())
2388       return std::max(this->stub_table_->addralign(),
2389                       static_cast<uint64_t>(this->original_addralign_));
2390     else
2391       return this->original_addralign_;
2392   }
2393
2394   // Finalize data size.
2395   void
2396   set_final_data_size();
2397
2398   // Reset address and file offset.
2399   void
2400   do_reset_address_and_file_offset();
2401
2402   // Output offset.
2403   bool
2404   do_output_offset(const Relobj* object, unsigned int shndx,
2405                    section_offset_type offset,
2406                    section_offset_type* poutput) const
2407   {
2408     if ((object == this->relobj())
2409         && (shndx == this->shndx())
2410         && (offset >= 0)
2411         && (offset <=
2412             convert_types<section_offset_type, uint32_t>(this->original_size_)))
2413       {
2414         *poutput = offset;
2415         return true;
2416       }
2417     else
2418       return false;
2419   }
2420
2421  private:
2422   // Copying is not allowed.
2423   AArch64_input_section(const AArch64_input_section&);
2424   AArch64_input_section& operator=(const AArch64_input_section&);
2425
2426   // The relocation stubs.
2427   The_stub_table* stub_table_;
2428   // Original section contents.  We have to make a copy here since the file
2429   // containing the original section may not be locked when we need to access
2430   // the contents.
2431   unsigned char* original_contents_;
2432   // Section size of the original input section.
2433   uint32_t original_size_;
2434   // Address alignment of the original input section.
2435   uint32_t original_addralign_;
2436 };  // End of AArch64_input_section
2437
2438
2439 // Finalize data size.
2440
2441 template<int size, bool big_endian>
2442 void
2443 AArch64_input_section<size, big_endian>::set_final_data_size()
2444 {
2445   off_t off = convert_types<off_t, uint64_t>(this->original_size_);
2446
2447   if (this->is_stub_table_owner())
2448     {
2449       this->stub_table_->finalize_data_size();
2450       off = align_address(off, this->stub_table_->addralign());
2451       off += this->stub_table_->data_size();
2452     }
2453   this->set_data_size(off);
2454 }
2455
2456
2457 // Reset address and file offset.
2458
2459 template<int size, bool big_endian>
2460 void
2461 AArch64_input_section<size, big_endian>::do_reset_address_and_file_offset()
2462 {
2463   // Size of the original input section contents.
2464   off_t off = convert_types<off_t, uint64_t>(this->original_size_);
2465
2466   // If this is a stub table owner, account for the stub table size.
2467   if (this->is_stub_table_owner())
2468     {
2469       The_stub_table* stub_table = this->stub_table_;
2470
2471       // Reset the stub table's address and file offset.  The
2472       // current data size for child will be updated after that.
2473       stub_table_->reset_address_and_file_offset();
2474       off = align_address(off, stub_table_->addralign());
2475       off += stub_table->current_data_size();
2476     }
2477
2478   this->set_current_data_size(off);
2479 }
2480
2481
2482 // Initialize an Arm_input_section.
2483
2484 template<int size, bool big_endian>
2485 void
2486 AArch64_input_section<size, big_endian>::init()
2487 {
2488   Relobj* relobj = this->relobj();
2489   unsigned int shndx = this->shndx();
2490
2491   // We have to cache original size, alignment and contents to avoid locking
2492   // the original file.
2493   this->original_addralign_ =
2494       convert_types<uint32_t, uint64_t>(relobj->section_addralign(shndx));
2495
2496   // This is not efficient but we expect only a small number of relaxed
2497   // input sections for stubs.
2498   section_size_type section_size;
2499   const unsigned char* section_contents =
2500       relobj->section_contents(shndx, &section_size, false);
2501   this->original_size_ =
2502       convert_types<uint32_t, uint64_t>(relobj->section_size(shndx));
2503
2504   gold_assert(this->original_contents_ == NULL);
2505   this->original_contents_ = new unsigned char[section_size];
2506   memcpy(this->original_contents_, section_contents, section_size);
2507
2508   // We want to make this look like the original input section after
2509   // output sections are finalized.
2510   Output_section* os = relobj->output_section(shndx);
2511   off_t offset = relobj->output_section_offset(shndx);
2512   gold_assert(os != NULL && !relobj->is_output_section_offset_invalid(shndx));
2513   this->set_address(os->address() + offset);
2514   this->set_file_offset(os->offset() + offset);
2515   this->set_current_data_size(this->original_size_);
2516   this->finalize_data_size();
2517 }
2518
2519
2520 // Write data to output file.
2521
2522 template<int size, bool big_endian>
2523 void
2524 AArch64_input_section<size, big_endian>::do_write(Output_file* of)
2525 {
2526   // We have to write out the original section content.
2527   gold_assert(this->original_contents_ != NULL);
2528   of->write(this->offset(), this->original_contents_,
2529             this->original_size_);
2530
2531   // If this owns a stub table and it is not empty, write it.
2532   if (this->is_stub_table_owner() && !this->stub_table_->empty())
2533     this->stub_table_->write(of);
2534 }
2535
2536
2537 // Arm output section class.  This is defined mainly to add a number of stub
2538 // generation methods.
2539
2540 template<int size, bool big_endian>
2541 class AArch64_output_section : public Output_section
2542 {
2543  public:
2544   typedef Target_aarch64<size, big_endian> The_target_aarch64;
2545   typedef AArch64_relobj<size, big_endian> The_aarch64_relobj;
2546   typedef Stub_table<size, big_endian> The_stub_table;
2547   typedef AArch64_input_section<size, big_endian> The_aarch64_input_section;
2548
2549  public:
2550   AArch64_output_section(const char* name, elfcpp::Elf_Word type,
2551                          elfcpp::Elf_Xword flags)
2552     : Output_section(name, type, flags)
2553   { }
2554
2555   ~AArch64_output_section() {}
2556
2557   // Group input sections for stub generation.
2558   void
2559   group_sections(section_size_type, bool, Target_aarch64<size, big_endian>*,
2560                  const Task*);
2561
2562  private:
2563   typedef Output_section::Input_section Input_section;
2564   typedef Output_section::Input_section_list Input_section_list;
2565
2566   // Create a stub group.
2567   void
2568   create_stub_group(Input_section_list::const_iterator,
2569                     Input_section_list::const_iterator,
2570                     Input_section_list::const_iterator,
2571                     The_target_aarch64*,
2572                     std::vector<Output_relaxed_input_section*>&,
2573                     const Task*);
2574 };  // End of AArch64_output_section
2575
2576
2577 // Create a stub group for input sections from FIRST to LAST. OWNER points to
2578 // the input section that will be the owner of the stub table.
2579
2580 template<int size, bool big_endian> void
2581 AArch64_output_section<size, big_endian>::create_stub_group(
2582     Input_section_list::const_iterator first,
2583     Input_section_list::const_iterator last,
2584     Input_section_list::const_iterator owner,
2585     The_target_aarch64* target,
2586     std::vector<Output_relaxed_input_section*>& new_relaxed_sections,
2587     const Task* task)
2588 {
2589   // Currently we convert ordinary input sections into relaxed sections only
2590   // at this point.
2591   The_aarch64_input_section* input_section;
2592   if (owner->is_relaxed_input_section())
2593     gold_unreachable();
2594   else
2595     {
2596       gold_assert(owner->is_input_section());
2597       // Create a new relaxed input section.  We need to lock the original
2598       // file.
2599       Task_lock_obj<Object> tl(task, owner->relobj());
2600       input_section =
2601           target->new_aarch64_input_section(owner->relobj(), owner->shndx());
2602       new_relaxed_sections.push_back(input_section);
2603     }
2604
2605   // Create a stub table.
2606   The_stub_table* stub_table =
2607       target->new_stub_table(input_section);
2608
2609   input_section->set_stub_table(stub_table);
2610
2611   Input_section_list::const_iterator p = first;
2612   // Look for input sections or relaxed input sections in [first ... last].
2613   do
2614     {
2615       if (p->is_input_section() || p->is_relaxed_input_section())
2616         {
2617           // The stub table information for input sections live
2618           // in their objects.
2619           The_aarch64_relobj* aarch64_relobj =
2620               static_cast<The_aarch64_relobj*>(p->relobj());
2621           aarch64_relobj->set_stub_table(p->shndx(), stub_table);
2622         }
2623     }
2624   while (p++ != last);
2625 }
2626
2627
2628 // Group input sections for stub generation. GROUP_SIZE is roughly the limit of
2629 // stub groups. We grow a stub group by adding input section until the size is
2630 // just below GROUP_SIZE. The last input section will be converted into a stub
2631 // table owner. If STUB_ALWAYS_AFTER_BRANCH is false, we also add input sectiond
2632 // after the stub table, effectively doubling the group size.
2633 //
2634 // This is similar to the group_sections() function in elf32-arm.c but is
2635 // implemented differently.
2636
2637 template<int size, bool big_endian>
2638 void AArch64_output_section<size, big_endian>::group_sections(
2639     section_size_type group_size,
2640     bool stubs_always_after_branch,
2641     Target_aarch64<size, big_endian>* target,
2642     const Task* task)
2643 {
2644   typedef enum
2645   {
2646     NO_GROUP,
2647     FINDING_STUB_SECTION,
2648     HAS_STUB_SECTION
2649   } State;
2650
2651   std::vector<Output_relaxed_input_section*> new_relaxed_sections;
2652
2653   State state = NO_GROUP;
2654   section_size_type off = 0;
2655   section_size_type group_begin_offset = 0;
2656   section_size_type group_end_offset = 0;
2657   section_size_type stub_table_end_offset = 0;
2658   Input_section_list::const_iterator group_begin =
2659       this->input_sections().end();
2660   Input_section_list::const_iterator stub_table =
2661       this->input_sections().end();
2662   Input_section_list::const_iterator group_end = this->input_sections().end();
2663   for (Input_section_list::const_iterator p = this->input_sections().begin();
2664        p != this->input_sections().end();
2665        ++p)
2666     {
2667       section_size_type section_begin_offset =
2668         align_address(off, p->addralign());
2669       section_size_type section_end_offset =
2670         section_begin_offset + p->data_size();
2671
2672       // Check to see if we should group the previously seen sections.
2673       switch (state)
2674         {
2675         case NO_GROUP:
2676           break;
2677
2678         case FINDING_STUB_SECTION:
2679           // Adding this section makes the group larger than GROUP_SIZE.
2680           if (section_end_offset - group_begin_offset >= group_size)
2681             {
2682               if (stubs_always_after_branch)
2683                 {
2684                   gold_assert(group_end != this->input_sections().end());
2685                   this->create_stub_group(group_begin, group_end, group_end,
2686                                           target, new_relaxed_sections,
2687                                           task);
2688                   state = NO_GROUP;
2689                 }
2690               else
2691                 {
2692                   // Input sections up to stub_group_size bytes after the stub
2693                   // table can be handled by it too.
2694                   state = HAS_STUB_SECTION;
2695                   stub_table = group_end;
2696                   stub_table_end_offset = group_end_offset;
2697                 }
2698             }
2699             break;
2700
2701         case HAS_STUB_SECTION:
2702           // Adding this section makes the post stub-section group larger
2703           // than GROUP_SIZE.
2704           gold_unreachable();
2705           // NOT SUPPORTED YET. For completeness only.
2706           if (section_end_offset - stub_table_end_offset >= group_size)
2707            {
2708              gold_assert(group_end != this->input_sections().end());
2709              this->create_stub_group(group_begin, group_end, stub_table,
2710                                      target, new_relaxed_sections, task);
2711              state = NO_GROUP;
2712            }
2713            break;
2714
2715           default:
2716             gold_unreachable();
2717         }
2718
2719       // If we see an input section and currently there is no group, start
2720       // a new one.  Skip any empty sections.  We look at the data size
2721       // instead of calling p->relobj()->section_size() to avoid locking.
2722       if ((p->is_input_section() || p->is_relaxed_input_section())
2723           && (p->data_size() != 0))
2724         {
2725           if (state == NO_GROUP)
2726             {
2727               state = FINDING_STUB_SECTION;
2728               group_begin = p;
2729               group_begin_offset = section_begin_offset;
2730             }
2731
2732           // Keep track of the last input section seen.
2733           group_end = p;
2734           group_end_offset = section_end_offset;
2735         }
2736
2737       off = section_end_offset;
2738     }
2739
2740   // Create a stub group for any ungrouped sections.
2741   if (state == FINDING_STUB_SECTION || state == HAS_STUB_SECTION)
2742     {
2743       gold_assert(group_end != this->input_sections().end());
2744       this->create_stub_group(group_begin, group_end,
2745                               (state == FINDING_STUB_SECTION
2746                                ? group_end
2747                                : stub_table),
2748                               target, new_relaxed_sections, task);
2749     }
2750
2751   if (!new_relaxed_sections.empty())
2752     this->convert_input_sections_to_relaxed_sections(new_relaxed_sections);
2753
2754   // Update the section offsets
2755   for (size_t i = 0; i < new_relaxed_sections.size(); ++i)
2756     {
2757       The_aarch64_relobj* relobj = static_cast<The_aarch64_relobj*>(
2758           new_relaxed_sections[i]->relobj());
2759       unsigned int shndx = new_relaxed_sections[i]->shndx();
2760       // Tell AArch64_relobj that this input section is converted.
2761       relobj->convert_input_section_to_relaxed_section(shndx);
2762     }
2763 }  // End of AArch64_output_section::group_sections
2764
2765
2766 AArch64_reloc_property_table* aarch64_reloc_property_table = NULL;
2767
2768
2769 // The aarch64 target class.
2770 // See the ABI at
2771 // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0056b/IHI0056B_aaelf64.pdf
2772 template<int size, bool big_endian>
2773 class Target_aarch64 : public Sized_target<size, big_endian>
2774 {
2775  public:
2776   typedef Target_aarch64<size, big_endian> This;
2777   typedef Output_data_reloc<elfcpp::SHT_RELA, true, size, big_endian>
2778       Reloc_section;
2779   typedef Relocate_info<size, big_endian> The_relocate_info;
2780   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
2781   typedef AArch64_relobj<size, big_endian> The_aarch64_relobj;
2782   typedef Reloc_stub<size, big_endian> The_reloc_stub;
2783   typedef Erratum_stub<size, big_endian> The_erratum_stub;
2784   typedef typename Reloc_stub<size, big_endian>::Key The_reloc_stub_key;
2785   typedef Stub_table<size, big_endian> The_stub_table;
2786   typedef std::vector<The_stub_table*> Stub_table_list;
2787   typedef typename Stub_table_list::iterator Stub_table_iterator;
2788   typedef AArch64_input_section<size, big_endian> The_aarch64_input_section;
2789   typedef AArch64_output_section<size, big_endian> The_aarch64_output_section;
2790   typedef Unordered_map<Section_id,
2791                         AArch64_input_section<size, big_endian>*,
2792                         Section_id_hash> AArch64_input_section_map;
2793   typedef AArch64_insn_utilities<big_endian> Insn_utilities;
2794   const static int TCB_SIZE = size / 8 * 2;
2795
2796   Target_aarch64(const Target::Target_info* info = &aarch64_info)
2797     : Sized_target<size, big_endian>(info),
2798       got_(NULL), plt_(NULL), got_plt_(NULL), got_irelative_(NULL),
2799       got_tlsdesc_(NULL), global_offset_table_(NULL), rela_dyn_(NULL),
2800       rela_irelative_(NULL), copy_relocs_(elfcpp::R_AARCH64_COPY),
2801       got_mod_index_offset_(-1U),
2802       tlsdesc_reloc_info_(), tls_base_symbol_defined_(false),
2803       stub_tables_(), stub_group_size_(0), aarch64_input_section_map_()
2804   { }
2805
2806   // Scan the relocations to determine unreferenced sections for
2807   // garbage collection.
2808   void
2809   gc_process_relocs(Symbol_table* symtab,
2810                     Layout* layout,
2811                     Sized_relobj_file<size, big_endian>* object,
2812                     unsigned int data_shndx,
2813                     unsigned int sh_type,
2814                     const unsigned char* prelocs,
2815                     size_t reloc_count,
2816                     Output_section* output_section,
2817                     bool needs_special_offset_handling,
2818                     size_t local_symbol_count,
2819                     const unsigned char* plocal_symbols);
2820
2821   // Scan the relocations to look for symbol adjustments.
2822   void
2823   scan_relocs(Symbol_table* symtab,
2824               Layout* layout,
2825               Sized_relobj_file<size, big_endian>* object,
2826               unsigned int data_shndx,
2827               unsigned int sh_type,
2828               const unsigned char* prelocs,
2829               size_t reloc_count,
2830               Output_section* output_section,
2831               bool needs_special_offset_handling,
2832               size_t local_symbol_count,
2833               const unsigned char* plocal_symbols);
2834
2835   // Finalize the sections.
2836   void
2837   do_finalize_sections(Layout*, const Input_objects*, Symbol_table*);
2838
2839   // Return the value to use for a dynamic which requires special
2840   // treatment.
2841   uint64_t
2842   do_dynsym_value(const Symbol*) const;
2843
2844   // Relocate a section.
2845   void
2846   relocate_section(const Relocate_info<size, big_endian>*,
2847                    unsigned int sh_type,
2848                    const unsigned char* prelocs,
2849                    size_t reloc_count,
2850                    Output_section* output_section,
2851                    bool needs_special_offset_handling,
2852                    unsigned char* view,
2853                    typename elfcpp::Elf_types<size>::Elf_Addr view_address,
2854                    section_size_type view_size,
2855                    const Reloc_symbol_changes*);
2856
2857   // Scan the relocs during a relocatable link.
2858   void
2859   scan_relocatable_relocs(Symbol_table* symtab,
2860                           Layout* layout,
2861                           Sized_relobj_file<size, big_endian>* object,
2862                           unsigned int data_shndx,
2863                           unsigned int sh_type,
2864                           const unsigned char* prelocs,
2865                           size_t reloc_count,
2866                           Output_section* output_section,
2867                           bool needs_special_offset_handling,
2868                           size_t local_symbol_count,
2869                           const unsigned char* plocal_symbols,
2870                           Relocatable_relocs*);
2871
2872   // Relocate a section during a relocatable link.
2873   void
2874   relocate_relocs(
2875       const Relocate_info<size, big_endian>*,
2876       unsigned int sh_type,
2877       const unsigned char* prelocs,
2878       size_t reloc_count,
2879       Output_section* output_section,
2880       typename elfcpp::Elf_types<size>::Elf_Off offset_in_output_section,
2881       const Relocatable_relocs*,
2882       unsigned char* view,
2883       typename elfcpp::Elf_types<size>::Elf_Addr view_address,
2884       section_size_type view_size,
2885       unsigned char* reloc_view,
2886       section_size_type reloc_view_size);
2887
2888   // Return the symbol index to use for a target specific relocation.
2889   // The only target specific relocation is R_AARCH64_TLSDESC for a
2890   // local symbol, which is an absolute reloc.
2891   unsigned int
2892   do_reloc_symbol_index(void*, unsigned int r_type) const
2893   {
2894     gold_assert(r_type == elfcpp::R_AARCH64_TLSDESC);
2895     return 0;
2896   }
2897
2898   // Return the addend to use for a target specific relocation.
2899   uint64_t
2900   do_reloc_addend(void* arg, unsigned int r_type, uint64_t addend) const;
2901
2902   // Return the PLT section.
2903   uint64_t
2904   do_plt_address_for_global(const Symbol* gsym) const
2905   { return this->plt_section()->address_for_global(gsym); }
2906
2907   uint64_t
2908   do_plt_address_for_local(const Relobj* relobj, unsigned int symndx) const
2909   { return this->plt_section()->address_for_local(relobj, symndx); }
2910
2911   // This function should be defined in targets that can use relocation
2912   // types to determine (implemented in local_reloc_may_be_function_pointer
2913   // and global_reloc_may_be_function_pointer)
2914   // if a function's pointer is taken.  ICF uses this in safe mode to only
2915   // fold those functions whose pointer is defintely not taken.
2916   bool
2917   do_can_check_for_function_pointers() const
2918   { return true; }
2919
2920   // Return the number of entries in the PLT.
2921   unsigned int
2922   plt_entry_count() const;
2923
2924   //Return the offset of the first non-reserved PLT entry.
2925   unsigned int
2926   first_plt_entry_offset() const;
2927
2928   // Return the size of each PLT entry.
2929   unsigned int
2930   plt_entry_size() const;
2931
2932   // Create a stub table.
2933   The_stub_table*
2934   new_stub_table(The_aarch64_input_section*);
2935
2936   // Create an aarch64 input section.
2937   The_aarch64_input_section*
2938   new_aarch64_input_section(Relobj*, unsigned int);
2939
2940   // Find an aarch64 input section instance for a given OBJ and SHNDX.
2941   The_aarch64_input_section*
2942   find_aarch64_input_section(Relobj*, unsigned int) const;
2943
2944   // Return the thread control block size.
2945   unsigned int
2946   tcb_size() const { return This::TCB_SIZE; }
2947
2948   // Scan a section for stub generation.
2949   void
2950   scan_section_for_stubs(const Relocate_info<size, big_endian>*, unsigned int,
2951                          const unsigned char*, size_t, Output_section*,
2952                          bool, const unsigned char*,
2953                          Address,
2954                          section_size_type);
2955
2956   // Scan a relocation section for stub.
2957   template<int sh_type>
2958   void
2959   scan_reloc_section_for_stubs(
2960       const The_relocate_info* relinfo,
2961       const unsigned char* prelocs,
2962       size_t reloc_count,
2963       Output_section* output_section,
2964       bool needs_special_offset_handling,
2965       const unsigned char* view,
2966       Address view_address,
2967       section_size_type);
2968
2969   // Relocate a single stub.
2970   void
2971   relocate_stub(The_reloc_stub*, const Relocate_info<size, big_endian>*,
2972                 Output_section*, unsigned char*, Address,
2973                 section_size_type);
2974
2975   // Get the default AArch64 target.
2976   static This*
2977   current_target()
2978   {
2979     gold_assert(parameters->target().machine_code() == elfcpp::EM_AARCH64
2980                 && parameters->target().get_size() == size
2981                 && parameters->target().is_big_endian() == big_endian);
2982     return static_cast<This*>(parameters->sized_target<size, big_endian>());
2983   }
2984
2985
2986   // Scan erratum 843419 for a part of a section.
2987   void
2988   scan_erratum_843419_span(
2989     AArch64_relobj<size, big_endian>*,
2990     unsigned int,
2991     const section_size_type,
2992     const section_size_type,
2993     unsigned char*,
2994     Address);
2995
2996   // Scan erratum 835769 for a part of a section.
2997   void
2998   scan_erratum_835769_span(
2999     AArch64_relobj<size, big_endian>*,
3000     unsigned int,
3001     const section_size_type,
3002     const section_size_type,
3003     unsigned char*,
3004     Address);
3005
3006  protected:
3007   void
3008   do_select_as_default_target()
3009   {
3010     gold_assert(aarch64_reloc_property_table == NULL);
3011     aarch64_reloc_property_table = new AArch64_reloc_property_table();
3012   }
3013
3014   // Add a new reloc argument, returning the index in the vector.
3015   size_t
3016   add_tlsdesc_info(Sized_relobj_file<size, big_endian>* object,
3017                    unsigned int r_sym)
3018   {
3019     this->tlsdesc_reloc_info_.push_back(Tlsdesc_info(object, r_sym));
3020     return this->tlsdesc_reloc_info_.size() - 1;
3021   }
3022
3023   virtual Output_data_plt_aarch64<size, big_endian>*
3024   do_make_data_plt(Layout* layout,
3025                    Output_data_got_aarch64<size, big_endian>* got,
3026                    Output_data_space* got_plt,
3027                    Output_data_space* got_irelative)
3028   {
3029     return new Output_data_plt_aarch64_standard<size, big_endian>(
3030       layout, got, got_plt, got_irelative);
3031   }
3032
3033
3034   // do_make_elf_object to override the same function in the base class.
3035   Object*
3036   do_make_elf_object(const std::string&, Input_file*, off_t,
3037                      const elfcpp::Ehdr<size, big_endian>&);
3038
3039   Output_data_plt_aarch64<size, big_endian>*
3040   make_data_plt(Layout* layout,
3041                 Output_data_got_aarch64<size, big_endian>* got,
3042                 Output_data_space* got_plt,
3043                 Output_data_space* got_irelative)
3044   {
3045     return this->do_make_data_plt(layout, got, got_plt, got_irelative);
3046   }
3047
3048   // We only need to generate stubs, and hence perform relaxation if we are
3049   // not doing relocatable linking.
3050   virtual bool
3051   do_may_relax() const
3052   { return !parameters->options().relocatable(); }
3053
3054   // Relaxation hook.  This is where we do stub generation.
3055   virtual bool
3056   do_relax(int, const Input_objects*, Symbol_table*, Layout*, const Task*);
3057
3058   void
3059   group_sections(Layout* layout,
3060                  section_size_type group_size,
3061                  bool stubs_always_after_branch,
3062                  const Task* task);
3063
3064   void
3065   scan_reloc_for_stub(const The_relocate_info*, unsigned int,
3066                       const Sized_symbol<size>*, unsigned int,
3067                       const Symbol_value<size>*,
3068                       typename elfcpp::Elf_types<size>::Elf_Swxword,
3069                       Address Elf_Addr);
3070
3071   // Make an output section.
3072   Output_section*
3073   do_make_output_section(const char* name, elfcpp::Elf_Word type,
3074                          elfcpp::Elf_Xword flags)
3075   { return new The_aarch64_output_section(name, type, flags); }
3076
3077  private:
3078   // The class which scans relocations.
3079   class Scan
3080   {
3081   public:
3082     Scan()
3083       : issued_non_pic_error_(false)
3084     { }
3085
3086     inline void
3087     local(Symbol_table* symtab, Layout* layout, Target_aarch64* target,
3088           Sized_relobj_file<size, big_endian>* object,
3089           unsigned int data_shndx,
3090           Output_section* output_section,
3091           const elfcpp::Rela<size, big_endian>& reloc, unsigned int r_type,
3092           const elfcpp::Sym<size, big_endian>& lsym,
3093           bool is_discarded);
3094
3095     inline void
3096     global(Symbol_table* symtab, Layout* layout, Target_aarch64* target,
3097            Sized_relobj_file<size, big_endian>* object,
3098            unsigned int data_shndx,
3099            Output_section* output_section,
3100            const elfcpp::Rela<size, big_endian>& reloc, unsigned int r_type,
3101            Symbol* gsym);
3102
3103     inline bool
3104     local_reloc_may_be_function_pointer(Symbol_table* , Layout* ,
3105                                         Target_aarch64<size, big_endian>* ,
3106                                         Sized_relobj_file<size, big_endian>* ,
3107                                         unsigned int ,
3108                                         Output_section* ,
3109                                         const elfcpp::Rela<size, big_endian>& ,
3110                                         unsigned int r_type,
3111                                         const elfcpp::Sym<size, big_endian>&);
3112
3113     inline bool
3114     global_reloc_may_be_function_pointer(Symbol_table* , Layout* ,
3115                                          Target_aarch64<size, big_endian>* ,
3116                                          Sized_relobj_file<size, big_endian>* ,
3117                                          unsigned int ,
3118                                          Output_section* ,
3119                                          const elfcpp::Rela<size, big_endian>& ,
3120                                          unsigned int r_type,
3121                                          Symbol* gsym);
3122
3123   private:
3124     static void
3125     unsupported_reloc_local(Sized_relobj_file<size, big_endian>*,
3126                             unsigned int r_type);
3127
3128     static void
3129     unsupported_reloc_global(Sized_relobj_file<size, big_endian>*,
3130                              unsigned int r_type, Symbol*);
3131
3132     inline bool
3133     possible_function_pointer_reloc(unsigned int r_type);
3134
3135     void
3136     check_non_pic(Relobj*, unsigned int r_type);
3137
3138     bool
3139     reloc_needs_plt_for_ifunc(Sized_relobj_file<size, big_endian>*,
3140                               unsigned int r_type);
3141
3142     // Whether we have issued an error about a non-PIC compilation.
3143     bool issued_non_pic_error_;
3144   };
3145
3146   // The class which implements relocation.
3147   class Relocate
3148   {
3149    public:
3150     Relocate()
3151       : skip_call_tls_get_addr_(false)
3152     { }
3153
3154     ~Relocate()
3155     { }
3156
3157     // Do a relocation.  Return false if the caller should not issue
3158     // any warnings about this relocation.
3159     inline bool
3160     relocate(const Relocate_info<size, big_endian>*, Target_aarch64*,
3161              Output_section*,
3162              size_t relnum, const elfcpp::Rela<size, big_endian>&,
3163              unsigned int r_type, const Sized_symbol<size>*,
3164              const Symbol_value<size>*,
3165              unsigned char*, typename elfcpp::Elf_types<size>::Elf_Addr,
3166              section_size_type);
3167
3168   private:
3169     inline typename AArch64_relocate_functions<size, big_endian>::Status
3170     relocate_tls(const Relocate_info<size, big_endian>*,
3171                  Target_aarch64<size, big_endian>*,
3172                  size_t,
3173                  const elfcpp::Rela<size, big_endian>&,
3174                  unsigned int r_type, const Sized_symbol<size>*,
3175                  const Symbol_value<size>*,
3176                  unsigned char*,
3177                  typename elfcpp::Elf_types<size>::Elf_Addr);
3178
3179     inline typename AArch64_relocate_functions<size, big_endian>::Status
3180     tls_gd_to_le(
3181                  const Relocate_info<size, big_endian>*,
3182                  Target_aarch64<size, big_endian>*,
3183                  const elfcpp::Rela<size, big_endian>&,
3184                  unsigned int,
3185                  unsigned char*,
3186                  const Symbol_value<size>*);
3187
3188     inline typename AArch64_relocate_functions<size, big_endian>::Status
3189     tls_ld_to_le(
3190                  const Relocate_info<size, big_endian>*,
3191                  Target_aarch64<size, big_endian>*,
3192                  const elfcpp::Rela<size, big_endian>&,
3193                  unsigned int,
3194                  unsigned char*,
3195                  const Symbol_value<size>*);
3196
3197     inline typename AArch64_relocate_functions<size, big_endian>::Status
3198     tls_ie_to_le(
3199                  const Relocate_info<size, big_endian>*,
3200                  Target_aarch64<size, big_endian>*,
3201                  const elfcpp::Rela<size, big_endian>&,
3202                  unsigned int,
3203                  unsigned char*,
3204                  const Symbol_value<size>*);
3205
3206     inline typename AArch64_relocate_functions<size, big_endian>::Status
3207     tls_desc_gd_to_le(
3208                  const Relocate_info<size, big_endian>*,
3209                  Target_aarch64<size, big_endian>*,
3210                  const elfcpp::Rela<size, big_endian>&,
3211                  unsigned int,
3212                  unsigned char*,
3213                  const Symbol_value<size>*);
3214
3215     inline typename AArch64_relocate_functions<size, big_endian>::Status
3216     tls_desc_gd_to_ie(
3217                  const Relocate_info<size, big_endian>*,
3218                  Target_aarch64<size, big_endian>*,
3219                  const elfcpp::Rela<size, big_endian>&,
3220                  unsigned int,
3221                  unsigned char*,
3222                  const Symbol_value<size>*,
3223                  typename elfcpp::Elf_types<size>::Elf_Addr,
3224                  typename elfcpp::Elf_types<size>::Elf_Addr);
3225
3226     bool skip_call_tls_get_addr_;
3227
3228   };  // End of class Relocate
3229
3230   // A class which returns the size required for a relocation type,
3231   // used while scanning relocs during a relocatable link.
3232   class Relocatable_size_for_reloc
3233   {
3234    public:
3235     unsigned int
3236     get_size_for_reloc(unsigned int, Relobj*);
3237   };
3238
3239   // Adjust TLS relocation type based on the options and whether this
3240   // is a local symbol.
3241   static tls::Tls_optimization
3242   optimize_tls_reloc(bool is_final, int r_type);
3243
3244   // Get the GOT section, creating it if necessary.
3245   Output_data_got_aarch64<size, big_endian>*
3246   got_section(Symbol_table*, Layout*);
3247
3248   // Get the GOT PLT section.
3249   Output_data_space*
3250   got_plt_section() const
3251   {
3252     gold_assert(this->got_plt_ != NULL);
3253     return this->got_plt_;
3254   }
3255
3256   // Get the GOT section for TLSDESC entries.
3257   Output_data_got<size, big_endian>*
3258   got_tlsdesc_section() const
3259   {
3260     gold_assert(this->got_tlsdesc_ != NULL);
3261     return this->got_tlsdesc_;
3262   }
3263
3264   // Create the PLT section.
3265   void
3266   make_plt_section(Symbol_table* symtab, Layout* layout);
3267
3268   // Create a PLT entry for a global symbol.
3269   void
3270   make_plt_entry(Symbol_table*, Layout*, Symbol*);
3271
3272   // Create a PLT entry for a local STT_GNU_IFUNC symbol.
3273   void
3274   make_local_ifunc_plt_entry(Symbol_table*, Layout*,
3275                              Sized_relobj_file<size, big_endian>* relobj,
3276                              unsigned int local_sym_index);
3277
3278   // Define the _TLS_MODULE_BASE_ symbol in the TLS segment.
3279   void
3280   define_tls_base_symbol(Symbol_table*, Layout*);
3281
3282   // Create the reserved PLT and GOT entries for the TLS descriptor resolver.
3283   void
3284   reserve_tlsdesc_entries(Symbol_table* symtab, Layout* layout);
3285
3286   // Create a GOT entry for the TLS module index.
3287   unsigned int
3288   got_mod_index_entry(Symbol_table* symtab, Layout* layout,
3289                       Sized_relobj_file<size, big_endian>* object);
3290
3291   // Get the PLT section.
3292   Output_data_plt_aarch64<size, big_endian>*
3293   plt_section() const
3294   {
3295     gold_assert(this->plt_ != NULL);
3296     return this->plt_;
3297   }
3298
3299   // Helper method to create erratum stubs for ST_E_843419 and ST_E_835769. For
3300   // ST_E_843419, we need an additional field for adrp offset.
3301   void create_erratum_stub(
3302     AArch64_relobj<size, big_endian>* relobj,
3303     unsigned int shndx,
3304     section_size_type erratum_insn_offset,
3305     Address erratum_address,
3306     typename Insn_utilities::Insntype erratum_insn,
3307     int erratum_type,
3308     unsigned int e843419_adrp_offset=0);
3309
3310   // Return whether this is a 3-insn erratum sequence.
3311   bool is_erratum_843419_sequence(
3312       typename elfcpp::Swap<32,big_endian>::Valtype insn1,
3313       typename elfcpp::Swap<32,big_endian>::Valtype insn2,
3314       typename elfcpp::Swap<32,big_endian>::Valtype insn3);
3315
3316   // Return whether this is a 835769 sequence.
3317   // (Similarly implemented as in elfnn-aarch64.c.)
3318   bool is_erratum_835769_sequence(
3319       typename elfcpp::Swap<32,big_endian>::Valtype,
3320       typename elfcpp::Swap<32,big_endian>::Valtype);
3321
3322   // Get the dynamic reloc section, creating it if necessary.
3323   Reloc_section*
3324   rela_dyn_section(Layout*);
3325
3326   // Get the section to use for TLSDESC relocations.
3327   Reloc_section*
3328   rela_tlsdesc_section(Layout*) const;
3329
3330   // Get the section to use for IRELATIVE relocations.
3331   Reloc_section*
3332   rela_irelative_section(Layout*);
3333
3334   // Add a potential copy relocation.
3335   void
3336   copy_reloc(Symbol_table* symtab, Layout* layout,
3337              Sized_relobj_file<size, big_endian>* object,
3338              unsigned int shndx, Output_section* output_section,
3339              Symbol* sym, const elfcpp::Rela<size, big_endian>& reloc)
3340   {
3341     this->copy_relocs_.copy_reloc(symtab, layout,
3342                                   symtab->get_sized_symbol<size>(sym),
3343                                   object, shndx, output_section,
3344                                   reloc, this->rela_dyn_section(layout));
3345   }
3346
3347   // Information about this specific target which we pass to the
3348   // general Target structure.
3349   static const Target::Target_info aarch64_info;
3350
3351   // The types of GOT entries needed for this platform.
3352   // These values are exposed to the ABI in an incremental link.
3353   // Do not renumber existing values without changing the version
3354   // number of the .gnu_incremental_inputs section.
3355   enum Got_type
3356   {
3357     GOT_TYPE_STANDARD = 0,      // GOT entry for a regular symbol
3358     GOT_TYPE_TLS_OFFSET = 1,    // GOT entry for TLS offset
3359     GOT_TYPE_TLS_PAIR = 2,      // GOT entry for TLS module/offset pair
3360     GOT_TYPE_TLS_DESC = 3       // GOT entry for TLS_DESC pair
3361   };
3362
3363   // This type is used as the argument to the target specific
3364   // relocation routines.  The only target specific reloc is
3365   // R_AARCh64_TLSDESC against a local symbol.
3366   struct Tlsdesc_info
3367   {
3368     Tlsdesc_info(Sized_relobj_file<size, big_endian>* a_object,
3369                  unsigned int a_r_sym)
3370       : object(a_object), r_sym(a_r_sym)
3371     { }
3372
3373     // The object in which the local symbol is defined.
3374     Sized_relobj_file<size, big_endian>* object;
3375     // The local symbol index in the object.
3376     unsigned int r_sym;
3377   };
3378
3379   // The GOT section.
3380   Output_data_got_aarch64<size, big_endian>* got_;
3381   // The PLT section.
3382   Output_data_plt_aarch64<size, big_endian>* plt_;
3383   // The GOT PLT section.
3384   Output_data_space* got_plt_;
3385   // The GOT section for IRELATIVE relocations.
3386   Output_data_space* got_irelative_;
3387   // The GOT section for TLSDESC relocations.
3388   Output_data_got<size, big_endian>* got_tlsdesc_;
3389   // The _GLOBAL_OFFSET_TABLE_ symbol.
3390   Symbol* global_offset_table_;
3391   // The dynamic reloc section.
3392   Reloc_section* rela_dyn_;
3393   // The section to use for IRELATIVE relocs.
3394   Reloc_section* rela_irelative_;
3395   // Relocs saved to avoid a COPY reloc.
3396   Copy_relocs<elfcpp::SHT_RELA, size, big_endian> copy_relocs_;
3397   // Offset of the GOT entry for the TLS module index.
3398   unsigned int got_mod_index_offset_;
3399   // We handle R_AARCH64_TLSDESC against a local symbol as a target
3400   // specific relocation. Here we store the object and local symbol
3401   // index for the relocation.
3402   std::vector<Tlsdesc_info> tlsdesc_reloc_info_;
3403   // True if the _TLS_MODULE_BASE_ symbol has been defined.
3404   bool tls_base_symbol_defined_;
3405   // List of stub_tables
3406   Stub_table_list stub_tables_;
3407   // Actual stub group size
3408   section_size_type stub_group_size_;
3409   AArch64_input_section_map aarch64_input_section_map_;
3410 };  // End of Target_aarch64
3411
3412
3413 template<>
3414 const Target::Target_info Target_aarch64<64, false>::aarch64_info =
3415 {
3416   64,                   // size
3417   false,                // is_big_endian
3418   elfcpp::EM_AARCH64,   // machine_code
3419   false,                // has_make_symbol
3420   false,                // has_resolve
3421   false,                // has_code_fill
3422   true,                 // is_default_stack_executable
3423   true,                 // can_icf_inline_merge_sections
3424   '\0',                 // wrap_char
3425   "/lib/ld.so.1",       // program interpreter
3426   0x400000,             // default_text_segment_address
3427   0x10000,              // abi_pagesize (overridable by -z max-page-size)
3428   0x1000,               // common_pagesize (overridable by -z common-page-size)
3429   false,                // isolate_execinstr
3430   0,                    // rosegment_gap
3431   elfcpp::SHN_UNDEF,    // small_common_shndx
3432   elfcpp::SHN_UNDEF,    // large_common_shndx
3433   0,                    // small_common_section_flags
3434   0,                    // large_common_section_flags
3435   NULL,                 // attributes_section
3436   NULL,                 // attributes_vendor
3437   "_start"              // entry_symbol_name
3438 };
3439
3440 template<>
3441 const Target::Target_info Target_aarch64<32, false>::aarch64_info =
3442 {
3443   32,                   // size
3444   false,                // is_big_endian
3445   elfcpp::EM_AARCH64,   // machine_code
3446   false,                // has_make_symbol
3447   false,                // has_resolve
3448   false,                // has_code_fill
3449   true,                 // is_default_stack_executable
3450   false,                // can_icf_inline_merge_sections
3451   '\0',                 // wrap_char
3452   "/lib/ld.so.1",       // program interpreter
3453   0x400000,             // default_text_segment_address
3454   0x10000,              // abi_pagesize (overridable by -z max-page-size)
3455   0x1000,               // common_pagesize (overridable by -z common-page-size)
3456   false,                // isolate_execinstr
3457   0,                    // rosegment_gap
3458   elfcpp::SHN_UNDEF,    // small_common_shndx
3459   elfcpp::SHN_UNDEF,    // large_common_shndx
3460   0,                    // small_common_section_flags
3461   0,                    // large_common_section_flags
3462   NULL,                 // attributes_section
3463   NULL,                 // attributes_vendor
3464   "_start"              // entry_symbol_name
3465 };
3466
3467 template<>
3468 const Target::Target_info Target_aarch64<64, true>::aarch64_info =
3469 {
3470   64,                   // size
3471   true,                 // is_big_endian
3472   elfcpp::EM_AARCH64,   // machine_code
3473   false,                // has_make_symbol
3474   false,                // has_resolve
3475   false,                // has_code_fill
3476   true,                 // is_default_stack_executable
3477   true,                 // can_icf_inline_merge_sections
3478   '\0',                 // wrap_char
3479   "/lib/ld.so.1",       // program interpreter
3480   0x400000,             // default_text_segment_address
3481   0x10000,              // abi_pagesize (overridable by -z max-page-size)
3482   0x1000,               // common_pagesize (overridable by -z common-page-size)
3483   false,                // isolate_execinstr
3484   0,                    // rosegment_gap
3485   elfcpp::SHN_UNDEF,    // small_common_shndx
3486   elfcpp::SHN_UNDEF,    // large_common_shndx
3487   0,                    // small_common_section_flags
3488   0,                    // large_common_section_flags
3489   NULL,                 // attributes_section
3490   NULL,                 // attributes_vendor
3491   "_start"              // entry_symbol_name
3492 };
3493
3494 template<>
3495 const Target::Target_info Target_aarch64<32, true>::aarch64_info =
3496 {
3497   32,                   // size
3498   true,                 // is_big_endian
3499   elfcpp::EM_AARCH64,   // machine_code
3500   false,                // has_make_symbol
3501   false,                // has_resolve
3502   false,                // has_code_fill
3503   true,                 // is_default_stack_executable
3504   false,                // can_icf_inline_merge_sections
3505   '\0',                 // wrap_char
3506   "/lib/ld.so.1",       // program interpreter
3507   0x400000,             // default_text_segment_address
3508   0x10000,              // abi_pagesize (overridable by -z max-page-size)
3509   0x1000,               // common_pagesize (overridable by -z common-page-size)
3510   false,                // isolate_execinstr
3511   0,                    // rosegment_gap
3512   elfcpp::SHN_UNDEF,    // small_common_shndx
3513   elfcpp::SHN_UNDEF,    // large_common_shndx
3514   0,                    // small_common_section_flags
3515   0,                    // large_common_section_flags
3516   NULL,                 // attributes_section
3517   NULL,                 // attributes_vendor
3518   "_start"              // entry_symbol_name
3519 };
3520
3521 // Get the GOT section, creating it if necessary.
3522
3523 template<int size, bool big_endian>
3524 Output_data_got_aarch64<size, big_endian>*
3525 Target_aarch64<size, big_endian>::got_section(Symbol_table* symtab,
3526                                               Layout* layout)
3527 {
3528   if (this->got_ == NULL)
3529     {
3530       gold_assert(symtab != NULL && layout != NULL);
3531
3532       // When using -z now, we can treat .got.plt as a relro section.
3533       // Without -z now, it is modified after program startup by lazy
3534       // PLT relocations.
3535       bool is_got_plt_relro = parameters->options().now();
3536       Output_section_order got_order = (is_got_plt_relro
3537                                         ? ORDER_RELRO
3538                                         : ORDER_RELRO_LAST);
3539       Output_section_order got_plt_order = (is_got_plt_relro
3540                                             ? ORDER_RELRO
3541                                             : ORDER_NON_RELRO_FIRST);
3542
3543       // Layout of .got and .got.plt sections.
3544       // .got[0] &_DYNAMIC                          <-_GLOBAL_OFFSET_TABLE_
3545       // ...
3546       // .gotplt[0] reserved for ld.so (&linkmap)   <--DT_PLTGOT
3547       // .gotplt[1] reserved for ld.so (resolver)
3548       // .gotplt[2] reserved
3549
3550       // Generate .got section.
3551       this->got_ = new Output_data_got_aarch64<size, big_endian>(symtab,
3552                                                                  layout);
3553       layout->add_output_section_data(".got", elfcpp::SHT_PROGBITS,
3554                                       (elfcpp::SHF_ALLOC | elfcpp::SHF_WRITE),
3555                                       this->got_, got_order, true);
3556       // The first word of GOT is reserved for the address of .dynamic.
3557       // We put 0 here now. The value will be replaced later in
3558       // Output_data_got_aarch64::do_write.
3559       this->got_->add_constant(0);
3560
3561       // Define _GLOBAL_OFFSET_TABLE_ at the start of the PLT.
3562       // _GLOBAL_OFFSET_TABLE_ value points to the start of the .got section,
3563       // even if there is a .got.plt section.
3564       this->global_offset_table_ =
3565         symtab->define_in_output_data("_GLOBAL_OFFSET_TABLE_", NULL,
3566                                       Symbol_table::PREDEFINED,
3567                                       this->got_,
3568                                       0, 0, elfcpp::STT_OBJECT,
3569                                       elfcpp::STB_LOCAL,
3570                                       elfcpp::STV_HIDDEN, 0,
3571                                       false, false);
3572
3573       // Generate .got.plt section.
3574       this->got_plt_ = new Output_data_space(size / 8, "** GOT PLT");
3575       layout->add_output_section_data(".got.plt", elfcpp::SHT_PROGBITS,
3576                                       (elfcpp::SHF_ALLOC
3577                                        | elfcpp::SHF_WRITE),
3578                                       this->got_plt_, got_plt_order,
3579                                       is_got_plt_relro);
3580
3581       // The first three entries are reserved.
3582       this->got_plt_->set_current_data_size(
3583         AARCH64_GOTPLT_RESERVE_COUNT * (size / 8));
3584
3585       // If there are any IRELATIVE relocations, they get GOT entries
3586       // in .got.plt after the jump slot entries.
3587       this->got_irelative_ = new Output_data_space(size / 8,
3588                                                    "** GOT IRELATIVE PLT");
3589       layout->add_output_section_data(".got.plt", elfcpp::SHT_PROGBITS,
3590                                       (elfcpp::SHF_ALLOC
3591                                        | elfcpp::SHF_WRITE),
3592                                       this->got_irelative_,
3593                                       got_plt_order,
3594                                       is_got_plt_relro);
3595
3596       // If there are any TLSDESC relocations, they get GOT entries in
3597       // .got.plt after the jump slot and IRELATIVE entries.
3598       this->got_tlsdesc_ = new Output_data_got<size, big_endian>();
3599       layout->add_output_section_data(".got.plt", elfcpp::SHT_PROGBITS,
3600                                       (elfcpp::SHF_ALLOC
3601                                        | elfcpp::SHF_WRITE),
3602                                       this->got_tlsdesc_,
3603                                       got_plt_order,
3604                                       is_got_plt_relro);
3605
3606       if (!is_got_plt_relro)
3607         {
3608           // Those bytes can go into the relro segment.
3609           layout->increase_relro(
3610             AARCH64_GOTPLT_RESERVE_COUNT * (size / 8));
3611         }
3612
3613     }
3614   return this->got_;
3615 }
3616
3617 // Get the dynamic reloc section, creating it if necessary.
3618
3619 template<int size, bool big_endian>
3620 typename Target_aarch64<size, big_endian>::Reloc_section*
3621 Target_aarch64<size, big_endian>::rela_dyn_section(Layout* layout)
3622 {
3623   if (this->rela_dyn_ == NULL)
3624     {
3625       gold_assert(layout != NULL);
3626       this->rela_dyn_ = new Reloc_section(parameters->options().combreloc());
3627       layout->add_output_section_data(".rela.dyn", elfcpp::SHT_RELA,
3628                                       elfcpp::SHF_ALLOC, this->rela_dyn_,
3629                                       ORDER_DYNAMIC_RELOCS, false);
3630     }
3631   return this->rela_dyn_;
3632 }
3633
3634 // Get the section to use for IRELATIVE relocs, creating it if
3635 // necessary.  These go in .rela.dyn, but only after all other dynamic
3636 // relocations.  They need to follow the other dynamic relocations so
3637 // that they can refer to global variables initialized by those
3638 // relocs.
3639
3640 template<int size, bool big_endian>
3641 typename Target_aarch64<size, big_endian>::Reloc_section*
3642 Target_aarch64<size, big_endian>::rela_irelative_section(Layout* layout)
3643 {
3644   if (this->rela_irelative_ == NULL)
3645     {
3646       // Make sure we have already created the dynamic reloc section.
3647       this->rela_dyn_section(layout);
3648       this->rela_irelative_ = new Reloc_section(false);
3649       layout->add_output_section_data(".rela.dyn", elfcpp::SHT_RELA,
3650                                       elfcpp::SHF_ALLOC, this->rela_irelative_,
3651                                       ORDER_DYNAMIC_RELOCS, false);
3652       gold_assert(this->rela_dyn_->output_section()
3653                   == this->rela_irelative_->output_section());
3654     }
3655   return this->rela_irelative_;
3656 }
3657
3658
3659 // do_make_elf_object to override the same function in the base class.  We need
3660 // to use a target-specific sub-class of Sized_relobj_file<size, big_endian> to
3661 // store backend specific information. Hence we need to have our own ELF object
3662 // creation.
3663
3664 template<int size, bool big_endian>
3665 Object*
3666 Target_aarch64<size, big_endian>::do_make_elf_object(
3667     const std::string& name,
3668     Input_file* input_file,
3669     off_t offset, const elfcpp::Ehdr<size, big_endian>& ehdr)
3670 {
3671   int et = ehdr.get_e_type();
3672   // ET_EXEC files are valid input for --just-symbols/-R,
3673   // and we treat them as relocatable objects.
3674   if (et == elfcpp::ET_EXEC && input_file->just_symbols())
3675     return Sized_target<size, big_endian>::do_make_elf_object(
3676         name, input_file, offset, ehdr);
3677   else if (et == elfcpp::ET_REL)
3678     {
3679       AArch64_relobj<size, big_endian>* obj =
3680         new AArch64_relobj<size, big_endian>(name, input_file, offset, ehdr);
3681       obj->setup();
3682       return obj;
3683     }
3684   else if (et == elfcpp::ET_DYN)
3685     {
3686       // Keep base implementation.
3687       Sized_dynobj<size, big_endian>* obj =
3688           new Sized_dynobj<size, big_endian>(name, input_file, offset, ehdr);
3689       obj->setup();
3690       return obj;
3691     }
3692   else
3693     {
3694       gold_error(_("%s: unsupported ELF file type %d"),
3695                  name.c_str(), et);
3696       return NULL;
3697     }
3698 }
3699
3700
3701 // Scan a relocation for stub generation.
3702
3703 template<int size, bool big_endian>
3704 void
3705 Target_aarch64<size, big_endian>::scan_reloc_for_stub(
3706     const Relocate_info<size, big_endian>* relinfo,
3707     unsigned int r_type,
3708     const Sized_symbol<size>* gsym,
3709     unsigned int r_sym,
3710     const Symbol_value<size>* psymval,
3711     typename elfcpp::Elf_types<size>::Elf_Swxword addend,
3712     Address address)
3713 {
3714   const AArch64_relobj<size, big_endian>* aarch64_relobj =
3715       static_cast<AArch64_relobj<size, big_endian>*>(relinfo->object);
3716
3717   Symbol_value<size> symval;
3718   if (gsym != NULL)
3719     {
3720       const AArch64_reloc_property* arp = aarch64_reloc_property_table->
3721         get_reloc_property(r_type);
3722       if (gsym->use_plt_offset(arp->reference_flags()))
3723         {
3724           // This uses a PLT, change the symbol value.
3725           symval.set_output_value(this->plt_section()->address()
3726                                   + gsym->plt_offset());
3727           psymval = &symval;
3728         }
3729       else if (gsym->is_undefined())
3730         // There is no need to generate a stub symbol is undefined.
3731         return;
3732     }
3733
3734   // Get the symbol value.
3735   typename Symbol_value<size>::Value value = psymval->value(aarch64_relobj, 0);
3736
3737   // Owing to pipelining, the PC relative branches below actually skip
3738   // two instructions when the branch offset is 0.
3739   Address destination = static_cast<Address>(-1);
3740   switch (r_type)
3741     {
3742     case elfcpp::R_AARCH64_CALL26:
3743     case elfcpp::R_AARCH64_JUMP26:
3744       destination = value + addend;
3745       break;
3746     default:
3747       gold_unreachable();
3748     }
3749
3750   int stub_type = The_reloc_stub::
3751       stub_type_for_reloc(r_type, address, destination);
3752   if (stub_type == ST_NONE)
3753     return;
3754
3755   The_stub_table* stub_table = aarch64_relobj->stub_table(relinfo->data_shndx);
3756   gold_assert(stub_table != NULL);
3757
3758   The_reloc_stub_key key(stub_type, gsym, aarch64_relobj, r_sym, addend);
3759   The_reloc_stub* stub = stub_table->find_reloc_stub(key);
3760   if (stub == NULL)
3761     {
3762       stub = new The_reloc_stub(stub_type);
3763       stub_table->add_reloc_stub(stub, key);
3764     }
3765   stub->set_destination_address(destination);
3766 }  // End of Target_aarch64::scan_reloc_for_stub
3767
3768
3769 // This function scans a relocation section for stub generation.
3770 // The template parameter Relocate must be a class type which provides
3771 // a single function, relocate(), which implements the machine
3772 // specific part of a relocation.
3773
3774 // BIG_ENDIAN is the endianness of the data.  SH_TYPE is the section type:
3775 // SHT_REL or SHT_RELA.
3776
3777 // PRELOCS points to the relocation data.  RELOC_COUNT is the number
3778 // of relocs.  OUTPUT_SECTION is the output section.
3779 // NEEDS_SPECIAL_OFFSET_HANDLING is true if input offsets need to be
3780 // mapped to output offsets.
3781
3782 // VIEW is the section data, VIEW_ADDRESS is its memory address, and
3783 // VIEW_SIZE is the size.  These refer to the input section, unless
3784 // NEEDS_SPECIAL_OFFSET_HANDLING is true, in which case they refer to
3785 // the output section.
3786
3787 template<int size, bool big_endian>
3788 template<int sh_type>
3789 void inline
3790 Target_aarch64<size, big_endian>::scan_reloc_section_for_stubs(
3791     const Relocate_info<size, big_endian>* relinfo,
3792     const unsigned char* prelocs,
3793     size_t reloc_count,
3794     Output_section* /*output_section*/,
3795     bool /*needs_special_offset_handling*/,
3796     const unsigned char* /*view*/,
3797     Address view_address,
3798     section_size_type)
3799 {
3800   typedef typename Reloc_types<sh_type,size,big_endian>::Reloc Reltype;
3801
3802   const int reloc_size =
3803       Reloc_types<sh_type,size,big_endian>::reloc_size;
3804   AArch64_relobj<size, big_endian>* object =
3805       static_cast<AArch64_relobj<size, big_endian>*>(relinfo->object);
3806   unsigned int local_count = object->local_symbol_count();
3807
3808   gold::Default_comdat_behavior default_comdat_behavior;
3809   Comdat_behavior comdat_behavior = CB_UNDETERMINED;
3810
3811   for (size_t i = 0; i < reloc_count; ++i, prelocs += reloc_size)
3812     {
3813       Reltype reloc(prelocs);
3814       typename elfcpp::Elf_types<size>::Elf_WXword r_info = reloc.get_r_info();
3815       unsigned int r_sym = elfcpp::elf_r_sym<size>(r_info);
3816       unsigned int r_type = elfcpp::elf_r_type<size>(r_info);
3817       if (r_type != elfcpp::R_AARCH64_CALL26
3818           && r_type != elfcpp::R_AARCH64_JUMP26)
3819         continue;
3820
3821       section_offset_type offset =
3822           convert_to_section_size_type(reloc.get_r_offset());
3823
3824       // Get the addend.
3825       typename elfcpp::Elf_types<size>::Elf_Swxword addend =
3826           reloc.get_r_addend();
3827
3828       const Sized_symbol<size>* sym;
3829       Symbol_value<size> symval;
3830       const Symbol_value<size> *psymval;
3831       bool is_defined_in_discarded_section;
3832       unsigned int shndx;
3833       if (r_sym < local_count)
3834         {
3835           sym = NULL;
3836           psymval = object->local_symbol(r_sym);
3837
3838           // If the local symbol belongs to a section we are discarding,
3839           // and that section is a debug section, try to find the
3840           // corresponding kept section and map this symbol to its
3841           // counterpart in the kept section.  The symbol must not
3842           // correspond to a section we are folding.
3843           bool is_ordinary;
3844           shndx = psymval->input_shndx(&is_ordinary);
3845           is_defined_in_discarded_section =
3846             (is_ordinary
3847              && shndx != elfcpp::SHN_UNDEF
3848              && !object->is_section_included(shndx)
3849              && !relinfo->symtab->is_section_folded(object, shndx));
3850
3851           // We need to compute the would-be final value of this local
3852           // symbol.
3853           if (!is_defined_in_discarded_section)
3854             {
3855               typedef Sized_relobj_file<size, big_endian> ObjType;
3856               typename ObjType::Compute_final_local_value_status status =
3857                 object->compute_final_local_value(r_sym, psymval, &symval,
3858                                                   relinfo->symtab);
3859               if (status == ObjType::CFLV_OK)
3860                 {
3861                   // Currently we cannot handle a branch to a target in
3862                   // a merged section.  If this is the case, issue an error
3863                   // and also free the merge symbol value.
3864                   if (!symval.has_output_value())
3865                     {
3866                       const std::string& section_name =
3867                         object->section_name(shndx);
3868                       object->error(_("cannot handle branch to local %u "
3869                                           "in a merged section %s"),
3870                                         r_sym, section_name.c_str());
3871                     }
3872                   psymval = &symval;
3873                 }
3874               else
3875                 {
3876                   // We cannot determine the final value.
3877                   continue;
3878                 }
3879             }
3880         }
3881       else
3882         {
3883           const Symbol* gsym;
3884           gsym = object->global_symbol(r_sym);
3885           gold_assert(gsym != NULL);
3886           if (gsym->is_forwarder())
3887             gsym = relinfo->symtab->resolve_forwards(gsym);
3888
3889           sym = static_cast<const Sized_symbol<size>*>(gsym);
3890           if (sym->has_symtab_index() && sym->symtab_index() != -1U)
3891             symval.set_output_symtab_index(sym->symtab_index());
3892           else
3893             symval.set_no_output_symtab_entry();
3894
3895           // We need to compute the would-be final value of this global
3896           // symbol.
3897           const Symbol_table* symtab = relinfo->symtab;
3898           const Sized_symbol<size>* sized_symbol =
3899               symtab->get_sized_symbol<size>(gsym);
3900           Symbol_table::Compute_final_value_status status;
3901           typename elfcpp::Elf_types<size>::Elf_Addr value =
3902               symtab->compute_final_value<size>(sized_symbol, &status);
3903
3904           // Skip this if the symbol has not output section.
3905           if (status == Symbol_table::CFVS_NO_OUTPUT_SECTION)
3906             continue;
3907           symval.set_output_value(value);
3908
3909           if (gsym->type() == elfcpp::STT_TLS)
3910             symval.set_is_tls_symbol();
3911           else if (gsym->type() == elfcpp::STT_GNU_IFUNC)
3912             symval.set_is_ifunc_symbol();
3913           psymval = &symval;
3914
3915           is_defined_in_discarded_section =
3916               (gsym->is_defined_in_discarded_section()
3917                && gsym->is_undefined());
3918           shndx = 0;
3919         }
3920
3921       Symbol_value<size> symval2;
3922       if (is_defined_in_discarded_section)
3923         {
3924           if (comdat_behavior == CB_UNDETERMINED)
3925             {
3926               std::string name = object->section_name(relinfo->data_shndx);
3927               comdat_behavior = default_comdat_behavior.get(name.c_str());
3928             }
3929           if (comdat_behavior == CB_PRETEND)
3930             {
3931               bool found;
3932               typename elfcpp::Elf_types<size>::Elf_Addr value =
3933                 object->map_to_kept_section(shndx, &found);
3934               if (found)
3935                 symval2.set_output_value(value + psymval->input_value());
3936               else
3937                 symval2.set_output_value(0);
3938             }
3939           else
3940             {
3941               if (comdat_behavior == CB_WARNING)
3942                 gold_warning_at_location(relinfo, i, offset,
3943                                          _("relocation refers to discarded "
3944                                            "section"));
3945               symval2.set_output_value(0);
3946             }
3947           symval2.set_no_output_symtab_entry();
3948           psymval = &symval2;
3949         }
3950
3951       // If symbol is a section symbol, we don't know the actual type of
3952       // destination.  Give up.
3953       if (psymval->is_section_symbol())
3954         continue;
3955
3956       this->scan_reloc_for_stub(relinfo, r_type, sym, r_sym, psymval,
3957                                 addend, view_address + offset);
3958     }  // End of iterating relocs in a section
3959 }  // End of Target_aarch64::scan_reloc_section_for_stubs
3960
3961
3962 // Scan an input section for stub generation.
3963
3964 template<int size, bool big_endian>
3965 void
3966 Target_aarch64<size, big_endian>::scan_section_for_stubs(
3967     const Relocate_info<size, big_endian>* relinfo,
3968     unsigned int sh_type,
3969     const unsigned char* prelocs,
3970     size_t reloc_count,
3971     Output_section* output_section,
3972     bool needs_special_offset_handling,
3973     const unsigned char* view,
3974     Address view_address,
3975     section_size_type view_size)
3976 {
3977   gold_assert(sh_type == elfcpp::SHT_RELA);
3978   this->scan_reloc_section_for_stubs<elfcpp::SHT_RELA>(
3979       relinfo,
3980       prelocs,
3981       reloc_count,
3982       output_section,
3983       needs_special_offset_handling,
3984       view,
3985       view_address,
3986       view_size);
3987 }
3988
3989
3990 // Relocate a single stub.
3991
3992 template<int size, bool big_endian>
3993 void Target_aarch64<size, big_endian>::
3994 relocate_stub(The_reloc_stub* stub,
3995               const The_relocate_info*,
3996               Output_section*,
3997               unsigned char* view,
3998               Address address,
3999               section_size_type)
4000 {
4001   typedef AArch64_relocate_functions<size, big_endian> The_reloc_functions;
4002   typedef typename The_reloc_functions::Status The_reloc_functions_status;
4003   typedef typename elfcpp::Swap<32,big_endian>::Valtype Insntype;
4004
4005   Insntype* ip = reinterpret_cast<Insntype*>(view);
4006   int insn_number = stub->insn_num();
4007   const uint32_t* insns = stub->insns();
4008   // Check the insns are really those stub insns.
4009   for (int i = 0; i < insn_number; ++i)
4010     {
4011       Insntype insn = elfcpp::Swap<32,big_endian>::readval(ip + i);
4012       gold_assert(((uint32_t)insn == insns[i]));
4013     }
4014
4015   Address dest = stub->destination_address();
4016
4017   switch(stub->type())
4018     {
4019     case ST_ADRP_BRANCH:
4020       {
4021         // 1st reloc is ADR_PREL_PG_HI21
4022         The_reloc_functions_status status =
4023             The_reloc_functions::adrp(view, dest, address);
4024         // An error should never arise in the above step. If so, please
4025         // check 'aarch64_valid_for_adrp_p'.
4026         gold_assert(status == The_reloc_functions::STATUS_OKAY);
4027
4028         // 2nd reloc is ADD_ABS_LO12_NC
4029         const AArch64_reloc_property* arp =
4030             aarch64_reloc_property_table->get_reloc_property(
4031                 elfcpp::R_AARCH64_ADD_ABS_LO12_NC);
4032         gold_assert(arp != NULL);
4033         status = The_reloc_functions::template
4034             rela_general<32>(view + 4, dest, 0, arp);
4035         // An error should never arise, it is an "_NC" relocation.
4036         gold_assert(status == The_reloc_functions::STATUS_OKAY);
4037       }
4038       break;
4039
4040     case ST_LONG_BRANCH_ABS:
4041       // 1st reloc is R_AARCH64_PREL64, at offset 8
4042       elfcpp::Swap<64,big_endian>::writeval(view + 8, dest);
4043       break;
4044
4045     case ST_LONG_BRANCH_PCREL:
4046       {
4047         // "PC" calculation is the 2nd insn in the stub.
4048         uint64_t offset = dest - (address + 4);
4049         // Offset is placed at offset 4 and 5.
4050         elfcpp::Swap<64,big_endian>::writeval(view + 16, offset);
4051       }
4052       break;
4053
4054     default:
4055       gold_unreachable();
4056     }
4057 }
4058
4059
4060 // A class to handle the PLT data.
4061 // This is an abstract base class that handles most of the linker details
4062 // but does not know the actual contents of PLT entries.  The derived
4063 // classes below fill in those details.
4064
4065 template<int size, bool big_endian>
4066 class Output_data_plt_aarch64 : public Output_section_data
4067 {
4068  public:
4069   typedef Output_data_reloc<elfcpp::SHT_RELA, true, size, big_endian>
4070       Reloc_section;
4071   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
4072
4073   Output_data_plt_aarch64(Layout* layout,
4074                           uint64_t addralign,
4075                           Output_data_got_aarch64<size, big_endian>* got,
4076                           Output_data_space* got_plt,
4077                           Output_data_space* got_irelative)
4078     : Output_section_data(addralign), tlsdesc_rel_(NULL), irelative_rel_(NULL),
4079       got_(got), got_plt_(got_plt), got_irelative_(got_irelative),
4080       count_(0), irelative_count_(0), tlsdesc_got_offset_(-1U)
4081   { this->init(layout); }
4082
4083   // Initialize the PLT section.
4084   void
4085   init(Layout* layout);
4086
4087   // Add an entry to the PLT.
4088   void
4089   add_entry(Symbol_table*, Layout*, Symbol* gsym);
4090
4091   // Add an entry to the PLT for a local STT_GNU_IFUNC symbol.
4092   unsigned int
4093   add_local_ifunc_entry(Symbol_table* symtab, Layout*,
4094                         Sized_relobj_file<size, big_endian>* relobj,
4095                         unsigned int local_sym_index);
4096
4097   // Add the relocation for a PLT entry.
4098   void
4099   add_relocation(Symbol_table*, Layout*, Symbol* gsym,
4100                  unsigned int got_offset);
4101
4102   // Add the reserved TLSDESC_PLT entry to the PLT.
4103   void
4104   reserve_tlsdesc_entry(unsigned int got_offset)
4105   { this->tlsdesc_got_offset_ = got_offset; }
4106
4107   // Return true if a TLSDESC_PLT entry has been reserved.
4108   bool
4109   has_tlsdesc_entry() const
4110   { return this->tlsdesc_got_offset_ != -1U; }
4111
4112   // Return the GOT offset for the reserved TLSDESC_PLT entry.
4113   unsigned int
4114   get_tlsdesc_got_offset() const
4115   { return this->tlsdesc_got_offset_; }
4116
4117   // Return the PLT offset of the reserved TLSDESC_PLT entry.
4118   unsigned int
4119   get_tlsdesc_plt_offset() const
4120   {
4121     return (this->first_plt_entry_offset() +
4122             (this->count_ + this->irelative_count_)
4123             * this->get_plt_entry_size());
4124   }
4125
4126   // Return the .rela.plt section data.
4127   Reloc_section*
4128   rela_plt()
4129   { return this->rel_; }
4130
4131   // Return where the TLSDESC relocations should go.
4132   Reloc_section*
4133   rela_tlsdesc(Layout*);
4134
4135   // Return where the IRELATIVE relocations should go in the PLT
4136   // relocations.
4137   Reloc_section*
4138   rela_irelative(Symbol_table*, Layout*);
4139
4140   // Return whether we created a section for IRELATIVE relocations.
4141   bool
4142   has_irelative_section() const
4143   { return this->irelative_rel_ != NULL; }
4144
4145   // Return the number of PLT entries.
4146   unsigned int
4147   entry_count() const
4148   { return this->count_ + this->irelative_count_; }
4149
4150   // Return the offset of the first non-reserved PLT entry.
4151   unsigned int
4152   first_plt_entry_offset() const
4153   { return this->do_first_plt_entry_offset(); }
4154
4155   // Return the size of a PLT entry.
4156   unsigned int
4157   get_plt_entry_size() const
4158   { return this->do_get_plt_entry_size(); }
4159
4160   // Return the reserved tlsdesc entry size.
4161   unsigned int
4162   get_plt_tlsdesc_entry_size() const
4163   { return this->do_get_plt_tlsdesc_entry_size(); }
4164
4165   // Return the PLT address to use for a global symbol.
4166   uint64_t
4167   address_for_global(const Symbol*);
4168
4169   // Return the PLT address to use for a local symbol.
4170   uint64_t
4171   address_for_local(const Relobj*, unsigned int symndx);
4172
4173  protected:
4174   // Fill in the first PLT entry.
4175   void
4176   fill_first_plt_entry(unsigned char* pov,
4177                        Address got_address,
4178                        Address plt_address)
4179   { this->do_fill_first_plt_entry(pov, got_address, plt_address); }
4180
4181   // Fill in a normal PLT entry.
4182   void
4183   fill_plt_entry(unsigned char* pov,
4184                  Address got_address,
4185                  Address plt_address,
4186                  unsigned int got_offset,
4187                  unsigned int plt_offset)
4188   {
4189     this->do_fill_plt_entry(pov, got_address, plt_address,
4190                             got_offset, plt_offset);
4191   }
4192
4193   // Fill in the reserved TLSDESC PLT entry.
4194   void
4195   fill_tlsdesc_entry(unsigned char* pov,
4196                      Address gotplt_address,
4197                      Address plt_address,
4198                      Address got_base,
4199                      unsigned int tlsdesc_got_offset,
4200                      unsigned int plt_offset)
4201   {
4202     this->do_fill_tlsdesc_entry(pov, gotplt_address, plt_address, got_base,
4203                                 tlsdesc_got_offset, plt_offset);
4204   }
4205
4206   virtual unsigned int
4207   do_first_plt_entry_offset() const = 0;
4208
4209   virtual unsigned int
4210   do_get_plt_entry_size() const = 0;
4211
4212   virtual unsigned int
4213   do_get_plt_tlsdesc_entry_size() const = 0;
4214
4215   virtual void
4216   do_fill_first_plt_entry(unsigned char* pov,
4217                           Address got_addr,
4218                           Address plt_addr) = 0;
4219
4220   virtual void
4221   do_fill_plt_entry(unsigned char* pov,
4222                     Address got_address,
4223                     Address plt_address,
4224                     unsigned int got_offset,
4225                     unsigned int plt_offset) = 0;
4226
4227   virtual void
4228   do_fill_tlsdesc_entry(unsigned char* pov,
4229                         Address gotplt_address,
4230                         Address plt_address,
4231                         Address got_base,
4232                         unsigned int tlsdesc_got_offset,
4233                         unsigned int plt_offset) = 0;
4234
4235   void
4236   do_adjust_output_section(Output_section* os);
4237
4238   // Write to a map file.
4239   void
4240   do_print_to_mapfile(Mapfile* mapfile) const
4241   { mapfile->print_output_data(this, _("** PLT")); }
4242
4243  private:
4244   // Set the final size.
4245   void
4246   set_final_data_size();
4247
4248   // Write out the PLT data.
4249   void
4250   do_write(Output_file*);
4251
4252   // The reloc section.
4253   Reloc_section* rel_;
4254
4255   // The TLSDESC relocs, if necessary.  These must follow the regular
4256   // PLT relocs.
4257   Reloc_section* tlsdesc_rel_;
4258
4259   // The IRELATIVE relocs, if necessary.  These must follow the
4260   // regular PLT relocations.
4261   Reloc_section* irelative_rel_;
4262
4263   // The .got section.
4264   Output_data_got_aarch64<size, big_endian>* got_;
4265
4266   // The .got.plt section.
4267   Output_data_space* got_plt_;
4268
4269   // The part of the .got.plt section used for IRELATIVE relocs.
4270   Output_data_space* got_irelative_;
4271
4272   // The number of PLT entries.
4273   unsigned int count_;
4274
4275   // Number of PLT entries with R_AARCH64_IRELATIVE relocs.  These
4276   // follow the regular PLT entries.
4277   unsigned int irelative_count_;
4278
4279   // GOT offset of the reserved TLSDESC_GOT entry for the lazy trampoline.
4280   // Communicated to the loader via DT_TLSDESC_GOT. The magic value -1
4281   // indicates an offset is not allocated.
4282   unsigned int tlsdesc_got_offset_;
4283 };
4284
4285 // Initialize the PLT section.
4286
4287 template<int size, bool big_endian>
4288 void
4289 Output_data_plt_aarch64<size, big_endian>::init(Layout* layout)
4290 {
4291   this->rel_ = new Reloc_section(false);
4292   layout->add_output_section_data(".rela.plt", elfcpp::SHT_RELA,
4293                                   elfcpp::SHF_ALLOC, this->rel_,
4294                                   ORDER_DYNAMIC_PLT_RELOCS, false);
4295 }
4296
4297 template<int size, bool big_endian>
4298 void
4299 Output_data_plt_aarch64<size, big_endian>::do_adjust_output_section(
4300     Output_section* os)
4301 {
4302   os->set_entsize(this->get_plt_entry_size());
4303 }
4304
4305 // Add an entry to the PLT.
4306
4307 template<int size, bool big_endian>
4308 void
4309 Output_data_plt_aarch64<size, big_endian>::add_entry(Symbol_table* symtab,
4310     Layout* layout, Symbol* gsym)
4311 {
4312   gold_assert(!gsym->has_plt_offset());
4313
4314   unsigned int* pcount;
4315   unsigned int plt_reserved;
4316   Output_section_data_build* got;
4317
4318   if (gsym->type() == elfcpp::STT_GNU_IFUNC
4319       && gsym->can_use_relative_reloc(false))
4320     {
4321       pcount = &this->irelative_count_;
4322       plt_reserved = 0;
4323       got = this->got_irelative_;
4324     }
4325   else
4326     {
4327       pcount = &this->count_;
4328       plt_reserved = this->first_plt_entry_offset();
4329       got = this->got_plt_;
4330     }
4331
4332   gsym->set_plt_offset((*pcount) * this->get_plt_entry_size()
4333                        + plt_reserved);
4334
4335   ++*pcount;
4336
4337   section_offset_type got_offset = got->current_data_size();
4338
4339   // Every PLT entry needs a GOT entry which points back to the PLT
4340   // entry (this will be changed by the dynamic linker, normally
4341   // lazily when the function is called).
4342   got->set_current_data_size(got_offset + size / 8);
4343
4344   // Every PLT entry needs a reloc.
4345   this->add_relocation(symtab, layout, gsym, got_offset);
4346
4347   // Note that we don't need to save the symbol. The contents of the
4348   // PLT are independent of which symbols are used. The symbols only
4349   // appear in the relocations.
4350 }
4351
4352 // Add an entry to the PLT for a local STT_GNU_IFUNC symbol.  Return
4353 // the PLT offset.
4354
4355 template<int size, bool big_endian>
4356 unsigned int
4357 Output_data_plt_aarch64<size, big_endian>::add_local_ifunc_entry(
4358     Symbol_table* symtab,
4359     Layout* layout,
4360     Sized_relobj_file<size, big_endian>* relobj,
4361     unsigned int local_sym_index)
4362 {
4363   unsigned int plt_offset = this->irelative_count_ * this->get_plt_entry_size();
4364   ++this->irelative_count_;
4365
4366   section_offset_type got_offset = this->got_irelative_->current_data_size();
4367
4368   // Every PLT entry needs a GOT entry which points back to the PLT
4369   // entry.
4370   this->got_irelative_->set_current_data_size(got_offset + size / 8);
4371
4372   // Every PLT entry needs a reloc.
4373   Reloc_section* rela = this->rela_irelative(symtab, layout);
4374   rela->add_symbolless_local_addend(relobj, local_sym_index,
4375                                     elfcpp::R_AARCH64_IRELATIVE,
4376                                     this->got_irelative_, got_offset, 0);
4377
4378   return plt_offset;
4379 }
4380
4381 // Add the relocation for a PLT entry.
4382
4383 template<int size, bool big_endian>
4384 void
4385 Output_data_plt_aarch64<size, big_endian>::add_relocation(
4386     Symbol_table* symtab, Layout* layout, Symbol* gsym, unsigned int got_offset)
4387 {
4388   if (gsym->type() == elfcpp::STT_GNU_IFUNC
4389       && gsym->can_use_relative_reloc(false))
4390     {
4391       Reloc_section* rela = this->rela_irelative(symtab, layout);
4392       rela->add_symbolless_global_addend(gsym, elfcpp::R_AARCH64_IRELATIVE,
4393                                          this->got_irelative_, got_offset, 0);
4394     }
4395   else
4396     {
4397       gsym->set_needs_dynsym_entry();
4398       this->rel_->add_global(gsym, elfcpp::R_AARCH64_JUMP_SLOT, this->got_plt_,
4399                              got_offset, 0);
4400     }
4401 }
4402
4403 // Return where the TLSDESC relocations should go, creating it if
4404 // necessary.  These follow the JUMP_SLOT relocations.
4405
4406 template<int size, bool big_endian>
4407 typename Output_data_plt_aarch64<size, big_endian>::Reloc_section*
4408 Output_data_plt_aarch64<size, big_endian>::rela_tlsdesc(Layout* layout)
4409 {
4410   if (this->tlsdesc_rel_ == NULL)
4411     {
4412       this->tlsdesc_rel_ = new Reloc_section(false);
4413       layout->add_output_section_data(".rela.plt", elfcpp::SHT_RELA,
4414                                       elfcpp::SHF_ALLOC, this->tlsdesc_rel_,
4415                                       ORDER_DYNAMIC_PLT_RELOCS, false);
4416       gold_assert(this->tlsdesc_rel_->output_section()
4417                   == this->rel_->output_section());
4418     }
4419   return this->tlsdesc_rel_;
4420 }
4421
4422 // Return where the IRELATIVE relocations should go in the PLT.  These
4423 // follow the JUMP_SLOT and the TLSDESC relocations.
4424
4425 template<int size, bool big_endian>
4426 typename Output_data_plt_aarch64<size, big_endian>::Reloc_section*
4427 Output_data_plt_aarch64<size, big_endian>::rela_irelative(Symbol_table* symtab,
4428                                                           Layout* layout)
4429 {
4430   if (this->irelative_rel_ == NULL)
4431     {
4432       // Make sure we have a place for the TLSDESC relocations, in
4433       // case we see any later on.
4434       this->rela_tlsdesc(layout);
4435       this->irelative_rel_ = new Reloc_section(false);
4436       layout->add_output_section_data(".rela.plt", elfcpp::SHT_RELA,
4437                                       elfcpp::SHF_ALLOC, this->irelative_rel_,
4438                                       ORDER_DYNAMIC_PLT_RELOCS, false);
4439       gold_assert(this->irelative_rel_->output_section()
4440                   == this->rel_->output_section());
4441
4442       if (parameters->doing_static_link())
4443         {
4444           // A statically linked executable will only have a .rela.plt
4445           // section to hold R_AARCH64_IRELATIVE relocs for
4446           // STT_GNU_IFUNC symbols.  The library will use these
4447           // symbols to locate the IRELATIVE relocs at program startup
4448           // time.
4449           symtab->define_in_output_data("__rela_iplt_start", NULL,
4450                                         Symbol_table::PREDEFINED,
4451                                         this->irelative_rel_, 0, 0,
4452                                         elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
4453                                         elfcpp::STV_HIDDEN, 0, false, true);
4454           symtab->define_in_output_data("__rela_iplt_end", NULL,
4455                                         Symbol_table::PREDEFINED,
4456                                         this->irelative_rel_, 0, 0,
4457                                         elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
4458                                         elfcpp::STV_HIDDEN, 0, true, true);
4459         }
4460     }
4461   return this->irelative_rel_;
4462 }
4463
4464 // Return the PLT address to use for a global symbol.
4465
4466 template<int size, bool big_endian>
4467 uint64_t
4468 Output_data_plt_aarch64<size, big_endian>::address_for_global(
4469   const Symbol* gsym)
4470 {
4471   uint64_t offset = 0;
4472   if (gsym->type() == elfcpp::STT_GNU_IFUNC
4473       && gsym->can_use_relative_reloc(false))
4474     offset = (this->first_plt_entry_offset() +
4475               this->count_ * this->get_plt_entry_size());
4476   return this->address() + offset + gsym->plt_offset();
4477 }
4478
4479 // Return the PLT address to use for a local symbol.  These are always
4480 // IRELATIVE relocs.
4481
4482 template<int size, bool big_endian>
4483 uint64_t
4484 Output_data_plt_aarch64<size, big_endian>::address_for_local(
4485     const Relobj* object,
4486     unsigned int r_sym)
4487 {
4488   return (this->address()
4489           + this->first_plt_entry_offset()
4490           + this->count_ * this->get_plt_entry_size()
4491           + object->local_plt_offset(r_sym));
4492 }
4493
4494 // Set the final size.
4495
4496 template<int size, bool big_endian>
4497 void
4498 Output_data_plt_aarch64<size, big_endian>::set_final_data_size()
4499 {
4500   unsigned int count = this->count_ + this->irelative_count_;
4501   unsigned int extra_size = 0;
4502   if (this->has_tlsdesc_entry())
4503     extra_size += this->get_plt_tlsdesc_entry_size();
4504   this->set_data_size(this->first_plt_entry_offset()
4505                       + count * this->get_plt_entry_size()
4506                       + extra_size);
4507 }
4508
4509 template<int size, bool big_endian>
4510 class Output_data_plt_aarch64_standard :
4511   public Output_data_plt_aarch64<size, big_endian>
4512 {
4513  public:
4514   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
4515   Output_data_plt_aarch64_standard(
4516       Layout* layout,
4517       Output_data_got_aarch64<size, big_endian>* got,
4518       Output_data_space* got_plt,
4519       Output_data_space* got_irelative)
4520     : Output_data_plt_aarch64<size, big_endian>(layout,
4521                                                 size == 32 ? 4 : 8,
4522                                                 got, got_plt,
4523                                                 got_irelative)
4524   { }
4525
4526  protected:
4527   // Return the offset of the first non-reserved PLT entry.
4528   virtual unsigned int
4529   do_first_plt_entry_offset() const
4530   { return this->first_plt_entry_size; }
4531
4532   // Return the size of a PLT entry
4533   virtual unsigned int
4534   do_get_plt_entry_size() const
4535   { return this->plt_entry_size; }
4536
4537   // Return the size of a tlsdesc entry
4538   virtual unsigned int
4539   do_get_plt_tlsdesc_entry_size() const
4540   { return this->plt_tlsdesc_entry_size; }
4541
4542   virtual void
4543   do_fill_first_plt_entry(unsigned char* pov,
4544                           Address got_address,
4545                           Address plt_address);
4546
4547   virtual void
4548   do_fill_plt_entry(unsigned char* pov,
4549                     Address got_address,
4550                     Address plt_address,
4551                     unsigned int got_offset,
4552                     unsigned int plt_offset);
4553
4554   virtual void
4555   do_fill_tlsdesc_entry(unsigned char* pov,
4556                         Address gotplt_address,
4557                         Address plt_address,
4558                         Address got_base,
4559                         unsigned int tlsdesc_got_offset,
4560                         unsigned int plt_offset);
4561
4562  private:
4563   // The size of the first plt entry size.
4564   static const int first_plt_entry_size = 32;
4565   // The size of the plt entry size.
4566   static const int plt_entry_size = 16;
4567   // The size of the plt tlsdesc entry size.
4568   static const int plt_tlsdesc_entry_size = 32;
4569   // Template for the first PLT entry.
4570   static const uint32_t first_plt_entry[first_plt_entry_size / 4];
4571   // Template for subsequent PLT entries.
4572   static const uint32_t plt_entry[plt_entry_size / 4];
4573   // The reserved TLSDESC entry in the PLT for an executable.
4574   static const uint32_t tlsdesc_plt_entry[plt_tlsdesc_entry_size / 4];
4575 };
4576
4577 // The first entry in the PLT for an executable.
4578
4579 template<>
4580 const uint32_t
4581 Output_data_plt_aarch64_standard<32, false>::
4582     first_plt_entry[first_plt_entry_size / 4] =
4583 {
4584   0xa9bf7bf0,   /* stp x16, x30, [sp, #-16]!  */
4585   0x90000010,   /* adrp x16, PLT_GOT+0x8  */
4586   0xb9400A11,   /* ldr w17, [x16, #PLT_GOT+0x8]  */
4587   0x11002210,   /* add w16, w16,#PLT_GOT+0x8   */
4588   0xd61f0220,   /* br x17  */
4589   0xd503201f,   /* nop */
4590   0xd503201f,   /* nop */
4591   0xd503201f,   /* nop */
4592 };
4593
4594
4595 template<>
4596 const uint32_t
4597 Output_data_plt_aarch64_standard<32, true>::
4598     first_plt_entry[first_plt_entry_size / 4] =
4599 {
4600   0xa9bf7bf0,   /* stp x16, x30, [sp, #-16]!  */
4601   0x90000010,   /* adrp x16, PLT_GOT+0x8  */
4602   0xb9400A11,   /* ldr w17, [x16, #PLT_GOT+0x8]  */
4603   0x11002210,   /* add w16, w16,#PLT_GOT+0x8   */
4604   0xd61f0220,   /* br x17  */
4605   0xd503201f,   /* nop */
4606   0xd503201f,   /* nop */
4607   0xd503201f,   /* nop */
4608 };
4609
4610
4611 template<>
4612 const uint32_t
4613 Output_data_plt_aarch64_standard<64, false>::
4614     first_plt_entry[first_plt_entry_size / 4] =
4615 {
4616   0xa9bf7bf0,   /* stp x16, x30, [sp, #-16]!  */
4617   0x90000010,   /* adrp x16, PLT_GOT+16  */
4618   0xf9400A11,   /* ldr x17, [x16, #PLT_GOT+0x10]  */
4619   0x91004210,   /* add x16, x16,#PLT_GOT+0x10   */
4620   0xd61f0220,   /* br x17  */
4621   0xd503201f,   /* nop */
4622   0xd503201f,   /* nop */
4623   0xd503201f,   /* nop */
4624 };
4625
4626
4627 template<>
4628 const uint32_t
4629 Output_data_plt_aarch64_standard<64, true>::
4630     first_plt_entry[first_plt_entry_size / 4] =
4631 {
4632   0xa9bf7bf0,   /* stp x16, x30, [sp, #-16]!  */
4633   0x90000010,   /* adrp x16, PLT_GOT+16  */
4634   0xf9400A11,   /* ldr x17, [x16, #PLT_GOT+0x10]  */
4635   0x91004210,   /* add x16, x16,#PLT_GOT+0x10   */
4636   0xd61f0220,   /* br x17  */
4637   0xd503201f,   /* nop */
4638   0xd503201f,   /* nop */
4639   0xd503201f,   /* nop */
4640 };
4641
4642
4643 template<>
4644 const uint32_t
4645 Output_data_plt_aarch64_standard<32, false>::
4646     plt_entry[plt_entry_size / 4] =
4647 {
4648   0x90000010,   /* adrp x16, PLTGOT + n * 4  */
4649   0xb9400211,   /* ldr w17, [w16, PLTGOT + n * 4] */
4650   0x11000210,   /* add w16, w16, :lo12:PLTGOT + n * 4  */
4651   0xd61f0220,   /* br x17.  */
4652 };
4653
4654
4655 template<>
4656 const uint32_t
4657 Output_data_plt_aarch64_standard<32, true>::
4658     plt_entry[plt_entry_size / 4] =
4659 {
4660   0x90000010,   /* adrp x16, PLTGOT + n * 4  */
4661   0xb9400211,   /* ldr w17, [w16, PLTGOT + n * 4] */
4662   0x11000210,   /* add w16, w16, :lo12:PLTGOT + n * 4  */
4663   0xd61f0220,   /* br x17.  */
4664 };
4665
4666
4667 template<>
4668 const uint32_t
4669 Output_data_plt_aarch64_standard<64, false>::
4670     plt_entry[plt_entry_size / 4] =
4671 {
4672   0x90000010,   /* adrp x16, PLTGOT + n * 8  */
4673   0xf9400211,   /* ldr x17, [x16, PLTGOT + n * 8] */
4674   0x91000210,   /* add x16, x16, :lo12:PLTGOT + n * 8  */
4675   0xd61f0220,   /* br x17.  */
4676 };
4677
4678
4679 template<>
4680 const uint32_t
4681 Output_data_plt_aarch64_standard<64, true>::
4682     plt_entry[plt_entry_size / 4] =
4683 {
4684   0x90000010,   /* adrp x16, PLTGOT + n * 8  */
4685   0xf9400211,   /* ldr x17, [x16, PLTGOT + n * 8] */
4686   0x91000210,   /* add x16, x16, :lo12:PLTGOT + n * 8  */
4687   0xd61f0220,   /* br x17.  */
4688 };
4689
4690
4691 template<int size, bool big_endian>
4692 void
4693 Output_data_plt_aarch64_standard<size, big_endian>::do_fill_first_plt_entry(
4694     unsigned char* pov,
4695     Address got_address,
4696     Address plt_address)
4697 {
4698   // PLT0 of the small PLT looks like this in ELF64 -
4699   // stp x16, x30, [sp, #-16]!          Save the reloc and lr on stack.
4700   // adrp x16, PLT_GOT + 16             Get the page base of the GOTPLT
4701   // ldr  x17, [x16, #:lo12:PLT_GOT+16] Load the address of the
4702   //                                    symbol resolver
4703   // add  x16, x16, #:lo12:PLT_GOT+16   Load the lo12 bits of the
4704   //                                    GOTPLT entry for this.
4705   // br   x17
4706   // PLT0 will be slightly different in ELF32 due to different got entry
4707   // size.
4708   memcpy(pov, this->first_plt_entry, this->first_plt_entry_size);
4709   Address gotplt_2nd_ent = got_address + (size / 8) * 2;
4710
4711   // Fill in the top 21 bits for this: ADRP x16, PLT_GOT + 8 * 2.
4712   // ADRP:  (PG(S+A)-PG(P)) >> 12) & 0x1fffff.
4713   // FIXME: This only works for 64bit
4714   AArch64_relocate_functions<size, big_endian>::adrp(pov + 4,
4715       gotplt_2nd_ent, plt_address + 4);
4716
4717   // Fill in R_AARCH64_LDST8_LO12
4718   elfcpp::Swap<32, big_endian>::writeval(
4719       pov + 8,
4720       ((this->first_plt_entry[2] & 0xffc003ff)
4721        | ((gotplt_2nd_ent & 0xff8) << 7)));
4722
4723   // Fill in R_AARCH64_ADD_ABS_LO12
4724   elfcpp::Swap<32, big_endian>::writeval(
4725       pov + 12,
4726       ((this->first_plt_entry[3] & 0xffc003ff)
4727        | ((gotplt_2nd_ent & 0xfff) << 10)));
4728 }
4729
4730
4731 // Subsequent entries in the PLT for an executable.
4732 // FIXME: This only works for 64bit
4733
4734 template<int size, bool big_endian>
4735 void
4736 Output_data_plt_aarch64_standard<size, big_endian>::do_fill_plt_entry(
4737     unsigned char* pov,
4738     Address got_address,
4739     Address plt_address,
4740     unsigned int got_offset,
4741     unsigned int plt_offset)
4742 {
4743   memcpy(pov, this->plt_entry, this->plt_entry_size);
4744
4745   Address gotplt_entry_address = got_address + got_offset;
4746   Address plt_entry_address = plt_address + plt_offset;
4747
4748   // Fill in R_AARCH64_PCREL_ADR_HI21
4749   AArch64_relocate_functions<size, big_endian>::adrp(
4750       pov,
4751       gotplt_entry_address,
4752       plt_entry_address);
4753
4754   // Fill in R_AARCH64_LDST64_ABS_LO12
4755   elfcpp::Swap<32, big_endian>::writeval(
4756       pov + 4,
4757       ((this->plt_entry[1] & 0xffc003ff)
4758        | ((gotplt_entry_address & 0xff8) << 7)));
4759
4760   // Fill in R_AARCH64_ADD_ABS_LO12
4761   elfcpp::Swap<32, big_endian>::writeval(
4762       pov + 8,
4763       ((this->plt_entry[2] & 0xffc003ff)
4764        | ((gotplt_entry_address & 0xfff) <<10)));
4765
4766 }
4767
4768
4769 template<>
4770 const uint32_t
4771 Output_data_plt_aarch64_standard<32, false>::
4772     tlsdesc_plt_entry[plt_tlsdesc_entry_size / 4] =
4773 {
4774   0xa9bf0fe2,   /* stp x2, x3, [sp, #-16]!  */
4775   0x90000002,   /* adrp x2, 0 */
4776   0x90000003,   /* adrp x3, 0 */
4777   0xb9400042,   /* ldr w2, [w2, #0] */
4778   0x11000063,   /* add w3, w3, 0 */
4779   0xd61f0040,   /* br x2 */
4780   0xd503201f,   /* nop */
4781   0xd503201f,   /* nop */
4782 };
4783
4784 template<>
4785 const uint32_t
4786 Output_data_plt_aarch64_standard<32, true>::
4787     tlsdesc_plt_entry[plt_tlsdesc_entry_size / 4] =
4788 {
4789   0xa9bf0fe2,   /* stp x2, x3, [sp, #-16]!  */
4790   0x90000002,   /* adrp x2, 0 */
4791   0x90000003,   /* adrp x3, 0 */
4792   0xb9400042,   /* ldr w2, [w2, #0] */
4793   0x11000063,   /* add w3, w3, 0 */
4794   0xd61f0040,   /* br x2 */
4795   0xd503201f,   /* nop */
4796   0xd503201f,   /* nop */
4797 };
4798
4799 template<>
4800 const uint32_t
4801 Output_data_plt_aarch64_standard<64, false>::
4802     tlsdesc_plt_entry[plt_tlsdesc_entry_size / 4] =
4803 {
4804   0xa9bf0fe2,   /* stp x2, x3, [sp, #-16]!  */
4805   0x90000002,   /* adrp x2, 0 */
4806   0x90000003,   /* adrp x3, 0 */
4807   0xf9400042,   /* ldr x2, [x2, #0] */
4808   0x91000063,   /* add x3, x3, 0 */
4809   0xd61f0040,   /* br x2 */
4810   0xd503201f,   /* nop */
4811   0xd503201f,   /* nop */
4812 };
4813
4814 template<>
4815 const uint32_t
4816 Output_data_plt_aarch64_standard<64, true>::
4817     tlsdesc_plt_entry[plt_tlsdesc_entry_size / 4] =
4818 {
4819   0xa9bf0fe2,   /* stp x2, x3, [sp, #-16]!  */
4820   0x90000002,   /* adrp x2, 0 */
4821   0x90000003,   /* adrp x3, 0 */
4822   0xf9400042,   /* ldr x2, [x2, #0] */
4823   0x91000063,   /* add x3, x3, 0 */
4824   0xd61f0040,   /* br x2 */
4825   0xd503201f,   /* nop */
4826   0xd503201f,   /* nop */
4827 };
4828
4829 template<int size, bool big_endian>
4830 void
4831 Output_data_plt_aarch64_standard<size, big_endian>::do_fill_tlsdesc_entry(
4832     unsigned char* pov,
4833     Address gotplt_address,
4834     Address plt_address,
4835     Address got_base,
4836     unsigned int tlsdesc_got_offset,
4837     unsigned int plt_offset)
4838 {
4839   memcpy(pov, tlsdesc_plt_entry, plt_tlsdesc_entry_size);
4840
4841   // move DT_TLSDESC_GOT address into x2
4842   // move .got.plt address into x3
4843   Address tlsdesc_got_entry = got_base + tlsdesc_got_offset;
4844   Address plt_entry_address = plt_address + plt_offset;
4845
4846   // R_AARCH64_ADR_PREL_PG_HI21
4847   AArch64_relocate_functions<size, big_endian>::adrp(
4848       pov + 4,
4849       tlsdesc_got_entry,
4850       plt_entry_address + 4);
4851
4852   // R_AARCH64_ADR_PREL_PG_HI21
4853   AArch64_relocate_functions<size, big_endian>::adrp(
4854       pov + 8,
4855       gotplt_address,
4856       plt_entry_address + 8);
4857
4858   // R_AARCH64_LDST64_ABS_LO12
4859   elfcpp::Swap<32, big_endian>::writeval(
4860       pov + 12,
4861       ((this->tlsdesc_plt_entry[3] & 0xffc003ff)
4862        | ((tlsdesc_got_entry & 0xff8) << 7)));
4863
4864   // R_AARCH64_ADD_ABS_LO12
4865   elfcpp::Swap<32, big_endian>::writeval(
4866       pov + 16,
4867       ((this->tlsdesc_plt_entry[4] & 0xffc003ff)
4868        | ((gotplt_address & 0xfff) << 10)));
4869 }
4870
4871 // Write out the PLT.  This uses the hand-coded instructions above,
4872 // and adjusts them as needed.  This is specified by the AMD64 ABI.
4873
4874 template<int size, bool big_endian>
4875 void
4876 Output_data_plt_aarch64<size, big_endian>::do_write(Output_file* of)
4877 {
4878   const off_t offset = this->offset();
4879   const section_size_type oview_size =
4880     convert_to_section_size_type(this->data_size());
4881   unsigned char* const oview = of->get_output_view(offset, oview_size);
4882
4883   const off_t got_file_offset = this->got_plt_->offset();
4884   gold_assert(got_file_offset + this->got_plt_->data_size()
4885               == this->got_irelative_->offset());
4886
4887   const section_size_type got_size =
4888       convert_to_section_size_type(this->got_plt_->data_size()
4889                                    + this->got_irelative_->data_size());
4890   unsigned char* const got_view = of->get_output_view(got_file_offset,
4891                                                       got_size);
4892
4893   unsigned char* pov = oview;
4894
4895   // The base address of the .plt section.
4896   typename elfcpp::Elf_types<size>::Elf_Addr plt_address = this->address();
4897   // The base address of the PLT portion of the .got section.
4898   typename elfcpp::Elf_types<size>::Elf_Addr gotplt_address
4899       = this->got_plt_->address();
4900
4901   this->fill_first_plt_entry(pov, gotplt_address, plt_address);
4902   pov += this->first_plt_entry_offset();
4903
4904   // The first three entries in .got.plt are reserved.
4905   unsigned char* got_pov = got_view;
4906   memset(got_pov, 0, size / 8 * AARCH64_GOTPLT_RESERVE_COUNT);
4907   got_pov += (size / 8) * AARCH64_GOTPLT_RESERVE_COUNT;
4908
4909   unsigned int plt_offset = this->first_plt_entry_offset();
4910   unsigned int got_offset = (size / 8) * AARCH64_GOTPLT_RESERVE_COUNT;
4911   const unsigned int count = this->count_ + this->irelative_count_;
4912   for (unsigned int plt_index = 0;
4913        plt_index < count;
4914        ++plt_index,
4915          pov += this->get_plt_entry_size(),
4916          got_pov += size / 8,
4917          plt_offset += this->get_plt_entry_size(),
4918          got_offset += size / 8)
4919     {
4920       // Set and adjust the PLT entry itself.
4921       this->fill_plt_entry(pov, gotplt_address, plt_address,
4922                            got_offset, plt_offset);
4923
4924       // Set the entry in the GOT, which points to plt0.
4925       elfcpp::Swap<size, big_endian>::writeval(got_pov, plt_address);
4926     }
4927
4928   if (this->has_tlsdesc_entry())
4929     {
4930       // Set and adjust the reserved TLSDESC PLT entry.
4931       unsigned int tlsdesc_got_offset = this->get_tlsdesc_got_offset();
4932       // The base address of the .base section.
4933       typename elfcpp::Elf_types<size>::Elf_Addr got_base =
4934           this->got_->address();
4935       this->fill_tlsdesc_entry(pov, gotplt_address, plt_address, got_base,
4936                                tlsdesc_got_offset, plt_offset);
4937       pov += this->get_plt_tlsdesc_entry_size();
4938     }
4939
4940   gold_assert(static_cast<section_size_type>(pov - oview) == oview_size);
4941   gold_assert(static_cast<section_size_type>(got_pov - got_view) == got_size);
4942
4943   of->write_output_view(offset, oview_size, oview);
4944   of->write_output_view(got_file_offset, got_size, got_view);
4945 }
4946
4947 // Telling how to update the immediate field of an instruction.
4948 struct AArch64_howto
4949 {
4950   // The immediate field mask.
4951   elfcpp::Elf_Xword dst_mask;
4952
4953   // The offset to apply relocation immediate
4954   int doffset;
4955
4956   // The second part offset, if the immediate field has two parts.
4957   // -1 if the immediate field has only one part.
4958   int doffset2;
4959 };
4960
4961 static const AArch64_howto aarch64_howto[AArch64_reloc_property::INST_NUM] =
4962 {
4963   {0, -1, -1},          // DATA
4964   {0x1fffe0, 5, -1},    // MOVW  [20:5]-imm16
4965   {0xffffe0, 5, -1},    // LD    [23:5]-imm19
4966   {0x60ffffe0, 29, 5},  // ADR   [30:29]-immlo  [23:5]-immhi
4967   {0x60ffffe0, 29, 5},  // ADRP  [30:29]-immlo  [23:5]-immhi
4968   {0x3ffc00, 10, -1},   // ADD   [21:10]-imm12
4969   {0x3ffc00, 10, -1},   // LDST  [21:10]-imm12
4970   {0x7ffe0, 5, -1},     // TBZNZ [18:5]-imm14
4971   {0xffffe0, 5, -1},    // CONDB [23:5]-imm19
4972   {0x3ffffff, 0, -1},   // B     [25:0]-imm26
4973   {0x3ffffff, 0, -1},   // CALL  [25:0]-imm26
4974 };
4975
4976 // AArch64 relocate function class
4977
4978 template<int size, bool big_endian>
4979 class AArch64_relocate_functions
4980 {
4981  public:
4982   typedef enum
4983   {
4984     STATUS_OKAY,        // No error during relocation.
4985     STATUS_OVERFLOW,    // Relocation overflow.
4986     STATUS_BAD_RELOC,   // Relocation cannot be applied.
4987   } Status;
4988
4989   typedef AArch64_relocate_functions<size, big_endian> This;
4990   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
4991   typedef Relocate_info<size, big_endian> The_relocate_info;
4992   typedef AArch64_relobj<size, big_endian> The_aarch64_relobj;
4993   typedef Reloc_stub<size, big_endian> The_reloc_stub;
4994   typedef Stub_table<size, big_endian> The_stub_table;
4995   typedef elfcpp::Rela<size, big_endian> The_rela;
4996   typedef typename elfcpp::Swap<size, big_endian>::Valtype AArch64_valtype;
4997
4998   // Return the page address of the address.
4999   // Page(address) = address & ~0xFFF
5000
5001   static inline AArch64_valtype
5002   Page(Address address)
5003   {
5004     return (address & (~static_cast<Address>(0xFFF)));
5005   }
5006
5007  private:
5008   // Update instruction (pointed by view) with selected bits (immed).
5009   // val = (val & ~dst_mask) | (immed << doffset)
5010
5011   template<int valsize>
5012   static inline void
5013   update_view(unsigned char* view,
5014               AArch64_valtype immed,
5015               elfcpp::Elf_Xword doffset,
5016               elfcpp::Elf_Xword dst_mask)
5017   {
5018     typedef typename elfcpp::Swap<valsize, big_endian>::Valtype Valtype;
5019     Valtype* wv = reinterpret_cast<Valtype*>(view);
5020     Valtype val = elfcpp::Swap<valsize, big_endian>::readval(wv);
5021
5022     // Clear immediate fields.
5023     val &= ~dst_mask;
5024     elfcpp::Swap<valsize, big_endian>::writeval(wv,
5025       static_cast<Valtype>(val | (immed << doffset)));
5026   }
5027
5028   // Update two parts of an instruction (pointed by view) with selected
5029   // bits (immed1 and immed2).
5030   // val = (val & ~dst_mask) | (immed1 << doffset1) | (immed2 << doffset2)
5031
5032   template<int valsize>
5033   static inline void
5034   update_view_two_parts(
5035     unsigned char* view,
5036     AArch64_valtype immed1,
5037     AArch64_valtype immed2,
5038     elfcpp::Elf_Xword doffset1,
5039     elfcpp::Elf_Xword doffset2,
5040     elfcpp::Elf_Xword dst_mask)
5041   {
5042     typedef typename elfcpp::Swap<valsize, big_endian>::Valtype Valtype;
5043     Valtype* wv = reinterpret_cast<Valtype*>(view);
5044     Valtype val = elfcpp::Swap<valsize, big_endian>::readval(wv);
5045     val &= ~dst_mask;
5046     elfcpp::Swap<valsize, big_endian>::writeval(wv,
5047       static_cast<Valtype>(val | (immed1 << doffset1) |
5048                            (immed2 << doffset2)));
5049   }
5050
5051   // Update adr or adrp instruction with immed.
5052   // In adr and adrp: [30:29] immlo   [23:5] immhi
5053
5054   static inline void
5055   update_adr(unsigned char* view, AArch64_valtype immed)
5056   {
5057     elfcpp::Elf_Xword dst_mask = (0x3 << 29) | (0x7ffff << 5);
5058     This::template update_view_two_parts<32>(
5059       view,
5060       immed & 0x3,
5061       (immed & 0x1ffffc) >> 2,
5062       29,
5063       5,
5064       dst_mask);
5065   }
5066
5067   // Update movz/movn instruction with bits immed.
5068   // Set instruction to movz if is_movz is true, otherwise set instruction
5069   // to movn.
5070
5071   static inline void
5072   update_movnz(unsigned char* view,
5073                AArch64_valtype immed,
5074                bool is_movz)
5075   {
5076     typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
5077     Valtype* wv = reinterpret_cast<Valtype*>(view);
5078     Valtype val = elfcpp::Swap<32, big_endian>::readval(wv);
5079
5080     const elfcpp::Elf_Xword doffset =
5081         aarch64_howto[AArch64_reloc_property::INST_MOVW].doffset;
5082     const elfcpp::Elf_Xword dst_mask =
5083         aarch64_howto[AArch64_reloc_property::INST_MOVW].dst_mask;
5084
5085     // Clear immediate fields and opc code.
5086     val &= ~(dst_mask | (0x3 << 29));
5087
5088     // Set instruction to movz or movn.
5089     // movz: [30:29] is 10   movn: [30:29] is 00
5090     if (is_movz)
5091       val |= (0x2 << 29);
5092
5093     elfcpp::Swap<32, big_endian>::writeval(wv,
5094       static_cast<Valtype>(val | (immed << doffset)));
5095   }
5096
5097   // Update selected bits in text.
5098
5099   template<int valsize>
5100   static inline typename This::Status
5101   reloc_common(unsigned char* view, Address x,
5102                 const AArch64_reloc_property* reloc_property)
5103   {
5104     // Select bits from X.
5105     Address immed = reloc_property->select_x_value(x);
5106
5107     // Update view.
5108     const AArch64_reloc_property::Reloc_inst inst =
5109       reloc_property->reloc_inst();
5110     // If it is a data relocation or instruction has 2 parts of immediate
5111     // fields, you should not call pcrela_general.
5112     gold_assert(aarch64_howto[inst].doffset2 == -1 &&
5113                 aarch64_howto[inst].doffset != -1);
5114     This::template update_view<valsize>(view, immed,
5115                                         aarch64_howto[inst].doffset,
5116                                         aarch64_howto[inst].dst_mask);
5117
5118     // Do check overflow or alignment if needed.
5119     return (reloc_property->checkup_x_value(x)
5120             ? This::STATUS_OKAY
5121             : This::STATUS_OVERFLOW);
5122   }
5123
5124  public:
5125
5126   // Construct a B insn. Note, although we group it here with other relocation
5127   // operation, there is actually no 'relocation' involved here.
5128   static inline void
5129   construct_b(unsigned char* view, unsigned int branch_offset)
5130   {
5131     update_view_two_parts<32>(view, 0x05, (branch_offset >> 2),
5132                               26, 0, 0xffffffff);
5133   }
5134
5135   // Do a simple rela relocation at unaligned addresses.
5136
5137   template<int valsize>
5138   static inline typename This::Status
5139   rela_ua(unsigned char* view,
5140           const Sized_relobj_file<size, big_endian>* object,
5141           const Symbol_value<size>* psymval,
5142           AArch64_valtype addend,
5143           const AArch64_reloc_property* reloc_property)
5144   {
5145     typedef typename elfcpp::Swap_unaligned<valsize, big_endian>::Valtype
5146       Valtype;
5147     typename elfcpp::Elf_types<size>::Elf_Addr x =
5148         psymval->value(object, addend);
5149     elfcpp::Swap_unaligned<valsize, big_endian>::writeval(view,
5150       static_cast<Valtype>(x));
5151     return (reloc_property->checkup_x_value(x)
5152             ? This::STATUS_OKAY
5153             : This::STATUS_OVERFLOW);
5154   }
5155
5156   // Do a simple pc-relative relocation at unaligned addresses.
5157
5158   template<int valsize>
5159   static inline typename This::Status
5160   pcrela_ua(unsigned char* view,
5161             const Sized_relobj_file<size, big_endian>* object,
5162             const Symbol_value<size>* psymval,
5163             AArch64_valtype addend,
5164             Address address,
5165             const AArch64_reloc_property* reloc_property)
5166   {
5167     typedef typename elfcpp::Swap_unaligned<valsize, big_endian>::Valtype
5168       Valtype;
5169     Address x = psymval->value(object, addend) - address;
5170     elfcpp::Swap_unaligned<valsize, big_endian>::writeval(view,
5171       static_cast<Valtype>(x));
5172     return (reloc_property->checkup_x_value(x)
5173             ? This::STATUS_OKAY
5174             : This::STATUS_OVERFLOW);
5175   }
5176
5177   // Do a simple rela relocation at aligned addresses.
5178
5179   template<int valsize>
5180   static inline typename This::Status
5181   rela(
5182     unsigned char* view,
5183     const Sized_relobj_file<size, big_endian>* object,
5184     const Symbol_value<size>* psymval,
5185     AArch64_valtype addend,
5186     const AArch64_reloc_property* reloc_property)
5187   {
5188     typedef typename elfcpp::Swap<valsize, big_endian>::Valtype Valtype;
5189     Valtype* wv = reinterpret_cast<Valtype*>(view);
5190     Address x = psymval->value(object, addend);
5191     elfcpp::Swap<valsize, big_endian>::writeval(wv,static_cast<Valtype>(x));
5192     return (reloc_property->checkup_x_value(x)
5193             ? This::STATUS_OKAY
5194             : This::STATUS_OVERFLOW);
5195   }
5196
5197   // Do relocate. Update selected bits in text.
5198   // new_val = (val & ~dst_mask) | (immed << doffset)
5199
5200   template<int valsize>
5201   static inline typename This::Status
5202   rela_general(unsigned char* view,
5203                const Sized_relobj_file<size, big_endian>* object,
5204                const Symbol_value<size>* psymval,
5205                AArch64_valtype addend,
5206                const AArch64_reloc_property* reloc_property)
5207   {
5208     // Calculate relocation.
5209     Address x = psymval->value(object, addend);
5210     return This::template reloc_common<valsize>(view, x, reloc_property);
5211   }
5212
5213   // Do relocate. Update selected bits in text.
5214   // new val = (val & ~dst_mask) | (immed << doffset)
5215
5216   template<int valsize>
5217   static inline typename This::Status
5218   rela_general(
5219     unsigned char* view,
5220     AArch64_valtype s,
5221     AArch64_valtype addend,
5222     const AArch64_reloc_property* reloc_property)
5223   {
5224     // Calculate relocation.
5225     Address x = s + addend;
5226     return This::template reloc_common<valsize>(view, x, reloc_property);
5227   }
5228
5229   // Do address relative relocate. Update selected bits in text.
5230   // new val = (val & ~dst_mask) | (immed << doffset)
5231
5232   template<int valsize>
5233   static inline typename This::Status
5234   pcrela_general(
5235     unsigned char* view,
5236     const Sized_relobj_file<size, big_endian>* object,
5237     const Symbol_value<size>* psymval,
5238     AArch64_valtype addend,
5239     Address address,
5240     const AArch64_reloc_property* reloc_property)
5241   {
5242     // Calculate relocation.
5243     Address x = psymval->value(object, addend) - address;
5244     return This::template reloc_common<valsize>(view, x, reloc_property);
5245   }
5246
5247
5248   // Calculate (S + A) - address, update adr instruction.
5249
5250   static inline typename This::Status
5251   adr(unsigned char* view,
5252       const Sized_relobj_file<size, big_endian>* object,
5253       const Symbol_value<size>* psymval,
5254       Address addend,
5255       Address address,
5256       const AArch64_reloc_property* /* reloc_property */)
5257   {
5258     AArch64_valtype x = psymval->value(object, addend) - address;
5259     // Pick bits [20:0] of X.
5260     AArch64_valtype immed = x & 0x1fffff;
5261     update_adr(view, immed);
5262     // Check -2^20 <= X < 2^20
5263     return (size == 64 && Bits<21>::has_overflow((x))
5264             ? This::STATUS_OVERFLOW
5265             : This::STATUS_OKAY);
5266   }
5267
5268   // Calculate PG(S+A) - PG(address), update adrp instruction.
5269   // R_AARCH64_ADR_PREL_PG_HI21
5270
5271   static inline typename This::Status
5272   adrp(
5273     unsigned char* view,
5274     Address sa,
5275     Address address)
5276   {
5277     AArch64_valtype x = This::Page(sa) - This::Page(address);
5278     // Pick [32:12] of X.
5279     AArch64_valtype immed = (x >> 12) & 0x1fffff;
5280     update_adr(view, immed);
5281     // Check -2^32 <= X < 2^32
5282     return (size == 64 && Bits<33>::has_overflow((x))
5283             ? This::STATUS_OVERFLOW
5284             : This::STATUS_OKAY);
5285   }
5286
5287   // Calculate PG(S+A) - PG(address), update adrp instruction.
5288   // R_AARCH64_ADR_PREL_PG_HI21
5289
5290   static inline typename This::Status
5291   adrp(unsigned char* view,
5292        const Sized_relobj_file<size, big_endian>* object,
5293        const Symbol_value<size>* psymval,
5294        Address addend,
5295        Address address,
5296        const AArch64_reloc_property* reloc_property)
5297   {
5298     Address sa = psymval->value(object, addend);
5299     AArch64_valtype x = This::Page(sa) - This::Page(address);
5300     // Pick [32:12] of X.
5301     AArch64_valtype immed = (x >> 12) & 0x1fffff;
5302     update_adr(view, immed);
5303     return (reloc_property->checkup_x_value(x)
5304             ? This::STATUS_OKAY
5305             : This::STATUS_OVERFLOW);
5306   }
5307
5308   // Update mov[n/z] instruction. Check overflow if needed.
5309   // If X >=0, set the instruction to movz and its immediate value to the
5310   // selected bits S.
5311   // If X < 0, set the instruction to movn and its immediate value to
5312   // NOT (selected bits of).
5313
5314   static inline typename This::Status
5315   movnz(unsigned char* view,
5316         AArch64_valtype x,
5317         const AArch64_reloc_property* reloc_property)
5318   {
5319     // Select bits from X.
5320     Address immed;
5321     bool is_movz;
5322     typedef typename elfcpp::Elf_types<size>::Elf_Swxword SignedW;
5323     if (static_cast<SignedW>(x) >= 0)
5324       {
5325         immed = reloc_property->select_x_value(x);
5326         is_movz = true;
5327       }
5328     else
5329       {
5330         immed = reloc_property->select_x_value(~x);;
5331         is_movz = false;
5332       }
5333
5334     // Update movnz instruction.
5335     update_movnz(view, immed, is_movz);
5336
5337     // Do check overflow or alignment if needed.
5338     return (reloc_property->checkup_x_value(x)
5339             ? This::STATUS_OKAY
5340             : This::STATUS_OVERFLOW);
5341   }
5342
5343   static inline bool
5344   maybe_apply_stub(unsigned int,
5345                    const The_relocate_info*,
5346                    const The_rela&,
5347                    unsigned char*,
5348                    Address,
5349                    const Sized_symbol<size>*,
5350                    const Symbol_value<size>*,
5351                    const Sized_relobj_file<size, big_endian>*,
5352                    section_size_type);
5353
5354 };  // End of AArch64_relocate_functions
5355
5356
5357 // For a certain relocation type (usually jump/branch), test to see if the
5358 // destination needs a stub to fulfil. If so, re-route the destination of the
5359 // original instruction to the stub, note, at this time, the stub has already
5360 // been generated.
5361
5362 template<int size, bool big_endian>
5363 bool
5364 AArch64_relocate_functions<size, big_endian>::
5365 maybe_apply_stub(unsigned int r_type,
5366                  const The_relocate_info* relinfo,
5367                  const The_rela& rela,
5368                  unsigned char* view,
5369                  Address address,
5370                  const Sized_symbol<size>* gsym,
5371                  const Symbol_value<size>* psymval,
5372                  const Sized_relobj_file<size, big_endian>* object,
5373                  section_size_type current_group_size)
5374 {
5375   if (parameters->options().relocatable())
5376     return false;
5377
5378   typename elfcpp::Elf_types<size>::Elf_Swxword addend = rela.get_r_addend();
5379   Address branch_target = psymval->value(object, 0) + addend;
5380   int stub_type =
5381     The_reloc_stub::stub_type_for_reloc(r_type, address, branch_target);
5382   if (stub_type == ST_NONE)
5383     return false;
5384
5385   const The_aarch64_relobj* aarch64_relobj =
5386       static_cast<const The_aarch64_relobj*>(object);
5387   The_stub_table* stub_table = aarch64_relobj->stub_table(relinfo->data_shndx);
5388   gold_assert(stub_table != NULL);
5389
5390   unsigned int r_sym = elfcpp::elf_r_sym<size>(rela.get_r_info());
5391   typename The_reloc_stub::Key stub_key(stub_type, gsym, object, r_sym, addend);
5392   The_reloc_stub* stub = stub_table->find_reloc_stub(stub_key);
5393   gold_assert(stub != NULL);
5394
5395   Address new_branch_target = stub_table->address() + stub->offset();
5396   typename elfcpp::Swap<size, big_endian>::Valtype branch_offset =
5397       new_branch_target - address;
5398   const AArch64_reloc_property* arp =
5399       aarch64_reloc_property_table->get_reloc_property(r_type);
5400   gold_assert(arp != NULL);
5401   typename This::Status status = This::template
5402       rela_general<32>(view, branch_offset, 0, arp);
5403   if (status != This::STATUS_OKAY)
5404     gold_error(_("Stub is too far away, try a smaller value "
5405                  "for '--stub-group-size'. The current value is 0x%lx."),
5406                static_cast<unsigned long>(current_group_size));
5407   return true;
5408 }
5409
5410
5411 // Group input sections for stub generation.
5412 //
5413 // We group input sections in an output section so that the total size,
5414 // including any padding space due to alignment is smaller than GROUP_SIZE
5415 // unless the only input section in group is bigger than GROUP_SIZE already.
5416 // Then an ARM stub table is created to follow the last input section
5417 // in group.  For each group an ARM stub table is created an is placed
5418 // after the last group.  If STUB_ALWAYS_AFTER_BRANCH is false, we further
5419 // extend the group after the stub table.
5420
5421 template<int size, bool big_endian>
5422 void
5423 Target_aarch64<size, big_endian>::group_sections(
5424     Layout* layout,
5425     section_size_type group_size,
5426     bool stubs_always_after_branch,
5427     const Task* task)
5428 {
5429   // Group input sections and insert stub table
5430   Layout::Section_list section_list;
5431   layout->get_executable_sections(&section_list);
5432   for (Layout::Section_list::const_iterator p = section_list.begin();
5433        p != section_list.end();
5434        ++p)
5435     {
5436       AArch64_output_section<size, big_endian>* output_section =
5437           static_cast<AArch64_output_section<size, big_endian>*>(*p);
5438       output_section->group_sections(group_size, stubs_always_after_branch,
5439                                      this, task);
5440     }
5441 }
5442
5443
5444 // Find the AArch64_input_section object corresponding to the SHNDX-th input
5445 // section of RELOBJ.
5446
5447 template<int size, bool big_endian>
5448 AArch64_input_section<size, big_endian>*
5449 Target_aarch64<size, big_endian>::find_aarch64_input_section(
5450     Relobj* relobj, unsigned int shndx) const
5451 {
5452   Section_id sid(relobj, shndx);
5453   typename AArch64_input_section_map::const_iterator p =
5454     this->aarch64_input_section_map_.find(sid);
5455   return (p != this->aarch64_input_section_map_.end()) ? p->second : NULL;
5456 }
5457
5458
5459 // Make a new AArch64_input_section object.
5460
5461 template<int size, bool big_endian>
5462 AArch64_input_section<size, big_endian>*
5463 Target_aarch64<size, big_endian>::new_aarch64_input_section(
5464     Relobj* relobj, unsigned int shndx)
5465 {
5466   Section_id sid(relobj, shndx);
5467
5468   AArch64_input_section<size, big_endian>* input_section =
5469       new AArch64_input_section<size, big_endian>(relobj, shndx);
5470   input_section->init();
5471
5472   // Register new AArch64_input_section in map for look-up.
5473   std::pair<typename AArch64_input_section_map::iterator,bool> ins =
5474       this->aarch64_input_section_map_.insert(
5475           std::make_pair(sid, input_section));
5476
5477   // Make sure that it we have not created another AArch64_input_section
5478   // for this input section already.
5479   gold_assert(ins.second);
5480
5481   return input_section;
5482 }
5483
5484
5485 // Relaxation hook.  This is where we do stub generation.
5486
5487 template<int size, bool big_endian>
5488 bool
5489 Target_aarch64<size, big_endian>::do_relax(
5490     int pass,
5491     const Input_objects* input_objects,
5492     Symbol_table* symtab,
5493     Layout* layout ,
5494     const Task* task)
5495 {
5496   gold_assert(!parameters->options().relocatable());
5497   if (pass == 1)
5498     {
5499       // We don't handle negative stub_group_size right now.
5500       this->stub_group_size_ = abs(parameters->options().stub_group_size());
5501       if (this->stub_group_size_ == 1)
5502         {
5503           // Leave room for 4096 4-byte stub entries. If we exceed that, then we
5504           // will fail to link.  The user will have to relink with an explicit
5505           // group size option.
5506           this->stub_group_size_ = The_reloc_stub::MAX_BRANCH_OFFSET -
5507                                    4096 * 4;
5508         }
5509       group_sections(layout, this->stub_group_size_, true, task);
5510     }
5511   else
5512     {
5513       // If this is not the first pass, addresses and file offsets have
5514       // been reset at this point, set them here.
5515       for (Stub_table_iterator sp = this->stub_tables_.begin();
5516            sp != this->stub_tables_.end(); ++sp)
5517         {
5518           The_stub_table* stt = *sp;
5519           The_aarch64_input_section* owner = stt->owner();
5520           off_t off = align_address(owner->original_size(),
5521                                     stt->addralign());
5522           stt->set_address_and_file_offset(owner->address() + off,
5523                                            owner->offset() + off);
5524         }
5525     }
5526
5527   // Scan relocs for relocation stubs
5528   for (Input_objects::Relobj_iterator op = input_objects->relobj_begin();
5529        op != input_objects->relobj_end();
5530        ++op)
5531     {
5532       The_aarch64_relobj* aarch64_relobj =
5533           static_cast<The_aarch64_relobj*>(*op);
5534       // Lock the object so we can read from it.  This is only called
5535       // single-threaded from Layout::finalize, so it is OK to lock.
5536       Task_lock_obj<Object> tl(task, aarch64_relobj);
5537       aarch64_relobj->scan_sections_for_stubs(this, symtab, layout);
5538     }
5539
5540   bool any_stub_table_changed = false;
5541   for (Stub_table_iterator siter = this->stub_tables_.begin();
5542        siter != this->stub_tables_.end() && !any_stub_table_changed; ++siter)
5543     {
5544       The_stub_table* stub_table = *siter;
5545       if (stub_table->update_data_size_changed_p())
5546         {
5547           The_aarch64_input_section* owner = stub_table->owner();
5548           uint64_t address = owner->address();
5549           off_t offset = owner->offset();
5550           owner->reset_address_and_file_offset();
5551           owner->set_address_and_file_offset(address, offset);
5552
5553           any_stub_table_changed = true;
5554         }
5555     }
5556
5557   // Do not continue relaxation.
5558   bool continue_relaxation = any_stub_table_changed;
5559   if (!continue_relaxation)
5560     for (Stub_table_iterator sp = this->stub_tables_.begin();
5561          (sp != this->stub_tables_.end());
5562          ++sp)
5563       (*sp)->finalize_stubs();
5564
5565   return continue_relaxation;
5566 }
5567
5568
5569 // Make a new Stub_table.
5570
5571 template<int size, bool big_endian>
5572 Stub_table<size, big_endian>*
5573 Target_aarch64<size, big_endian>::new_stub_table(
5574     AArch64_input_section<size, big_endian>* owner)
5575 {
5576   Stub_table<size, big_endian>* stub_table =
5577       new Stub_table<size, big_endian>(owner);
5578   stub_table->set_address(align_address(
5579       owner->address() + owner->data_size(), 8));
5580   stub_table->set_file_offset(owner->offset() + owner->data_size());
5581   stub_table->finalize_data_size();
5582
5583   this->stub_tables_.push_back(stub_table);
5584
5585   return stub_table;
5586 }
5587
5588
5589 template<int size, bool big_endian>
5590 uint64_t
5591 Target_aarch64<size, big_endian>::do_reloc_addend(
5592     void* arg, unsigned int r_type, uint64_t) const
5593 {
5594   gold_assert(r_type == elfcpp::R_AARCH64_TLSDESC);
5595   uintptr_t intarg = reinterpret_cast<uintptr_t>(arg);
5596   gold_assert(intarg < this->tlsdesc_reloc_info_.size());
5597   const Tlsdesc_info& ti(this->tlsdesc_reloc_info_[intarg]);
5598   const Symbol_value<size>* psymval = ti.object->local_symbol(ti.r_sym);
5599   gold_assert(psymval->is_tls_symbol());
5600   // The value of a TLS symbol is the offset in the TLS segment.
5601   return psymval->value(ti.object, 0);
5602 }
5603
5604 // Return the number of entries in the PLT.
5605
5606 template<int size, bool big_endian>
5607 unsigned int
5608 Target_aarch64<size, big_endian>::plt_entry_count() const
5609 {
5610   if (this->plt_ == NULL)
5611     return 0;
5612   return this->plt_->entry_count();
5613 }
5614
5615 // Return the offset of the first non-reserved PLT entry.
5616
5617 template<int size, bool big_endian>
5618 unsigned int
5619 Target_aarch64<size, big_endian>::first_plt_entry_offset() const
5620 {
5621   return this->plt_->first_plt_entry_offset();
5622 }
5623
5624 // Return the size of each PLT entry.
5625
5626 template<int size, bool big_endian>
5627 unsigned int
5628 Target_aarch64<size, big_endian>::plt_entry_size() const
5629 {
5630   return this->plt_->get_plt_entry_size();
5631 }
5632
5633 // Define the _TLS_MODULE_BASE_ symbol in the TLS segment.
5634
5635 template<int size, bool big_endian>
5636 void
5637 Target_aarch64<size, big_endian>::define_tls_base_symbol(
5638     Symbol_table* symtab, Layout* layout)
5639 {
5640   if (this->tls_base_symbol_defined_)
5641     return;
5642
5643   Output_segment* tls_segment = layout->tls_segment();
5644   if (tls_segment != NULL)
5645     {
5646       // _TLS_MODULE_BASE_ always points to the beginning of tls segment.
5647       symtab->define_in_output_segment("_TLS_MODULE_BASE_", NULL,
5648                                        Symbol_table::PREDEFINED,
5649                                        tls_segment, 0, 0,
5650                                        elfcpp::STT_TLS,
5651                                        elfcpp::STB_LOCAL,
5652                                        elfcpp::STV_HIDDEN, 0,
5653                                        Symbol::SEGMENT_START,
5654                                        true);
5655     }
5656   this->tls_base_symbol_defined_ = true;
5657 }
5658
5659 // Create the reserved PLT and GOT entries for the TLS descriptor resolver.
5660
5661 template<int size, bool big_endian>
5662 void
5663 Target_aarch64<size, big_endian>::reserve_tlsdesc_entries(
5664     Symbol_table* symtab, Layout* layout)
5665 {
5666   if (this->plt_ == NULL)
5667     this->make_plt_section(symtab, layout);
5668
5669   if (!this->plt_->has_tlsdesc_entry())
5670     {
5671       // Allocate the TLSDESC_GOT entry.
5672       Output_data_got_aarch64<size, big_endian>* got =
5673           this->got_section(symtab, layout);
5674       unsigned int got_offset = got->add_constant(0);
5675
5676       // Allocate the TLSDESC_PLT entry.
5677       this->plt_->reserve_tlsdesc_entry(got_offset);
5678     }
5679 }
5680
5681 // Create a GOT entry for the TLS module index.
5682
5683 template<int size, bool big_endian>
5684 unsigned int
5685 Target_aarch64<size, big_endian>::got_mod_index_entry(
5686     Symbol_table* symtab, Layout* layout,
5687     Sized_relobj_file<size, big_endian>* object)
5688 {
5689   if (this->got_mod_index_offset_ == -1U)
5690     {
5691       gold_assert(symtab != NULL && layout != NULL && object != NULL);
5692       Reloc_section* rela_dyn = this->rela_dyn_section(layout);
5693       Output_data_got_aarch64<size, big_endian>* got =
5694           this->got_section(symtab, layout);
5695       unsigned int got_offset = got->add_constant(0);
5696       rela_dyn->add_local(object, 0, elfcpp::R_AARCH64_TLS_DTPMOD64, got,
5697                           got_offset, 0);
5698       got->add_constant(0);
5699       this->got_mod_index_offset_ = got_offset;
5700     }
5701   return this->got_mod_index_offset_;
5702 }
5703
5704 // Optimize the TLS relocation type based on what we know about the
5705 // symbol.  IS_FINAL is true if the final address of this symbol is
5706 // known at link time.
5707
5708 template<int size, bool big_endian>
5709 tls::Tls_optimization
5710 Target_aarch64<size, big_endian>::optimize_tls_reloc(bool is_final,
5711                                                      int r_type)
5712 {
5713   // If we are generating a shared library, then we can't do anything
5714   // in the linker
5715   if (parameters->options().shared())
5716     return tls::TLSOPT_NONE;
5717
5718   switch (r_type)
5719     {
5720     case elfcpp::R_AARCH64_TLSGD_ADR_PAGE21:
5721     case elfcpp::R_AARCH64_TLSGD_ADD_LO12_NC:
5722     case elfcpp::R_AARCH64_TLSDESC_LD_PREL19:
5723     case elfcpp::R_AARCH64_TLSDESC_ADR_PREL21:
5724     case elfcpp::R_AARCH64_TLSDESC_ADR_PAGE21:
5725     case elfcpp::R_AARCH64_TLSDESC_LD64_LO12:
5726     case elfcpp::R_AARCH64_TLSDESC_ADD_LO12:
5727     case elfcpp::R_AARCH64_TLSDESC_OFF_G1:
5728     case elfcpp::R_AARCH64_TLSDESC_OFF_G0_NC:
5729     case elfcpp::R_AARCH64_TLSDESC_LDR:
5730     case elfcpp::R_AARCH64_TLSDESC_ADD:
5731     case elfcpp::R_AARCH64_TLSDESC_CALL:
5732       // These are General-Dynamic which permits fully general TLS
5733       // access.  Since we know that we are generating an executable,
5734       // we can convert this to Initial-Exec.  If we also know that
5735       // this is a local symbol, we can further switch to Local-Exec.
5736       if (is_final)
5737         return tls::TLSOPT_TO_LE;
5738       return tls::TLSOPT_TO_IE;
5739
5740     case elfcpp::R_AARCH64_TLSLD_ADR_PAGE21:
5741     case elfcpp::R_AARCH64_TLSLD_ADD_LO12_NC:
5742     case elfcpp::R_AARCH64_TLSLD_MOVW_DTPREL_G1:
5743     case elfcpp::R_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
5744     case elfcpp::R_AARCH64_TLSLD_ADD_DTPREL_HI12:
5745     case elfcpp::R_AARCH64_TLSLD_ADD_DTPREL_LO12_NC:
5746       // These are Local-Dynamic, which refer to local symbols in the
5747       // dynamic TLS block. Since we know that we generating an
5748       // executable, we can switch to Local-Exec.
5749       return tls::TLSOPT_TO_LE;
5750
5751     case elfcpp::R_AARCH64_TLSIE_MOVW_GOTTPREL_G1:
5752     case elfcpp::R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC:
5753     case elfcpp::R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
5754     case elfcpp::R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
5755     case elfcpp::R_AARCH64_TLSIE_LD_GOTTPREL_PREL19:
5756       // These are Initial-Exec relocs which get the thread offset
5757       // from the GOT. If we know that we are linking against the
5758       // local symbol, we can switch to Local-Exec, which links the
5759       // thread offset into the instruction.
5760       if (is_final)
5761         return tls::TLSOPT_TO_LE;
5762       return tls::TLSOPT_NONE;
5763
5764     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G2:
5765     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G1:
5766     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
5767     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G0:
5768     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
5769     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_HI12:
5770     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_LO12:
5771     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
5772       // When we already have Local-Exec, there is nothing further we
5773       // can do.
5774       return tls::TLSOPT_NONE;
5775
5776     default:
5777       gold_unreachable();
5778     }
5779 }
5780
5781 // Returns true if this relocation type could be that of a function pointer.
5782
5783 template<int size, bool big_endian>
5784 inline bool
5785 Target_aarch64<size, big_endian>::Scan::possible_function_pointer_reloc(
5786   unsigned int r_type)
5787 {
5788   switch (r_type)
5789     {
5790     case elfcpp::R_AARCH64_ADR_PREL_PG_HI21:
5791     case elfcpp::R_AARCH64_ADR_PREL_PG_HI21_NC:
5792     case elfcpp::R_AARCH64_ADD_ABS_LO12_NC:
5793     case elfcpp::R_AARCH64_ADR_GOT_PAGE:
5794     case elfcpp::R_AARCH64_LD64_GOT_LO12_NC:
5795       {
5796         return true;
5797       }
5798     }
5799   return false;
5800 }
5801
5802 // For safe ICF, scan a relocation for a local symbol to check if it
5803 // corresponds to a function pointer being taken.  In that case mark
5804 // the function whose pointer was taken as not foldable.
5805
5806 template<int size, bool big_endian>
5807 inline bool
5808 Target_aarch64<size, big_endian>::Scan::local_reloc_may_be_function_pointer(
5809   Symbol_table* ,
5810   Layout* ,
5811   Target_aarch64<size, big_endian>* ,
5812   Sized_relobj_file<size, big_endian>* ,
5813   unsigned int ,
5814   Output_section* ,
5815   const elfcpp::Rela<size, big_endian>& ,
5816   unsigned int r_type,
5817   const elfcpp::Sym<size, big_endian>&)
5818 {
5819   // When building a shared library, do not fold any local symbols.
5820   return (parameters->options().shared()
5821           || possible_function_pointer_reloc(r_type));
5822 }
5823
5824 // For safe ICF, scan a relocation for a global symbol to check if it
5825 // corresponds to a function pointer being taken.  In that case mark
5826 // the function whose pointer was taken as not foldable.
5827
5828 template<int size, bool big_endian>
5829 inline bool
5830 Target_aarch64<size, big_endian>::Scan::global_reloc_may_be_function_pointer(
5831   Symbol_table* ,
5832   Layout* ,
5833   Target_aarch64<size, big_endian>* ,
5834   Sized_relobj_file<size, big_endian>* ,
5835   unsigned int ,
5836   Output_section* ,
5837   const elfcpp::Rela<size, big_endian>& ,
5838   unsigned int r_type,
5839   Symbol* gsym)
5840 {
5841   // When building a shared library, do not fold symbols whose visibility
5842   // is hidden, internal or protected.
5843   return ((parameters->options().shared()
5844            && (gsym->visibility() == elfcpp::STV_INTERNAL
5845                || gsym->visibility() == elfcpp::STV_PROTECTED
5846                || gsym->visibility() == elfcpp::STV_HIDDEN))
5847           || possible_function_pointer_reloc(r_type));
5848 }
5849
5850 // Report an unsupported relocation against a local symbol.
5851
5852 template<int size, bool big_endian>
5853 void
5854 Target_aarch64<size, big_endian>::Scan::unsupported_reloc_local(
5855      Sized_relobj_file<size, big_endian>* object,
5856      unsigned int r_type)
5857 {
5858   gold_error(_("%s: unsupported reloc %u against local symbol"),
5859              object->name().c_str(), r_type);
5860 }
5861
5862 // We are about to emit a dynamic relocation of type R_TYPE.  If the
5863 // dynamic linker does not support it, issue an error.
5864
5865 template<int size, bool big_endian>
5866 void
5867 Target_aarch64<size, big_endian>::Scan::check_non_pic(Relobj* object,
5868                                                       unsigned int r_type)
5869 {
5870   gold_assert(r_type != elfcpp::R_AARCH64_NONE);
5871
5872   switch (r_type)
5873     {
5874     // These are the relocation types supported by glibc for AARCH64.
5875     case elfcpp::R_AARCH64_NONE:
5876     case elfcpp::R_AARCH64_COPY:
5877     case elfcpp::R_AARCH64_GLOB_DAT:
5878     case elfcpp::R_AARCH64_JUMP_SLOT:
5879     case elfcpp::R_AARCH64_RELATIVE:
5880     case elfcpp::R_AARCH64_TLS_DTPREL64:
5881     case elfcpp::R_AARCH64_TLS_DTPMOD64:
5882     case elfcpp::R_AARCH64_TLS_TPREL64:
5883     case elfcpp::R_AARCH64_TLSDESC:
5884     case elfcpp::R_AARCH64_IRELATIVE:
5885     case elfcpp::R_AARCH64_ABS32:
5886     case elfcpp::R_AARCH64_ABS64:
5887       return;
5888
5889     default:
5890       break;
5891     }
5892
5893   // This prevents us from issuing more than one error per reloc
5894   // section. But we can still wind up issuing more than one
5895   // error per object file.
5896   if (this->issued_non_pic_error_)
5897     return;
5898   gold_assert(parameters->options().output_is_position_independent());
5899   object->error(_("requires unsupported dynamic reloc; "
5900                   "recompile with -fPIC"));
5901   this->issued_non_pic_error_ = true;
5902   return;
5903 }
5904
5905 // Return whether we need to make a PLT entry for a relocation of the
5906 // given type against a STT_GNU_IFUNC symbol.
5907
5908 template<int size, bool big_endian>
5909 bool
5910 Target_aarch64<size, big_endian>::Scan::reloc_needs_plt_for_ifunc(
5911     Sized_relobj_file<size, big_endian>* object,
5912     unsigned int r_type)
5913 {
5914   const AArch64_reloc_property* arp =
5915       aarch64_reloc_property_table->get_reloc_property(r_type);
5916   gold_assert(arp != NULL);
5917
5918   int flags = arp->reference_flags();
5919   if (flags & Symbol::TLS_REF)
5920     {
5921       gold_error(_("%s: unsupported TLS reloc %s for IFUNC symbol"),
5922                  object->name().c_str(), arp->name().c_str());
5923       return false;
5924     }
5925   return flags != 0;
5926 }
5927
5928 // Scan a relocation for a local symbol.
5929
5930 template<int size, bool big_endian>
5931 inline void
5932 Target_aarch64<size, big_endian>::Scan::local(
5933     Symbol_table* symtab,
5934     Layout* layout,
5935     Target_aarch64<size, big_endian>* target,
5936     Sized_relobj_file<size, big_endian>* object,
5937     unsigned int data_shndx,
5938     Output_section* output_section,
5939     const elfcpp::Rela<size, big_endian>& rela,
5940     unsigned int r_type,
5941     const elfcpp::Sym<size, big_endian>& lsym,
5942     bool is_discarded)
5943 {
5944   if (is_discarded)
5945     return;
5946
5947   typedef Output_data_reloc<elfcpp::SHT_RELA, true, size, big_endian>
5948       Reloc_section;
5949   Output_data_got_aarch64<size, big_endian>* got =
5950       target->got_section(symtab, layout);
5951   unsigned int r_sym = elfcpp::elf_r_sym<size>(rela.get_r_info());
5952
5953   // A local STT_GNU_IFUNC symbol may require a PLT entry.
5954   bool is_ifunc = lsym.get_st_type() == elfcpp::STT_GNU_IFUNC;
5955   if (is_ifunc && this->reloc_needs_plt_for_ifunc(object, r_type))
5956     target->make_local_ifunc_plt_entry(symtab, layout, object, r_sym);
5957
5958   switch (r_type)
5959     {
5960     case elfcpp::R_AARCH64_ABS32:
5961     case elfcpp::R_AARCH64_ABS16:
5962       if (parameters->options().output_is_position_independent())
5963         {
5964           gold_error(_("%s: unsupported reloc %u in pos independent link."),
5965                      object->name().c_str(), r_type);
5966         }
5967       break;
5968
5969     case elfcpp::R_AARCH64_ABS64:
5970       // If building a shared library or pie, we need to mark this as a dynmic
5971       // reloction, so that the dynamic loader can relocate it.
5972       if (parameters->options().output_is_position_independent())
5973         {
5974           Reloc_section* rela_dyn = target->rela_dyn_section(layout);
5975           rela_dyn->add_local_relative(object, r_sym,
5976                                        elfcpp::R_AARCH64_RELATIVE,
5977                                        output_section,
5978                                        data_shndx,
5979                                        rela.get_r_offset(),
5980                                        rela.get_r_addend(),
5981                                        is_ifunc);
5982         }
5983       break;
5984
5985     case elfcpp::R_AARCH64_PREL64:
5986     case elfcpp::R_AARCH64_PREL32:
5987     case elfcpp::R_AARCH64_PREL16:
5988       break;
5989
5990     case elfcpp::R_AARCH64_ADR_GOT_PAGE:
5991     case elfcpp::R_AARCH64_LD64_GOT_LO12_NC:
5992       // This pair of relocations is used to access a specific GOT entry.
5993       {
5994         bool is_new = false;
5995         // This symbol requires a GOT entry.
5996         if (is_ifunc)
5997           is_new = got->add_local_plt(object, r_sym, GOT_TYPE_STANDARD);
5998         else
5999           is_new = got->add_local(object, r_sym, GOT_TYPE_STANDARD);
6000         if (is_new && parameters->options().output_is_position_independent())
6001           target->rela_dyn_section(layout)->
6002             add_local_relative(object,
6003                                r_sym,
6004                                elfcpp::R_AARCH64_RELATIVE,
6005                                got,
6006                                object->local_got_offset(r_sym,
6007                                                         GOT_TYPE_STANDARD),
6008                                0,
6009                                false);
6010       }
6011       break;
6012
6013     case elfcpp::R_AARCH64_LD_PREL_LO19:        // 273
6014     case elfcpp::R_AARCH64_ADR_PREL_LO21:       // 274
6015     case elfcpp::R_AARCH64_ADR_PREL_PG_HI21:    // 275
6016     case elfcpp::R_AARCH64_ADR_PREL_PG_HI21_NC: // 276
6017     case elfcpp::R_AARCH64_ADD_ABS_LO12_NC:     // 277
6018     case elfcpp::R_AARCH64_LDST8_ABS_LO12_NC:   // 278
6019     case elfcpp::R_AARCH64_LDST16_ABS_LO12_NC:  // 284
6020     case elfcpp::R_AARCH64_LDST32_ABS_LO12_NC:  // 285
6021     case elfcpp::R_AARCH64_LDST64_ABS_LO12_NC:  // 286
6022     case elfcpp::R_AARCH64_LDST128_ABS_LO12_NC: // 299
6023        break;
6024
6025     // Control flow, pc-relative. We don't need to do anything for a relative
6026     // addressing relocation against a local symbol if it does not reference
6027     // the GOT.
6028     case elfcpp::R_AARCH64_TSTBR14:
6029     case elfcpp::R_AARCH64_CONDBR19:
6030     case elfcpp::R_AARCH64_JUMP26:
6031     case elfcpp::R_AARCH64_CALL26:
6032       break;
6033
6034     case elfcpp::R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
6035     case elfcpp::R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
6036       {
6037         tls::Tls_optimization tlsopt = Target_aarch64<size, big_endian>::
6038           optimize_tls_reloc(!parameters->options().shared(), r_type);
6039         if (tlsopt == tls::TLSOPT_TO_LE)
6040           break;
6041
6042         layout->set_has_static_tls();
6043         // Create a GOT entry for the tp-relative offset.
6044         if (!parameters->doing_static_link())
6045           {
6046             got->add_local_with_rel(object, r_sym, GOT_TYPE_TLS_OFFSET,
6047                                     target->rela_dyn_section(layout),
6048                                     elfcpp::R_AARCH64_TLS_TPREL64);
6049           }
6050         else if (!object->local_has_got_offset(r_sym,
6051                                                GOT_TYPE_TLS_OFFSET))
6052           {
6053             got->add_local(object, r_sym, GOT_TYPE_TLS_OFFSET);
6054             unsigned int got_offset =
6055                 object->local_got_offset(r_sym, GOT_TYPE_TLS_OFFSET);
6056             const elfcpp::Elf_Xword addend = rela.get_r_addend();
6057             gold_assert(addend == 0);
6058             got->add_static_reloc(got_offset, elfcpp::R_AARCH64_TLS_TPREL64,
6059                                   object, r_sym);
6060           }
6061       }
6062       break;
6063
6064     case elfcpp::R_AARCH64_TLSGD_ADR_PAGE21:
6065     case elfcpp::R_AARCH64_TLSGD_ADD_LO12_NC:
6066       {
6067         tls::Tls_optimization tlsopt = Target_aarch64<size, big_endian>::
6068             optimize_tls_reloc(!parameters->options().shared(), r_type);
6069         if (tlsopt == tls::TLSOPT_TO_LE)
6070           {
6071             layout->set_has_static_tls();
6072             break;
6073           }
6074         gold_assert(tlsopt == tls::TLSOPT_NONE);
6075
6076         got->add_local_pair_with_rel(object,r_sym, data_shndx,
6077                                      GOT_TYPE_TLS_PAIR,
6078                                      target->rela_dyn_section(layout),
6079                                      elfcpp::R_AARCH64_TLS_DTPMOD64);
6080       }
6081       break;
6082
6083     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G2:
6084     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G1:
6085     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
6086     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G0:
6087     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
6088     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_HI12:
6089     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_LO12:
6090     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
6091       {
6092         layout->set_has_static_tls();
6093         bool output_is_shared = parameters->options().shared();
6094         if (output_is_shared)
6095           gold_error(_("%s: unsupported TLSLE reloc %u in shared code."),
6096                      object->name().c_str(), r_type);
6097       }
6098       break;
6099
6100     case elfcpp::R_AARCH64_TLSLD_ADR_PAGE21:
6101     case elfcpp::R_AARCH64_TLSLD_ADD_LO12_NC:
6102       {
6103         tls::Tls_optimization tlsopt = Target_aarch64<size, big_endian>::
6104             optimize_tls_reloc(!parameters->options().shared(), r_type);
6105         if (tlsopt == tls::TLSOPT_NONE)
6106           {
6107             // Create a GOT entry for the module index.
6108             target->got_mod_index_entry(symtab, layout, object);
6109           }
6110         else if (tlsopt != tls::TLSOPT_TO_LE)
6111           unsupported_reloc_local(object, r_type);
6112       }
6113       break;
6114
6115     case elfcpp::R_AARCH64_TLSLD_MOVW_DTPREL_G1:
6116     case elfcpp::R_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
6117     case elfcpp::R_AARCH64_TLSLD_ADD_DTPREL_HI12:
6118     case elfcpp::R_AARCH64_TLSLD_ADD_DTPREL_LO12_NC:
6119       break;
6120
6121     case elfcpp::R_AARCH64_TLSDESC_ADR_PAGE21:
6122     case elfcpp::R_AARCH64_TLSDESC_LD64_LO12:
6123     case elfcpp::R_AARCH64_TLSDESC_ADD_LO12:
6124       {
6125         tls::Tls_optimization tlsopt = Target_aarch64<size, big_endian>::
6126             optimize_tls_reloc(!parameters->options().shared(), r_type);
6127         target->define_tls_base_symbol(symtab, layout);
6128         if (tlsopt == tls::TLSOPT_NONE)
6129           {
6130             // Create reserved PLT and GOT entries for the resolver.
6131             target->reserve_tlsdesc_entries(symtab, layout);
6132
6133             // Generate a double GOT entry with an R_AARCH64_TLSDESC reloc.
6134             // The R_AARCH64_TLSDESC reloc is resolved lazily, so the GOT
6135             // entry needs to be in an area in .got.plt, not .got. Call
6136             // got_section to make sure the section has been created.
6137             target->got_section(symtab, layout);
6138             Output_data_got<size, big_endian>* got =
6139                 target->got_tlsdesc_section();
6140             unsigned int r_sym = elfcpp::elf_r_sym<size>(rela.get_r_info());
6141             if (!object->local_has_got_offset(r_sym, GOT_TYPE_TLS_DESC))
6142               {
6143                 unsigned int got_offset = got->add_constant(0);
6144                 got->add_constant(0);
6145                 object->set_local_got_offset(r_sym, GOT_TYPE_TLS_DESC,
6146                                              got_offset);
6147                 Reloc_section* rt = target->rela_tlsdesc_section(layout);
6148                 // We store the arguments we need in a vector, and use
6149                 // the index into the vector as the parameter to pass
6150                 // to the target specific routines.
6151                 uintptr_t intarg = target->add_tlsdesc_info(object, r_sym);
6152                 void* arg = reinterpret_cast<void*>(intarg);
6153                 rt->add_target_specific(elfcpp::R_AARCH64_TLSDESC, arg,
6154                                         got, got_offset, 0);
6155               }
6156           }
6157         else if (tlsopt != tls::TLSOPT_TO_LE)
6158           unsupported_reloc_local(object, r_type);
6159       }
6160       break;
6161
6162     case elfcpp::R_AARCH64_TLSDESC_CALL:
6163       break;
6164
6165     default:
6166       unsupported_reloc_local(object, r_type);
6167     }
6168 }
6169
6170
6171 // Report an unsupported relocation against a global symbol.
6172
6173 template<int size, bool big_endian>
6174 void
6175 Target_aarch64<size, big_endian>::Scan::unsupported_reloc_global(
6176     Sized_relobj_file<size, big_endian>* object,
6177     unsigned int r_type,
6178     Symbol* gsym)
6179 {
6180   gold_error(_("%s: unsupported reloc %u against global symbol %s"),
6181              object->name().c_str(), r_type, gsym->demangled_name().c_str());
6182 }
6183
6184 template<int size, bool big_endian>
6185 inline void
6186 Target_aarch64<size, big_endian>::Scan::global(
6187     Symbol_table* symtab,
6188     Layout* layout,
6189     Target_aarch64<size, big_endian>* target,
6190     Sized_relobj_file<size, big_endian> * object,
6191     unsigned int data_shndx,
6192     Output_section* output_section,
6193     const elfcpp::Rela<size, big_endian>& rela,
6194     unsigned int r_type,
6195     Symbol* gsym)
6196 {
6197   // A STT_GNU_IFUNC symbol may require a PLT entry.
6198   if (gsym->type() == elfcpp::STT_GNU_IFUNC
6199       && this->reloc_needs_plt_for_ifunc(object, r_type))
6200     target->make_plt_entry(symtab, layout, gsym);
6201
6202   typedef Output_data_reloc<elfcpp::SHT_RELA, true, size, big_endian>
6203     Reloc_section;
6204   const AArch64_reloc_property* arp =
6205       aarch64_reloc_property_table->get_reloc_property(r_type);
6206   gold_assert(arp != NULL);
6207
6208   switch (r_type)
6209     {
6210     case elfcpp::R_AARCH64_ABS16:
6211     case elfcpp::R_AARCH64_ABS32:
6212     case elfcpp::R_AARCH64_ABS64:
6213       {
6214         // Make a PLT entry if necessary.
6215         if (gsym->needs_plt_entry())
6216           {
6217             target->make_plt_entry(symtab, layout, gsym);
6218             // Since this is not a PC-relative relocation, we may be
6219             // taking the address of a function. In that case we need to
6220             // set the entry in the dynamic symbol table to the address of
6221             // the PLT entry.
6222             if (gsym->is_from_dynobj() && !parameters->options().shared())
6223               gsym->set_needs_dynsym_value();
6224           }
6225         // Make a dynamic relocation if necessary.
6226         if (gsym->needs_dynamic_reloc(arp->reference_flags()))
6227           {
6228             if (!parameters->options().output_is_position_independent()
6229                 && gsym->may_need_copy_reloc())
6230               {
6231                 target->copy_reloc(symtab, layout, object,
6232                                    data_shndx, output_section, gsym, rela);
6233               }
6234             else if (r_type == elfcpp::R_AARCH64_ABS64
6235                      && gsym->type() == elfcpp::STT_GNU_IFUNC
6236                      && gsym->can_use_relative_reloc(false)
6237                      && !gsym->is_from_dynobj()
6238                      && !gsym->is_undefined()
6239                      && !gsym->is_preemptible())
6240               {
6241                 // Use an IRELATIVE reloc for a locally defined STT_GNU_IFUNC
6242                 // symbol. This makes a function address in a PIE executable
6243                 // match the address in a shared library that it links against.
6244                 Reloc_section* rela_dyn =
6245                     target->rela_irelative_section(layout);
6246                 unsigned int r_type = elfcpp::R_AARCH64_IRELATIVE;
6247                 rela_dyn->add_symbolless_global_addend(gsym, r_type,
6248                                                        output_section, object,
6249                                                        data_shndx,
6250                                                        rela.get_r_offset(),
6251                                                        rela.get_r_addend());
6252               }
6253             else if (r_type == elfcpp::R_AARCH64_ABS64
6254                      && gsym->can_use_relative_reloc(false))
6255               {
6256                 Reloc_section* rela_dyn = target->rela_dyn_section(layout);
6257                 rela_dyn->add_global_relative(gsym,
6258                                               elfcpp::R_AARCH64_RELATIVE,
6259                                               output_section,
6260                                               object,
6261                                               data_shndx,
6262                                               rela.get_r_offset(),
6263                                               rela.get_r_addend(),
6264                                               false);
6265               }
6266             else
6267               {
6268                 check_non_pic(object, r_type);
6269                 Output_data_reloc<elfcpp::SHT_RELA, true, size, big_endian>*
6270                     rela_dyn = target->rela_dyn_section(layout);
6271                 rela_dyn->add_global(
6272                   gsym, r_type, output_section, object,
6273                   data_shndx, rela.get_r_offset(),rela.get_r_addend());
6274               }
6275           }
6276       }
6277       break;
6278
6279     case elfcpp::R_AARCH64_PREL16:
6280     case elfcpp::R_AARCH64_PREL32:
6281     case elfcpp::R_AARCH64_PREL64:
6282       // This is used to fill the GOT absolute address.
6283       if (gsym->needs_plt_entry())
6284         {
6285           target->make_plt_entry(symtab, layout, gsym);
6286         }
6287       break;
6288
6289     case elfcpp::R_AARCH64_LD_PREL_LO19:        // 273
6290     case elfcpp::R_AARCH64_ADR_PREL_LO21:       // 274
6291     case elfcpp::R_AARCH64_ADR_PREL_PG_HI21:    // 275
6292     case elfcpp::R_AARCH64_ADR_PREL_PG_HI21_NC: // 276
6293     case elfcpp::R_AARCH64_ADD_ABS_LO12_NC:     // 277
6294     case elfcpp::R_AARCH64_LDST8_ABS_LO12_NC:   // 278
6295     case elfcpp::R_AARCH64_LDST16_ABS_LO12_NC:  // 284
6296     case elfcpp::R_AARCH64_LDST32_ABS_LO12_NC:  // 285
6297     case elfcpp::R_AARCH64_LDST64_ABS_LO12_NC:  // 286
6298     case elfcpp::R_AARCH64_LDST128_ABS_LO12_NC: // 299
6299       {
6300         if (gsym->needs_plt_entry())
6301           target->make_plt_entry(symtab, layout, gsym);
6302         // Make a dynamic relocation if necessary.
6303         if (gsym->needs_dynamic_reloc(arp->reference_flags()))
6304           {
6305             if (parameters->options().output_is_executable()
6306                 && gsym->may_need_copy_reloc())
6307               {
6308                 target->copy_reloc(symtab, layout, object,
6309                                    data_shndx, output_section, gsym, rela);
6310               }
6311           }
6312         break;
6313       }
6314
6315     case elfcpp::R_AARCH64_ADR_GOT_PAGE:
6316     case elfcpp::R_AARCH64_LD64_GOT_LO12_NC:
6317       {
6318         // This pair of relocations is used to access a specific GOT entry.
6319         // Note a GOT entry is an *address* to a symbol.
6320         // The symbol requires a GOT entry
6321         Output_data_got_aarch64<size, big_endian>* got =
6322           target->got_section(symtab, layout);
6323         if (gsym->final_value_is_known())
6324           {
6325             // For a STT_GNU_IFUNC symbol we want the PLT address.
6326             if (gsym->type() == elfcpp::STT_GNU_IFUNC)
6327               got->add_global_plt(gsym, GOT_TYPE_STANDARD);
6328             else
6329               got->add_global(gsym, GOT_TYPE_STANDARD);
6330           }
6331         else
6332           {
6333             // If this symbol is not fully resolved, we need to add a dynamic
6334             // relocation for it.
6335             Reloc_section* rela_dyn = target->rela_dyn_section(layout);
6336
6337             // Use a GLOB_DAT rather than a RELATIVE reloc if:
6338             //
6339             // 1) The symbol may be defined in some other module.
6340             // 2) We are building a shared library and this is a protected
6341             // symbol; using GLOB_DAT means that the dynamic linker can use
6342             // the address of the PLT in the main executable when appropriate
6343             // so that function address comparisons work.
6344             // 3) This is a STT_GNU_IFUNC symbol in position dependent code,
6345             // again so that function address comparisons work.
6346             if (gsym->is_from_dynobj()
6347                 || gsym->is_undefined()
6348                 || gsym->is_preemptible()
6349                 || (gsym->visibility() == elfcpp::STV_PROTECTED
6350                     && parameters->options().shared())
6351                 || (gsym->type() == elfcpp::STT_GNU_IFUNC
6352                     && parameters->options().output_is_position_independent()))
6353               got->add_global_with_rel(gsym, GOT_TYPE_STANDARD,
6354                                        rela_dyn, elfcpp::R_AARCH64_GLOB_DAT);
6355             else
6356               {
6357                 // For a STT_GNU_IFUNC symbol we want to write the PLT
6358                 // offset into the GOT, so that function pointer
6359                 // comparisons work correctly.
6360                 bool is_new;
6361                 if (gsym->type() != elfcpp::STT_GNU_IFUNC)
6362                   is_new = got->add_global(gsym, GOT_TYPE_STANDARD);
6363                 else
6364                   {
6365                     is_new = got->add_global_plt(gsym, GOT_TYPE_STANDARD);
6366                     // Tell the dynamic linker to use the PLT address
6367                     // when resolving relocations.
6368                     if (gsym->is_from_dynobj()
6369                         && !parameters->options().shared())
6370                       gsym->set_needs_dynsym_value();
6371                   }
6372                 if (is_new)
6373                   {
6374                     rela_dyn->add_global_relative(
6375                         gsym, elfcpp::R_AARCH64_RELATIVE,
6376                         got,
6377                         gsym->got_offset(GOT_TYPE_STANDARD),
6378                         0,
6379                         false);
6380                   }
6381               }
6382           }
6383         break;
6384       }
6385
6386     case elfcpp::R_AARCH64_TSTBR14:
6387     case elfcpp::R_AARCH64_CONDBR19:
6388     case elfcpp::R_AARCH64_JUMP26:
6389     case elfcpp::R_AARCH64_CALL26:
6390       {
6391         if (gsym->final_value_is_known())
6392           break;
6393
6394         if (gsym->is_defined() &&
6395             !gsym->is_from_dynobj() &&
6396             !gsym->is_preemptible())
6397           break;
6398
6399         // Make plt entry for function call.
6400         target->make_plt_entry(symtab, layout, gsym);
6401         break;
6402       }
6403
6404     case elfcpp::R_AARCH64_TLSGD_ADR_PAGE21:
6405     case elfcpp::R_AARCH64_TLSGD_ADD_LO12_NC:  // General dynamic
6406       {
6407         tls::Tls_optimization tlsopt = Target_aarch64<size, big_endian>::
6408             optimize_tls_reloc(gsym->final_value_is_known(), r_type);
6409         if (tlsopt == tls::TLSOPT_TO_LE)
6410           {
6411             layout->set_has_static_tls();
6412             break;
6413           }
6414         gold_assert(tlsopt == tls::TLSOPT_NONE);
6415
6416         // General dynamic.
6417         Output_data_got_aarch64<size, big_endian>* got =
6418             target->got_section(symtab, layout);
6419         // Create 2 consecutive entries for module index and offset.
6420         got->add_global_pair_with_rel(gsym, GOT_TYPE_TLS_PAIR,
6421                                       target->rela_dyn_section(layout),
6422                                       elfcpp::R_AARCH64_TLS_DTPMOD64,
6423                                       elfcpp::R_AARCH64_TLS_DTPREL64);
6424       }
6425       break;
6426
6427     case elfcpp::R_AARCH64_TLSLD_ADR_PAGE21:
6428     case elfcpp::R_AARCH64_TLSLD_ADD_LO12_NC:  // Local dynamic
6429       {
6430         tls::Tls_optimization tlsopt = Target_aarch64<size, big_endian>::
6431             optimize_tls_reloc(!parameters->options().shared(), r_type);
6432         if (tlsopt == tls::TLSOPT_NONE)
6433           {
6434             // Create a GOT entry for the module index.
6435             target->got_mod_index_entry(symtab, layout, object);
6436           }
6437         else if (tlsopt != tls::TLSOPT_TO_LE)
6438           unsupported_reloc_local(object, r_type);
6439       }
6440       break;
6441
6442     case elfcpp::R_AARCH64_TLSLD_MOVW_DTPREL_G1:
6443     case elfcpp::R_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
6444     case elfcpp::R_AARCH64_TLSLD_ADD_DTPREL_HI12:
6445     case elfcpp::R_AARCH64_TLSLD_ADD_DTPREL_LO12_NC:  // Other local dynamic
6446       break;
6447
6448     case elfcpp::R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
6449     case elfcpp::R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:  // Initial executable
6450       {
6451         tls::Tls_optimization tlsopt = Target_aarch64<size, big_endian>::
6452           optimize_tls_reloc(gsym->final_value_is_known(), r_type);
6453         if (tlsopt == tls::TLSOPT_TO_LE)
6454           break;
6455
6456         layout->set_has_static_tls();
6457         // Create a GOT entry for the tp-relative offset.
6458         Output_data_got_aarch64<size, big_endian>* got
6459           = target->got_section(symtab, layout);
6460         if (!parameters->doing_static_link())
6461           {
6462             got->add_global_with_rel(
6463               gsym, GOT_TYPE_TLS_OFFSET,
6464               target->rela_dyn_section(layout),
6465               elfcpp::R_AARCH64_TLS_TPREL64);
6466           }
6467         if (!gsym->has_got_offset(GOT_TYPE_TLS_OFFSET))
6468           {
6469             got->add_global(gsym, GOT_TYPE_TLS_OFFSET);
6470             unsigned int got_offset =
6471               gsym->got_offset(GOT_TYPE_TLS_OFFSET);
6472             const elfcpp::Elf_Xword addend = rela.get_r_addend();
6473             gold_assert(addend == 0);
6474             got->add_static_reloc(got_offset,
6475                                   elfcpp::R_AARCH64_TLS_TPREL64, gsym);
6476           }
6477       }
6478       break;
6479
6480     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G2:
6481     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G1:
6482     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
6483     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G0:
6484     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
6485     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_HI12:
6486     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_LO12:
6487     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:  // Local executable
6488       layout->set_has_static_tls();
6489       if (parameters->options().shared())
6490         gold_error(_("%s: unsupported TLSLE reloc type %u in shared objects."),
6491                    object->name().c_str(), r_type);
6492       break;
6493
6494     case elfcpp::R_AARCH64_TLSDESC_ADR_PAGE21:
6495     case elfcpp::R_AARCH64_TLSDESC_LD64_LO12:
6496     case elfcpp::R_AARCH64_TLSDESC_ADD_LO12:  // TLS descriptor
6497       {
6498         target->define_tls_base_symbol(symtab, layout);
6499         tls::Tls_optimization tlsopt = Target_aarch64<size, big_endian>::
6500             optimize_tls_reloc(gsym->final_value_is_known(), r_type);
6501         if (tlsopt == tls::TLSOPT_NONE)
6502           {
6503             // Create reserved PLT and GOT entries for the resolver.
6504             target->reserve_tlsdesc_entries(symtab, layout);
6505
6506             // Create a double GOT entry with an R_AARCH64_TLSDESC
6507             // relocation. The R_AARCH64_TLSDESC is resolved lazily, so the GOT
6508             // entry needs to be in an area in .got.plt, not .got. Call
6509             // got_section to make sure the section has been created.
6510             target->got_section(symtab, layout);
6511             Output_data_got<size, big_endian>* got =
6512                 target->got_tlsdesc_section();
6513             Reloc_section* rt = target->rela_tlsdesc_section(layout);
6514             got->add_global_pair_with_rel(gsym, GOT_TYPE_TLS_DESC, rt,
6515                                           elfcpp::R_AARCH64_TLSDESC, 0);
6516           }
6517         else if (tlsopt == tls::TLSOPT_TO_IE)
6518           {
6519             // Create a GOT entry for the tp-relative offset.
6520             Output_data_got<size, big_endian>* got
6521                 = target->got_section(symtab, layout);
6522             got->add_global_with_rel(gsym, GOT_TYPE_TLS_OFFSET,
6523                                      target->rela_dyn_section(layout),
6524                                      elfcpp::R_AARCH64_TLS_TPREL64);
6525           }
6526         else if (tlsopt != tls::TLSOPT_TO_LE)
6527           unsupported_reloc_global(object, r_type, gsym);
6528       }
6529       break;
6530
6531     case elfcpp::R_AARCH64_TLSDESC_CALL:
6532       break;
6533
6534     default:
6535       gold_error(_("%s: unsupported reloc type in global scan"),
6536                  aarch64_reloc_property_table->
6537                  reloc_name_in_error_message(r_type).c_str());
6538     }
6539   return;
6540 }  // End of Scan::global
6541
6542
6543 // Create the PLT section.
6544 template<int size, bool big_endian>
6545 void
6546 Target_aarch64<size, big_endian>::make_plt_section(
6547   Symbol_table* symtab, Layout* layout)
6548 {
6549   if (this->plt_ == NULL)
6550     {
6551       // Create the GOT section first.
6552       this->got_section(symtab, layout);
6553
6554       this->plt_ = this->make_data_plt(layout, this->got_, this->got_plt_,
6555                                        this->got_irelative_);
6556
6557       layout->add_output_section_data(".plt", elfcpp::SHT_PROGBITS,
6558                                       (elfcpp::SHF_ALLOC
6559                                        | elfcpp::SHF_EXECINSTR),
6560                                       this->plt_, ORDER_PLT, false);
6561
6562       // Make the sh_info field of .rela.plt point to .plt.
6563       Output_section* rela_plt_os = this->plt_->rela_plt()->output_section();
6564       rela_plt_os->set_info_section(this->plt_->output_section());
6565     }
6566 }
6567
6568 // Return the section for TLSDESC relocations.
6569
6570 template<int size, bool big_endian>
6571 typename Target_aarch64<size, big_endian>::Reloc_section*
6572 Target_aarch64<size, big_endian>::rela_tlsdesc_section(Layout* layout) const
6573 {
6574   return this->plt_section()->rela_tlsdesc(layout);
6575 }
6576
6577 // Create a PLT entry for a global symbol.
6578
6579 template<int size, bool big_endian>
6580 void
6581 Target_aarch64<size, big_endian>::make_plt_entry(
6582     Symbol_table* symtab,
6583     Layout* layout,
6584     Symbol* gsym)
6585 {
6586   if (gsym->has_plt_offset())
6587     return;
6588
6589   if (this->plt_ == NULL)
6590     this->make_plt_section(symtab, layout);
6591
6592   this->plt_->add_entry(symtab, layout, gsym);
6593 }
6594
6595 // Make a PLT entry for a local STT_GNU_IFUNC symbol.
6596
6597 template<int size, bool big_endian>
6598 void
6599 Target_aarch64<size, big_endian>::make_local_ifunc_plt_entry(
6600     Symbol_table* symtab, Layout* layout,
6601     Sized_relobj_file<size, big_endian>* relobj,
6602     unsigned int local_sym_index)
6603 {
6604   if (relobj->local_has_plt_offset(local_sym_index))
6605     return;
6606   if (this->plt_ == NULL)
6607     this->make_plt_section(symtab, layout);
6608   unsigned int plt_offset = this->plt_->add_local_ifunc_entry(symtab, layout,
6609                                                               relobj,
6610                                                               local_sym_index);
6611   relobj->set_local_plt_offset(local_sym_index, plt_offset);
6612 }
6613
6614 template<int size, bool big_endian>
6615 void
6616 Target_aarch64<size, big_endian>::gc_process_relocs(
6617     Symbol_table* symtab,
6618     Layout* layout,
6619     Sized_relobj_file<size, big_endian>* object,
6620     unsigned int data_shndx,
6621     unsigned int sh_type,
6622     const unsigned char* prelocs,
6623     size_t reloc_count,
6624     Output_section* output_section,
6625     bool needs_special_offset_handling,
6626     size_t local_symbol_count,
6627     const unsigned char* plocal_symbols)
6628 {
6629   if (sh_type == elfcpp::SHT_REL)
6630     {
6631       return;
6632     }
6633
6634   gold::gc_process_relocs<
6635     size, big_endian,
6636     Target_aarch64<size, big_endian>,
6637     elfcpp::SHT_RELA,
6638     typename Target_aarch64<size, big_endian>::Scan,
6639     typename Target_aarch64<size, big_endian>::Relocatable_size_for_reloc>(
6640     symtab,
6641     layout,
6642     this,
6643     object,
6644     data_shndx,
6645     prelocs,
6646     reloc_count,
6647     output_section,
6648     needs_special_offset_handling,
6649     local_symbol_count,
6650     plocal_symbols);
6651 }
6652
6653 // Scan relocations for a section.
6654
6655 template<int size, bool big_endian>
6656 void
6657 Target_aarch64<size, big_endian>::scan_relocs(
6658     Symbol_table* symtab,
6659     Layout* layout,
6660     Sized_relobj_file<size, big_endian>* object,
6661     unsigned int data_shndx,
6662     unsigned int sh_type,
6663     const unsigned char* prelocs,
6664     size_t reloc_count,
6665     Output_section* output_section,
6666     bool needs_special_offset_handling,
6667     size_t local_symbol_count,
6668     const unsigned char* plocal_symbols)
6669 {
6670   if (sh_type == elfcpp::SHT_REL)
6671     {
6672       gold_error(_("%s: unsupported REL reloc section"),
6673                  object->name().c_str());
6674       return;
6675     }
6676   gold::scan_relocs<size, big_endian, Target_aarch64, elfcpp::SHT_RELA, Scan>(
6677     symtab,
6678     layout,
6679     this,
6680     object,
6681     data_shndx,
6682     prelocs,
6683     reloc_count,
6684     output_section,
6685     needs_special_offset_handling,
6686     local_symbol_count,
6687     plocal_symbols);
6688 }
6689
6690 // Return the value to use for a dynamic which requires special
6691 // treatment.  This is how we support equality comparisons of function
6692 // pointers across shared library boundaries, as described in the
6693 // processor specific ABI supplement.
6694
6695 template<int size, bool big_endian>
6696 uint64_t
6697 Target_aarch64<size, big_endian>::do_dynsym_value(const Symbol* gsym) const
6698 {
6699   gold_assert(gsym->is_from_dynobj() && gsym->has_plt_offset());
6700   return this->plt_address_for_global(gsym);
6701 }
6702
6703
6704 // Finalize the sections.
6705
6706 template<int size, bool big_endian>
6707 void
6708 Target_aarch64<size, big_endian>::do_finalize_sections(
6709     Layout* layout,
6710     const Input_objects*,
6711     Symbol_table* symtab)
6712 {
6713   const Reloc_section* rel_plt = (this->plt_ == NULL
6714                                   ? NULL
6715                                   : this->plt_->rela_plt());
6716   layout->add_target_dynamic_tags(false, this->got_plt_, rel_plt,
6717                                   this->rela_dyn_, true, false);
6718
6719   // Emit any relocs we saved in an attempt to avoid generating COPY
6720   // relocs.
6721   if (this->copy_relocs_.any_saved_relocs())
6722     this->copy_relocs_.emit(this->rela_dyn_section(layout));
6723
6724   // Fill in some more dynamic tags.
6725   Output_data_dynamic* const odyn = layout->dynamic_data();
6726   if (odyn != NULL)
6727     {
6728       if (this->plt_ != NULL
6729           && this->plt_->output_section() != NULL
6730           && this->plt_ ->has_tlsdesc_entry())
6731         {
6732           unsigned int plt_offset = this->plt_->get_tlsdesc_plt_offset();
6733           unsigned int got_offset = this->plt_->get_tlsdesc_got_offset();
6734           this->got_->finalize_data_size();
6735           odyn->add_section_plus_offset(elfcpp::DT_TLSDESC_PLT,
6736                                         this->plt_, plt_offset);
6737           odyn->add_section_plus_offset(elfcpp::DT_TLSDESC_GOT,
6738                                         this->got_, got_offset);
6739         }
6740     }
6741
6742   // Set the size of the _GLOBAL_OFFSET_TABLE_ symbol to the size of
6743   // the .got.plt section.
6744   Symbol* sym = this->global_offset_table_;
6745   if (sym != NULL)
6746     {
6747       uint64_t data_size = this->got_plt_->current_data_size();
6748       symtab->get_sized_symbol<size>(sym)->set_symsize(data_size);
6749
6750       // If the .got section is more than 0x8000 bytes, we add
6751       // 0x8000 to the value of _GLOBAL_OFFSET_TABLE_, so that 16
6752       // bit relocations have a greater chance of working.
6753       if (data_size >= 0x8000)
6754         symtab->get_sized_symbol<size>(sym)->set_value(
6755           symtab->get_sized_symbol<size>(sym)->value() + 0x8000);
6756     }
6757
6758   if (parameters->doing_static_link()
6759       && (this->plt_ == NULL || !this->plt_->has_irelative_section()))
6760     {
6761       // If linking statically, make sure that the __rela_iplt symbols
6762       // were defined if necessary, even if we didn't create a PLT.
6763       static const Define_symbol_in_segment syms[] =
6764         {
6765           {
6766             "__rela_iplt_start",        // name
6767             elfcpp::PT_LOAD,            // segment_type
6768             elfcpp::PF_W,               // segment_flags_set
6769             elfcpp::PF(0),              // segment_flags_clear
6770             0,                          // value
6771             0,                          // size
6772             elfcpp::STT_NOTYPE,         // type
6773             elfcpp::STB_GLOBAL,         // binding
6774             elfcpp::STV_HIDDEN,         // visibility
6775             0,                          // nonvis
6776             Symbol::SEGMENT_START,      // offset_from_base
6777             true                        // only_if_ref
6778           },
6779           {
6780             "__rela_iplt_end",          // name
6781             elfcpp::PT_LOAD,            // segment_type
6782             elfcpp::PF_W,               // segment_flags_set
6783             elfcpp::PF(0),              // segment_flags_clear
6784             0,                          // value
6785             0,                          // size
6786             elfcpp::STT_NOTYPE,         // type
6787             elfcpp::STB_GLOBAL,         // binding
6788             elfcpp::STV_HIDDEN,         // visibility
6789             0,                          // nonvis
6790             Symbol::SEGMENT_START,      // offset_from_base
6791             true                        // only_if_ref
6792           }
6793         };
6794
6795       symtab->define_symbols(layout, 2, syms,
6796                              layout->script_options()->saw_sections_clause());
6797     }
6798
6799   return;
6800 }
6801
6802 // Perform a relocation.
6803
6804 template<int size, bool big_endian>
6805 inline bool
6806 Target_aarch64<size, big_endian>::Relocate::relocate(
6807     const Relocate_info<size, big_endian>* relinfo,
6808     Target_aarch64<size, big_endian>* target,
6809     Output_section* ,
6810     size_t relnum,
6811     const elfcpp::Rela<size, big_endian>& rela,
6812     unsigned int r_type,
6813     const Sized_symbol<size>* gsym,
6814     const Symbol_value<size>* psymval,
6815     unsigned char* view,
6816     typename elfcpp::Elf_types<size>::Elf_Addr address,
6817     section_size_type /* view_size */)
6818 {
6819   if (view == NULL)
6820     return true;
6821
6822   typedef AArch64_relocate_functions<size, big_endian> Reloc;
6823
6824   const AArch64_reloc_property* reloc_property =
6825       aarch64_reloc_property_table->get_reloc_property(r_type);
6826
6827   if (reloc_property == NULL)
6828     {
6829       std::string reloc_name =
6830           aarch64_reloc_property_table->reloc_name_in_error_message(r_type);
6831       gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
6832                              _("cannot relocate %s in object file"),
6833                              reloc_name.c_str());
6834       return true;
6835     }
6836
6837   const Sized_relobj_file<size, big_endian>* object = relinfo->object;
6838
6839   // Pick the value to use for symbols defined in the PLT.
6840   Symbol_value<size> symval;
6841   if (gsym != NULL
6842       && gsym->use_plt_offset(reloc_property->reference_flags()))
6843     {
6844       symval.set_output_value(target->plt_address_for_global(gsym));
6845       psymval = &symval;
6846     }
6847   else if (gsym == NULL && psymval->is_ifunc_symbol())
6848     {
6849       unsigned int r_sym = elfcpp::elf_r_sym<size>(rela.get_r_info());
6850       if (object->local_has_plt_offset(r_sym))
6851         {
6852           symval.set_output_value(target->plt_address_for_local(object, r_sym));
6853           psymval = &symval;
6854         }
6855     }
6856
6857   const elfcpp::Elf_Xword addend = rela.get_r_addend();
6858
6859   // Get the GOT offset if needed.
6860   // For aarch64, the GOT pointer points to the start of the GOT section.
6861   bool have_got_offset = false;
6862   int got_offset = 0;
6863   int got_base = (target->got_ != NULL
6864                   ? (target->got_->current_data_size() >= 0x8000
6865                      ? 0x8000 : 0)
6866                   : 0);
6867   switch (r_type)
6868     {
6869     case elfcpp::R_AARCH64_MOVW_GOTOFF_G0:
6870     case elfcpp::R_AARCH64_MOVW_GOTOFF_G0_NC:
6871     case elfcpp::R_AARCH64_MOVW_GOTOFF_G1:
6872     case elfcpp::R_AARCH64_MOVW_GOTOFF_G1_NC:
6873     case elfcpp::R_AARCH64_MOVW_GOTOFF_G2:
6874     case elfcpp::R_AARCH64_MOVW_GOTOFF_G2_NC:
6875     case elfcpp::R_AARCH64_MOVW_GOTOFF_G3:
6876     case elfcpp::R_AARCH64_GOTREL64:
6877     case elfcpp::R_AARCH64_GOTREL32:
6878     case elfcpp::R_AARCH64_GOT_LD_PREL19:
6879     case elfcpp::R_AARCH64_LD64_GOTOFF_LO15:
6880     case elfcpp::R_AARCH64_ADR_GOT_PAGE:
6881     case elfcpp::R_AARCH64_LD64_GOT_LO12_NC:
6882     case elfcpp::R_AARCH64_LD64_GOTPAGE_LO15:
6883       if (gsym != NULL)
6884         {
6885           gold_assert(gsym->has_got_offset(GOT_TYPE_STANDARD));
6886           got_offset = gsym->got_offset(GOT_TYPE_STANDARD) - got_base;
6887         }
6888       else
6889         {
6890           unsigned int r_sym = elfcpp::elf_r_sym<size>(rela.get_r_info());
6891           gold_assert(object->local_has_got_offset(r_sym, GOT_TYPE_STANDARD));
6892           got_offset = (object->local_got_offset(r_sym, GOT_TYPE_STANDARD)
6893                         - got_base);
6894         }
6895       have_got_offset = true;
6896       break;
6897
6898     default:
6899       break;
6900     }
6901
6902   typename Reloc::Status reloc_status = Reloc::STATUS_OKAY;
6903   typename elfcpp::Elf_types<size>::Elf_Addr value;
6904   switch (r_type)
6905     {
6906     case elfcpp::R_AARCH64_NONE:
6907       break;
6908
6909     case elfcpp::R_AARCH64_ABS64:
6910       reloc_status = Reloc::template rela_ua<64>(
6911         view, object, psymval, addend, reloc_property);
6912       break;
6913
6914     case elfcpp::R_AARCH64_ABS32:
6915       reloc_status = Reloc::template rela_ua<32>(
6916         view, object, psymval, addend, reloc_property);
6917       break;
6918
6919     case elfcpp::R_AARCH64_ABS16:
6920       reloc_status = Reloc::template rela_ua<16>(
6921         view, object, psymval, addend, reloc_property);
6922       break;
6923
6924     case elfcpp::R_AARCH64_PREL64:
6925       reloc_status = Reloc::template pcrela_ua<64>(
6926         view, object, psymval, addend, address, reloc_property);
6927       break;
6928
6929     case elfcpp::R_AARCH64_PREL32:
6930       reloc_status = Reloc::template pcrela_ua<32>(
6931         view, object, psymval, addend, address, reloc_property);
6932       break;
6933
6934     case elfcpp::R_AARCH64_PREL16:
6935       reloc_status = Reloc::template pcrela_ua<16>(
6936         view, object, psymval, addend, address, reloc_property);
6937       break;
6938
6939     case elfcpp::R_AARCH64_LD_PREL_LO19:
6940       reloc_status = Reloc::template pcrela_general<32>(
6941           view, object, psymval, addend, address, reloc_property);
6942       break;
6943
6944     case elfcpp::R_AARCH64_ADR_PREL_LO21:
6945       reloc_status = Reloc::adr(view, object, psymval, addend,
6946                                 address, reloc_property);
6947       break;
6948
6949     case elfcpp::R_AARCH64_ADR_PREL_PG_HI21_NC:
6950     case elfcpp::R_AARCH64_ADR_PREL_PG_HI21:
6951       reloc_status = Reloc::adrp(view, object, psymval, addend, address,
6952                                  reloc_property);
6953       break;
6954
6955     case elfcpp::R_AARCH64_LDST8_ABS_LO12_NC:
6956     case elfcpp::R_AARCH64_LDST16_ABS_LO12_NC:
6957     case elfcpp::R_AARCH64_LDST32_ABS_LO12_NC:
6958     case elfcpp::R_AARCH64_LDST64_ABS_LO12_NC:
6959     case elfcpp::R_AARCH64_LDST128_ABS_LO12_NC:
6960     case elfcpp::R_AARCH64_ADD_ABS_LO12_NC:
6961       reloc_status = Reloc::template rela_general<32>(
6962         view, object, psymval, addend, reloc_property);
6963       break;
6964
6965     case elfcpp::R_AARCH64_CALL26:
6966       if (this->skip_call_tls_get_addr_)
6967         {
6968           // Double check that the TLSGD insn has been optimized away.
6969           typedef typename elfcpp::Swap<32, big_endian>::Valtype Insntype;
6970           Insntype insn = elfcpp::Swap<32, big_endian>::readval(
6971               reinterpret_cast<Insntype*>(view));
6972           gold_assert((insn & 0xff000000) == 0x91000000);
6973
6974           reloc_status = Reloc::STATUS_OKAY;
6975           this->skip_call_tls_get_addr_ = false;
6976           // Return false to stop further processing this reloc.
6977           return false;
6978         }
6979       // Fallthrough
6980     case elfcpp::R_AARCH64_JUMP26:
6981       if (Reloc::maybe_apply_stub(r_type, relinfo, rela, view, address,
6982                                   gsym, psymval, object,
6983                                   target->stub_group_size_))
6984         break;
6985       // Fallthrough
6986     case elfcpp::R_AARCH64_TSTBR14:
6987     case elfcpp::R_AARCH64_CONDBR19:
6988       reloc_status = Reloc::template pcrela_general<32>(
6989         view, object, psymval, addend, address, reloc_property);
6990       break;
6991
6992     case elfcpp::R_AARCH64_ADR_GOT_PAGE:
6993       gold_assert(have_got_offset);
6994       value = target->got_->address() + got_base + got_offset;
6995       reloc_status = Reloc::adrp(view, value + addend, address);
6996       break;
6997
6998     case elfcpp::R_AARCH64_LD64_GOT_LO12_NC:
6999       gold_assert(have_got_offset);
7000       value = target->got_->address() + got_base + got_offset;
7001       reloc_status = Reloc::template rela_general<32>(
7002         view, value, addend, reloc_property);
7003       break;
7004
7005     case elfcpp::R_AARCH64_TLSGD_ADR_PAGE21:
7006     case elfcpp::R_AARCH64_TLSGD_ADD_LO12_NC:
7007     case elfcpp::R_AARCH64_TLSLD_ADR_PAGE21:
7008     case elfcpp::R_AARCH64_TLSLD_ADD_LO12_NC:
7009     case elfcpp::R_AARCH64_TLSLD_MOVW_DTPREL_G1:
7010     case elfcpp::R_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
7011     case elfcpp::R_AARCH64_TLSLD_ADD_DTPREL_HI12:
7012     case elfcpp::R_AARCH64_TLSLD_ADD_DTPREL_LO12_NC:
7013     case elfcpp::R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
7014     case elfcpp::R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
7015     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G2:
7016     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G1:
7017     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
7018     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G0:
7019     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
7020     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_HI12:
7021     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_LO12:
7022     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
7023     case elfcpp::R_AARCH64_TLSDESC_ADR_PAGE21:
7024     case elfcpp::R_AARCH64_TLSDESC_LD64_LO12:
7025     case elfcpp::R_AARCH64_TLSDESC_ADD_LO12:
7026     case elfcpp::R_AARCH64_TLSDESC_CALL:
7027       reloc_status = relocate_tls(relinfo, target, relnum, rela, r_type,
7028                                   gsym, psymval, view, address);
7029       break;
7030
7031     // These are dynamic relocations, which are unexpected when linking.
7032     case elfcpp::R_AARCH64_COPY:
7033     case elfcpp::R_AARCH64_GLOB_DAT:
7034     case elfcpp::R_AARCH64_JUMP_SLOT:
7035     case elfcpp::R_AARCH64_RELATIVE:
7036     case elfcpp::R_AARCH64_IRELATIVE:
7037     case elfcpp::R_AARCH64_TLS_DTPREL64:
7038     case elfcpp::R_AARCH64_TLS_DTPMOD64:
7039     case elfcpp::R_AARCH64_TLS_TPREL64:
7040     case elfcpp::R_AARCH64_TLSDESC:
7041       gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
7042                              _("unexpected reloc %u in object file"),
7043                              r_type);
7044       break;
7045
7046     default:
7047       gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
7048                              _("unsupported reloc %s"),
7049                              reloc_property->name().c_str());
7050       break;
7051     }
7052
7053   // Report any errors.
7054   switch (reloc_status)
7055     {
7056     case Reloc::STATUS_OKAY:
7057       break;
7058     case Reloc::STATUS_OVERFLOW:
7059       gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
7060                              _("relocation overflow in %s"),
7061                              reloc_property->name().c_str());
7062       break;
7063     case Reloc::STATUS_BAD_RELOC:
7064       gold_error_at_location(
7065           relinfo,
7066           relnum,
7067           rela.get_r_offset(),
7068           _("unexpected opcode while processing relocation %s"),
7069           reloc_property->name().c_str());
7070       break;
7071     default:
7072       gold_unreachable();
7073     }
7074
7075   return true;
7076 }
7077
7078
7079 template<int size, bool big_endian>
7080 inline
7081 typename AArch64_relocate_functions<size, big_endian>::Status
7082 Target_aarch64<size, big_endian>::Relocate::relocate_tls(
7083     const Relocate_info<size, big_endian>* relinfo,
7084     Target_aarch64<size, big_endian>* target,
7085     size_t relnum,
7086     const elfcpp::Rela<size, big_endian>& rela,
7087     unsigned int r_type, const Sized_symbol<size>* gsym,
7088     const Symbol_value<size>* psymval,
7089     unsigned char* view,
7090     typename elfcpp::Elf_types<size>::Elf_Addr address)
7091 {
7092   typedef AArch64_relocate_functions<size, big_endian> aarch64_reloc_funcs;
7093   typedef typename elfcpp::Elf_types<size>::Elf_Addr AArch64_address;
7094
7095   Output_segment* tls_segment = relinfo->layout->tls_segment();
7096   const elfcpp::Elf_Xword addend = rela.get_r_addend();
7097   const AArch64_reloc_property* reloc_property =
7098       aarch64_reloc_property_table->get_reloc_property(r_type);
7099   gold_assert(reloc_property != NULL);
7100
7101   const bool is_final = (gsym == NULL
7102                          ? !parameters->options().shared()
7103                          : gsym->final_value_is_known());
7104   tls::Tls_optimization tlsopt = Target_aarch64<size, big_endian>::
7105       optimize_tls_reloc(is_final, r_type);
7106
7107   Sized_relobj_file<size, big_endian>* object = relinfo->object;
7108   int tls_got_offset_type;
7109   switch (r_type)
7110     {
7111     case elfcpp::R_AARCH64_TLSGD_ADR_PAGE21:
7112     case elfcpp::R_AARCH64_TLSGD_ADD_LO12_NC:  // Global-dynamic
7113       {
7114         if (tlsopt == tls::TLSOPT_TO_LE)
7115           {
7116             if (tls_segment == NULL)
7117               {
7118                 gold_assert(parameters->errors()->error_count() > 0
7119                             || issue_undefined_symbol_error(gsym));
7120                 return aarch64_reloc_funcs::STATUS_BAD_RELOC;
7121               }
7122             return tls_gd_to_le(relinfo, target, rela, r_type, view,
7123                                 psymval);
7124           }
7125         else if (tlsopt == tls::TLSOPT_NONE)
7126           {
7127             tls_got_offset_type = GOT_TYPE_TLS_PAIR;
7128             // Firstly get the address for the got entry.
7129             typename elfcpp::Elf_types<size>::Elf_Addr got_entry_address;
7130             if (gsym != NULL)
7131               {
7132                 gold_assert(gsym->has_got_offset(tls_got_offset_type));
7133                 got_entry_address = target->got_->address() +
7134                                     gsym->got_offset(tls_got_offset_type);
7135               }
7136             else
7137               {
7138                 unsigned int r_sym = elfcpp::elf_r_sym<size>(rela.get_r_info());
7139                 gold_assert(
7140                   object->local_has_got_offset(r_sym, tls_got_offset_type));
7141                 got_entry_address = target->got_->address() +
7142                   object->local_got_offset(r_sym, tls_got_offset_type);
7143               }
7144
7145             // Relocate the address into adrp/ld, adrp/add pair.
7146             switch (r_type)
7147               {
7148               case elfcpp::R_AARCH64_TLSGD_ADR_PAGE21:
7149                 return aarch64_reloc_funcs::adrp(
7150                   view, got_entry_address + addend, address);
7151
7152                 break;
7153
7154               case elfcpp::R_AARCH64_TLSGD_ADD_LO12_NC:
7155                 return aarch64_reloc_funcs::template rela_general<32>(
7156                   view, got_entry_address, addend, reloc_property);
7157                 break;
7158
7159               default:
7160                 gold_unreachable();
7161               }
7162           }
7163         gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
7164                                _("unsupported gd_to_ie relaxation on %u"),
7165                                r_type);
7166       }
7167       break;
7168
7169     case elfcpp::R_AARCH64_TLSLD_ADR_PAGE21:
7170     case elfcpp::R_AARCH64_TLSLD_ADD_LO12_NC:  // Local-dynamic
7171       {
7172         if (tlsopt == tls::TLSOPT_TO_LE)
7173           {
7174             if (tls_segment == NULL)
7175               {
7176                 gold_assert(parameters->errors()->error_count() > 0
7177                             || issue_undefined_symbol_error(gsym));
7178                 return aarch64_reloc_funcs::STATUS_BAD_RELOC;
7179               }
7180             return this->tls_ld_to_le(relinfo, target, rela, r_type, view,
7181                                       psymval);
7182           }
7183
7184         gold_assert(tlsopt == tls::TLSOPT_NONE);
7185         // Relocate the field with the offset of the GOT entry for
7186         // the module index.
7187         typename elfcpp::Elf_types<size>::Elf_Addr got_entry_address;
7188         got_entry_address = (target->got_mod_index_entry(NULL, NULL, NULL) +
7189                              target->got_->address());
7190
7191         switch (r_type)
7192           {
7193           case elfcpp::R_AARCH64_TLSLD_ADR_PAGE21:
7194             return aarch64_reloc_funcs::adrp(
7195               view, got_entry_address + addend, address);
7196             break;
7197
7198           case elfcpp::R_AARCH64_TLSLD_ADD_LO12_NC:
7199             return aarch64_reloc_funcs::template rela_general<32>(
7200               view, got_entry_address, addend, reloc_property);
7201             break;
7202
7203           default:
7204             gold_unreachable();
7205           }
7206       }
7207       break;
7208
7209     case elfcpp::R_AARCH64_TLSLD_MOVW_DTPREL_G1:
7210     case elfcpp::R_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
7211     case elfcpp::R_AARCH64_TLSLD_ADD_DTPREL_HI12:
7212     case elfcpp::R_AARCH64_TLSLD_ADD_DTPREL_LO12_NC:  // Other local-dynamic
7213       {
7214         AArch64_address value = psymval->value(object, 0);
7215         if (tlsopt == tls::TLSOPT_TO_LE)
7216           {
7217             if (tls_segment == NULL)
7218               {
7219                 gold_assert(parameters->errors()->error_count() > 0
7220                             || issue_undefined_symbol_error(gsym));
7221                 return aarch64_reloc_funcs::STATUS_BAD_RELOC;
7222               }
7223           }
7224         switch (r_type)
7225           {
7226           case elfcpp::R_AARCH64_TLSLD_MOVW_DTPREL_G1:
7227             return aarch64_reloc_funcs::movnz(view, value + addend,
7228                                               reloc_property);
7229             break;
7230
7231           case elfcpp::R_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
7232           case elfcpp::R_AARCH64_TLSLD_ADD_DTPREL_HI12:
7233           case elfcpp::R_AARCH64_TLSLD_ADD_DTPREL_LO12_NC:
7234             return aarch64_reloc_funcs::template rela_general<32>(
7235                 view, value, addend, reloc_property);
7236             break;
7237
7238           default:
7239             gold_unreachable();
7240           }
7241         // We should never reach here.
7242       }
7243       break;
7244
7245     case elfcpp::R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
7246     case elfcpp::R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:  // Initial-exec
7247       {
7248         if (tlsopt == tls::TLSOPT_TO_LE)
7249           {
7250             if (tls_segment == NULL)
7251               {
7252                 gold_assert(parameters->errors()->error_count() > 0
7253                             || issue_undefined_symbol_error(gsym));
7254                 return aarch64_reloc_funcs::STATUS_BAD_RELOC;
7255               }
7256             return tls_ie_to_le(relinfo, target, rela, r_type, view,
7257                                 psymval);
7258           }
7259         tls_got_offset_type = GOT_TYPE_TLS_OFFSET;
7260
7261         // Firstly get the address for the got entry.
7262         typename elfcpp::Elf_types<size>::Elf_Addr got_entry_address;
7263         if (gsym != NULL)
7264           {
7265             gold_assert(gsym->has_got_offset(tls_got_offset_type));
7266             got_entry_address = target->got_->address() +
7267                                 gsym->got_offset(tls_got_offset_type);
7268           }
7269         else
7270           {
7271             unsigned int r_sym = elfcpp::elf_r_sym<size>(rela.get_r_info());
7272             gold_assert(
7273                 object->local_has_got_offset(r_sym, tls_got_offset_type));
7274             got_entry_address = target->got_->address() +
7275                 object->local_got_offset(r_sym, tls_got_offset_type);
7276           }
7277         // Relocate the address into adrp/ld, adrp/add pair.
7278         switch (r_type)
7279           {
7280           case elfcpp::R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
7281             return aarch64_reloc_funcs::adrp(view, got_entry_address + addend,
7282                                              address);
7283             break;
7284           case elfcpp::R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
7285             return aarch64_reloc_funcs::template rela_general<32>(
7286               view, got_entry_address, addend, reloc_property);
7287           default:
7288             gold_unreachable();
7289           }
7290       }
7291       // We shall never reach here.
7292       break;
7293
7294     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G2:
7295     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G1:
7296     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
7297     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G0:
7298     case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
7299     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_HI12:
7300     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_LO12:
7301     case elfcpp::R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
7302       {
7303         gold_assert(tls_segment != NULL);
7304         AArch64_address value = psymval->value(object, 0);
7305
7306         if (!parameters->options().shared())
7307           {
7308             AArch64_address aligned_tcb_size =
7309                 align_address(target->tcb_size(),
7310                               tls_segment->maximum_alignment());
7311             value += aligned_tcb_size;
7312             switch (r_type)
7313               {
7314               case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G2:
7315               case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G1:
7316               case elfcpp::R_AARCH64_TLSLE_MOVW_TPREL_G0:
7317                 return aarch64_reloc_funcs::movnz(view, value + addend,
7318                                                   reloc_property);
7319               default:
7320                 return aarch64_reloc_funcs::template
7321                   rela_general<32>(view,
7322                                    value,
7323                                    addend,
7324                                    reloc_property);
7325               }
7326           }
7327         else
7328           gold_error(_("%s: unsupported reloc %u "
7329                        "in non-static TLSLE mode."),
7330                      object->name().c_str(), r_type);
7331       }
7332       break;
7333
7334     case elfcpp::R_AARCH64_TLSDESC_ADR_PAGE21:
7335     case elfcpp::R_AARCH64_TLSDESC_LD64_LO12:
7336     case elfcpp::R_AARCH64_TLSDESC_ADD_LO12:
7337     case elfcpp::R_AARCH64_TLSDESC_CALL:
7338       {
7339         if (tlsopt == tls::TLSOPT_TO_LE)
7340           {
7341             if (tls_segment == NULL)
7342               {
7343                 gold_assert(parameters->errors()->error_count() > 0
7344                             || issue_undefined_symbol_error(gsym));
7345                 return aarch64_reloc_funcs::STATUS_BAD_RELOC;
7346               }
7347             return tls_desc_gd_to_le(relinfo, target, rela, r_type,
7348                                      view, psymval);
7349           }
7350         else
7351           {
7352             tls_got_offset_type = (tlsopt == tls::TLSOPT_TO_IE
7353                                    ? GOT_TYPE_TLS_OFFSET
7354                                    : GOT_TYPE_TLS_DESC);
7355             unsigned int got_tlsdesc_offset = 0;
7356             if (r_type != elfcpp::R_AARCH64_TLSDESC_CALL
7357                 && tlsopt == tls::TLSOPT_NONE)
7358               {
7359                 // We created GOT entries in the .got.tlsdesc portion of the
7360                 // .got.plt section, but the offset stored in the symbol is the
7361                 // offset within .got.tlsdesc.
7362                 got_tlsdesc_offset = (target->got_->data_size()
7363                                       + target->got_plt_section()->data_size());
7364               }
7365             typename elfcpp::Elf_types<size>::Elf_Addr got_entry_address;
7366             if (gsym != NULL)
7367               {
7368                 gold_assert(gsym->has_got_offset(tls_got_offset_type));
7369                 got_entry_address = target->got_->address()
7370                                     + got_tlsdesc_offset
7371                                     + gsym->got_offset(tls_got_offset_type);
7372               }
7373             else
7374               {
7375                 unsigned int r_sym = elfcpp::elf_r_sym<size>(rela.get_r_info());
7376                 gold_assert(
7377                     object->local_has_got_offset(r_sym, tls_got_offset_type));
7378                 got_entry_address = target->got_->address() +
7379                   got_tlsdesc_offset +
7380                   object->local_got_offset(r_sym, tls_got_offset_type);
7381               }
7382             if (tlsopt == tls::TLSOPT_TO_IE)
7383               {
7384                 if (tls_segment == NULL)
7385                   {
7386                     gold_assert(parameters->errors()->error_count() > 0
7387                                 || issue_undefined_symbol_error(gsym));
7388                     return aarch64_reloc_funcs::STATUS_BAD_RELOC;
7389                   }
7390                 return tls_desc_gd_to_ie(relinfo, target, rela, r_type,
7391                                          view, psymval, got_entry_address,
7392                                          address);
7393               }
7394
7395             // Now do tlsdesc relocation.
7396             switch (r_type)
7397               {
7398               case elfcpp::R_AARCH64_TLSDESC_ADR_PAGE21:
7399                 return aarch64_reloc_funcs::adrp(view,
7400                                                  got_entry_address + addend,
7401                                                  address);
7402                 break;
7403               case elfcpp::R_AARCH64_TLSDESC_LD64_LO12:
7404               case elfcpp::R_AARCH64_TLSDESC_ADD_LO12:
7405                 return aarch64_reloc_funcs::template rela_general<32>(
7406                   view, got_entry_address, addend, reloc_property);
7407                 break;
7408               case elfcpp::R_AARCH64_TLSDESC_CALL:
7409                 return aarch64_reloc_funcs::STATUS_OKAY;
7410                 break;
7411               default:
7412                 gold_unreachable();
7413               }
7414           }
7415         }
7416       break;
7417
7418     default:
7419       gold_error(_("%s: unsupported TLS reloc %u."),
7420                  object->name().c_str(), r_type);
7421     }
7422   return aarch64_reloc_funcs::STATUS_BAD_RELOC;
7423 }  // End of relocate_tls.
7424
7425
7426 template<int size, bool big_endian>
7427 inline
7428 typename AArch64_relocate_functions<size, big_endian>::Status
7429 Target_aarch64<size, big_endian>::Relocate::tls_gd_to_le(
7430              const Relocate_info<size, big_endian>* relinfo,
7431              Target_aarch64<size, big_endian>* target,
7432              const elfcpp::Rela<size, big_endian>& rela,
7433              unsigned int r_type,
7434              unsigned char* view,
7435              const Symbol_value<size>* psymval)
7436 {
7437   typedef AArch64_relocate_functions<size, big_endian> aarch64_reloc_funcs;
7438   typedef typename elfcpp::Swap<32, big_endian>::Valtype Insntype;
7439   typedef typename elfcpp::Elf_types<size>::Elf_Addr AArch64_address;
7440
7441   Insntype* ip = reinterpret_cast<Insntype*>(view);
7442   Insntype insn1 = elfcpp::Swap<32, big_endian>::readval(ip);
7443   Insntype insn2 = elfcpp::Swap<32, big_endian>::readval(ip + 1);
7444   Insntype insn3 = elfcpp::Swap<32, big_endian>::readval(ip + 2);
7445
7446   if (r_type == elfcpp::R_AARCH64_TLSGD_ADD_LO12_NC)
7447     {
7448       // This is the 2nd relocs, optimization should already have been
7449       // done.
7450       gold_assert((insn1 & 0xfff00000) == 0x91400000);
7451       return aarch64_reloc_funcs::STATUS_OKAY;
7452     }
7453
7454   // The original sequence is -
7455   //   90000000        adrp    x0, 0 <main>
7456   //   91000000        add     x0, x0, #0x0
7457   //   94000000        bl      0 <__tls_get_addr>
7458   // optimized to sequence -
7459   //   d53bd040        mrs     x0, tpidr_el0
7460   //   91400000        add     x0, x0, #0x0, lsl #12
7461   //   91000000        add     x0, x0, #0x0
7462
7463   // Unlike tls_ie_to_le, we change the 3 insns in one function call when we
7464   // encounter the first relocation "R_AARCH64_TLSGD_ADR_PAGE21". Because we
7465   // have to change "bl tls_get_addr", which does not have a corresponding tls
7466   // relocation type. So before proceeding, we need to make sure compiler
7467   // does not change the sequence.
7468   if(!(insn1 == 0x90000000      // adrp x0,0
7469        && insn2 == 0x91000000   // add x0, x0, #0x0
7470        && insn3 == 0x94000000)) // bl 0
7471     {
7472       // Ideally we should give up gd_to_le relaxation and do gd access.
7473       // However the gd_to_le relaxation decision has been made early
7474       // in the scan stage, where we did not allocate any GOT entry for
7475       // this symbol. Therefore we have to exit and report error now.
7476       gold_error(_("unexpected reloc insn sequence while relaxing "
7477                    "tls gd to le for reloc %u."), r_type);
7478       return aarch64_reloc_funcs::STATUS_BAD_RELOC;
7479     }
7480
7481   // Write new insns.
7482   insn1 = 0xd53bd040;  // mrs x0, tpidr_el0
7483   insn2 = 0x91400000;  // add x0, x0, #0x0, lsl #12
7484   insn3 = 0x91000000;  // add x0, x0, #0x0
7485   elfcpp::Swap<32, big_endian>::writeval(ip, insn1);
7486   elfcpp::Swap<32, big_endian>::writeval(ip + 1, insn2);
7487   elfcpp::Swap<32, big_endian>::writeval(ip + 2, insn3);
7488
7489   // Calculate tprel value.
7490   Output_segment* tls_segment = relinfo->layout->tls_segment();
7491   gold_assert(tls_segment != NULL);
7492   AArch64_address value = psymval->value(relinfo->object, 0);
7493   const elfcpp::Elf_Xword addend = rela.get_r_addend();
7494   AArch64_address aligned_tcb_size =
7495       align_address(target->tcb_size(), tls_segment->maximum_alignment());
7496   AArch64_address x = value + aligned_tcb_size;
7497
7498   // After new insns are written, apply TLSLE relocs.
7499   const AArch64_reloc_property* rp1 =
7500       aarch64_reloc_property_table->get_reloc_property(
7501           elfcpp::R_AARCH64_TLSLE_ADD_TPREL_HI12);
7502   const AArch64_reloc_property* rp2 =
7503       aarch64_reloc_property_table->get_reloc_property(
7504           elfcpp::R_AARCH64_TLSLE_ADD_TPREL_LO12);
7505   gold_assert(rp1 != NULL && rp2 != NULL);
7506
7507   typename aarch64_reloc_funcs::Status s1 =
7508       aarch64_reloc_funcs::template rela_general<32>(view + 4,
7509                                                      x,
7510                                                      addend,
7511                                                      rp1);
7512   if (s1 != aarch64_reloc_funcs::STATUS_OKAY)
7513     return s1;
7514
7515   typename aarch64_reloc_funcs::Status s2 =
7516       aarch64_reloc_funcs::template rela_general<32>(view + 8,
7517                                                      x,
7518                                                      addend,
7519                                                      rp2);
7520
7521   this->skip_call_tls_get_addr_ = true;
7522   return s2;
7523 }  // End of tls_gd_to_le
7524
7525
7526 template<int size, bool big_endian>
7527 inline
7528 typename AArch64_relocate_functions<size, big_endian>::Status
7529 Target_aarch64<size, big_endian>::Relocate::tls_ld_to_le(
7530              const Relocate_info<size, big_endian>* relinfo,
7531              Target_aarch64<size, big_endian>* target,
7532              const elfcpp::Rela<size, big_endian>& rela,
7533              unsigned int r_type,
7534              unsigned char* view,
7535              const Symbol_value<size>* psymval)
7536 {
7537   typedef AArch64_relocate_functions<size, big_endian> aarch64_reloc_funcs;
7538   typedef typename elfcpp::Swap<32, big_endian>::Valtype Insntype;
7539   typedef typename elfcpp::Elf_types<size>::Elf_Addr AArch64_address;
7540
7541   Insntype* ip = reinterpret_cast<Insntype*>(view);
7542   Insntype insn1 = elfcpp::Swap<32, big_endian>::readval(ip);
7543   Insntype insn2 = elfcpp::Swap<32, big_endian>::readval(ip + 1);
7544   Insntype insn3 = elfcpp::Swap<32, big_endian>::readval(ip + 2);
7545
7546   if (r_type == elfcpp::R_AARCH64_TLSLD_ADD_LO12_NC)
7547     {
7548       // This is the 2nd relocs, optimization should already have been
7549       // done.
7550       gold_assert((insn1 & 0xfff00000) == 0x91400000);
7551       return aarch64_reloc_funcs::STATUS_OKAY;
7552     }
7553
7554   // The original sequence is -
7555   //   90000000        adrp    x0, 0 <main>
7556   //   91000000        add     x0, x0, #0x0
7557   //   94000000        bl      0 <__tls_get_addr>
7558   // optimized to sequence -
7559   //   d53bd040        mrs     x0, tpidr_el0
7560   //   91400000        add     x0, x0, #0x0, lsl #12
7561   //   91000000        add     x0, x0, #0x0
7562
7563   // Unlike tls_ie_to_le, we change the 3 insns in one function call when we
7564   // encounter the first relocation "R_AARCH64_TLSLD_ADR_PAGE21". Because we
7565   // have to change "bl tls_get_addr", which does not have a corresponding tls
7566   // relocation type. So before proceeding, we need to make sure compiler
7567   // does not change the sequence.
7568   if(!(insn1 == 0x90000000      // adrp x0,0
7569        && insn2 == 0x91000000   // add x0, x0, #0x0
7570        && insn3 == 0x94000000)) // bl 0
7571     {
7572       // Ideally we should give up gd_to_le relaxation and do gd access.
7573       // However the gd_to_le relaxation decision has been made early
7574       // in the scan stage, where we did not allocate any GOT entry for
7575       // this symbol. Therefore we have to exit and report error now.
7576       gold_error(_("unexpected reloc insn sequence while relaxing "
7577                    "tls gd to le for reloc %u."), r_type);
7578       return aarch64_reloc_funcs::STATUS_BAD_RELOC;
7579     }
7580
7581   // Write new insns.
7582   insn1 = 0xd53bd040;  // mrs x0, tpidr_el0
7583   insn2 = 0x91400000;  // add x0, x0, #0x0, lsl #12
7584   insn3 = 0x91000000;  // add x0, x0, #0x0
7585   elfcpp::Swap<32, big_endian>::writeval(ip, insn1);
7586   elfcpp::Swap<32, big_endian>::writeval(ip + 1, insn2);
7587   elfcpp::Swap<32, big_endian>::writeval(ip + 2, insn3);
7588
7589   // Calculate tprel value.
7590   Output_segment* tls_segment = relinfo->layout->tls_segment();
7591   gold_assert(tls_segment != NULL);
7592   AArch64_address value = psymval->value(relinfo->object, 0);
7593   const elfcpp::Elf_Xword addend = rela.get_r_addend();
7594   AArch64_address aligned_tcb_size =
7595       align_address(target->tcb_size(), tls_segment->maximum_alignment());
7596   AArch64_address x = value + aligned_tcb_size;
7597
7598   // After new insns are written, apply TLSLE relocs.
7599   const AArch64_reloc_property* rp1 =
7600       aarch64_reloc_property_table->get_reloc_property(
7601           elfcpp::R_AARCH64_TLSLE_ADD_TPREL_HI12);
7602   const AArch64_reloc_property* rp2 =
7603       aarch64_reloc_property_table->get_reloc_property(
7604           elfcpp::R_AARCH64_TLSLE_ADD_TPREL_LO12);
7605   gold_assert(rp1 != NULL && rp2 != NULL);
7606
7607   typename aarch64_reloc_funcs::Status s1 =
7608       aarch64_reloc_funcs::template rela_general<32>(view + 4,
7609                                                      x,
7610                                                      addend,
7611                                                      rp1);
7612   if (s1 != aarch64_reloc_funcs::STATUS_OKAY)
7613     return s1;
7614
7615   typename aarch64_reloc_funcs::Status s2 =
7616       aarch64_reloc_funcs::template rela_general<32>(view + 8,
7617                                                      x,
7618                                                      addend,
7619                                                      rp2);
7620
7621   this->skip_call_tls_get_addr_ = true;
7622   return s2;
7623
7624 }  // End of tls_ld_to_le
7625
7626 template<int size, bool big_endian>
7627 inline
7628 typename AArch64_relocate_functions<size, big_endian>::Status
7629 Target_aarch64<size, big_endian>::Relocate::tls_ie_to_le(
7630              const Relocate_info<size, big_endian>* relinfo,
7631              Target_aarch64<size, big_endian>* target,
7632              const elfcpp::Rela<size, big_endian>& rela,
7633              unsigned int r_type,
7634              unsigned char* view,
7635              const Symbol_value<size>* psymval)
7636 {
7637   typedef typename elfcpp::Elf_types<size>::Elf_Addr AArch64_address;
7638   typedef typename elfcpp::Swap<32, big_endian>::Valtype Insntype;
7639   typedef AArch64_relocate_functions<size, big_endian> aarch64_reloc_funcs;
7640
7641   AArch64_address value = psymval->value(relinfo->object, 0);
7642   Output_segment* tls_segment = relinfo->layout->tls_segment();
7643   AArch64_address aligned_tcb_address =
7644       align_address(target->tcb_size(), tls_segment->maximum_alignment());
7645   const elfcpp::Elf_Xword addend = rela.get_r_addend();
7646   AArch64_address x = value + addend + aligned_tcb_address;
7647   // "x" is the offset to tp, we can only do this if x is within
7648   // range [0, 2^32-1]
7649   if (!(size == 32 || (size == 64 && (static_cast<uint64_t>(x) >> 32) == 0)))
7650     {
7651       gold_error(_("TLS variable referred by reloc %u is too far from TP."),
7652                  r_type);
7653       return aarch64_reloc_funcs::STATUS_BAD_RELOC;
7654     }
7655
7656   Insntype* ip = reinterpret_cast<Insntype*>(view);
7657   Insntype insn = elfcpp::Swap<32, big_endian>::readval(ip);
7658   unsigned int regno;
7659   Insntype newinsn;
7660   if (r_type == elfcpp::R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21)
7661     {
7662       // Generate movz.
7663       regno = (insn & 0x1f);
7664       newinsn = (0xd2a00000 | regno) | (((x >> 16) & 0xffff) << 5);
7665     }
7666   else if (r_type == elfcpp::R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC)
7667     {
7668       // Generate movk.
7669       regno = (insn & 0x1f);
7670       gold_assert(regno == ((insn >> 5) & 0x1f));
7671       newinsn = (0xf2800000 | regno) | ((x & 0xffff) << 5);
7672     }
7673   else
7674     gold_unreachable();
7675
7676   elfcpp::Swap<32, big_endian>::writeval(ip, newinsn);
7677   return aarch64_reloc_funcs::STATUS_OKAY;
7678 }  // End of tls_ie_to_le
7679
7680
7681 template<int size, bool big_endian>
7682 inline
7683 typename AArch64_relocate_functions<size, big_endian>::Status
7684 Target_aarch64<size, big_endian>::Relocate::tls_desc_gd_to_le(
7685              const Relocate_info<size, big_endian>* relinfo,
7686              Target_aarch64<size, big_endian>* target,
7687              const elfcpp::Rela<size, big_endian>& rela,
7688              unsigned int r_type,
7689              unsigned char* view,
7690              const Symbol_value<size>* psymval)
7691 {
7692   typedef typename elfcpp::Elf_types<size>::Elf_Addr AArch64_address;
7693   typedef typename elfcpp::Swap<32, big_endian>::Valtype Insntype;
7694   typedef AArch64_relocate_functions<size, big_endian> aarch64_reloc_funcs;
7695
7696   // TLSDESC-GD sequence is like:
7697   //   adrp  x0, :tlsdesc:v1
7698   //   ldr   x1, [x0, #:tlsdesc_lo12:v1]
7699   //   add   x0, x0, :tlsdesc_lo12:v1
7700   //   .tlsdesccall    v1
7701   //   blr   x1
7702   // After desc_gd_to_le optimization, the sequence will be like:
7703   //   movz  x0, #0x0, lsl #16
7704   //   movk  x0, #0x10
7705   //   nop
7706   //   nop
7707
7708   // Calculate tprel value.
7709   Output_segment* tls_segment = relinfo->layout->tls_segment();
7710   gold_assert(tls_segment != NULL);
7711   Insntype* ip = reinterpret_cast<Insntype*>(view);
7712   const elfcpp::Elf_Xword addend = rela.get_r_addend();
7713   AArch64_address value = psymval->value(relinfo->object, addend);
7714   AArch64_address aligned_tcb_size =
7715       align_address(target->tcb_size(), tls_segment->maximum_alignment());
7716   AArch64_address x = value + aligned_tcb_size;
7717   // x is the offset to tp, we can only do this if x is within range
7718   // [0, 2^32-1]. If x is out of range, fail and exit.
7719   if (size == 64 && (static_cast<uint64_t>(x) >> 32) != 0)
7720     {
7721       gold_error(_("TLS variable referred by reloc %u is too far from TP. "
7722                    "We Can't do gd_to_le relaxation.\n"), r_type);
7723       return aarch64_reloc_funcs::STATUS_BAD_RELOC;
7724     }
7725   Insntype newinsn;
7726   switch (r_type)
7727     {
7728     case elfcpp::R_AARCH64_TLSDESC_ADD_LO12:
7729     case elfcpp::R_AARCH64_TLSDESC_CALL:
7730       // Change to nop
7731       newinsn = 0xd503201f;
7732       break;
7733
7734     case elfcpp::R_AARCH64_TLSDESC_ADR_PAGE21:
7735       // Change to movz.
7736       newinsn = 0xd2a00000 | (((x >> 16) & 0xffff) << 5);
7737       break;
7738
7739     case elfcpp::R_AARCH64_TLSDESC_LD64_LO12:
7740       // Change to movk.
7741       newinsn = 0xf2800000 | ((x & 0xffff) << 5);
7742       break;
7743
7744     default:
7745       gold_error(_("unsupported tlsdesc gd_to_le optimization on reloc %u"),
7746                  r_type);
7747       gold_unreachable();
7748     }
7749   elfcpp::Swap<32, big_endian>::writeval(ip, newinsn);
7750   return aarch64_reloc_funcs::STATUS_OKAY;
7751 }  // End of tls_desc_gd_to_le
7752
7753
7754 template<int size, bool big_endian>
7755 inline
7756 typename AArch64_relocate_functions<size, big_endian>::Status
7757 Target_aarch64<size, big_endian>::Relocate::tls_desc_gd_to_ie(
7758              const Relocate_info<size, big_endian>* /* relinfo */,
7759              Target_aarch64<size, big_endian>* /* target */,
7760              const elfcpp::Rela<size, big_endian>& rela,
7761              unsigned int r_type,
7762              unsigned char* view,
7763              const Symbol_value<size>* /* psymval */,
7764              typename elfcpp::Elf_types<size>::Elf_Addr got_entry_address,
7765              typename elfcpp::Elf_types<size>::Elf_Addr address)
7766 {
7767   typedef typename elfcpp::Swap<32, big_endian>::Valtype Insntype;
7768   typedef AArch64_relocate_functions<size, big_endian> aarch64_reloc_funcs;
7769
7770   // TLSDESC-GD sequence is like:
7771   //   adrp  x0, :tlsdesc:v1
7772   //   ldr   x1, [x0, #:tlsdesc_lo12:v1]
7773   //   add   x0, x0, :tlsdesc_lo12:v1
7774   //   .tlsdesccall    v1
7775   //   blr   x1
7776   // After desc_gd_to_ie optimization, the sequence will be like:
7777   //   adrp  x0, :tlsie:v1
7778   //   ldr   x0, [x0, :tlsie_lo12:v1]
7779   //   nop
7780   //   nop
7781
7782   Insntype* ip = reinterpret_cast<Insntype*>(view);
7783   const elfcpp::Elf_Xword addend = rela.get_r_addend();
7784   Insntype newinsn;
7785   switch (r_type)
7786     {
7787     case elfcpp::R_AARCH64_TLSDESC_ADD_LO12:
7788     case elfcpp::R_AARCH64_TLSDESC_CALL:
7789       // Change to nop
7790       newinsn = 0xd503201f;
7791       elfcpp::Swap<32, big_endian>::writeval(ip, newinsn);
7792       break;
7793
7794     case elfcpp::R_AARCH64_TLSDESC_ADR_PAGE21:
7795       {
7796         return aarch64_reloc_funcs::adrp(view, got_entry_address + addend,
7797                                          address);
7798       }
7799       break;
7800
7801     case elfcpp::R_AARCH64_TLSDESC_LD64_LO12:
7802       {
7803        // Set ldr target register to be x0.
7804        Insntype insn = elfcpp::Swap<32, big_endian>::readval(ip);
7805        insn &= 0xffffffe0;
7806        elfcpp::Swap<32, big_endian>::writeval(ip, insn);
7807        // Do relocation.
7808         const AArch64_reloc_property* reloc_property =
7809             aarch64_reloc_property_table->get_reloc_property(
7810               elfcpp::R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC);
7811         return aarch64_reloc_funcs::template rela_general<32>(
7812                  view, got_entry_address, addend, reloc_property);
7813       }
7814       break;
7815
7816     default:
7817       gold_error(_("Don't support tlsdesc gd_to_ie optimization on reloc %u"),
7818                  r_type);
7819       gold_unreachable();
7820     }
7821   return aarch64_reloc_funcs::STATUS_OKAY;
7822 }  // End of tls_desc_gd_to_ie
7823
7824 // Relocate section data.
7825
7826 template<int size, bool big_endian>
7827 void
7828 Target_aarch64<size, big_endian>::relocate_section(
7829     const Relocate_info<size, big_endian>* relinfo,
7830     unsigned int sh_type,
7831     const unsigned char* prelocs,
7832     size_t reloc_count,
7833     Output_section* output_section,
7834     bool needs_special_offset_handling,
7835     unsigned char* view,
7836     typename elfcpp::Elf_types<size>::Elf_Addr address,
7837     section_size_type view_size,
7838     const Reloc_symbol_changes* reloc_symbol_changes)
7839 {
7840   gold_assert(sh_type == elfcpp::SHT_RELA);
7841   typedef typename Target_aarch64<size, big_endian>::Relocate AArch64_relocate;
7842   gold::relocate_section<size, big_endian, Target_aarch64, elfcpp::SHT_RELA,
7843                          AArch64_relocate, gold::Default_comdat_behavior>(
7844     relinfo,
7845     this,
7846     prelocs,
7847     reloc_count,
7848     output_section,
7849     needs_special_offset_handling,
7850     view,
7851     address,
7852     view_size,
7853     reloc_symbol_changes);
7854 }
7855
7856 // Return the size of a relocation while scanning during a relocatable
7857 // link.
7858
7859 template<int size, bool big_endian>
7860 unsigned int
7861 Target_aarch64<size, big_endian>::Relocatable_size_for_reloc::
7862 get_size_for_reloc(
7863     unsigned int ,
7864     Relobj* )
7865 {
7866   // We will never support SHT_REL relocations.
7867   gold_unreachable();
7868   return 0;
7869 }
7870
7871 // Scan the relocs during a relocatable link.
7872
7873 template<int size, bool big_endian>
7874 void
7875 Target_aarch64<size, big_endian>::scan_relocatable_relocs(
7876     Symbol_table* symtab,
7877     Layout* layout,
7878     Sized_relobj_file<size, big_endian>* object,
7879     unsigned int data_shndx,
7880     unsigned int sh_type,
7881     const unsigned char* prelocs,
7882     size_t reloc_count,
7883     Output_section* output_section,
7884     bool needs_special_offset_handling,
7885     size_t local_symbol_count,
7886     const unsigned char* plocal_symbols,
7887     Relocatable_relocs* rr)
7888 {
7889   gold_assert(sh_type == elfcpp::SHT_RELA);
7890
7891   typedef gold::Default_scan_relocatable_relocs<elfcpp::SHT_RELA,
7892     Relocatable_size_for_reloc> Scan_relocatable_relocs;
7893
7894   gold::scan_relocatable_relocs<size, big_endian, elfcpp::SHT_RELA,
7895       Scan_relocatable_relocs>(
7896     symtab,
7897     layout,
7898     object,
7899     data_shndx,
7900     prelocs,
7901     reloc_count,
7902     output_section,
7903     needs_special_offset_handling,
7904     local_symbol_count,
7905     plocal_symbols,
7906     rr);
7907 }
7908
7909 // Relocate a section during a relocatable link.
7910
7911 template<int size, bool big_endian>
7912 void
7913 Target_aarch64<size, big_endian>::relocate_relocs(
7914     const Relocate_info<size, big_endian>* relinfo,
7915     unsigned int sh_type,
7916     const unsigned char* prelocs,
7917     size_t reloc_count,
7918     Output_section* output_section,
7919     typename elfcpp::Elf_types<size>::Elf_Off offset_in_output_section,
7920     const Relocatable_relocs* rr,
7921     unsigned char* view,
7922     typename elfcpp::Elf_types<size>::Elf_Addr view_address,
7923     section_size_type view_size,
7924     unsigned char* reloc_view,
7925     section_size_type reloc_view_size)
7926 {
7927   gold_assert(sh_type == elfcpp::SHT_RELA);
7928
7929   gold::relocate_relocs<size, big_endian, elfcpp::SHT_RELA>(
7930     relinfo,
7931     prelocs,
7932     reloc_count,
7933     output_section,
7934     offset_in_output_section,
7935     rr,
7936     view,
7937     view_address,
7938     view_size,
7939     reloc_view,
7940     reloc_view_size);
7941 }
7942
7943
7944 // Return whether this is a 3-insn erratum sequence.
7945
7946 template<int size, bool big_endian>
7947 bool
7948 Target_aarch64<size, big_endian>::is_erratum_843419_sequence(
7949     typename elfcpp::Swap<32,big_endian>::Valtype insn1,
7950     typename elfcpp::Swap<32,big_endian>::Valtype insn2,
7951     typename elfcpp::Swap<32,big_endian>::Valtype insn3)
7952 {
7953   unsigned rt1, rt2;
7954   bool load, pair;
7955
7956   // The 2nd insn is a single register load or store; or register pair
7957   // store.
7958   if (Insn_utilities::aarch64_mem_op_p(insn2, &rt1, &rt2, &pair, &load)
7959       && (!pair || (pair && !load)))
7960     {
7961       // The 3rd insn is a load or store instruction from the "Load/store
7962       // register (unsigned immediate)" encoding class, using Rn as the
7963       // base address register.
7964       if (Insn_utilities::aarch64_ldst_uimm(insn3)
7965           && (Insn_utilities::aarch64_rn(insn3)
7966               == Insn_utilities::aarch64_rd(insn1)))
7967         return true;
7968     }
7969   return false;
7970 }
7971
7972
7973 // Return whether this is a 835769 sequence.
7974 // (Similarly implemented as in elfnn-aarch64.c.)
7975
7976 template<int size, bool big_endian>
7977 bool
7978 Target_aarch64<size, big_endian>::is_erratum_835769_sequence(
7979     typename elfcpp::Swap<32,big_endian>::Valtype insn1,
7980     typename elfcpp::Swap<32,big_endian>::Valtype insn2)
7981 {
7982   uint32_t rt;
7983   uint32_t rt2;
7984   uint32_t rn;
7985   uint32_t rm;
7986   uint32_t ra;
7987   bool pair;
7988   bool load;
7989
7990   if (Insn_utilities::aarch64_mlxl(insn2)
7991       && Insn_utilities::aarch64_mem_op_p (insn1, &rt, &rt2, &pair, &load))
7992     {
7993       /* Any SIMD memory op is independent of the subsequent MLA
7994          by definition of the erratum.  */
7995       if (Insn_utilities::aarch64_bit(insn1, 26))
7996         return true;
7997
7998       /* If not SIMD, check for integer memory ops and MLA relationship.  */
7999       rn = Insn_utilities::aarch64_rn(insn2);
8000       ra = Insn_utilities::aarch64_ra(insn2);
8001       rm = Insn_utilities::aarch64_rm(insn2);
8002
8003       /* If this is a load and there's a true(RAW) dependency, we are safe
8004          and this is not an erratum sequence.  */
8005       if (load &&
8006           (rt == rn || rt == rm || rt == ra
8007            || (pair && (rt2 == rn || rt2 == rm || rt2 == ra))))
8008         return false;
8009
8010       /* We conservatively put out stubs for all other cases (including
8011          writebacks).  */
8012       return true;
8013     }
8014
8015   return false;
8016 }
8017
8018
8019 // Helper method to create erratum stub for ST_E_843419 and ST_E_835769.
8020
8021 template<int size, bool big_endian>
8022 void
8023 Target_aarch64<size, big_endian>::create_erratum_stub(
8024     AArch64_relobj<size, big_endian>* relobj,
8025     unsigned int shndx,
8026     section_size_type erratum_insn_offset,
8027     Address erratum_address,
8028     typename Insn_utilities::Insntype erratum_insn,
8029     int erratum_type,
8030     unsigned int e843419_adrp_offset)
8031 {
8032   gold_assert(erratum_type == ST_E_843419 || erratum_type == ST_E_835769);
8033   The_stub_table* stub_table = relobj->stub_table(shndx);
8034   gold_assert(stub_table != NULL);
8035   if (stub_table->find_erratum_stub(relobj,
8036                                     shndx,
8037                                     erratum_insn_offset) == NULL)
8038     {
8039       const int BPI = AArch64_insn_utilities<big_endian>::BYTES_PER_INSN;
8040       The_erratum_stub* stub;
8041       if (erratum_type == ST_E_835769)
8042         stub = new The_erratum_stub(relobj, erratum_type, shndx,
8043                                     erratum_insn_offset);
8044       else if (erratum_type == ST_E_843419)
8045         stub = new E843419_stub<size, big_endian>(
8046             relobj, shndx, erratum_insn_offset, e843419_adrp_offset);
8047       else
8048         gold_unreachable();
8049       stub->set_erratum_insn(erratum_insn);
8050       stub->set_erratum_address(erratum_address);
8051       // For erratum ST_E_843419 and ST_E_835769, the destination address is
8052       // always the next insn after erratum insn.
8053       stub->set_destination_address(erratum_address + BPI);
8054       stub_table->add_erratum_stub(stub);
8055     }
8056 }
8057
8058
8059 // Scan erratum for section SHNDX range [output_address + span_start,
8060 // output_address + span_end). Note here we do not share the code with
8061 // scan_erratum_843419_span function, because for 843419 we optimize by only
8062 // scanning the last few insns of a page, whereas for 835769, we need to scan
8063 // every insn.
8064
8065 template<int size, bool big_endian>
8066 void
8067 Target_aarch64<size, big_endian>::scan_erratum_835769_span(
8068     AArch64_relobj<size, big_endian>*  relobj,
8069     unsigned int shndx,
8070     const section_size_type span_start,
8071     const section_size_type span_end,
8072     unsigned char* input_view,
8073     Address output_address)
8074 {
8075   typedef typename Insn_utilities::Insntype Insntype;
8076
8077   const int BPI = AArch64_insn_utilities<big_endian>::BYTES_PER_INSN;
8078
8079   // Adjust output_address and view to the start of span.
8080   output_address += span_start;
8081   input_view += span_start;
8082
8083   section_size_type span_length = span_end - span_start;
8084   section_size_type offset = 0;
8085   for (offset = 0; offset + BPI < span_length; offset += BPI)
8086     {
8087       Insntype* ip = reinterpret_cast<Insntype*>(input_view + offset);
8088       Insntype insn1 = ip[0];
8089       Insntype insn2 = ip[1];
8090       if (is_erratum_835769_sequence(insn1, insn2))
8091         {
8092           Insntype erratum_insn = insn2;
8093           // "span_start + offset" is the offset for insn1. So for insn2, it is
8094           // "span_start + offset + BPI".
8095           section_size_type erratum_insn_offset = span_start + offset + BPI;
8096           Address erratum_address = output_address + offset + BPI;
8097           gold_info(_("Erratum 835769 found and fixed at \"%s\", "
8098                          "section %d, offset 0x%08x."),
8099                        relobj->name().c_str(), shndx,
8100                        (unsigned int)(span_start + offset));
8101
8102           this->create_erratum_stub(relobj, shndx,
8103                                     erratum_insn_offset, erratum_address,
8104                                     erratum_insn, ST_E_835769);
8105           offset += BPI;  // Skip mac insn.
8106         }
8107     }
8108 }  // End of "Target_aarch64::scan_erratum_835769_span".
8109
8110
8111 // Scan erratum for section SHNDX range
8112 // [output_address + span_start, output_address + span_end).
8113
8114 template<int size, bool big_endian>
8115 void
8116 Target_aarch64<size, big_endian>::scan_erratum_843419_span(
8117     AArch64_relobj<size, big_endian>*  relobj,
8118     unsigned int shndx,
8119     const section_size_type span_start,
8120     const section_size_type span_end,
8121     unsigned char* input_view,
8122     Address output_address)
8123 {
8124   typedef typename Insn_utilities::Insntype Insntype;
8125
8126   // Adjust output_address and view to the start of span.
8127   output_address += span_start;
8128   input_view += span_start;
8129
8130   if ((output_address & 0x03) != 0)
8131     return;
8132
8133   section_size_type offset = 0;
8134   section_size_type span_length = span_end - span_start;
8135   // The first instruction must be ending at 0xFF8 or 0xFFC.
8136   unsigned int page_offset = output_address & 0xFFF;
8137   // Make sure starting position, that is "output_address+offset",
8138   // starts at page position 0xff8 or 0xffc.
8139   if (page_offset < 0xff8)
8140     offset = 0xff8 - page_offset;
8141   while (offset + 3 * Insn_utilities::BYTES_PER_INSN <= span_length)
8142     {
8143       Insntype* ip = reinterpret_cast<Insntype*>(input_view + offset);
8144       Insntype insn1 = ip[0];
8145       if (Insn_utilities::is_adrp(insn1))
8146         {
8147           Insntype insn2 = ip[1];
8148           Insntype insn3 = ip[2];
8149           Insntype erratum_insn;
8150           unsigned insn_offset;
8151           bool do_report = false;
8152           if (is_erratum_843419_sequence(insn1, insn2, insn3))
8153             {
8154               do_report = true;
8155               erratum_insn = insn3;
8156               insn_offset = 2 * Insn_utilities::BYTES_PER_INSN;
8157             }
8158           else if (offset + 4 * Insn_utilities::BYTES_PER_INSN <= span_length)
8159             {
8160               // Optionally we can have an insn between ins2 and ins3
8161               Insntype insn_opt = ip[2];
8162               // And insn_opt must not be a branch.
8163               if (!Insn_utilities::aarch64_b(insn_opt)
8164                   && !Insn_utilities::aarch64_bl(insn_opt)
8165                   && !Insn_utilities::aarch64_blr(insn_opt)
8166                   && !Insn_utilities::aarch64_br(insn_opt))
8167                 {
8168                   // And insn_opt must not write to dest reg in insn1. However
8169                   // we do a conservative scan, which means we may fix/report
8170                   // more than necessary, but it doesn't hurt.
8171
8172                   Insntype insn4 = ip[3];
8173                   if (is_erratum_843419_sequence(insn1, insn2, insn4))
8174                     {
8175                       do_report = true;
8176                       erratum_insn = insn4;
8177                       insn_offset = 3 * Insn_utilities::BYTES_PER_INSN;
8178                     }
8179                 }
8180             }
8181           if (do_report)
8182             {
8183               gold_info(_("Erratum 843419 found and fixed at \"%s\", "
8184                              "section %d, offset 0x%08x."),
8185                            relobj->name().c_str(), shndx,
8186                            (unsigned int)(span_start + offset));
8187               unsigned int erratum_insn_offset =
8188                 span_start + offset + insn_offset;
8189               Address erratum_address =
8190                 output_address + offset + insn_offset;
8191               create_erratum_stub(relobj, shndx,
8192                                   erratum_insn_offset, erratum_address,
8193                                   erratum_insn, ST_E_843419,
8194                                   span_start + offset);
8195             }
8196         }
8197
8198       // Advance to next candidate instruction. We only consider instruction
8199       // sequences starting at a page offset of 0xff8 or 0xffc.
8200       page_offset = (output_address + offset) & 0xfff;
8201       if (page_offset == 0xff8)
8202         offset += 4;
8203       else  // (page_offset == 0xffc), we move to next page's 0xff8.
8204         offset += 0xffc;
8205     }
8206 }  // End of "Target_aarch64::scan_erratum_843419_span".
8207
8208
8209 // The selector for aarch64 object files.
8210
8211 template<int size, bool big_endian>
8212 class Target_selector_aarch64 : public Target_selector
8213 {
8214  public:
8215   Target_selector_aarch64();
8216
8217   virtual Target*
8218   do_instantiate_target()
8219   { return new Target_aarch64<size, big_endian>(); }
8220 };
8221
8222 template<>
8223 Target_selector_aarch64<32, true>::Target_selector_aarch64()
8224   : Target_selector(elfcpp::EM_AARCH64, 32, true,
8225                     "elf32-bigaarch64", "aarch64_elf32_be_vec")
8226 { }
8227
8228 template<>
8229 Target_selector_aarch64<32, false>::Target_selector_aarch64()
8230   : Target_selector(elfcpp::EM_AARCH64, 32, false,
8231                     "elf32-littleaarch64", "aarch64_elf32_le_vec")
8232 { }
8233
8234 template<>
8235 Target_selector_aarch64<64, true>::Target_selector_aarch64()
8236   : Target_selector(elfcpp::EM_AARCH64, 64, true,
8237                     "elf64-bigaarch64", "aarch64_elf64_be_vec")
8238 { }
8239
8240 template<>
8241 Target_selector_aarch64<64, false>::Target_selector_aarch64()
8242   : Target_selector(elfcpp::EM_AARCH64, 64, false,
8243                     "elf64-littleaarch64", "aarch64_elf64_le_vec")
8244 { }
8245
8246 Target_selector_aarch64<32, true> target_selector_aarch64elf32b;
8247 Target_selector_aarch64<32, false> target_selector_aarch64elf32;
8248 Target_selector_aarch64<64, true> target_selector_aarch64elfb;
8249 Target_selector_aarch64<64, false> target_selector_aarch64elf;
8250
8251 } // End anonymous namespace.