2010-03-19 Doug Kwan <dougkwan@google.com>
[external/binutils.git] / gold / arm.cc
1 // arm.cc -- arm target support for gold.
2
3 // Copyright 2009, 2010 Free Software Foundation, Inc.
4 // Written by Doug Kwan <dougkwan@google.com> based on the i386 code
5 // by Ian Lance Taylor <iant@google.com>.
6 // This file also contains borrowed and adapted code from
7 // bfd/elf32-arm.c.
8
9 // This file is part of gold.
10
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 3 of the License, or
14 // (at your option) any later version.
15
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 // GNU General Public License for more details.
20
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
24 // MA 02110-1301, USA.
25
26 #include "gold.h"
27
28 #include <cstring>
29 #include <limits>
30 #include <cstdio>
31 #include <string>
32 #include <algorithm>
33 #include <map>
34 #include <utility>
35 #include <set>
36
37 #include "elfcpp.h"
38 #include "parameters.h"
39 #include "reloc.h"
40 #include "arm.h"
41 #include "object.h"
42 #include "symtab.h"
43 #include "layout.h"
44 #include "output.h"
45 #include "copy-relocs.h"
46 #include "target.h"
47 #include "target-reloc.h"
48 #include "target-select.h"
49 #include "tls.h"
50 #include "defstd.h"
51 #include "gc.h"
52 #include "attributes.h"
53 #include "arm-reloc-property.h"
54
55 namespace
56 {
57
58 using namespace gold;
59
60 template<bool big_endian>
61 class Output_data_plt_arm;
62
63 template<bool big_endian>
64 class Stub_table;
65
66 template<bool big_endian>
67 class Arm_input_section;
68
69 class Arm_exidx_cantunwind;
70
71 class Arm_exidx_merged_section;
72
73 class Arm_exidx_fixup;
74
75 template<bool big_endian>
76 class Arm_output_section;
77
78 class Arm_exidx_input_section;
79
80 template<bool big_endian>
81 class Arm_relobj;
82
83 template<bool big_endian>
84 class Arm_relocate_functions;
85
86 template<bool big_endian>
87 class Arm_output_data_got;
88
89 template<bool big_endian>
90 class Target_arm;
91
92 // For convenience.
93 typedef elfcpp::Elf_types<32>::Elf_Addr Arm_address;
94
95 // Maximum branch offsets for ARM, THUMB and THUMB2.
96 const int32_t ARM_MAX_FWD_BRANCH_OFFSET = ((((1 << 23) - 1) << 2) + 8);
97 const int32_t ARM_MAX_BWD_BRANCH_OFFSET = ((-((1 << 23) << 2)) + 8);
98 const int32_t THM_MAX_FWD_BRANCH_OFFSET = ((1 << 22) -2 + 4);
99 const int32_t THM_MAX_BWD_BRANCH_OFFSET = (-(1 << 22) + 4);
100 const int32_t THM2_MAX_FWD_BRANCH_OFFSET = (((1 << 24) - 2) + 4);
101 const int32_t THM2_MAX_BWD_BRANCH_OFFSET = (-(1 << 24) + 4);
102
103 // Thread Control Block size.
104 const size_t ARM_TCB_SIZE = 8;
105
106 // The arm target class.
107 //
108 // This is a very simple port of gold for ARM-EABI.  It is intended for
109 // supporting Android only for the time being.
110 // 
111 // TODOs:
112 // - Implement all static relocation types documented in arm-reloc.def.
113 // - Make PLTs more flexible for different architecture features like
114 //   Thumb-2 and BE8.
115 // There are probably a lot more.
116
117 // Ideally we would like to avoid using global variables but this is used
118 // very in many places and sometimes in loops.  If we use a function
119 // returning a static instance of Arm_reloc_property_table, it will very
120 // slow in an threaded environment since the static instance needs to be
121 // locked.  The pointer is below initialized in the
122 // Target::do_select_as_default_target() hook so that we do not spend time
123 // building the table if we are not linking ARM objects.
124 //
125 // An alternative is to to process the information in arm-reloc.def in
126 // compilation time and generate a representation of it in PODs only.  That
127 // way we can avoid initialization when the linker starts.
128
129 Arm_reloc_property_table *arm_reloc_property_table = NULL;
130
131 // Instruction template class.  This class is similar to the insn_sequence
132 // struct in bfd/elf32-arm.c.
133
134 class Insn_template
135 {
136  public:
137   // Types of instruction templates.
138   enum Type
139     {
140       THUMB16_TYPE = 1,
141       // THUMB16_SPECIAL_TYPE is used by sub-classes of Stub for instruction 
142       // templates with class-specific semantics.  Currently this is used
143       // only by the Cortex_a8_stub class for handling condition codes in
144       // conditional branches.
145       THUMB16_SPECIAL_TYPE,
146       THUMB32_TYPE,
147       ARM_TYPE,
148       DATA_TYPE
149     };
150
151   // Factory methods to create instruction templates in different formats.
152
153   static const Insn_template
154   thumb16_insn(uint32_t data)
155   { return Insn_template(data, THUMB16_TYPE, elfcpp::R_ARM_NONE, 0); } 
156
157   // A Thumb conditional branch, in which the proper condition is inserted
158   // when we build the stub.
159   static const Insn_template
160   thumb16_bcond_insn(uint32_t data)
161   { return Insn_template(data, THUMB16_SPECIAL_TYPE, elfcpp::R_ARM_NONE, 1); } 
162
163   static const Insn_template
164   thumb32_insn(uint32_t data)
165   { return Insn_template(data, THUMB32_TYPE, elfcpp::R_ARM_NONE, 0); } 
166
167   static const Insn_template
168   thumb32_b_insn(uint32_t data, int reloc_addend)
169   {
170     return Insn_template(data, THUMB32_TYPE, elfcpp::R_ARM_THM_JUMP24,
171                          reloc_addend);
172   } 
173
174   static const Insn_template
175   arm_insn(uint32_t data)
176   { return Insn_template(data, ARM_TYPE, elfcpp::R_ARM_NONE, 0); }
177
178   static const Insn_template
179   arm_rel_insn(unsigned data, int reloc_addend)
180   { return Insn_template(data, ARM_TYPE, elfcpp::R_ARM_JUMP24, reloc_addend); }
181
182   static const Insn_template
183   data_word(unsigned data, unsigned int r_type, int reloc_addend)
184   { return Insn_template(data, DATA_TYPE, r_type, reloc_addend); } 
185
186   // Accessors.  This class is used for read-only objects so no modifiers
187   // are provided.
188
189   uint32_t
190   data() const
191   { return this->data_; }
192
193   // Return the instruction sequence type of this.
194   Type
195   type() const
196   { return this->type_; }
197
198   // Return the ARM relocation type of this.
199   unsigned int
200   r_type() const
201   { return this->r_type_; }
202
203   int32_t
204   reloc_addend() const
205   { return this->reloc_addend_; }
206
207   // Return size of instruction template in bytes.
208   size_t
209   size() const;
210
211   // Return byte-alignment of instruction template.
212   unsigned
213   alignment() const;
214
215  private:
216   // We make the constructor private to ensure that only the factory
217   // methods are used.
218   inline
219   Insn_template(unsigned data, Type type, unsigned int r_type, int reloc_addend)
220     : data_(data), type_(type), r_type_(r_type), reloc_addend_(reloc_addend)
221   { }
222
223   // Instruction specific data.  This is used to store information like
224   // some of the instruction bits.
225   uint32_t data_;
226   // Instruction template type.
227   Type type_;
228   // Relocation type if there is a relocation or R_ARM_NONE otherwise.
229   unsigned int r_type_;
230   // Relocation addend.
231   int32_t reloc_addend_;
232 };
233
234 // Macro for generating code to stub types. One entry per long/short
235 // branch stub
236
237 #define DEF_STUBS \
238   DEF_STUB(long_branch_any_any) \
239   DEF_STUB(long_branch_v4t_arm_thumb) \
240   DEF_STUB(long_branch_thumb_only) \
241   DEF_STUB(long_branch_v4t_thumb_thumb) \
242   DEF_STUB(long_branch_v4t_thumb_arm) \
243   DEF_STUB(short_branch_v4t_thumb_arm) \
244   DEF_STUB(long_branch_any_arm_pic) \
245   DEF_STUB(long_branch_any_thumb_pic) \
246   DEF_STUB(long_branch_v4t_thumb_thumb_pic) \
247   DEF_STUB(long_branch_v4t_arm_thumb_pic) \
248   DEF_STUB(long_branch_v4t_thumb_arm_pic) \
249   DEF_STUB(long_branch_thumb_only_pic) \
250   DEF_STUB(a8_veneer_b_cond) \
251   DEF_STUB(a8_veneer_b) \
252   DEF_STUB(a8_veneer_bl) \
253   DEF_STUB(a8_veneer_blx) \
254   DEF_STUB(v4_veneer_bx)
255
256 // Stub types.
257
258 #define DEF_STUB(x) arm_stub_##x,
259 typedef enum
260   {
261     arm_stub_none,
262     DEF_STUBS
263
264     // First reloc stub type.
265     arm_stub_reloc_first = arm_stub_long_branch_any_any,
266     // Last  reloc stub type.
267     arm_stub_reloc_last = arm_stub_long_branch_thumb_only_pic,
268
269     // First Cortex-A8 stub type.
270     arm_stub_cortex_a8_first = arm_stub_a8_veneer_b_cond,
271     // Last Cortex-A8 stub type.
272     arm_stub_cortex_a8_last = arm_stub_a8_veneer_blx,
273     
274     // Last stub type.
275     arm_stub_type_last = arm_stub_v4_veneer_bx
276   } Stub_type;
277 #undef DEF_STUB
278
279 // Stub template class.  Templates are meant to be read-only objects.
280 // A stub template for a stub type contains all read-only attributes
281 // common to all stubs of the same type.
282
283 class Stub_template
284 {
285  public:
286   Stub_template(Stub_type, const Insn_template*, size_t);
287
288   ~Stub_template()
289   { }
290
291   // Return stub type.
292   Stub_type
293   type() const
294   { return this->type_; }
295
296   // Return an array of instruction templates.
297   const Insn_template*
298   insns() const
299   { return this->insns_; }
300
301   // Return size of template in number of instructions.
302   size_t
303   insn_count() const
304   { return this->insn_count_; }
305
306   // Return size of template in bytes.
307   size_t
308   size() const
309   { return this->size_; }
310
311   // Return alignment of the stub template.
312   unsigned
313   alignment() const
314   { return this->alignment_; }
315   
316   // Return whether entry point is in thumb mode.
317   bool
318   entry_in_thumb_mode() const
319   { return this->entry_in_thumb_mode_; }
320
321   // Return number of relocations in this template.
322   size_t
323   reloc_count() const
324   { return this->relocs_.size(); }
325
326   // Return index of the I-th instruction with relocation.
327   size_t
328   reloc_insn_index(size_t i) const
329   {
330     gold_assert(i < this->relocs_.size());
331     return this->relocs_[i].first;
332   }
333
334   // Return the offset of the I-th instruction with relocation from the
335   // beginning of the stub.
336   section_size_type
337   reloc_offset(size_t i) const
338   {
339     gold_assert(i < this->relocs_.size());
340     return this->relocs_[i].second;
341   }
342
343  private:
344   // This contains information about an instruction template with a relocation
345   // and its offset from start of stub.
346   typedef std::pair<size_t, section_size_type> Reloc;
347
348   // A Stub_template may not be copied.  We want to share templates as much
349   // as possible.
350   Stub_template(const Stub_template&);
351   Stub_template& operator=(const Stub_template&);
352   
353   // Stub type.
354   Stub_type type_;
355   // Points to an array of Insn_templates.
356   const Insn_template* insns_;
357   // Number of Insn_templates in insns_[].
358   size_t insn_count_;
359   // Size of templated instructions in bytes.
360   size_t size_;
361   // Alignment of templated instructions.
362   unsigned alignment_;
363   // Flag to indicate if entry is in thumb mode.
364   bool entry_in_thumb_mode_;
365   // A table of reloc instruction indices and offsets.  We can find these by
366   // looking at the instruction templates but we pre-compute and then stash
367   // them here for speed. 
368   std::vector<Reloc> relocs_;
369 };
370
371 //
372 // A class for code stubs.  This is a base class for different type of
373 // stubs used in the ARM target.
374 //
375
376 class Stub
377 {
378  private:
379   static const section_offset_type invalid_offset =
380     static_cast<section_offset_type>(-1);
381
382  public:
383   Stub(const Stub_template* stub_template)
384     : stub_template_(stub_template), offset_(invalid_offset)
385   { }
386
387   virtual
388    ~Stub()
389   { }
390
391   // Return the stub template.
392   const Stub_template*
393   stub_template() const
394   { return this->stub_template_; }
395
396   // Return offset of code stub from beginning of its containing stub table.
397   section_offset_type
398   offset() const
399   {
400     gold_assert(this->offset_ != invalid_offset);
401     return this->offset_;
402   }
403
404   // Set offset of code stub from beginning of its containing stub table.
405   void
406   set_offset(section_offset_type offset)
407   { this->offset_ = offset; }
408   
409   // Return the relocation target address of the i-th relocation in the
410   // stub.  This must be defined in a child class.
411   Arm_address
412   reloc_target(size_t i)
413   { return this->do_reloc_target(i); }
414
415   // Write a stub at output VIEW.  BIG_ENDIAN select how a stub is written.
416   void
417   write(unsigned char* view, section_size_type view_size, bool big_endian)
418   { this->do_write(view, view_size, big_endian); }
419
420   // Return the instruction for THUMB16_SPECIAL_TYPE instruction template
421   // for the i-th instruction.
422   uint16_t
423   thumb16_special(size_t i)
424   { return this->do_thumb16_special(i); }
425
426  protected:
427   // This must be defined in the child class.
428   virtual Arm_address
429   do_reloc_target(size_t) = 0;
430
431   // This may be overridden in the child class.
432   virtual void
433   do_write(unsigned char* view, section_size_type view_size, bool big_endian)
434   {
435     if (big_endian)
436       this->do_fixed_endian_write<true>(view, view_size);
437     else
438       this->do_fixed_endian_write<false>(view, view_size);
439   }
440   
441   // This must be overridden if a child class uses the THUMB16_SPECIAL_TYPE
442   // instruction template.
443   virtual uint16_t
444   do_thumb16_special(size_t)
445   { gold_unreachable(); }
446
447  private:
448   // A template to implement do_write.
449   template<bool big_endian>
450   void inline
451   do_fixed_endian_write(unsigned char*, section_size_type);
452
453   // Its template.
454   const Stub_template* stub_template_;
455   // Offset within the section of containing this stub.
456   section_offset_type offset_;
457 };
458
459 // Reloc stub class.  These are stubs we use to fix up relocation because
460 // of limited branch ranges.
461
462 class Reloc_stub : public Stub
463 {
464  public:
465   static const unsigned int invalid_index = static_cast<unsigned int>(-1);
466   // We assume we never jump to this address.
467   static const Arm_address invalid_address = static_cast<Arm_address>(-1);
468
469   // Return destination address.
470   Arm_address
471   destination_address() const
472   {
473     gold_assert(this->destination_address_ != this->invalid_address);
474     return this->destination_address_;
475   }
476
477   // Set destination address.
478   void
479   set_destination_address(Arm_address address)
480   {
481     gold_assert(address != this->invalid_address);
482     this->destination_address_ = address;
483   }
484
485   // Reset destination address.
486   void
487   reset_destination_address()
488   { this->destination_address_ = this->invalid_address; }
489
490   // Determine stub type for a branch of a relocation of R_TYPE going
491   // from BRANCH_ADDRESS to BRANCH_TARGET.  If TARGET_IS_THUMB is set,
492   // the branch target is a thumb instruction.  TARGET is used for look
493   // up ARM-specific linker settings.
494   static Stub_type
495   stub_type_for_reloc(unsigned int r_type, Arm_address branch_address,
496                       Arm_address branch_target, bool target_is_thumb);
497
498   // Reloc_stub key.  A key is logically a triplet of a stub type, a symbol
499   // and an addend.  Since we treat global and local symbol differently, we
500   // use a Symbol object for a global symbol and a object-index pair for
501   // a local symbol.
502   class Key
503   {
504    public:
505     // If SYMBOL is not null, this is a global symbol, we ignore RELOBJ and
506     // R_SYM.  Otherwise, this is a local symbol and RELOBJ must non-NULL
507     // and R_SYM must not be invalid_index.
508     Key(Stub_type stub_type, const Symbol* symbol, const Relobj* relobj,
509         unsigned int r_sym, int32_t addend)
510       : stub_type_(stub_type), addend_(addend)
511     {
512       if (symbol != NULL)
513         {
514           this->r_sym_ = Reloc_stub::invalid_index;
515           this->u_.symbol = symbol;
516         }
517       else
518         {
519           gold_assert(relobj != NULL && r_sym != invalid_index);
520           this->r_sym_ = r_sym;
521           this->u_.relobj = relobj;
522         }
523     }
524
525     ~Key()
526     { }
527
528     // Accessors: Keys are meant to be read-only object so no modifiers are
529     // provided.
530
531     // Return stub type.
532     Stub_type
533     stub_type() const
534     { return this->stub_type_; }
535
536     // Return the local symbol index or invalid_index.
537     unsigned int
538     r_sym() const
539     { return this->r_sym_; }
540
541     // Return the symbol if there is one.
542     const Symbol*
543     symbol() const
544     { return this->r_sym_ == invalid_index ? this->u_.symbol : NULL; }
545
546     // Return the relobj if there is one.
547     const Relobj*
548     relobj() const
549     { return this->r_sym_ != invalid_index ? this->u_.relobj : NULL; }
550
551     // Whether this equals to another key k.
552     bool
553     eq(const Key& k) const 
554     {
555       return ((this->stub_type_ == k.stub_type_)
556               && (this->r_sym_ == k.r_sym_)
557               && ((this->r_sym_ != Reloc_stub::invalid_index)
558                   ? (this->u_.relobj == k.u_.relobj)
559                   : (this->u_.symbol == k.u_.symbol))
560               && (this->addend_ == k.addend_));
561     }
562
563     // Return a hash value.
564     size_t
565     hash_value() const
566     {
567       return (this->stub_type_
568               ^ this->r_sym_
569               ^ gold::string_hash<char>(
570                     (this->r_sym_ != Reloc_stub::invalid_index)
571                     ? this->u_.relobj->name().c_str()
572                     : this->u_.symbol->name())
573               ^ this->addend_);
574     }
575
576     // Functors for STL associative containers.
577     struct hash
578     {
579       size_t
580       operator()(const Key& k) const
581       { return k.hash_value(); }
582     };
583
584     struct equal_to
585     {
586       bool
587       operator()(const Key& k1, const Key& k2) const
588       { return k1.eq(k2); }
589     };
590
591     // Name of key.  This is mainly for debugging.
592     std::string
593     name() const;
594
595    private:
596     // Stub type.
597     Stub_type stub_type_;
598     // If this is a local symbol, this is the index in the defining object.
599     // Otherwise, it is invalid_index for a global symbol.
600     unsigned int r_sym_;
601     // If r_sym_ is invalid index.  This points to a global symbol.
602     // Otherwise, this points a relobj.  We used the unsized and target
603     // independent Symbol and Relobj classes instead of Sized_symbol<32> and  
604     // Arm_relobj.  This is done to avoid making the stub class a template
605     // as most of the stub machinery is endianity-neutral.  However, it
606     // may require a bit of casting done by users of this class.
607     union
608     {
609       const Symbol* symbol;
610       const Relobj* relobj;
611     } u_;
612     // Addend associated with a reloc.
613     int32_t addend_;
614   };
615
616  protected:
617   // Reloc_stubs are created via a stub factory.  So these are protected.
618   Reloc_stub(const Stub_template* stub_template)
619     : Stub(stub_template), destination_address_(invalid_address)
620   { }
621
622   ~Reloc_stub()
623   { }
624
625   friend class Stub_factory;
626
627   // Return the relocation target address of the i-th relocation in the
628   // stub.
629   Arm_address
630   do_reloc_target(size_t i)
631   {
632     // All reloc stub have only one relocation.
633     gold_assert(i == 0);
634     return this->destination_address_;
635   }
636
637  private:
638   // Address of destination.
639   Arm_address destination_address_;
640 };
641
642 // Cortex-A8 stub class.  We need a Cortex-A8 stub to redirect any 32-bit
643 // THUMB branch that meets the following conditions:
644 // 
645 // 1. The branch straddles across a page boundary. i.e. lower 12-bit of
646 //    branch address is 0xffe.
647 // 2. The branch target address is in the same page as the first word of the
648 //    branch.
649 // 3. The branch follows a 32-bit instruction which is not a branch.
650 //
651 // To do the fix up, we need to store the address of the branch instruction
652 // and its target at least.  We also need to store the original branch
653 // instruction bits for the condition code in a conditional branch.  The
654 // condition code is used in a special instruction template.  We also want
655 // to identify input sections needing Cortex-A8 workaround quickly.  We store
656 // extra information about object and section index of the code section
657 // containing a branch being fixed up.  The information is used to mark
658 // the code section when we finalize the Cortex-A8 stubs.
659 //
660
661 class Cortex_a8_stub : public Stub
662 {
663  public:
664   ~Cortex_a8_stub()
665   { }
666
667   // Return the object of the code section containing the branch being fixed
668   // up.
669   Relobj*
670   relobj() const
671   { return this->relobj_; }
672
673   // Return the section index of the code section containing the branch being
674   // fixed up.
675   unsigned int
676   shndx() const
677   { return this->shndx_; }
678
679   // Return the source address of stub.  This is the address of the original
680   // branch instruction.  LSB is 1 always set to indicate that it is a THUMB
681   // instruction.
682   Arm_address
683   source_address() const
684   { return this->source_address_; }
685
686   // Return the destination address of the stub.  This is the branch taken
687   // address of the original branch instruction.  LSB is 1 if it is a THUMB
688   // instruction address.
689   Arm_address
690   destination_address() const
691   { return this->destination_address_; }
692
693   // Return the instruction being fixed up.
694   uint32_t
695   original_insn() const
696   { return this->original_insn_; }
697
698  protected:
699   // Cortex_a8_stubs are created via a stub factory.  So these are protected.
700   Cortex_a8_stub(const Stub_template* stub_template, Relobj* relobj,
701                  unsigned int shndx, Arm_address source_address,
702                  Arm_address destination_address, uint32_t original_insn)
703     : Stub(stub_template), relobj_(relobj), shndx_(shndx),
704       source_address_(source_address | 1U),
705       destination_address_(destination_address),
706       original_insn_(original_insn)
707   { }
708
709   friend class Stub_factory;
710
711   // Return the relocation target address of the i-th relocation in the
712   // stub.
713   Arm_address
714   do_reloc_target(size_t i)
715   {
716     if (this->stub_template()->type() == arm_stub_a8_veneer_b_cond)
717       {
718         // The conditional branch veneer has two relocations.
719         gold_assert(i < 2);
720         return i == 0 ? this->source_address_ + 4 : this->destination_address_;
721       }
722     else
723       {
724         // All other Cortex-A8 stubs have only one relocation.
725         gold_assert(i == 0);
726         return this->destination_address_;
727       }
728   }
729
730   // Return an instruction for the THUMB16_SPECIAL_TYPE instruction template.
731   uint16_t
732   do_thumb16_special(size_t);
733
734  private:
735   // Object of the code section containing the branch being fixed up.
736   Relobj* relobj_;
737   // Section index of the code section containing the branch begin fixed up.
738   unsigned int shndx_;
739   // Source address of original branch.
740   Arm_address source_address_;
741   // Destination address of the original branch.
742   Arm_address destination_address_;
743   // Original branch instruction.  This is needed for copying the condition
744   // code from a condition branch to its stub.
745   uint32_t original_insn_;
746 };
747
748 // ARMv4 BX Rx branch relocation stub class.
749 class Arm_v4bx_stub : public Stub
750 {
751  public:
752   ~Arm_v4bx_stub()
753   { }
754
755   // Return the associated register.
756   uint32_t
757   reg() const
758   { return this->reg_; }
759
760  protected:
761   // Arm V4BX stubs are created via a stub factory.  So these are protected.
762   Arm_v4bx_stub(const Stub_template* stub_template, const uint32_t reg)
763     : Stub(stub_template), reg_(reg)
764   { }
765
766   friend class Stub_factory;
767
768   // Return the relocation target address of the i-th relocation in the
769   // stub.
770   Arm_address
771   do_reloc_target(size_t)
772   { gold_unreachable(); }
773
774   // This may be overridden in the child class.
775   virtual void
776   do_write(unsigned char* view, section_size_type view_size, bool big_endian)
777   {
778     if (big_endian)
779       this->do_fixed_endian_v4bx_write<true>(view, view_size);
780     else
781       this->do_fixed_endian_v4bx_write<false>(view, view_size);
782   }
783
784  private:
785   // A template to implement do_write.
786   template<bool big_endian>
787   void inline
788   do_fixed_endian_v4bx_write(unsigned char* view, section_size_type)
789   {
790     const Insn_template* insns = this->stub_template()->insns();
791     elfcpp::Swap<32, big_endian>::writeval(view,
792                                            (insns[0].data()
793                                            + (this->reg_ << 16)));
794     view += insns[0].size();
795     elfcpp::Swap<32, big_endian>::writeval(view,
796                                            (insns[1].data() + this->reg_));
797     view += insns[1].size();
798     elfcpp::Swap<32, big_endian>::writeval(view,
799                                            (insns[2].data() + this->reg_));
800   }
801
802   // A register index (r0-r14), which is associated with the stub.
803   uint32_t reg_;
804 };
805
806 // Stub factory class.
807
808 class Stub_factory
809 {
810  public:
811   // Return the unique instance of this class.
812   static const Stub_factory&
813   get_instance()
814   {
815     static Stub_factory singleton;
816     return singleton;
817   }
818
819   // Make a relocation stub.
820   Reloc_stub*
821   make_reloc_stub(Stub_type stub_type) const
822   {
823     gold_assert(stub_type >= arm_stub_reloc_first
824                 && stub_type <= arm_stub_reloc_last);
825     return new Reloc_stub(this->stub_templates_[stub_type]);
826   }
827
828   // Make a Cortex-A8 stub.
829   Cortex_a8_stub*
830   make_cortex_a8_stub(Stub_type stub_type, Relobj* relobj, unsigned int shndx,
831                       Arm_address source, Arm_address destination,
832                       uint32_t original_insn) const
833   {
834     gold_assert(stub_type >= arm_stub_cortex_a8_first
835                 && stub_type <= arm_stub_cortex_a8_last);
836     return new Cortex_a8_stub(this->stub_templates_[stub_type], relobj, shndx,
837                               source, destination, original_insn);
838   }
839
840   // Make an ARM V4BX relocation stub.
841   // This method creates a stub from the arm_stub_v4_veneer_bx template only.
842   Arm_v4bx_stub*
843   make_arm_v4bx_stub(uint32_t reg) const
844   {
845     gold_assert(reg < 0xf);
846     return new Arm_v4bx_stub(this->stub_templates_[arm_stub_v4_veneer_bx],
847                              reg);
848   }
849
850  private:
851   // Constructor and destructor are protected since we only return a single
852   // instance created in Stub_factory::get_instance().
853   
854   Stub_factory();
855
856   // A Stub_factory may not be copied since it is a singleton.
857   Stub_factory(const Stub_factory&);
858   Stub_factory& operator=(Stub_factory&);
859   
860   // Stub templates.  These are initialized in the constructor.
861   const Stub_template* stub_templates_[arm_stub_type_last+1];
862 };
863
864 // A class to hold stubs for the ARM target.
865
866 template<bool big_endian>
867 class Stub_table : public Output_data
868 {
869  public:
870   Stub_table(Arm_input_section<big_endian>* owner)
871     : Output_data(), owner_(owner), reloc_stubs_(), reloc_stubs_size_(0),
872       reloc_stubs_addralign_(1), cortex_a8_stubs_(), arm_v4bx_stubs_(0xf),
873       prev_data_size_(0), prev_addralign_(1)
874   { }
875
876   ~Stub_table()
877   { }
878
879   // Owner of this stub table.
880   Arm_input_section<big_endian>*
881   owner() const
882   { return this->owner_; }
883
884   // Whether this stub table is empty.
885   bool
886   empty() const
887   {
888     return (this->reloc_stubs_.empty()
889             && this->cortex_a8_stubs_.empty()
890             && this->arm_v4bx_stubs_.empty());
891   }
892
893   // Return the current data size.
894   off_t
895   current_data_size() const
896   { return this->current_data_size_for_child(); }
897
898   // Add a STUB with using KEY.  Caller is reponsible for avoid adding
899   // if already a STUB with the same key has been added. 
900   void
901   add_reloc_stub(Reloc_stub* stub, const Reloc_stub::Key& key)
902   {
903     const Stub_template* stub_template = stub->stub_template();
904     gold_assert(stub_template->type() == key.stub_type());
905     this->reloc_stubs_[key] = stub;
906
907     // Assign stub offset early.  We can do this because we never remove
908     // reloc stubs and they are in the beginning of the stub table.
909     uint64_t align = stub_template->alignment();
910     this->reloc_stubs_size_ = align_address(this->reloc_stubs_size_, align);
911     stub->set_offset(this->reloc_stubs_size_);
912     this->reloc_stubs_size_ += stub_template->size();
913     this->reloc_stubs_addralign_ =
914       std::max(this->reloc_stubs_addralign_, align);
915   }
916
917   // Add a Cortex-A8 STUB that fixes up a THUMB branch at ADDRESS.
918   // Caller is reponsible for avoid adding if already a STUB with the same
919   // address has been added. 
920   void
921   add_cortex_a8_stub(Arm_address address, Cortex_a8_stub* stub)
922   {
923     std::pair<Arm_address, Cortex_a8_stub*> value(address, stub);
924     this->cortex_a8_stubs_.insert(value);
925   }
926
927   // Add an ARM V4BX relocation stub. A register index will be retrieved
928   // from the stub.
929   void
930   add_arm_v4bx_stub(Arm_v4bx_stub* stub)
931   {
932     gold_assert(stub != NULL && this->arm_v4bx_stubs_[stub->reg()] == NULL);
933     this->arm_v4bx_stubs_[stub->reg()] = stub;
934   }
935
936   // Remove all Cortex-A8 stubs.
937   void
938   remove_all_cortex_a8_stubs();
939
940   // Look up a relocation stub using KEY.  Return NULL if there is none.
941   Reloc_stub*
942   find_reloc_stub(const Reloc_stub::Key& key) const
943   {
944     typename Reloc_stub_map::const_iterator p = this->reloc_stubs_.find(key);
945     return (p != this->reloc_stubs_.end()) ? p->second : NULL;
946   }
947
948   // Look up an arm v4bx relocation stub using the register index.
949   // Return NULL if there is none.
950   Arm_v4bx_stub*
951   find_arm_v4bx_stub(const uint32_t reg) const
952   {
953     gold_assert(reg < 0xf);
954     return this->arm_v4bx_stubs_[reg];
955   }
956
957   // Relocate stubs in this stub table.
958   void
959   relocate_stubs(const Relocate_info<32, big_endian>*,
960                  Target_arm<big_endian>*, Output_section*,
961                  unsigned char*, Arm_address, section_size_type);
962
963   // Update data size and alignment at the end of a relaxation pass.  Return
964   // true if either data size or alignment is different from that of the
965   // previous relaxation pass.
966   bool
967   update_data_size_and_addralign();
968
969   // Finalize stubs.  Set the offsets of all stubs and mark input sections
970   // needing the Cortex-A8 workaround.
971   void
972   finalize_stubs();
973   
974   // Apply Cortex-A8 workaround to an address range.
975   void
976   apply_cortex_a8_workaround_to_address_range(Target_arm<big_endian>*,
977                                               unsigned char*, Arm_address,
978                                               section_size_type);
979
980  protected:
981   // Write out section contents.
982   void
983   do_write(Output_file*);
984  
985   // Return the required alignment.
986   uint64_t
987   do_addralign() const
988   { return this->prev_addralign_; }
989
990   // Reset address and file offset.
991   void
992   do_reset_address_and_file_offset()
993   { this->set_current_data_size_for_child(this->prev_data_size_); }
994
995   // Set final data size.
996   void
997   set_final_data_size()
998   { this->set_data_size(this->current_data_size()); }
999   
1000  private:
1001   // Relocate one stub.
1002   void
1003   relocate_stub(Stub*, const Relocate_info<32, big_endian>*,
1004                 Target_arm<big_endian>*, Output_section*,
1005                 unsigned char*, Arm_address, section_size_type);
1006
1007   // Unordered map of relocation stubs.
1008   typedef
1009     Unordered_map<Reloc_stub::Key, Reloc_stub*, Reloc_stub::Key::hash,
1010                   Reloc_stub::Key::equal_to>
1011     Reloc_stub_map;
1012
1013   // List of Cortex-A8 stubs ordered by addresses of branches being
1014   // fixed up in output.
1015   typedef std::map<Arm_address, Cortex_a8_stub*> Cortex_a8_stub_list;
1016   // List of Arm V4BX relocation stubs ordered by associated registers.
1017   typedef std::vector<Arm_v4bx_stub*> Arm_v4bx_stub_list;
1018
1019   // Owner of this stub table.
1020   Arm_input_section<big_endian>* owner_;
1021   // The relocation stubs.
1022   Reloc_stub_map reloc_stubs_;
1023   // Size of reloc stubs.
1024   off_t reloc_stubs_size_;
1025   // Maximum address alignment of reloc stubs.
1026   uint64_t reloc_stubs_addralign_;
1027   // The cortex_a8_stubs.
1028   Cortex_a8_stub_list cortex_a8_stubs_;
1029   // The Arm V4BX relocation stubs.
1030   Arm_v4bx_stub_list arm_v4bx_stubs_;
1031   // data size of this in the previous pass.
1032   off_t prev_data_size_;
1033   // address alignment of this in the previous pass.
1034   uint64_t prev_addralign_;
1035 };
1036
1037 // Arm_exidx_cantunwind class.  This represents an EXIDX_CANTUNWIND entry
1038 // we add to the end of an EXIDX input section that goes into the output.
1039
1040 class Arm_exidx_cantunwind : public Output_section_data
1041 {
1042  public:
1043   Arm_exidx_cantunwind(Relobj* relobj, unsigned int shndx)
1044     : Output_section_data(8, 4, true), relobj_(relobj), shndx_(shndx)
1045   { }
1046
1047   // Return the object containing the section pointed by this.
1048   Relobj*
1049   relobj() const
1050   { return this->relobj_; }
1051
1052   // Return the section index of the section pointed by this.
1053   unsigned int
1054   shndx() const
1055   { return this->shndx_; }
1056
1057  protected:
1058   void
1059   do_write(Output_file* of)
1060   {
1061     if (parameters->target().is_big_endian())
1062       this->do_fixed_endian_write<true>(of);
1063     else
1064       this->do_fixed_endian_write<false>(of);
1065   }
1066
1067  private:
1068   // Implement do_write for a given endianity.
1069   template<bool big_endian>
1070   void inline
1071   do_fixed_endian_write(Output_file*);
1072   
1073   // The object containing the section pointed by this.
1074   Relobj* relobj_;
1075   // The section index of the section pointed by this.
1076   unsigned int shndx_;
1077 };
1078
1079 // During EXIDX coverage fix-up, we compact an EXIDX section.  The
1080 // Offset map is used to map input section offset within the EXIDX section
1081 // to the output offset from the start of this EXIDX section. 
1082
1083 typedef std::map<section_offset_type, section_offset_type>
1084         Arm_exidx_section_offset_map;
1085
1086 // Arm_exidx_merged_section class.  This represents an EXIDX input section
1087 // with some of its entries merged.
1088
1089 class Arm_exidx_merged_section : public Output_relaxed_input_section
1090 {
1091  public:
1092   // Constructor for Arm_exidx_merged_section.
1093   // EXIDX_INPUT_SECTION points to the unmodified EXIDX input section.
1094   // SECTION_OFFSET_MAP points to a section offset map describing how
1095   // parts of the input section are mapped to output.  DELETED_BYTES is
1096   // the number of bytes deleted from the EXIDX input section.
1097   Arm_exidx_merged_section(
1098       const Arm_exidx_input_section& exidx_input_section,
1099       const Arm_exidx_section_offset_map& section_offset_map,
1100       uint32_t deleted_bytes);
1101
1102   // Return the original EXIDX input section.
1103   const Arm_exidx_input_section&
1104   exidx_input_section() const
1105   { return this->exidx_input_section_; }
1106
1107   // Return the section offset map.
1108   const Arm_exidx_section_offset_map&
1109   section_offset_map() const
1110   { return this->section_offset_map_; }
1111
1112  protected:
1113   // Write merged section into file OF.
1114   void
1115   do_write(Output_file* of);
1116
1117   bool
1118   do_output_offset(const Relobj*, unsigned int, section_offset_type,
1119                   section_offset_type*) const;
1120
1121  private:
1122   // Original EXIDX input section.
1123   const Arm_exidx_input_section& exidx_input_section_;
1124   // Section offset map.
1125   const Arm_exidx_section_offset_map& section_offset_map_;
1126 };
1127
1128 // A class to wrap an ordinary input section containing executable code.
1129
1130 template<bool big_endian>
1131 class Arm_input_section : public Output_relaxed_input_section
1132 {
1133  public:
1134   Arm_input_section(Relobj* relobj, unsigned int shndx)
1135     : Output_relaxed_input_section(relobj, shndx, 1),
1136       original_addralign_(1), original_size_(0), stub_table_(NULL)
1137   { }
1138
1139   ~Arm_input_section()
1140   { }
1141
1142   // Initialize.
1143   void
1144   init();
1145   
1146   // Whether this is a stub table owner.
1147   bool
1148   is_stub_table_owner() const
1149   { return this->stub_table_ != NULL && this->stub_table_->owner() == this; }
1150
1151   // Return the stub table.
1152   Stub_table<big_endian>*
1153   stub_table() const
1154   { return this->stub_table_; }
1155
1156   // Set the stub_table.
1157   void
1158   set_stub_table(Stub_table<big_endian>* stub_table)
1159   { this->stub_table_ = stub_table; }
1160
1161   // Downcast a base pointer to an Arm_input_section pointer.  This is
1162   // not type-safe but we only use Arm_input_section not the base class.
1163   static Arm_input_section<big_endian>*
1164   as_arm_input_section(Output_relaxed_input_section* poris)
1165   { return static_cast<Arm_input_section<big_endian>*>(poris); }
1166
1167  protected:
1168   // Write data to output file.
1169   void
1170   do_write(Output_file*);
1171
1172   // Return required alignment of this.
1173   uint64_t
1174   do_addralign() const
1175   {
1176     if (this->is_stub_table_owner())
1177       return std::max(this->stub_table_->addralign(),
1178                       this->original_addralign_);
1179     else
1180       return this->original_addralign_;
1181   }
1182
1183   // Finalize data size.
1184   void
1185   set_final_data_size();
1186
1187   // Reset address and file offset.
1188   void
1189   do_reset_address_and_file_offset();
1190
1191   // Output offset.
1192   bool
1193   do_output_offset(const Relobj* object, unsigned int shndx,
1194                    section_offset_type offset,
1195                    section_offset_type* poutput) const
1196   {
1197     if ((object == this->relobj())
1198         && (shndx == this->shndx())
1199         && (offset >= 0)
1200         && (convert_types<uint64_t, section_offset_type>(offset)
1201             <= this->original_size_))
1202       {
1203         *poutput = offset;
1204         return true;
1205       }
1206     else
1207       return false;
1208   }
1209
1210  private:
1211   // Copying is not allowed.
1212   Arm_input_section(const Arm_input_section&);
1213   Arm_input_section& operator=(const Arm_input_section&);
1214
1215   // Address alignment of the original input section.
1216   uint64_t original_addralign_;
1217   // Section size of the original input section.
1218   uint64_t original_size_;
1219   // Stub table.
1220   Stub_table<big_endian>* stub_table_;
1221 };
1222
1223 // Arm_exidx_fixup class.  This is used to define a number of methods
1224 // and keep states for fixing up EXIDX coverage.
1225
1226 class Arm_exidx_fixup
1227 {
1228  public:
1229   Arm_exidx_fixup(Output_section* exidx_output_section)
1230     : exidx_output_section_(exidx_output_section), last_unwind_type_(UT_NONE),
1231       last_inlined_entry_(0), last_input_section_(NULL),
1232       section_offset_map_(NULL), first_output_text_section_(NULL)
1233   { }
1234
1235   ~Arm_exidx_fixup()
1236   { delete this->section_offset_map_; }
1237
1238   // Process an EXIDX section for entry merging.  Return  number of bytes to
1239   // be deleted in output.  If parts of the input EXIDX section are merged
1240   // a heap allocated Arm_exidx_section_offset_map is store in the located
1241   // PSECTION_OFFSET_MAP.  The caller owns the map and is reponsible for
1242   // releasing it.
1243   template<bool big_endian>
1244   uint32_t
1245   process_exidx_section(const Arm_exidx_input_section* exidx_input_section,
1246                         Arm_exidx_section_offset_map** psection_offset_map);
1247   
1248   // Append an EXIDX_CANTUNWIND entry pointing at the end of the last
1249   // input section, if there is not one already.
1250   void
1251   add_exidx_cantunwind_as_needed();
1252
1253   // Return the output section for the text section which is linked to the
1254   // first exidx input in output.
1255   Output_section*
1256   first_output_text_section() const
1257   { return this->first_output_text_section_; }
1258
1259  private:
1260   // Copying is not allowed.
1261   Arm_exidx_fixup(const Arm_exidx_fixup&);
1262   Arm_exidx_fixup& operator=(const Arm_exidx_fixup&);
1263
1264   // Type of EXIDX unwind entry.
1265   enum Unwind_type
1266   {
1267     // No type.
1268     UT_NONE,
1269     // EXIDX_CANTUNWIND.
1270     UT_EXIDX_CANTUNWIND,
1271     // Inlined entry.
1272     UT_INLINED_ENTRY,
1273     // Normal entry.
1274     UT_NORMAL_ENTRY,
1275   };
1276
1277   // Process an EXIDX entry.  We only care about the second word of the
1278   // entry.  Return true if the entry can be deleted.
1279   bool
1280   process_exidx_entry(uint32_t second_word);
1281
1282   // Update the current section offset map during EXIDX section fix-up.
1283   // If there is no map, create one.  INPUT_OFFSET is the offset of a
1284   // reference point, DELETED_BYTES is the number of deleted by in the
1285   // section so far.  If DELETE_ENTRY is true, the reference point and
1286   // all offsets after the previous reference point are discarded.
1287   void
1288   update_offset_map(section_offset_type input_offset,
1289                     section_size_type deleted_bytes, bool delete_entry);
1290
1291   // EXIDX output section.
1292   Output_section* exidx_output_section_;
1293   // Unwind type of the last EXIDX entry processed.
1294   Unwind_type last_unwind_type_;
1295   // Last seen inlined EXIDX entry.
1296   uint32_t last_inlined_entry_;
1297   // Last processed EXIDX input section.
1298   const Arm_exidx_input_section* last_input_section_;
1299   // Section offset map created in process_exidx_section.
1300   Arm_exidx_section_offset_map* section_offset_map_;
1301   // Output section for the text section which is linked to the first exidx
1302   // input in output.
1303   Output_section* first_output_text_section_;
1304 };
1305
1306 // Arm output section class.  This is defined mainly to add a number of
1307 // stub generation methods.
1308
1309 template<bool big_endian>
1310 class Arm_output_section : public Output_section
1311 {
1312  public:
1313   typedef std::vector<std::pair<Relobj*, unsigned int> > Text_section_list;
1314
1315   Arm_output_section(const char* name, elfcpp::Elf_Word type,
1316                      elfcpp::Elf_Xword flags)
1317     : Output_section(name, type, flags)
1318   { }
1319
1320   ~Arm_output_section()
1321   { }
1322   
1323   // Group input sections for stub generation.
1324   void
1325   group_sections(section_size_type, bool, Target_arm<big_endian>*);
1326
1327   // Downcast a base pointer to an Arm_output_section pointer.  This is
1328   // not type-safe but we only use Arm_output_section not the base class.
1329   static Arm_output_section<big_endian>*
1330   as_arm_output_section(Output_section* os)
1331   { return static_cast<Arm_output_section<big_endian>*>(os); }
1332
1333   // Append all input text sections in this into LIST.
1334   void
1335   append_text_sections_to_list(Text_section_list* list);
1336
1337   // Fix EXIDX coverage of this EXIDX output section.  SORTED_TEXT_SECTION
1338   // is a list of text input sections sorted in ascending order of their
1339   // output addresses.
1340   void
1341   fix_exidx_coverage(Layout* layout,
1342                      const Text_section_list& sorted_text_section,
1343                      Symbol_table* symtab);
1344
1345  private:
1346   // For convenience.
1347   typedef Output_section::Input_section Input_section;
1348   typedef Output_section::Input_section_list Input_section_list;
1349
1350   // Create a stub group.
1351   void create_stub_group(Input_section_list::const_iterator,
1352                          Input_section_list::const_iterator,
1353                          Input_section_list::const_iterator,
1354                          Target_arm<big_endian>*,
1355                          std::vector<Output_relaxed_input_section*>*);
1356 };
1357
1358 // Arm_exidx_input_section class.  This represents an EXIDX input section.
1359
1360 class Arm_exidx_input_section
1361 {
1362  public:
1363   static const section_offset_type invalid_offset =
1364     static_cast<section_offset_type>(-1);
1365
1366   Arm_exidx_input_section(Relobj* relobj, unsigned int shndx,
1367                           unsigned int link, uint32_t size, uint32_t addralign)
1368     : relobj_(relobj), shndx_(shndx), link_(link), size_(size),
1369       addralign_(addralign)
1370   { }
1371
1372   ~Arm_exidx_input_section()
1373   { }
1374         
1375   // Accessors:  This is a read-only class.
1376
1377   // Return the object containing this EXIDX input section.
1378   Relobj*
1379   relobj() const
1380   { return this->relobj_; }
1381
1382   // Return the section index of this EXIDX input section.
1383   unsigned int
1384   shndx() const
1385   { return this->shndx_; }
1386
1387   // Return the section index of linked text section in the same object.
1388   unsigned int
1389   link() const
1390   { return this->link_; }
1391
1392   // Return size of the EXIDX input section.
1393   uint32_t
1394   size() const
1395   { return this->size_; }
1396
1397   // Reutnr address alignment of EXIDX input section.
1398   uint32_t
1399   addralign() const
1400   { return this->addralign_; }
1401
1402  private:
1403   // Object containing this.
1404   Relobj* relobj_;
1405   // Section index of this.
1406   unsigned int shndx_;
1407   // text section linked to this in the same object.
1408   unsigned int link_;
1409   // Size of this.  For ARM 32-bit is sufficient.
1410   uint32_t size_;
1411   // Address alignment of this.  For ARM 32-bit is sufficient.
1412   uint32_t addralign_;
1413 };
1414
1415 // Arm_relobj class.
1416
1417 template<bool big_endian>
1418 class Arm_relobj : public Sized_relobj<32, big_endian>
1419 {
1420  public:
1421   static const Arm_address invalid_address = static_cast<Arm_address>(-1);
1422
1423   Arm_relobj(const std::string& name, Input_file* input_file, off_t offset,
1424              const typename elfcpp::Ehdr<32, big_endian>& ehdr)
1425     : Sized_relobj<32, big_endian>(name, input_file, offset, ehdr),
1426       stub_tables_(), local_symbol_is_thumb_function_(),
1427       attributes_section_data_(NULL), mapping_symbols_info_(),
1428       section_has_cortex_a8_workaround_(NULL), exidx_section_map_(),
1429       output_local_symbol_count_needs_update_(false)
1430   { }
1431
1432   ~Arm_relobj()
1433   { delete this->attributes_section_data_; }
1434  
1435   // Return the stub table of the SHNDX-th section if there is one.
1436   Stub_table<big_endian>*
1437   stub_table(unsigned int shndx) const
1438   {
1439     gold_assert(shndx < this->stub_tables_.size());
1440     return this->stub_tables_[shndx];
1441   }
1442
1443   // Set STUB_TABLE to be the stub_table of the SHNDX-th section.
1444   void
1445   set_stub_table(unsigned int shndx, Stub_table<big_endian>* stub_table)
1446   {
1447     gold_assert(shndx < this->stub_tables_.size());
1448     this->stub_tables_[shndx] = stub_table;
1449   }
1450
1451   // Whether a local symbol is a THUMB function.  R_SYM is the symbol table
1452   // index.  This is only valid after do_count_local_symbol is called.
1453   bool
1454   local_symbol_is_thumb_function(unsigned int r_sym) const
1455   {
1456     gold_assert(r_sym < this->local_symbol_is_thumb_function_.size());
1457     return this->local_symbol_is_thumb_function_[r_sym];
1458   }
1459   
1460   // Scan all relocation sections for stub generation.
1461   void
1462   scan_sections_for_stubs(Target_arm<big_endian>*, const Symbol_table*,
1463                           const Layout*);
1464
1465   // Convert regular input section with index SHNDX to a relaxed section.
1466   void
1467   convert_input_section_to_relaxed_section(unsigned shndx)
1468   {
1469     // The stubs have relocations and we need to process them after writing
1470     // out the stubs.  So relocation now must follow section write.
1471     this->set_section_offset(shndx, -1ULL);
1472     this->set_relocs_must_follow_section_writes();
1473   }
1474
1475   // Downcast a base pointer to an Arm_relobj pointer.  This is
1476   // not type-safe but we only use Arm_relobj not the base class.
1477   static Arm_relobj<big_endian>*
1478   as_arm_relobj(Relobj* relobj)
1479   { return static_cast<Arm_relobj<big_endian>*>(relobj); }
1480
1481   // Processor-specific flags in ELF file header.  This is valid only after
1482   // reading symbols.
1483   elfcpp::Elf_Word
1484   processor_specific_flags() const
1485   { return this->processor_specific_flags_; }
1486
1487   // Attribute section data  This is the contents of the .ARM.attribute section
1488   // if there is one.
1489   const Attributes_section_data*
1490   attributes_section_data() const
1491   { return this->attributes_section_data_; }
1492
1493   // Mapping symbol location.
1494   typedef std::pair<unsigned int, Arm_address> Mapping_symbol_position;
1495
1496   // Functor for STL container.
1497   struct Mapping_symbol_position_less
1498   {
1499     bool
1500     operator()(const Mapping_symbol_position& p1,
1501                const Mapping_symbol_position& p2) const
1502     {
1503       return (p1.first < p2.first
1504               || (p1.first == p2.first && p1.second < p2.second));
1505     }
1506   };
1507   
1508   // We only care about the first character of a mapping symbol, so
1509   // we only store that instead of the whole symbol name.
1510   typedef std::map<Mapping_symbol_position, char,
1511                    Mapping_symbol_position_less> Mapping_symbols_info;
1512
1513   // Whether a section contains any Cortex-A8 workaround.
1514   bool
1515   section_has_cortex_a8_workaround(unsigned int shndx) const
1516   { 
1517     return (this->section_has_cortex_a8_workaround_ != NULL
1518             && (*this->section_has_cortex_a8_workaround_)[shndx]);
1519   }
1520   
1521   // Mark a section that has Cortex-A8 workaround.
1522   void
1523   mark_section_for_cortex_a8_workaround(unsigned int shndx)
1524   {
1525     if (this->section_has_cortex_a8_workaround_ == NULL)
1526       this->section_has_cortex_a8_workaround_ =
1527         new std::vector<bool>(this->shnum(), false);
1528     (*this->section_has_cortex_a8_workaround_)[shndx] = true;
1529   }
1530
1531   // Return the EXIDX section of an text section with index SHNDX or NULL
1532   // if the text section has no associated EXIDX section.
1533   const Arm_exidx_input_section*
1534   exidx_input_section_by_link(unsigned int shndx) const
1535   {
1536     Exidx_section_map::const_iterator p = this->exidx_section_map_.find(shndx);
1537     return ((p != this->exidx_section_map_.end()
1538              && p->second->link() == shndx)
1539             ? p->second
1540             : NULL);
1541   }
1542
1543   // Return the EXIDX section with index SHNDX or NULL if there is none.
1544   const Arm_exidx_input_section*
1545   exidx_input_section_by_shndx(unsigned shndx) const
1546   {
1547     Exidx_section_map::const_iterator p = this->exidx_section_map_.find(shndx);
1548     return ((p != this->exidx_section_map_.end()
1549              && p->second->shndx() == shndx)
1550             ? p->second
1551             : NULL);
1552   }
1553
1554   // Whether output local symbol count needs updating.
1555   bool
1556   output_local_symbol_count_needs_update() const
1557   { return this->output_local_symbol_count_needs_update_; }
1558
1559   // Set output_local_symbol_count_needs_update flag to be true.
1560   void
1561   set_output_local_symbol_count_needs_update()
1562   { this->output_local_symbol_count_needs_update_ = true; }
1563   
1564   // Update output local symbol count at the end of relaxation.
1565   void
1566   update_output_local_symbol_count();
1567
1568  protected:
1569   // Post constructor setup.
1570   void
1571   do_setup()
1572   {
1573     // Call parent's setup method.
1574     Sized_relobj<32, big_endian>::do_setup();
1575
1576     // Initialize look-up tables.
1577     Stub_table_list empty_stub_table_list(this->shnum(), NULL);
1578     this->stub_tables_.swap(empty_stub_table_list);
1579   }
1580
1581   // Count the local symbols.
1582   void
1583   do_count_local_symbols(Stringpool_template<char>*,
1584                          Stringpool_template<char>*);
1585
1586   void
1587   do_relocate_sections(const Symbol_table* symtab, const Layout* layout,
1588                        const unsigned char* pshdrs,
1589                        typename Sized_relobj<32, big_endian>::Views* pivews);
1590
1591   // Read the symbol information.
1592   void
1593   do_read_symbols(Read_symbols_data* sd);
1594
1595   // Process relocs for garbage collection.
1596   void
1597   do_gc_process_relocs(Symbol_table*, Layout*, Read_relocs_data*);
1598
1599  private:
1600
1601   // Whether a section needs to be scanned for relocation stubs.
1602   bool
1603   section_needs_reloc_stub_scanning(const elfcpp::Shdr<32, big_endian>&,
1604                                     const Relobj::Output_sections&,
1605                                     const Symbol_table *, const unsigned char*);
1606
1607   // Whether a section is a scannable text section.
1608   bool
1609   section_is_scannable(const elfcpp::Shdr<32, big_endian>&, unsigned int,
1610                        const Output_section*, const Symbol_table *);
1611
1612   // Whether a section needs to be scanned for the Cortex-A8 erratum.
1613   bool
1614   section_needs_cortex_a8_stub_scanning(const elfcpp::Shdr<32, big_endian>&,
1615                                         unsigned int, Output_section*,
1616                                         const Symbol_table *);
1617
1618   // Scan a section for the Cortex-A8 erratum.
1619   void
1620   scan_section_for_cortex_a8_erratum(const elfcpp::Shdr<32, big_endian>&,
1621                                      unsigned int, Output_section*,
1622                                      Target_arm<big_endian>*);
1623
1624   // Find the linked text section of an EXIDX section by looking at the
1625   // first reloction of the EXIDX section.  PSHDR points to the section
1626   // headers of a relocation section and PSYMS points to the local symbols.
1627   // PSHNDX points to a location storing the text section index if found.
1628   // Return whether we can find the linked section.
1629   bool
1630   find_linked_text_section(const unsigned char* pshdr,
1631                            const unsigned char* psyms, unsigned int* pshndx);
1632
1633   //
1634   // Make a new Arm_exidx_input_section object for EXIDX section with
1635   // index SHNDX and section header SHDR.  TEXT_SHNDX is the section
1636   // index of the linked text section.
1637   void
1638   make_exidx_input_section(unsigned int shndx,
1639                            const elfcpp::Shdr<32, big_endian>& shdr,
1640                            unsigned int text_shndx);
1641
1642   // Return the output address of either a plain input section or a
1643   // relaxed input section.  SHNDX is the section index.
1644   Arm_address
1645   simple_input_section_output_address(unsigned int, Output_section*);
1646
1647   typedef std::vector<Stub_table<big_endian>*> Stub_table_list;
1648   typedef Unordered_map<unsigned int, const Arm_exidx_input_section*>
1649     Exidx_section_map;
1650
1651   // List of stub tables.
1652   Stub_table_list stub_tables_;
1653   // Bit vector to tell if a local symbol is a thumb function or not.
1654   // This is only valid after do_count_local_symbol is called.
1655   std::vector<bool> local_symbol_is_thumb_function_;
1656   // processor-specific flags in ELF file header.
1657   elfcpp::Elf_Word processor_specific_flags_;
1658   // Object attributes if there is an .ARM.attributes section or NULL.
1659   Attributes_section_data* attributes_section_data_;
1660   // Mapping symbols information.
1661   Mapping_symbols_info mapping_symbols_info_;
1662   // Bitmap to indicate sections with Cortex-A8 workaround or NULL.
1663   std::vector<bool>* section_has_cortex_a8_workaround_;
1664   // Map a text section to its associated .ARM.exidx section, if there is one.
1665   Exidx_section_map exidx_section_map_;
1666   // Whether output local symbol count needs updating.
1667   bool output_local_symbol_count_needs_update_;
1668 };
1669
1670 // Arm_dynobj class.
1671
1672 template<bool big_endian>
1673 class Arm_dynobj : public Sized_dynobj<32, big_endian>
1674 {
1675  public:
1676   Arm_dynobj(const std::string& name, Input_file* input_file, off_t offset,
1677              const elfcpp::Ehdr<32, big_endian>& ehdr)
1678     : Sized_dynobj<32, big_endian>(name, input_file, offset, ehdr),
1679       processor_specific_flags_(0), attributes_section_data_(NULL)
1680   { }
1681  
1682   ~Arm_dynobj()
1683   { delete this->attributes_section_data_; }
1684
1685   // Downcast a base pointer to an Arm_relobj pointer.  This is
1686   // not type-safe but we only use Arm_relobj not the base class.
1687   static Arm_dynobj<big_endian>*
1688   as_arm_dynobj(Dynobj* dynobj)
1689   { return static_cast<Arm_dynobj<big_endian>*>(dynobj); }
1690
1691   // Processor-specific flags in ELF file header.  This is valid only after
1692   // reading symbols.
1693   elfcpp::Elf_Word
1694   processor_specific_flags() const
1695   { return this->processor_specific_flags_; }
1696
1697   // Attributes section data.
1698   const Attributes_section_data*
1699   attributes_section_data() const
1700   { return this->attributes_section_data_; }
1701
1702  protected:
1703   // Read the symbol information.
1704   void
1705   do_read_symbols(Read_symbols_data* sd);
1706
1707  private:
1708   // processor-specific flags in ELF file header.
1709   elfcpp::Elf_Word processor_specific_flags_;
1710   // Object attributes if there is an .ARM.attributes section or NULL.
1711   Attributes_section_data* attributes_section_data_;
1712 };
1713
1714 // Functor to read reloc addends during stub generation.
1715
1716 template<int sh_type, bool big_endian>
1717 struct Stub_addend_reader
1718 {
1719   // Return the addend for a relocation of a particular type.  Depending
1720   // on whether this is a REL or RELA relocation, read the addend from a
1721   // view or from a Reloc object.
1722   elfcpp::Elf_types<32>::Elf_Swxword
1723   operator()(
1724     unsigned int /* r_type */,
1725     const unsigned char* /* view */,
1726     const typename Reloc_types<sh_type,
1727                                32, big_endian>::Reloc& /* reloc */) const;
1728 };
1729
1730 // Specialized Stub_addend_reader for SHT_REL type relocation sections.
1731
1732 template<bool big_endian>
1733 struct Stub_addend_reader<elfcpp::SHT_REL, big_endian>
1734 {
1735   elfcpp::Elf_types<32>::Elf_Swxword
1736   operator()(
1737     unsigned int,
1738     const unsigned char*,
1739     const typename Reloc_types<elfcpp::SHT_REL, 32, big_endian>::Reloc&) const;
1740 };
1741
1742 // Specialized Stub_addend_reader for RELA type relocation sections.
1743 // We currently do not handle RELA type relocation sections but it is trivial
1744 // to implement the addend reader.  This is provided for completeness and to
1745 // make it easier to add support for RELA relocation sections in the future.
1746
1747 template<bool big_endian>
1748 struct Stub_addend_reader<elfcpp::SHT_RELA, big_endian>
1749 {
1750   elfcpp::Elf_types<32>::Elf_Swxword
1751   operator()(
1752     unsigned int,
1753     const unsigned char*,
1754     const typename Reloc_types<elfcpp::SHT_RELA, 32,
1755                                big_endian>::Reloc& reloc) const
1756   { return reloc.get_r_addend(); }
1757 };
1758
1759 // Cortex_a8_reloc class.  We keep record of relocation that may need
1760 // the Cortex-A8 erratum workaround.
1761
1762 class Cortex_a8_reloc
1763 {
1764  public:
1765   Cortex_a8_reloc(Reloc_stub* reloc_stub, unsigned r_type,
1766                   Arm_address destination)
1767     : reloc_stub_(reloc_stub), r_type_(r_type), destination_(destination)
1768   { }
1769
1770   ~Cortex_a8_reloc()
1771   { }
1772
1773   // Accessors:  This is a read-only class.
1774   
1775   // Return the relocation stub associated with this relocation if there is
1776   // one.
1777   const Reloc_stub*
1778   reloc_stub() const
1779   { return this->reloc_stub_; } 
1780   
1781   // Return the relocation type.
1782   unsigned int
1783   r_type() const
1784   { return this->r_type_; }
1785
1786   // Return the destination address of the relocation.  LSB stores the THUMB
1787   // bit.
1788   Arm_address
1789   destination() const
1790   { return this->destination_; }
1791
1792  private:
1793   // Associated relocation stub if there is one, or NULL.
1794   const Reloc_stub* reloc_stub_;
1795   // Relocation type.
1796   unsigned int r_type_;
1797   // Destination address of this relocation.  LSB is used to distinguish
1798   // ARM/THUMB mode.
1799   Arm_address destination_;
1800 };
1801
1802 // Arm_output_data_got class.  We derive this from Output_data_got to add
1803 // extra methods to handle TLS relocations in a static link.
1804
1805 template<bool big_endian>
1806 class Arm_output_data_got : public Output_data_got<32, big_endian>
1807 {
1808  public:
1809   Arm_output_data_got(Symbol_table* symtab, Layout* layout)
1810     : Output_data_got<32, big_endian>(), symbol_table_(symtab), layout_(layout)
1811   { }
1812
1813   // Add a static entry for the GOT entry at OFFSET.  GSYM is a global
1814   // symbol and R_TYPE is the code of a dynamic relocation that needs to be
1815   // applied in a static link.
1816   void
1817   add_static_reloc(unsigned int got_offset, unsigned int r_type, Symbol* gsym)
1818   { this->static_relocs_.push_back(Static_reloc(got_offset, r_type, gsym)); }
1819
1820   // Add a static reloc for the GOT entry at OFFSET.  RELOBJ is an object
1821   // defining a local symbol with INDEX.  R_TYPE is the code of a dynamic
1822   // relocation that needs to be applied in a static link.
1823   void
1824   add_static_reloc(unsigned int got_offset, unsigned int r_type,
1825                    Sized_relobj<32, big_endian>* relobj, unsigned int index)
1826   {
1827     this->static_relocs_.push_back(Static_reloc(got_offset, r_type, relobj,
1828                                                 index));
1829   }
1830
1831   // Add a GOT pair for R_ARM_TLS_GD32.  The creates a pair of GOT entries.
1832   // The first one is initialized to be 1, which is the module index for
1833   // the main executable and the second one 0.  A reloc of the type
1834   // R_ARM_TLS_DTPOFF32 will be created for the second GOT entry and will
1835   // be applied by gold.  GSYM is a global symbol.
1836   void
1837   add_tls_gd32_with_static_reloc(unsigned int got_type, Symbol* gsym);
1838
1839   // Same as the above but for a local symbol in OBJECT with INDEX.
1840   void
1841   add_tls_gd32_with_static_reloc(unsigned int got_type,
1842                                  Sized_relobj<32, big_endian>* object,
1843                                  unsigned int index);
1844
1845  protected:
1846   // Write out the GOT table.
1847   void
1848   do_write(Output_file*);
1849
1850  private:
1851   // This class represent dynamic relocations that need to be applied by
1852   // gold because we are using TLS relocations in a static link.
1853   class Static_reloc
1854   {
1855    public:
1856     Static_reloc(unsigned int got_offset, unsigned int r_type, Symbol* gsym)
1857       : got_offset_(got_offset), r_type_(r_type), symbol_is_global_(true)
1858     { this->u_.global.symbol = gsym; }
1859
1860     Static_reloc(unsigned int got_offset, unsigned int r_type,
1861           Sized_relobj<32, big_endian>* relobj, unsigned int index)
1862       : got_offset_(got_offset), r_type_(r_type), symbol_is_global_(false)
1863     {
1864       this->u_.local.relobj = relobj;
1865       this->u_.local.index = index;
1866     }
1867
1868     // Return the GOT offset.
1869     unsigned int
1870     got_offset() const
1871     { return this->got_offset_; }
1872
1873     // Relocation type.
1874     unsigned int
1875     r_type() const
1876     { return this->r_type_; }
1877
1878     // Whether the symbol is global or not.
1879     bool
1880     symbol_is_global() const
1881     { return this->symbol_is_global_; }
1882
1883     // For a relocation against a global symbol, the global symbol.
1884     Symbol*
1885     symbol() const
1886     {
1887       gold_assert(this->symbol_is_global_);
1888       return this->u_.global.symbol;
1889     }
1890
1891     // For a relocation against a local symbol, the defining object.
1892     Sized_relobj<32, big_endian>*
1893     relobj() const
1894     {
1895       gold_assert(!this->symbol_is_global_);
1896       return this->u_.local.relobj;
1897     }
1898
1899     // For a relocation against a local symbol, the local symbol index.
1900     unsigned int
1901     index() const
1902     {
1903       gold_assert(!this->symbol_is_global_);
1904       return this->u_.local.index;
1905     }
1906
1907    private:
1908     // GOT offset of the entry to which this relocation is applied.
1909     unsigned int got_offset_;
1910     // Type of relocation.
1911     unsigned int r_type_;
1912     // Whether this relocation is against a global symbol.
1913     bool symbol_is_global_;
1914     // A global or local symbol.
1915     union
1916     {
1917       struct
1918       {
1919         // For a global symbol, the symbol itself.
1920         Symbol* symbol;
1921       } global;
1922       struct
1923       {
1924         // For a local symbol, the object defining object.
1925         Sized_relobj<32, big_endian>* relobj;
1926         // For a local symbol, the symbol index.
1927         unsigned int index;
1928       } local;
1929     } u_;
1930   };
1931
1932   // Symbol table of the output object.
1933   Symbol_table* symbol_table_;
1934   // Layout of the output object.
1935   Layout* layout_;
1936   // Static relocs to be applied to the GOT.
1937   std::vector<Static_reloc> static_relocs_;
1938 };
1939
1940 // Utilities for manipulating integers of up to 32-bits
1941
1942 namespace utils
1943 {
1944   // Sign extend an n-bit unsigned integer stored in an uint32_t into
1945   // an int32_t.  NO_BITS must be between 1 to 32.
1946   template<int no_bits>
1947   static inline int32_t
1948   sign_extend(uint32_t bits)
1949   {
1950     gold_assert(no_bits >= 0 && no_bits <= 32);
1951     if (no_bits == 32)
1952       return static_cast<int32_t>(bits);
1953     uint32_t mask = (~((uint32_t) 0)) >> (32 - no_bits);
1954     bits &= mask;
1955     uint32_t top_bit = 1U << (no_bits - 1);
1956     int32_t as_signed = static_cast<int32_t>(bits);
1957     return (bits & top_bit) ? as_signed + (-top_bit * 2) : as_signed;
1958   }
1959
1960   // Detects overflow of an NO_BITS integer stored in a uint32_t.
1961   template<int no_bits>
1962   static inline bool
1963   has_overflow(uint32_t bits)
1964   {
1965     gold_assert(no_bits >= 0 && no_bits <= 32);
1966     if (no_bits == 32)
1967       return false;
1968     int32_t max = (1 << (no_bits - 1)) - 1;
1969     int32_t min = -(1 << (no_bits - 1));
1970     int32_t as_signed = static_cast<int32_t>(bits);
1971     return as_signed > max || as_signed < min;
1972   }
1973
1974   // Detects overflow of an NO_BITS integer stored in a uint32_t when it
1975   // fits in the given number of bits as either a signed or unsigned value.
1976   // For example, has_signed_unsigned_overflow<8> would check
1977   // -128 <= bits <= 255
1978   template<int no_bits>
1979   static inline bool
1980   has_signed_unsigned_overflow(uint32_t bits)
1981   {
1982     gold_assert(no_bits >= 2 && no_bits <= 32);
1983     if (no_bits == 32)
1984       return false;
1985     int32_t max = static_cast<int32_t>((1U << no_bits) - 1);
1986     int32_t min = -(1 << (no_bits - 1));
1987     int32_t as_signed = static_cast<int32_t>(bits);
1988     return as_signed > max || as_signed < min;
1989   }
1990
1991   // Select bits from A and B using bits in MASK.  For each n in [0..31],
1992   // the n-th bit in the result is chosen from the n-th bits of A and B.
1993   // A zero selects A and a one selects B.
1994   static inline uint32_t
1995   bit_select(uint32_t a, uint32_t b, uint32_t mask)
1996   { return (a & ~mask) | (b & mask); }
1997 };
1998
1999 template<bool big_endian>
2000 class Target_arm : public Sized_target<32, big_endian>
2001 {
2002  public:
2003   typedef Output_data_reloc<elfcpp::SHT_REL, true, 32, big_endian>
2004     Reloc_section;
2005
2006   // When were are relocating a stub, we pass this as the relocation number.
2007   static const size_t fake_relnum_for_stubs = static_cast<size_t>(-1);
2008
2009   Target_arm()
2010     : Sized_target<32, big_endian>(&arm_info),
2011       got_(NULL), plt_(NULL), got_plt_(NULL), rel_dyn_(NULL),
2012       copy_relocs_(elfcpp::R_ARM_COPY), dynbss_(NULL), 
2013       got_mod_index_offset_(-1U), tls_base_symbol_defined_(false),
2014       stub_tables_(), stub_factory_(Stub_factory::get_instance()),
2015       may_use_blx_(false), should_force_pic_veneer_(false),
2016       arm_input_section_map_(), attributes_section_data_(NULL),
2017       fix_cortex_a8_(false), cortex_a8_relocs_info_()
2018   { }
2019
2020   // Whether we can use BLX.
2021   bool
2022   may_use_blx() const
2023   { return this->may_use_blx_; }
2024
2025   // Set use-BLX flag.
2026   void
2027   set_may_use_blx(bool value)
2028   { this->may_use_blx_ = value; }
2029   
2030   // Whether we force PCI branch veneers.
2031   bool
2032   should_force_pic_veneer() const
2033   { return this->should_force_pic_veneer_; }
2034
2035   // Set PIC veneer flag.
2036   void
2037   set_should_force_pic_veneer(bool value)
2038   { this->should_force_pic_veneer_ = value; }
2039   
2040   // Whether we use THUMB-2 instructions.
2041   bool
2042   using_thumb2() const
2043   {
2044     Object_attribute* attr =
2045       this->get_aeabi_object_attribute(elfcpp::Tag_CPU_arch);
2046     int arch = attr->int_value();
2047     return arch == elfcpp::TAG_CPU_ARCH_V6T2 || arch >= elfcpp::TAG_CPU_ARCH_V7;
2048   }
2049
2050   // Whether we use THUMB/THUMB-2 instructions only.
2051   bool
2052   using_thumb_only() const
2053   {
2054     Object_attribute* attr =
2055       this->get_aeabi_object_attribute(elfcpp::Tag_CPU_arch);
2056     if (attr->int_value() != elfcpp::TAG_CPU_ARCH_V7
2057         && attr->int_value() != elfcpp::TAG_CPU_ARCH_V7E_M)
2058       return false;
2059     attr = this->get_aeabi_object_attribute(elfcpp::Tag_CPU_arch_profile);
2060     return attr->int_value() == 'M';
2061   }
2062
2063   // Whether we have an NOP instruction.  If not, use mov r0, r0 instead.
2064   bool
2065   may_use_arm_nop() const
2066   {
2067     Object_attribute* attr =
2068       this->get_aeabi_object_attribute(elfcpp::Tag_CPU_arch);
2069     int arch = attr->int_value();
2070     return (arch == elfcpp::TAG_CPU_ARCH_V6T2
2071             || arch == elfcpp::TAG_CPU_ARCH_V6K
2072             || arch == elfcpp::TAG_CPU_ARCH_V7
2073             || arch == elfcpp::TAG_CPU_ARCH_V7E_M);
2074   }
2075
2076   // Whether we have THUMB-2 NOP.W instruction.
2077   bool
2078   may_use_thumb2_nop() const
2079   {
2080     Object_attribute* attr =
2081       this->get_aeabi_object_attribute(elfcpp::Tag_CPU_arch);
2082     int arch = attr->int_value();
2083     return (arch == elfcpp::TAG_CPU_ARCH_V6T2
2084             || arch == elfcpp::TAG_CPU_ARCH_V7
2085             || arch == elfcpp::TAG_CPU_ARCH_V7E_M);
2086   }
2087   
2088   // Process the relocations to determine unreferenced sections for 
2089   // garbage collection.
2090   void
2091   gc_process_relocs(Symbol_table* symtab,
2092                     Layout* layout,
2093                     Sized_relobj<32, big_endian>* object,
2094                     unsigned int data_shndx,
2095                     unsigned int sh_type,
2096                     const unsigned char* prelocs,
2097                     size_t reloc_count,
2098                     Output_section* output_section,
2099                     bool needs_special_offset_handling,
2100                     size_t local_symbol_count,
2101                     const unsigned char* plocal_symbols);
2102
2103   // Scan the relocations to look for symbol adjustments.
2104   void
2105   scan_relocs(Symbol_table* symtab,
2106               Layout* layout,
2107               Sized_relobj<32, big_endian>* object,
2108               unsigned int data_shndx,
2109               unsigned int sh_type,
2110               const unsigned char* prelocs,
2111               size_t reloc_count,
2112               Output_section* output_section,
2113               bool needs_special_offset_handling,
2114               size_t local_symbol_count,
2115               const unsigned char* plocal_symbols);
2116
2117   // Finalize the sections.
2118   void
2119   do_finalize_sections(Layout*, const Input_objects*, Symbol_table*);
2120
2121   // Return the value to use for a dynamic symbol which requires special
2122   // treatment.
2123   uint64_t
2124   do_dynsym_value(const Symbol*) const;
2125
2126   // Relocate a section.
2127   void
2128   relocate_section(const Relocate_info<32, big_endian>*,
2129                    unsigned int sh_type,
2130                    const unsigned char* prelocs,
2131                    size_t reloc_count,
2132                    Output_section* output_section,
2133                    bool needs_special_offset_handling,
2134                    unsigned char* view,
2135                    Arm_address view_address,
2136                    section_size_type view_size,
2137                    const Reloc_symbol_changes*);
2138
2139   // Scan the relocs during a relocatable link.
2140   void
2141   scan_relocatable_relocs(Symbol_table* symtab,
2142                           Layout* layout,
2143                           Sized_relobj<32, big_endian>* object,
2144                           unsigned int data_shndx,
2145                           unsigned int sh_type,
2146                           const unsigned char* prelocs,
2147                           size_t reloc_count,
2148                           Output_section* output_section,
2149                           bool needs_special_offset_handling,
2150                           size_t local_symbol_count,
2151                           const unsigned char* plocal_symbols,
2152                           Relocatable_relocs*);
2153
2154   // Relocate a section during a relocatable link.
2155   void
2156   relocate_for_relocatable(const Relocate_info<32, big_endian>*,
2157                            unsigned int sh_type,
2158                            const unsigned char* prelocs,
2159                            size_t reloc_count,
2160                            Output_section* output_section,
2161                            off_t offset_in_output_section,
2162                            const Relocatable_relocs*,
2163                            unsigned char* view,
2164                            Arm_address view_address,
2165                            section_size_type view_size,
2166                            unsigned char* reloc_view,
2167                            section_size_type reloc_view_size);
2168
2169   // Return whether SYM is defined by the ABI.
2170   bool
2171   do_is_defined_by_abi(Symbol* sym) const
2172   { return strcmp(sym->name(), "__tls_get_addr") == 0; }
2173
2174   // Return whether there is a GOT section.
2175   bool
2176   has_got_section() const
2177   { return this->got_ != NULL; }
2178
2179   // Return the size of the GOT section.
2180   section_size_type
2181   got_size()
2182   {
2183     gold_assert(this->got_ != NULL);
2184     return this->got_->data_size();
2185   }
2186
2187   // Map platform-specific reloc types
2188   static unsigned int
2189   get_real_reloc_type (unsigned int r_type);
2190
2191   //
2192   // Methods to support stub-generations.
2193   //
2194   
2195   // Return the stub factory
2196   const Stub_factory&
2197   stub_factory() const
2198   { return this->stub_factory_; }
2199
2200   // Make a new Arm_input_section object.
2201   Arm_input_section<big_endian>*
2202   new_arm_input_section(Relobj*, unsigned int);
2203
2204   // Find the Arm_input_section object corresponding to the SHNDX-th input
2205   // section of RELOBJ.
2206   Arm_input_section<big_endian>*
2207   find_arm_input_section(Relobj* relobj, unsigned int shndx) const;
2208
2209   // Make a new Stub_table
2210   Stub_table<big_endian>*
2211   new_stub_table(Arm_input_section<big_endian>*);
2212
2213   // Scan a section for stub generation.
2214   void
2215   scan_section_for_stubs(const Relocate_info<32, big_endian>*, unsigned int,
2216                          const unsigned char*, size_t, Output_section*,
2217                          bool, const unsigned char*, Arm_address,
2218                          section_size_type);
2219
2220   // Relocate a stub. 
2221   void
2222   relocate_stub(Stub*, const Relocate_info<32, big_endian>*,
2223                 Output_section*, unsigned char*, Arm_address,
2224                 section_size_type);
2225  
2226   // Get the default ARM target.
2227   static Target_arm<big_endian>*
2228   default_target()
2229   {
2230     gold_assert(parameters->target().machine_code() == elfcpp::EM_ARM
2231                 && parameters->target().is_big_endian() == big_endian);
2232     return static_cast<Target_arm<big_endian>*>(
2233              parameters->sized_target<32, big_endian>());
2234   }
2235
2236   // Whether NAME belongs to a mapping symbol.
2237   static bool
2238   is_mapping_symbol_name(const char* name)
2239   {
2240     return (name
2241             && name[0] == '$'
2242             && (name[1] == 'a' || name[1] == 't' || name[1] == 'd')
2243             && (name[2] == '\0' || name[2] == '.'));
2244   }
2245
2246   // Whether we work around the Cortex-A8 erratum.
2247   bool
2248   fix_cortex_a8() const
2249   { return this->fix_cortex_a8_; }
2250
2251   // Whether we fix R_ARM_V4BX relocation.
2252   // 0 - do not fix
2253   // 1 - replace with MOV instruction (armv4 target)
2254   // 2 - make interworking veneer (>= armv4t targets only)
2255   General_options::Fix_v4bx
2256   fix_v4bx() const
2257   { return parameters->options().fix_v4bx(); }
2258
2259   // Scan a span of THUMB code section for Cortex-A8 erratum.
2260   void
2261   scan_span_for_cortex_a8_erratum(Arm_relobj<big_endian>*, unsigned int,
2262                                   section_size_type, section_size_type,
2263                                   const unsigned char*, Arm_address);
2264
2265   // Apply Cortex-A8 workaround to a branch.
2266   void
2267   apply_cortex_a8_workaround(const Cortex_a8_stub*, Arm_address,
2268                              unsigned char*, Arm_address);
2269
2270  protected:
2271   // Make an ELF object.
2272   Object*
2273   do_make_elf_object(const std::string&, Input_file*, off_t,
2274                      const elfcpp::Ehdr<32, big_endian>& ehdr);
2275
2276   Object*
2277   do_make_elf_object(const std::string&, Input_file*, off_t,
2278                      const elfcpp::Ehdr<32, !big_endian>&)
2279   { gold_unreachable(); }
2280
2281   Object*
2282   do_make_elf_object(const std::string&, Input_file*, off_t,
2283                       const elfcpp::Ehdr<64, false>&)
2284   { gold_unreachable(); }
2285
2286   Object*
2287   do_make_elf_object(const std::string&, Input_file*, off_t,
2288                      const elfcpp::Ehdr<64, true>&)
2289   { gold_unreachable(); }
2290
2291   // Make an output section.
2292   Output_section*
2293   do_make_output_section(const char* name, elfcpp::Elf_Word type,
2294                          elfcpp::Elf_Xword flags)
2295   { return new Arm_output_section<big_endian>(name, type, flags); }
2296
2297   void
2298   do_adjust_elf_header(unsigned char* view, int len) const;
2299
2300   // We only need to generate stubs, and hence perform relaxation if we are
2301   // not doing relocatable linking.
2302   bool
2303   do_may_relax() const
2304   { return !parameters->options().relocatable(); }
2305
2306   bool
2307   do_relax(int, const Input_objects*, Symbol_table*, Layout*);
2308
2309   // Determine whether an object attribute tag takes an integer, a
2310   // string or both.
2311   int
2312   do_attribute_arg_type(int tag) const;
2313
2314   // Reorder tags during output.
2315   int
2316   do_attributes_order(int num) const;
2317
2318   // This is called when the target is selected as the default.
2319   void
2320   do_select_as_default_target()
2321   {
2322     // No locking is required since there should only be one default target.
2323     // We cannot have both the big-endian and little-endian ARM targets
2324     // as the default.
2325     gold_assert(arm_reloc_property_table == NULL);
2326     arm_reloc_property_table = new Arm_reloc_property_table();
2327   }
2328
2329  private:
2330   // The class which scans relocations.
2331   class Scan
2332   {
2333    public:
2334     Scan()
2335       : issued_non_pic_error_(false)
2336     { }
2337
2338     inline void
2339     local(Symbol_table* symtab, Layout* layout, Target_arm* target,
2340           Sized_relobj<32, big_endian>* object,
2341           unsigned int data_shndx,
2342           Output_section* output_section,
2343           const elfcpp::Rel<32, big_endian>& reloc, unsigned int r_type,
2344           const elfcpp::Sym<32, big_endian>& lsym);
2345
2346     inline void
2347     global(Symbol_table* symtab, Layout* layout, Target_arm* target,
2348            Sized_relobj<32, big_endian>* object,
2349            unsigned int data_shndx,
2350            Output_section* output_section,
2351            const elfcpp::Rel<32, big_endian>& reloc, unsigned int r_type,
2352            Symbol* gsym);
2353
2354     inline bool
2355     local_reloc_may_be_function_pointer(Symbol_table* , Layout* , Target_arm* ,
2356                                         Sized_relobj<32, big_endian>* ,
2357                                         unsigned int ,
2358                                         Output_section* ,
2359                                         const elfcpp::Rel<32, big_endian>& ,
2360                                         unsigned int ,
2361                                         const elfcpp::Sym<32, big_endian>&)
2362     { return false; }
2363
2364     inline bool
2365     global_reloc_may_be_function_pointer(Symbol_table* , Layout* , Target_arm* ,
2366                                          Sized_relobj<32, big_endian>* ,
2367                                          unsigned int ,
2368                                          Output_section* ,
2369                                          const elfcpp::Rel<32, big_endian>& ,
2370                                          unsigned int , Symbol*)
2371     { return false; }
2372
2373    private:
2374     static void
2375     unsupported_reloc_local(Sized_relobj<32, big_endian>*,
2376                             unsigned int r_type);
2377
2378     static void
2379     unsupported_reloc_global(Sized_relobj<32, big_endian>*,
2380                              unsigned int r_type, Symbol*);
2381
2382     void
2383     check_non_pic(Relobj*, unsigned int r_type);
2384
2385     // Almost identical to Symbol::needs_plt_entry except that it also
2386     // handles STT_ARM_TFUNC.
2387     static bool
2388     symbol_needs_plt_entry(const Symbol* sym)
2389     {
2390       // An undefined symbol from an executable does not need a PLT entry.
2391       if (sym->is_undefined() && !parameters->options().shared())
2392         return false;
2393
2394       return (!parameters->doing_static_link()
2395               && (sym->type() == elfcpp::STT_FUNC
2396                   || sym->type() == elfcpp::STT_ARM_TFUNC)
2397               && (sym->is_from_dynobj()
2398                   || sym->is_undefined()
2399                   || sym->is_preemptible()));
2400     }
2401
2402     // Whether we have issued an error about a non-PIC compilation.
2403     bool issued_non_pic_error_;
2404   };
2405
2406   // The class which implements relocation.
2407   class Relocate
2408   {
2409    public:
2410     Relocate()
2411     { }
2412
2413     ~Relocate()
2414     { }
2415
2416     // Return whether the static relocation needs to be applied.
2417     inline bool
2418     should_apply_static_reloc(const Sized_symbol<32>* gsym,
2419                               int ref_flags,
2420                               bool is_32bit,
2421                               Output_section* output_section);
2422
2423     // Do a relocation.  Return false if the caller should not issue
2424     // any warnings about this relocation.
2425     inline bool
2426     relocate(const Relocate_info<32, big_endian>*, Target_arm*,
2427              Output_section*,  size_t relnum,
2428              const elfcpp::Rel<32, big_endian>&,
2429              unsigned int r_type, const Sized_symbol<32>*,
2430              const Symbol_value<32>*,
2431              unsigned char*, Arm_address,
2432              section_size_type);
2433
2434     // Return whether we want to pass flag NON_PIC_REF for this
2435     // reloc.  This means the relocation type accesses a symbol not via
2436     // GOT or PLT.
2437     static inline bool
2438     reloc_is_non_pic (unsigned int r_type)
2439     {
2440       switch (r_type)
2441         {
2442         // These relocation types reference GOT or PLT entries explicitly.
2443         case elfcpp::R_ARM_GOT_BREL:
2444         case elfcpp::R_ARM_GOT_ABS:
2445         case elfcpp::R_ARM_GOT_PREL:
2446         case elfcpp::R_ARM_GOT_BREL12:
2447         case elfcpp::R_ARM_PLT32_ABS:
2448         case elfcpp::R_ARM_TLS_GD32:
2449         case elfcpp::R_ARM_TLS_LDM32:
2450         case elfcpp::R_ARM_TLS_IE32:
2451         case elfcpp::R_ARM_TLS_IE12GP:
2452
2453         // These relocate types may use PLT entries.
2454         case elfcpp::R_ARM_CALL:
2455         case elfcpp::R_ARM_THM_CALL:
2456         case elfcpp::R_ARM_JUMP24:
2457         case elfcpp::R_ARM_THM_JUMP24:
2458         case elfcpp::R_ARM_THM_JUMP19:
2459         case elfcpp::R_ARM_PLT32:
2460         case elfcpp::R_ARM_THM_XPC22:
2461         case elfcpp::R_ARM_PREL31:
2462         case elfcpp::R_ARM_SBREL31:
2463           return false;
2464
2465         default:
2466           return true;
2467         }
2468     }
2469
2470    private:
2471     // Do a TLS relocation.
2472     inline typename Arm_relocate_functions<big_endian>::Status
2473     relocate_tls(const Relocate_info<32, big_endian>*, Target_arm<big_endian>*,
2474                  size_t, const elfcpp::Rel<32, big_endian>&, unsigned int,
2475                  const Sized_symbol<32>*, const Symbol_value<32>*,
2476                  unsigned char*, elfcpp::Elf_types<32>::Elf_Addr,
2477                  section_size_type);
2478
2479   };
2480
2481   // A class which returns the size required for a relocation type,
2482   // used while scanning relocs during a relocatable link.
2483   class Relocatable_size_for_reloc
2484   {
2485    public:
2486     unsigned int
2487     get_size_for_reloc(unsigned int, Relobj*);
2488   };
2489
2490   // Adjust TLS relocation type based on the options and whether this
2491   // is a local symbol.
2492   static tls::Tls_optimization
2493   optimize_tls_reloc(bool is_final, int r_type);
2494
2495   // Get the GOT section, creating it if necessary.
2496   Arm_output_data_got<big_endian>*
2497   got_section(Symbol_table*, Layout*);
2498
2499   // Get the GOT PLT section.
2500   Output_data_space*
2501   got_plt_section() const
2502   {
2503     gold_assert(this->got_plt_ != NULL);
2504     return this->got_plt_;
2505   }
2506
2507   // Create a PLT entry for a global symbol.
2508   void
2509   make_plt_entry(Symbol_table*, Layout*, Symbol*);
2510
2511   // Define the _TLS_MODULE_BASE_ symbol in the TLS segment.
2512   void
2513   define_tls_base_symbol(Symbol_table*, Layout*);
2514
2515   // Create a GOT entry for the TLS module index.
2516   unsigned int
2517   got_mod_index_entry(Symbol_table* symtab, Layout* layout,
2518                       Sized_relobj<32, big_endian>* object);
2519
2520   // Get the PLT section.
2521   const Output_data_plt_arm<big_endian>*
2522   plt_section() const
2523   {
2524     gold_assert(this->plt_ != NULL);
2525     return this->plt_;
2526   }
2527
2528   // Get the dynamic reloc section, creating it if necessary.
2529   Reloc_section*
2530   rel_dyn_section(Layout*);
2531
2532   // Get the section to use for TLS_DESC relocations.
2533   Reloc_section*
2534   rel_tls_desc_section(Layout*) const;
2535
2536   // Return true if the symbol may need a COPY relocation.
2537   // References from an executable object to non-function symbols
2538   // defined in a dynamic object may need a COPY relocation.
2539   bool
2540   may_need_copy_reloc(Symbol* gsym)
2541   {
2542     return (gsym->type() != elfcpp::STT_ARM_TFUNC
2543             && gsym->may_need_copy_reloc());
2544   }
2545
2546   // Add a potential copy relocation.
2547   void
2548   copy_reloc(Symbol_table* symtab, Layout* layout,
2549              Sized_relobj<32, big_endian>* object,
2550              unsigned int shndx, Output_section* output_section,
2551              Symbol* sym, const elfcpp::Rel<32, big_endian>& reloc)
2552   {
2553     this->copy_relocs_.copy_reloc(symtab, layout,
2554                                   symtab->get_sized_symbol<32>(sym),
2555                                   object, shndx, output_section, reloc,
2556                                   this->rel_dyn_section(layout));
2557   }
2558
2559   // Whether two EABI versions are compatible.
2560   static bool
2561   are_eabi_versions_compatible(elfcpp::Elf_Word v1, elfcpp::Elf_Word v2);
2562
2563   // Merge processor-specific flags from input object and those in the ELF
2564   // header of the output.
2565   void
2566   merge_processor_specific_flags(const std::string&, elfcpp::Elf_Word);
2567
2568   // Get the secondary compatible architecture.
2569   static int
2570   get_secondary_compatible_arch(const Attributes_section_data*);
2571
2572   // Set the secondary compatible architecture.
2573   static void
2574   set_secondary_compatible_arch(Attributes_section_data*, int);
2575
2576   static int
2577   tag_cpu_arch_combine(const char*, int, int*, int, int);
2578
2579   // Helper to print AEABI enum tag value.
2580   static std::string
2581   aeabi_enum_name(unsigned int);
2582
2583   // Return string value for TAG_CPU_name.
2584   static std::string
2585   tag_cpu_name_value(unsigned int);
2586
2587   // Merge object attributes from input object and those in the output.
2588   void
2589   merge_object_attributes(const char*, const Attributes_section_data*);
2590
2591   // Helper to get an AEABI object attribute
2592   Object_attribute*
2593   get_aeabi_object_attribute(int tag) const
2594   {
2595     Attributes_section_data* pasd = this->attributes_section_data_;
2596     gold_assert(pasd != NULL);
2597     Object_attribute* attr =
2598       pasd->get_attribute(Object_attribute::OBJ_ATTR_PROC, tag);
2599     gold_assert(attr != NULL);
2600     return attr;
2601   }
2602
2603   //
2604   // Methods to support stub-generations.
2605   //
2606
2607   // Group input sections for stub generation.
2608   void
2609   group_sections(Layout*, section_size_type, bool);
2610
2611   // Scan a relocation for stub generation.
2612   void
2613   scan_reloc_for_stub(const Relocate_info<32, big_endian>*, unsigned int,
2614                       const Sized_symbol<32>*, unsigned int,
2615                       const Symbol_value<32>*,
2616                       elfcpp::Elf_types<32>::Elf_Swxword, Arm_address);
2617
2618   // Scan a relocation section for stub.
2619   template<int sh_type>
2620   void
2621   scan_reloc_section_for_stubs(
2622       const Relocate_info<32, big_endian>* relinfo,
2623       const unsigned char* prelocs,
2624       size_t reloc_count,
2625       Output_section* output_section,
2626       bool needs_special_offset_handling,
2627       const unsigned char* view,
2628       elfcpp::Elf_types<32>::Elf_Addr view_address,
2629       section_size_type);
2630
2631   // Fix .ARM.exidx section coverage.
2632   void
2633   fix_exidx_coverage(Layout*, Arm_output_section<big_endian>*, Symbol_table*);
2634
2635   // Functors for STL set.
2636   struct output_section_address_less_than
2637   {
2638     bool
2639     operator()(const Output_section* s1, const Output_section* s2) const
2640     { return s1->address() < s2->address(); }
2641   };
2642
2643   // Information about this specific target which we pass to the
2644   // general Target structure.
2645   static const Target::Target_info arm_info;
2646
2647   // The types of GOT entries needed for this platform.
2648   enum Got_type
2649   {
2650     GOT_TYPE_STANDARD = 0,      // GOT entry for a regular symbol
2651     GOT_TYPE_TLS_NOFFSET = 1,   // GOT entry for negative TLS offset
2652     GOT_TYPE_TLS_OFFSET = 2,    // GOT entry for positive TLS offset
2653     GOT_TYPE_TLS_PAIR = 3,      // GOT entry for TLS module/offset pair
2654     GOT_TYPE_TLS_DESC = 4       // GOT entry for TLS_DESC pair
2655   };
2656
2657   typedef typename std::vector<Stub_table<big_endian>*> Stub_table_list;
2658
2659   // Map input section to Arm_input_section.
2660   typedef Unordered_map<Section_id,
2661                         Arm_input_section<big_endian>*,
2662                         Section_id_hash>
2663           Arm_input_section_map;
2664     
2665   // Map output addresses to relocs for Cortex-A8 erratum.
2666   typedef Unordered_map<Arm_address, const Cortex_a8_reloc*>
2667           Cortex_a8_relocs_info;
2668
2669   // The GOT section.
2670   Arm_output_data_got<big_endian>* got_;
2671   // The PLT section.
2672   Output_data_plt_arm<big_endian>* plt_;
2673   // The GOT PLT section.
2674   Output_data_space* got_plt_;
2675   // The dynamic reloc section.
2676   Reloc_section* rel_dyn_;
2677   // Relocs saved to avoid a COPY reloc.
2678   Copy_relocs<elfcpp::SHT_REL, 32, big_endian> copy_relocs_;
2679   // Space for variables copied with a COPY reloc.
2680   Output_data_space* dynbss_;
2681   // Offset of the GOT entry for the TLS module index.
2682   unsigned int got_mod_index_offset_;
2683   // True if the _TLS_MODULE_BASE_ symbol has been defined.
2684   bool tls_base_symbol_defined_;
2685   // Vector of Stub_tables created.
2686   Stub_table_list stub_tables_;
2687   // Stub factory.
2688   const Stub_factory &stub_factory_;
2689   // Whether we can use BLX.
2690   bool may_use_blx_;
2691   // Whether we force PIC branch veneers.
2692   bool should_force_pic_veneer_;
2693   // Map for locating Arm_input_sections.
2694   Arm_input_section_map arm_input_section_map_;
2695   // Attributes section data in output.
2696   Attributes_section_data* attributes_section_data_;
2697   // Whether we want to fix code for Cortex-A8 erratum.
2698   bool fix_cortex_a8_;
2699   // Map addresses to relocs for Cortex-A8 erratum.
2700   Cortex_a8_relocs_info cortex_a8_relocs_info_;
2701 };
2702
2703 template<bool big_endian>
2704 const Target::Target_info Target_arm<big_endian>::arm_info =
2705 {
2706   32,                   // size
2707   big_endian,           // is_big_endian
2708   elfcpp::EM_ARM,       // machine_code
2709   false,                // has_make_symbol
2710   false,                // has_resolve
2711   false,                // has_code_fill
2712   true,                 // is_default_stack_executable
2713   '\0',                 // wrap_char
2714   "/usr/lib/libc.so.1", // dynamic_linker
2715   0x8000,               // default_text_segment_address
2716   0x1000,               // abi_pagesize (overridable by -z max-page-size)
2717   0x1000,               // common_pagesize (overridable by -z common-page-size)
2718   elfcpp::SHN_UNDEF,    // small_common_shndx
2719   elfcpp::SHN_UNDEF,    // large_common_shndx
2720   0,                    // small_common_section_flags
2721   0,                    // large_common_section_flags
2722   ".ARM.attributes",    // attributes_section
2723   "aeabi"               // attributes_vendor
2724 };
2725
2726 // Arm relocate functions class
2727 //
2728
2729 template<bool big_endian>
2730 class Arm_relocate_functions : public Relocate_functions<32, big_endian>
2731 {
2732  public:
2733   typedef enum
2734   {
2735     STATUS_OKAY,        // No error during relocation.
2736     STATUS_OVERFLOW,    // Relocation oveflow.
2737     STATUS_BAD_RELOC    // Relocation cannot be applied.
2738   } Status;
2739
2740  private:
2741   typedef Relocate_functions<32, big_endian> Base;
2742   typedef Arm_relocate_functions<big_endian> This;
2743
2744   // Encoding of imm16 argument for movt and movw ARM instructions
2745   // from ARM ARM:
2746   //     
2747   //     imm16 := imm4 | imm12
2748   //
2749   //  f e d c b a 9 8 7 6 5 4 3 2 1 0 f e d c b a 9 8 7 6 5 4 3 2 1 0 
2750   // +-------+---------------+-------+-------+-----------------------+
2751   // |       |               |imm4   |       |imm12                  |
2752   // +-------+---------------+-------+-------+-----------------------+
2753
2754   // Extract the relocation addend from VAL based on the ARM
2755   // instruction encoding described above.
2756   static inline typename elfcpp::Swap<32, big_endian>::Valtype
2757   extract_arm_movw_movt_addend(
2758       typename elfcpp::Swap<32, big_endian>::Valtype val)
2759   {
2760     // According to the Elf ABI for ARM Architecture the immediate
2761     // field is sign-extended to form the addend.
2762     return utils::sign_extend<16>(((val >> 4) & 0xf000) | (val & 0xfff));
2763   }
2764
2765   // Insert X into VAL based on the ARM instruction encoding described
2766   // above.
2767   static inline typename elfcpp::Swap<32, big_endian>::Valtype
2768   insert_val_arm_movw_movt(
2769       typename elfcpp::Swap<32, big_endian>::Valtype val,
2770       typename elfcpp::Swap<32, big_endian>::Valtype x)
2771   {
2772     val &= 0xfff0f000;
2773     val |= x & 0x0fff;
2774     val |= (x & 0xf000) << 4;
2775     return val;
2776   }
2777
2778   // Encoding of imm16 argument for movt and movw Thumb2 instructions
2779   // from ARM ARM:
2780   //     
2781   //     imm16 := imm4 | i | imm3 | imm8
2782   //
2783   //  f e d c b a 9 8 7 6 5 4 3 2 1 0  f e d c b a 9 8 7 6 5 4 3 2 1 0 
2784   // +---------+-+-----------+-------++-+-----+-------+---------------+
2785   // |         |i|           |imm4   || |imm3 |       |imm8           |
2786   // +---------+-+-----------+-------++-+-----+-------+---------------+
2787
2788   // Extract the relocation addend from VAL based on the Thumb2
2789   // instruction encoding described above.
2790   static inline typename elfcpp::Swap<32, big_endian>::Valtype
2791   extract_thumb_movw_movt_addend(
2792       typename elfcpp::Swap<32, big_endian>::Valtype val)
2793   {
2794     // According to the Elf ABI for ARM Architecture the immediate
2795     // field is sign-extended to form the addend.
2796     return utils::sign_extend<16>(((val >> 4) & 0xf000)
2797                                   | ((val >> 15) & 0x0800)
2798                                   | ((val >> 4) & 0x0700)
2799                                   | (val & 0x00ff));
2800   }
2801
2802   // Insert X into VAL based on the Thumb2 instruction encoding
2803   // described above.
2804   static inline typename elfcpp::Swap<32, big_endian>::Valtype
2805   insert_val_thumb_movw_movt(
2806       typename elfcpp::Swap<32, big_endian>::Valtype val,
2807       typename elfcpp::Swap<32, big_endian>::Valtype x)
2808   {
2809     val &= 0xfbf08f00;
2810     val |= (x & 0xf000) << 4;
2811     val |= (x & 0x0800) << 15;
2812     val |= (x & 0x0700) << 4;
2813     val |= (x & 0x00ff);
2814     return val;
2815   }
2816
2817   // Calculate the smallest constant Kn for the specified residual.
2818   // (see (AAELF 4.6.1.4 Static ARM relocations, Group Relocations, p.32)
2819   static uint32_t
2820   calc_grp_kn(typename elfcpp::Swap<32, big_endian>::Valtype residual)
2821   {
2822     int32_t msb;
2823
2824     if (residual == 0)
2825       return 0;
2826     // Determine the most significant bit in the residual and
2827     // align the resulting value to a 2-bit boundary.
2828     for (msb = 30; (msb >= 0) && !(residual & (3 << msb)); msb -= 2)
2829       ;
2830     // The desired shift is now (msb - 6), or zero, whichever
2831     // is the greater.
2832     return (((msb - 6) < 0) ? 0 : (msb - 6));
2833   }
2834
2835   // Calculate the final residual for the specified group index.
2836   // If the passed group index is less than zero, the method will return
2837   // the value of the specified residual without any change.
2838   // (see (AAELF 4.6.1.4 Static ARM relocations, Group Relocations, p.32)
2839   static typename elfcpp::Swap<32, big_endian>::Valtype
2840   calc_grp_residual(typename elfcpp::Swap<32, big_endian>::Valtype residual,
2841                     const int group)
2842   {
2843     for (int n = 0; n <= group; n++)
2844       {
2845         // Calculate which part of the value to mask.
2846         uint32_t shift = calc_grp_kn(residual);
2847         // Calculate the residual for the next time around.
2848         residual &= ~(residual & (0xff << shift));
2849       }
2850
2851     return residual;
2852   }
2853
2854   // Calculate the value of Gn for the specified group index.
2855   // We return it in the form of an encoded constant-and-rotation.
2856   // (see (AAELF 4.6.1.4 Static ARM relocations, Group Relocations, p.32)
2857   static typename elfcpp::Swap<32, big_endian>::Valtype
2858   calc_grp_gn(typename elfcpp::Swap<32, big_endian>::Valtype residual,
2859               const int group)
2860   {
2861     typename elfcpp::Swap<32, big_endian>::Valtype gn = 0;
2862     uint32_t shift = 0;
2863
2864     for (int n = 0; n <= group; n++)
2865       {
2866         // Calculate which part of the value to mask.
2867         shift = calc_grp_kn(residual);
2868         // Calculate Gn in 32-bit as well as encoded constant-and-rotation form.
2869         gn = residual & (0xff << shift);
2870         // Calculate the residual for the next time around.
2871         residual &= ~gn;
2872       }
2873     // Return Gn in the form of an encoded constant-and-rotation.
2874     return ((gn >> shift) | ((gn <= 0xff ? 0 : (32 - shift) / 2) << 8));
2875   }
2876
2877  public:
2878   // Handle ARM long branches.
2879   static typename This::Status
2880   arm_branch_common(unsigned int, const Relocate_info<32, big_endian>*,
2881                     unsigned char *, const Sized_symbol<32>*,
2882                     const Arm_relobj<big_endian>*, unsigned int,
2883                     const Symbol_value<32>*, Arm_address, Arm_address, bool);
2884
2885   // Handle THUMB long branches.
2886   static typename This::Status
2887   thumb_branch_common(unsigned int, const Relocate_info<32, big_endian>*,
2888                       unsigned char *, const Sized_symbol<32>*,
2889                       const Arm_relobj<big_endian>*, unsigned int,
2890                       const Symbol_value<32>*, Arm_address, Arm_address, bool);
2891
2892
2893   // Return the branch offset of a 32-bit THUMB branch.
2894   static inline int32_t
2895   thumb32_branch_offset(uint16_t upper_insn, uint16_t lower_insn)
2896   {
2897     // We use the Thumb-2 encoding (backwards compatible with Thumb-1)
2898     // involving the J1 and J2 bits.
2899     uint32_t s = (upper_insn & (1U << 10)) >> 10;
2900     uint32_t upper = upper_insn & 0x3ffU;
2901     uint32_t lower = lower_insn & 0x7ffU;
2902     uint32_t j1 = (lower_insn & (1U << 13)) >> 13;
2903     uint32_t j2 = (lower_insn & (1U << 11)) >> 11;
2904     uint32_t i1 = j1 ^ s ? 0 : 1;
2905     uint32_t i2 = j2 ^ s ? 0 : 1;
2906
2907     return utils::sign_extend<25>((s << 24) | (i1 << 23) | (i2 << 22)
2908                                   | (upper << 12) | (lower << 1));
2909   }
2910
2911   // Insert OFFSET to a 32-bit THUMB branch and return the upper instruction.
2912   // UPPER_INSN is the original upper instruction of the branch.  Caller is
2913   // responsible for overflow checking and BLX offset adjustment.
2914   static inline uint16_t
2915   thumb32_branch_upper(uint16_t upper_insn, int32_t offset)
2916   {
2917     uint32_t s = offset < 0 ? 1 : 0;
2918     uint32_t bits = static_cast<uint32_t>(offset);
2919     return (upper_insn & ~0x7ffU) | ((bits >> 12) & 0x3ffU) | (s << 10);
2920   }
2921
2922   // Insert OFFSET to a 32-bit THUMB branch and return the lower instruction.
2923   // LOWER_INSN is the original lower instruction of the branch.  Caller is
2924   // responsible for overflow checking and BLX offset adjustment.
2925   static inline uint16_t
2926   thumb32_branch_lower(uint16_t lower_insn, int32_t offset)
2927   {
2928     uint32_t s = offset < 0 ? 1 : 0;
2929     uint32_t bits = static_cast<uint32_t>(offset);
2930     return ((lower_insn & ~0x2fffU)
2931             | ((((bits >> 23) & 1) ^ !s) << 13)
2932             | ((((bits >> 22) & 1) ^ !s) << 11)
2933             | ((bits >> 1) & 0x7ffU));
2934   }
2935
2936   // Return the branch offset of a 32-bit THUMB conditional branch.
2937   static inline int32_t
2938   thumb32_cond_branch_offset(uint16_t upper_insn, uint16_t lower_insn)
2939   {
2940     uint32_t s = (upper_insn & 0x0400U) >> 10;
2941     uint32_t j1 = (lower_insn & 0x2000U) >> 13;
2942     uint32_t j2 = (lower_insn & 0x0800U) >> 11;
2943     uint32_t lower = (lower_insn & 0x07ffU);
2944     uint32_t upper = (s << 8) | (j2 << 7) | (j1 << 6) | (upper_insn & 0x003fU);
2945
2946     return utils::sign_extend<21>((upper << 12) | (lower << 1));
2947   }
2948
2949   // Insert OFFSET to a 32-bit THUMB conditional branch and return the upper
2950   // instruction.  UPPER_INSN is the original upper instruction of the branch.
2951   // Caller is responsible for overflow checking.
2952   static inline uint16_t
2953   thumb32_cond_branch_upper(uint16_t upper_insn, int32_t offset)
2954   {
2955     uint32_t s = offset < 0 ? 1 : 0;
2956     uint32_t bits = static_cast<uint32_t>(offset);
2957     return (upper_insn & 0xfbc0U) | (s << 10) | ((bits & 0x0003f000U) >> 12);
2958   }
2959
2960   // Insert OFFSET to a 32-bit THUMB conditional branch and return the lower
2961   // instruction.  LOWER_INSN is the original lower instruction of the branch.
2962   // Caller is reponsible for overflow checking.
2963   static inline uint16_t
2964   thumb32_cond_branch_lower(uint16_t lower_insn, int32_t offset)
2965   {
2966     uint32_t bits = static_cast<uint32_t>(offset);
2967     uint32_t j2 = (bits & 0x00080000U) >> 19;
2968     uint32_t j1 = (bits & 0x00040000U) >> 18;
2969     uint32_t lo = (bits & 0x00000ffeU) >> 1;
2970
2971     return (lower_insn & 0xd000U) | (j1 << 13) | (j2 << 11) | lo;
2972   }
2973
2974   // R_ARM_ABS8: S + A
2975   static inline typename This::Status
2976   abs8(unsigned char *view,
2977        const Sized_relobj<32, big_endian>* object,
2978        const Symbol_value<32>* psymval)
2979   {
2980     typedef typename elfcpp::Swap<8, big_endian>::Valtype Valtype;
2981     typedef typename elfcpp::Swap<32, big_endian>::Valtype Reltype;
2982     Valtype* wv = reinterpret_cast<Valtype*>(view);
2983     Valtype val = elfcpp::Swap<8, big_endian>::readval(wv);
2984     Reltype addend = utils::sign_extend<8>(val);
2985     Reltype x = psymval->value(object, addend);
2986     val = utils::bit_select(val, x, 0xffU);
2987     elfcpp::Swap<8, big_endian>::writeval(wv, val);
2988     return (utils::has_signed_unsigned_overflow<8>(x)
2989             ? This::STATUS_OVERFLOW
2990             : This::STATUS_OKAY);
2991   }
2992
2993   // R_ARM_THM_ABS5: S + A
2994   static inline typename This::Status
2995   thm_abs5(unsigned char *view,
2996        const Sized_relobj<32, big_endian>* object,
2997        const Symbol_value<32>* psymval)
2998   {
2999     typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
3000     typedef typename elfcpp::Swap<32, big_endian>::Valtype Reltype;
3001     Valtype* wv = reinterpret_cast<Valtype*>(view);
3002     Valtype val = elfcpp::Swap<16, big_endian>::readval(wv);
3003     Reltype addend = (val & 0x7e0U) >> 6;
3004     Reltype x = psymval->value(object, addend);
3005     val = utils::bit_select(val, x << 6, 0x7e0U);
3006     elfcpp::Swap<16, big_endian>::writeval(wv, val);
3007     return (utils::has_overflow<5>(x)
3008             ? This::STATUS_OVERFLOW
3009             : This::STATUS_OKAY);
3010   }
3011
3012   // R_ARM_ABS12: S + A
3013   static inline typename This::Status
3014   abs12(unsigned char *view,
3015         const Sized_relobj<32, big_endian>* object,
3016         const Symbol_value<32>* psymval)
3017   {
3018     typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
3019     typedef typename elfcpp::Swap<32, big_endian>::Valtype Reltype;
3020     Valtype* wv = reinterpret_cast<Valtype*>(view);
3021     Valtype val = elfcpp::Swap<32, big_endian>::readval(wv);
3022     Reltype addend = val & 0x0fffU;
3023     Reltype x = psymval->value(object, addend);
3024     val = utils::bit_select(val, x, 0x0fffU);
3025     elfcpp::Swap<32, big_endian>::writeval(wv, val);
3026     return (utils::has_overflow<12>(x)
3027             ? This::STATUS_OVERFLOW
3028             : This::STATUS_OKAY);
3029   }
3030
3031   // R_ARM_ABS16: S + A
3032   static inline typename This::Status
3033   abs16(unsigned char *view,
3034         const Sized_relobj<32, big_endian>* object,
3035         const Symbol_value<32>* psymval)
3036   {
3037     typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
3038     typedef typename elfcpp::Swap<32, big_endian>::Valtype Reltype;
3039     Valtype* wv = reinterpret_cast<Valtype*>(view);
3040     Valtype val = elfcpp::Swap<16, big_endian>::readval(wv);
3041     Reltype addend = utils::sign_extend<16>(val);
3042     Reltype x = psymval->value(object, addend);
3043     val = utils::bit_select(val, x, 0xffffU);
3044     elfcpp::Swap<16, big_endian>::writeval(wv, val);
3045     return (utils::has_signed_unsigned_overflow<16>(x)
3046             ? This::STATUS_OVERFLOW
3047             : This::STATUS_OKAY);
3048   }
3049
3050   // R_ARM_ABS32: (S + A) | T
3051   static inline typename This::Status
3052   abs32(unsigned char *view,
3053         const Sized_relobj<32, big_endian>* object,
3054         const Symbol_value<32>* psymval,
3055         Arm_address thumb_bit)
3056   {
3057     typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
3058     Valtype* wv = reinterpret_cast<Valtype*>(view);
3059     Valtype addend = elfcpp::Swap<32, big_endian>::readval(wv);
3060     Valtype x = psymval->value(object, addend) | thumb_bit;
3061     elfcpp::Swap<32, big_endian>::writeval(wv, x);
3062     return This::STATUS_OKAY;
3063   }
3064
3065   // R_ARM_REL32: (S + A) | T - P
3066   static inline typename This::Status
3067   rel32(unsigned char *view,
3068         const Sized_relobj<32, big_endian>* object,
3069         const Symbol_value<32>* psymval,
3070         Arm_address address,
3071         Arm_address thumb_bit)
3072   {
3073     typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
3074     Valtype* wv = reinterpret_cast<Valtype*>(view);
3075     Valtype addend = elfcpp::Swap<32, big_endian>::readval(wv);
3076     Valtype x = (psymval->value(object, addend) | thumb_bit) - address;
3077     elfcpp::Swap<32, big_endian>::writeval(wv, x);
3078     return This::STATUS_OKAY;
3079   }
3080
3081   // R_ARM_THM_JUMP24: (S + A) | T - P
3082   static typename This::Status
3083   thm_jump19(unsigned char *view, const Arm_relobj<big_endian>* object,
3084              const Symbol_value<32>* psymval, Arm_address address,
3085              Arm_address thumb_bit);
3086
3087   // R_ARM_THM_JUMP6: S + A â€“ P
3088   static inline typename This::Status
3089   thm_jump6(unsigned char *view,
3090             const Sized_relobj<32, big_endian>* object,
3091             const Symbol_value<32>* psymval,
3092             Arm_address address)
3093   {
3094     typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
3095     typedef typename elfcpp::Swap<16, big_endian>::Valtype Reltype;
3096     Valtype* wv = reinterpret_cast<Valtype*>(view);
3097     Valtype val = elfcpp::Swap<16, big_endian>::readval(wv);
3098     // bit[9]:bit[7:3]:’0’ (mask: 0x02f8)
3099     Reltype addend = (((val & 0x0200) >> 3) | ((val & 0x00f8) >> 2));
3100     Reltype x = (psymval->value(object, addend) - address);
3101     val = (val & 0xfd07) | ((x  & 0x0040) << 3) | ((val & 0x003e) << 2);
3102     elfcpp::Swap<16, big_endian>::writeval(wv, val);
3103     // CZB does only forward jumps.
3104     return ((x > 0x007e)
3105             ? This::STATUS_OVERFLOW
3106             : This::STATUS_OKAY);
3107   }
3108
3109   // R_ARM_THM_JUMP8: S + A â€“ P
3110   static inline typename This::Status
3111   thm_jump8(unsigned char *view,
3112             const Sized_relobj<32, big_endian>* object,
3113             const Symbol_value<32>* psymval,
3114             Arm_address address)
3115   {
3116     typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
3117     typedef typename elfcpp::Swap<16, big_endian>::Valtype Reltype;
3118     Valtype* wv = reinterpret_cast<Valtype*>(view);
3119     Valtype val = elfcpp::Swap<16, big_endian>::readval(wv);
3120     Reltype addend = utils::sign_extend<8>((val & 0x00ff) << 1);
3121     Reltype x = (psymval->value(object, addend) - address);
3122     elfcpp::Swap<16, big_endian>::writeval(wv, (val & 0xff00) | ((x & 0x01fe) >> 1));
3123     return (utils::has_overflow<8>(x)
3124             ? This::STATUS_OVERFLOW
3125             : This::STATUS_OKAY);
3126   }
3127
3128   // R_ARM_THM_JUMP11: S + A â€“ P
3129   static inline typename This::Status
3130   thm_jump11(unsigned char *view,
3131             const Sized_relobj<32, big_endian>* object,
3132             const Symbol_value<32>* psymval,
3133             Arm_address address)
3134   {
3135     typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
3136     typedef typename elfcpp::Swap<16, big_endian>::Valtype Reltype;
3137     Valtype* wv = reinterpret_cast<Valtype*>(view);
3138     Valtype val = elfcpp::Swap<16, big_endian>::readval(wv);
3139     Reltype addend = utils::sign_extend<11>((val & 0x07ff) << 1);
3140     Reltype x = (psymval->value(object, addend) - address);
3141     elfcpp::Swap<16, big_endian>::writeval(wv, (val & 0xf800) | ((x & 0x0ffe) >> 1));
3142     return (utils::has_overflow<11>(x)
3143             ? This::STATUS_OVERFLOW
3144             : This::STATUS_OKAY);
3145   }
3146
3147   // R_ARM_BASE_PREL: B(S) + A - P
3148   static inline typename This::Status
3149   base_prel(unsigned char* view,
3150             Arm_address origin,
3151             Arm_address address)
3152   {
3153     Base::rel32(view, origin - address);
3154     return STATUS_OKAY;
3155   }
3156
3157   // R_ARM_BASE_ABS: B(S) + A
3158   static inline typename This::Status
3159   base_abs(unsigned char* view,
3160            Arm_address origin)
3161   {
3162     Base::rel32(view, origin);
3163     return STATUS_OKAY;
3164   }
3165
3166   // R_ARM_GOT_BREL: GOT(S) + A - GOT_ORG
3167   static inline typename This::Status
3168   got_brel(unsigned char* view,
3169            typename elfcpp::Swap<32, big_endian>::Valtype got_offset)
3170   {
3171     Base::rel32(view, got_offset);
3172     return This::STATUS_OKAY;
3173   }
3174
3175   // R_ARM_GOT_PREL: GOT(S) + A - P
3176   static inline typename This::Status
3177   got_prel(unsigned char *view,
3178            Arm_address got_entry,
3179            Arm_address address)
3180   {
3181     Base::rel32(view, got_entry - address);
3182     return This::STATUS_OKAY;
3183   }
3184
3185   // R_ARM_PREL: (S + A) | T - P
3186   static inline typename This::Status
3187   prel31(unsigned char *view,
3188          const Sized_relobj<32, big_endian>* object,
3189          const Symbol_value<32>* psymval,
3190          Arm_address address,
3191          Arm_address thumb_bit)
3192   {
3193     typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
3194     Valtype* wv = reinterpret_cast<Valtype*>(view);
3195     Valtype val = elfcpp::Swap<32, big_endian>::readval(wv);
3196     Valtype addend = utils::sign_extend<31>(val);
3197     Valtype x = (psymval->value(object, addend) | thumb_bit) - address;
3198     val = utils::bit_select(val, x, 0x7fffffffU);
3199     elfcpp::Swap<32, big_endian>::writeval(wv, val);
3200     return (utils::has_overflow<31>(x) ?
3201             This::STATUS_OVERFLOW : This::STATUS_OKAY);
3202   }
3203
3204   // R_ARM_MOVW_ABS_NC: (S + A) | T     (relative address base is )
3205   // R_ARM_MOVW_PREL_NC: (S + A) | T - P
3206   // R_ARM_MOVW_BREL_NC: ((S + A) | T) - B(S)
3207   // R_ARM_MOVW_BREL: ((S + A) | T) - B(S)
3208   static inline typename This::Status
3209   movw(unsigned char* view,
3210        const Sized_relobj<32, big_endian>* object,
3211        const Symbol_value<32>* psymval,
3212        Arm_address relative_address_base,
3213        Arm_address thumb_bit,
3214        bool check_overflow)
3215   {
3216     typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
3217     Valtype* wv = reinterpret_cast<Valtype*>(view);
3218     Valtype val = elfcpp::Swap<32, big_endian>::readval(wv);
3219     Valtype addend = This::extract_arm_movw_movt_addend(val);
3220     Valtype x = ((psymval->value(object, addend) | thumb_bit)
3221                  - relative_address_base);
3222     val = This::insert_val_arm_movw_movt(val, x);
3223     elfcpp::Swap<32, big_endian>::writeval(wv, val);
3224     return ((check_overflow && utils::has_overflow<16>(x))
3225             ? This::STATUS_OVERFLOW
3226             : This::STATUS_OKAY);
3227   }
3228
3229   // R_ARM_MOVT_ABS: S + A      (relative address base is 0)
3230   // R_ARM_MOVT_PREL: S + A - P
3231   // R_ARM_MOVT_BREL: S + A - B(S)
3232   static inline typename This::Status
3233   movt(unsigned char* view,
3234        const Sized_relobj<32, big_endian>* object,
3235        const Symbol_value<32>* psymval,
3236        Arm_address relative_address_base)
3237   {
3238     typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
3239     Valtype* wv = reinterpret_cast<Valtype*>(view);
3240     Valtype val = elfcpp::Swap<32, big_endian>::readval(wv);
3241     Valtype addend = This::extract_arm_movw_movt_addend(val);
3242     Valtype x = (psymval->value(object, addend) - relative_address_base) >> 16;
3243     val = This::insert_val_arm_movw_movt(val, x);
3244     elfcpp::Swap<32, big_endian>::writeval(wv, val);
3245     // FIXME: IHI0044D says that we should check for overflow.
3246     return This::STATUS_OKAY;
3247   }
3248
3249   // R_ARM_THM_MOVW_ABS_NC: S + A | T           (relative_address_base is 0)
3250   // R_ARM_THM_MOVW_PREL_NC: (S + A) | T - P
3251   // R_ARM_THM_MOVW_BREL_NC: ((S + A) | T) - B(S)
3252   // R_ARM_THM_MOVW_BREL: ((S + A) | T) - B(S)
3253   static inline typename This::Status
3254   thm_movw(unsigned char *view,
3255            const Sized_relobj<32, big_endian>* object,
3256            const Symbol_value<32>* psymval,
3257            Arm_address relative_address_base,
3258            Arm_address thumb_bit,
3259            bool check_overflow)
3260   {
3261     typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
3262     typedef typename elfcpp::Swap<32, big_endian>::Valtype Reltype;
3263     Valtype* wv = reinterpret_cast<Valtype*>(view);
3264     Reltype val = (elfcpp::Swap<16, big_endian>::readval(wv) << 16)
3265                   | elfcpp::Swap<16, big_endian>::readval(wv + 1);
3266     Reltype addend = This::extract_thumb_movw_movt_addend(val);
3267     Reltype x =
3268       (psymval->value(object, addend) | thumb_bit) - relative_address_base;
3269     val = This::insert_val_thumb_movw_movt(val, x);
3270     elfcpp::Swap<16, big_endian>::writeval(wv, val >> 16);
3271     elfcpp::Swap<16, big_endian>::writeval(wv + 1, val & 0xffff);
3272     return ((check_overflow && utils::has_overflow<16>(x))
3273             ? This::STATUS_OVERFLOW
3274             : This::STATUS_OKAY);
3275   }
3276
3277   // R_ARM_THM_MOVT_ABS: S + A          (relative address base is 0)
3278   // R_ARM_THM_MOVT_PREL: S + A - P
3279   // R_ARM_THM_MOVT_BREL: S + A - B(S)
3280   static inline typename This::Status
3281   thm_movt(unsigned char* view,
3282            const Sized_relobj<32, big_endian>* object,
3283            const Symbol_value<32>* psymval,
3284            Arm_address relative_address_base)
3285   {
3286     typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
3287     typedef typename elfcpp::Swap<32, big_endian>::Valtype Reltype;
3288     Valtype* wv = reinterpret_cast<Valtype*>(view);
3289     Reltype val = (elfcpp::Swap<16, big_endian>::readval(wv) << 16)
3290                   | elfcpp::Swap<16, big_endian>::readval(wv + 1);
3291     Reltype addend = This::extract_thumb_movw_movt_addend(val);
3292     Reltype x = (psymval->value(object, addend) - relative_address_base) >> 16;
3293     val = This::insert_val_thumb_movw_movt(val, x);
3294     elfcpp::Swap<16, big_endian>::writeval(wv, val >> 16);
3295     elfcpp::Swap<16, big_endian>::writeval(wv + 1, val & 0xffff);
3296     return This::STATUS_OKAY;
3297   }
3298
3299   // R_ARM_THM_ALU_PREL_11_0: ((S + A) | T) - Pa (Thumb32)
3300   static inline typename This::Status
3301   thm_alu11(unsigned char* view,
3302             const Sized_relobj<32, big_endian>* object,
3303             const Symbol_value<32>* psymval,
3304             Arm_address address,
3305             Arm_address thumb_bit)
3306   {
3307     typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
3308     typedef typename elfcpp::Swap<32, big_endian>::Valtype Reltype;
3309     Valtype* wv = reinterpret_cast<Valtype*>(view);
3310     Reltype insn = (elfcpp::Swap<16, big_endian>::readval(wv) << 16)
3311                    | elfcpp::Swap<16, big_endian>::readval(wv + 1);
3312
3313     //        f e d c b|a|9|8 7 6 5|4|3 2 1 0||f|e d c|b a 9 8|7 6 5 4 3 2 1 0
3314     // -----------------------------------------------------------------------
3315     // ADD{S} 1 1 1 1 0|i|0|1 0 0 0|S|1 1 0 1||0|imm3 |Rd     |imm8
3316     // ADDW   1 1 1 1 0|i|1|0 0 0 0|0|1 1 0 1||0|imm3 |Rd     |imm8
3317     // ADR[+] 1 1 1 1 0|i|1|0 0 0 0|0|1 1 1 1||0|imm3 |Rd     |imm8
3318     // SUB{S} 1 1 1 1 0|i|0|1 1 0 1|S|1 1 0 1||0|imm3 |Rd     |imm8
3319     // SUBW   1 1 1 1 0|i|1|0 1 0 1|0|1 1 0 1||0|imm3 |Rd     |imm8
3320     // ADR[-] 1 1 1 1 0|i|1|0 1 0 1|0|1 1 1 1||0|imm3 |Rd     |imm8
3321
3322     // Determine a sign for the addend.
3323     const int sign = ((insn & 0xf8ef0000) == 0xf0ad0000
3324                       || (insn & 0xf8ef0000) == 0xf0af0000) ? -1 : 1;
3325     // Thumb2 addend encoding:
3326     // imm12 := i | imm3 | imm8
3327     int32_t addend = (insn & 0xff)
3328                      | ((insn & 0x00007000) >> 4)
3329                      | ((insn & 0x04000000) >> 15);
3330     // Apply a sign to the added.
3331     addend *= sign;
3332
3333     int32_t x = (psymval->value(object, addend) | thumb_bit)
3334                 - (address & 0xfffffffc);
3335     Reltype val = abs(x);
3336     // Mask out the value and a distinct part of the ADD/SUB opcode
3337     // (bits 7:5 of opword).
3338     insn = (insn & 0xfb0f8f00)
3339            | (val & 0xff)
3340            | ((val & 0x700) << 4)
3341            | ((val & 0x800) << 15);
3342     // Set the opcode according to whether the value to go in the
3343     // place is negative.
3344     if (x < 0)
3345       insn |= 0x00a00000;
3346
3347     elfcpp::Swap<16, big_endian>::writeval(wv, insn >> 16);
3348     elfcpp::Swap<16, big_endian>::writeval(wv + 1, insn & 0xffff);
3349     return ((val > 0xfff) ?
3350             This::STATUS_OVERFLOW : This::STATUS_OKAY);
3351   }
3352
3353   // R_ARM_THM_PC8: S + A - Pa (Thumb)
3354   static inline typename This::Status
3355   thm_pc8(unsigned char* view,
3356           const Sized_relobj<32, big_endian>* object,
3357           const Symbol_value<32>* psymval,
3358           Arm_address address)
3359   {
3360     typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
3361     typedef typename elfcpp::Swap<16, big_endian>::Valtype Reltype;
3362     Valtype* wv = reinterpret_cast<Valtype*>(view);
3363     Valtype insn = elfcpp::Swap<16, big_endian>::readval(wv);
3364     Reltype addend = ((insn & 0x00ff) << 2);
3365     int32_t x = (psymval->value(object, addend) - (address & 0xfffffffc));
3366     Reltype val = abs(x);
3367     insn = (insn & 0xff00) | ((val & 0x03fc) >> 2);
3368
3369     elfcpp::Swap<16, big_endian>::writeval(wv, insn);
3370     return ((val > 0x03fc)
3371             ? This::STATUS_OVERFLOW
3372             : This::STATUS_OKAY);
3373   }
3374
3375   // R_ARM_THM_PC12: S + A - Pa (Thumb32)
3376   static inline typename This::Status
3377   thm_pc12(unsigned char* view,
3378            const Sized_relobj<32, big_endian>* object,
3379            const Symbol_value<32>* psymval,
3380            Arm_address address)
3381   {
3382     typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
3383     typedef typename elfcpp::Swap<32, big_endian>::Valtype Reltype;
3384     Valtype* wv = reinterpret_cast<Valtype*>(view);
3385     Reltype insn = (elfcpp::Swap<16, big_endian>::readval(wv) << 16)
3386                    | elfcpp::Swap<16, big_endian>::readval(wv + 1);
3387     // Determine a sign for the addend (positive if the U bit is 1).
3388     const int sign = (insn & 0x00800000) ? 1 : -1;
3389     int32_t addend = (insn & 0xfff);
3390     // Apply a sign to the added.
3391     addend *= sign;
3392
3393     int32_t x = (psymval->value(object, addend) - (address & 0xfffffffc));
3394     Reltype val = abs(x);
3395     // Mask out and apply the value and the U bit.
3396     insn = (insn & 0xff7ff000) | (val & 0xfff);
3397     // Set the U bit according to whether the value to go in the
3398     // place is positive.
3399     if (x >= 0)
3400       insn |= 0x00800000;
3401
3402     elfcpp::Swap<16, big_endian>::writeval(wv, insn >> 16);
3403     elfcpp::Swap<16, big_endian>::writeval(wv + 1, insn & 0xffff);
3404     return ((val > 0xfff) ?
3405             This::STATUS_OVERFLOW : This::STATUS_OKAY);
3406   }
3407
3408   // R_ARM_V4BX
3409   static inline typename This::Status
3410   v4bx(const Relocate_info<32, big_endian>* relinfo,
3411        unsigned char *view,
3412        const Arm_relobj<big_endian>* object,
3413        const Arm_address address,
3414        const bool is_interworking)
3415   {
3416
3417     typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
3418     Valtype* wv = reinterpret_cast<Valtype*>(view);
3419     Valtype val = elfcpp::Swap<32, big_endian>::readval(wv);
3420
3421     // Ensure that we have a BX instruction.
3422     gold_assert((val & 0x0ffffff0) == 0x012fff10);
3423     const uint32_t reg = (val & 0xf);
3424     if (is_interworking && reg != 0xf)
3425       {
3426         Stub_table<big_endian>* stub_table =
3427             object->stub_table(relinfo->data_shndx);
3428         gold_assert(stub_table != NULL);
3429
3430         Arm_v4bx_stub* stub = stub_table->find_arm_v4bx_stub(reg);
3431         gold_assert(stub != NULL);
3432
3433         int32_t veneer_address =
3434             stub_table->address() + stub->offset() - 8 - address;
3435         gold_assert((veneer_address <= ARM_MAX_FWD_BRANCH_OFFSET)
3436                     && (veneer_address >= ARM_MAX_BWD_BRANCH_OFFSET));
3437         // Replace with a branch to veneer (B <addr>)
3438         val = (val & 0xf0000000) | 0x0a000000
3439               | ((veneer_address >> 2) & 0x00ffffff);
3440       }
3441     else
3442       {
3443         // Preserve Rm (lowest four bits) and the condition code
3444         // (highest four bits). Other bits encode MOV PC,Rm.
3445         val = (val & 0xf000000f) | 0x01a0f000;
3446       }
3447     elfcpp::Swap<32, big_endian>::writeval(wv, val);
3448     return This::STATUS_OKAY;
3449   }
3450
3451   // R_ARM_ALU_PC_G0_NC: ((S + A) | T) - P
3452   // R_ARM_ALU_PC_G0:    ((S + A) | T) - P
3453   // R_ARM_ALU_PC_G1_NC: ((S + A) | T) - P
3454   // R_ARM_ALU_PC_G1:    ((S + A) | T) - P
3455   // R_ARM_ALU_PC_G2:    ((S + A) | T) - P
3456   // R_ARM_ALU_SB_G0_NC: ((S + A) | T) - B(S)
3457   // R_ARM_ALU_SB_G0:    ((S + A) | T) - B(S)
3458   // R_ARM_ALU_SB_G1_NC: ((S + A) | T) - B(S)
3459   // R_ARM_ALU_SB_G1:    ((S + A) | T) - B(S)
3460   // R_ARM_ALU_SB_G2:    ((S + A) | T) - B(S)
3461   static inline typename This::Status
3462   arm_grp_alu(unsigned char* view,
3463         const Sized_relobj<32, big_endian>* object,
3464         const Symbol_value<32>* psymval,
3465         const int group,
3466         Arm_address address,
3467         Arm_address thumb_bit,
3468         bool check_overflow)
3469   {
3470     gold_assert(group >= 0 && group < 3);
3471     typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
3472     Valtype* wv = reinterpret_cast<Valtype*>(view);
3473     Valtype insn = elfcpp::Swap<32, big_endian>::readval(wv);
3474
3475     // ALU group relocations are allowed only for the ADD/SUB instructions.
3476     // (0x00800000 - ADD, 0x00400000 - SUB)
3477     const Valtype opcode = insn & 0x01e00000;
3478     if (opcode != 0x00800000 && opcode != 0x00400000)
3479       return This::STATUS_BAD_RELOC;
3480
3481     // Determine a sign for the addend.
3482     const int sign = (opcode == 0x00800000) ? 1 : -1;
3483     // shifter = rotate_imm * 2
3484     const uint32_t shifter = (insn & 0xf00) >> 7;
3485     // Initial addend value.
3486     int32_t addend = insn & 0xff;
3487     // Rotate addend right by shifter.
3488     addend = (addend >> shifter) | (addend << (32 - shifter));
3489     // Apply a sign to the added.
3490     addend *= sign;
3491
3492     int32_t x = ((psymval->value(object, addend) | thumb_bit) - address);
3493     Valtype gn = Arm_relocate_functions::calc_grp_gn(abs(x), group);
3494     // Check for overflow if required
3495     if (check_overflow
3496         && (Arm_relocate_functions::calc_grp_residual(abs(x), group) != 0))
3497       return This::STATUS_OVERFLOW;
3498
3499     // Mask out the value and the ADD/SUB part of the opcode; take care
3500     // not to destroy the S bit.
3501     insn &= 0xff1ff000;
3502     // Set the opcode according to whether the value to go in the
3503     // place is negative.
3504     insn |= ((x < 0) ? 0x00400000 : 0x00800000);
3505     // Encode the offset (encoded Gn).
3506     insn |= gn;
3507
3508     elfcpp::Swap<32, big_endian>::writeval(wv, insn);
3509     return This::STATUS_OKAY;
3510   }
3511
3512   // R_ARM_LDR_PC_G0: S + A - P
3513   // R_ARM_LDR_PC_G1: S + A - P
3514   // R_ARM_LDR_PC_G2: S + A - P
3515   // R_ARM_LDR_SB_G0: S + A - B(S)
3516   // R_ARM_LDR_SB_G1: S + A - B(S)
3517   // R_ARM_LDR_SB_G2: S + A - B(S)
3518   static inline typename This::Status
3519   arm_grp_ldr(unsigned char* view,
3520         const Sized_relobj<32, big_endian>* object,
3521         const Symbol_value<32>* psymval,
3522         const int group,
3523         Arm_address address)
3524   {
3525     gold_assert(group >= 0 && group < 3);
3526     typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
3527     Valtype* wv = reinterpret_cast<Valtype*>(view);
3528     Valtype insn = elfcpp::Swap<32, big_endian>::readval(wv);
3529
3530     const int sign = (insn & 0x00800000) ? 1 : -1;
3531     int32_t addend = (insn & 0xfff) * sign;
3532     int32_t x = (psymval->value(object, addend) - address);
3533     // Calculate the relevant G(n-1) value to obtain this stage residual.
3534     Valtype residual =
3535         Arm_relocate_functions::calc_grp_residual(abs(x), group - 1);
3536     if (residual >= 0x1000)
3537       return This::STATUS_OVERFLOW;
3538
3539     // Mask out the value and U bit.
3540     insn &= 0xff7ff000;
3541     // Set the U bit for non-negative values.
3542     if (x >= 0)
3543       insn |= 0x00800000;
3544     insn |= residual;
3545
3546     elfcpp::Swap<32, big_endian>::writeval(wv, insn);
3547     return This::STATUS_OKAY;
3548   }
3549
3550   // R_ARM_LDRS_PC_G0: S + A - P
3551   // R_ARM_LDRS_PC_G1: S + A - P
3552   // R_ARM_LDRS_PC_G2: S + A - P
3553   // R_ARM_LDRS_SB_G0: S + A - B(S)
3554   // R_ARM_LDRS_SB_G1: S + A - B(S)
3555   // R_ARM_LDRS_SB_G2: S + A - B(S)
3556   static inline typename This::Status
3557   arm_grp_ldrs(unsigned char* view,
3558         const Sized_relobj<32, big_endian>* object,
3559         const Symbol_value<32>* psymval,
3560         const int group,
3561         Arm_address address)
3562   {
3563     gold_assert(group >= 0 && group < 3);
3564     typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
3565     Valtype* wv = reinterpret_cast<Valtype*>(view);
3566     Valtype insn = elfcpp::Swap<32, big_endian>::readval(wv);
3567
3568     const int sign = (insn & 0x00800000) ? 1 : -1;
3569     int32_t addend = (((insn & 0xf00) >> 4) + (insn & 0xf)) * sign;
3570     int32_t x = (psymval->value(object, addend) - address);
3571     // Calculate the relevant G(n-1) value to obtain this stage residual.
3572     Valtype residual =
3573         Arm_relocate_functions::calc_grp_residual(abs(x), group - 1);
3574    if (residual >= 0x100)
3575       return This::STATUS_OVERFLOW;
3576
3577     // Mask out the value and U bit.
3578     insn &= 0xff7ff0f0;
3579     // Set the U bit for non-negative values.
3580     if (x >= 0)
3581       insn |= 0x00800000;
3582     insn |= ((residual & 0xf0) << 4) | (residual & 0xf);
3583
3584     elfcpp::Swap<32, big_endian>::writeval(wv, insn);
3585     return This::STATUS_OKAY;
3586   }
3587
3588   // R_ARM_LDC_PC_G0: S + A - P
3589   // R_ARM_LDC_PC_G1: S + A - P
3590   // R_ARM_LDC_PC_G2: S + A - P
3591   // R_ARM_LDC_SB_G0: S + A - B(S)
3592   // R_ARM_LDC_SB_G1: S + A - B(S)
3593   // R_ARM_LDC_SB_G2: S + A - B(S)
3594   static inline typename This::Status
3595   arm_grp_ldc(unsigned char* view,
3596       const Sized_relobj<32, big_endian>* object,
3597       const Symbol_value<32>* psymval,
3598       const int group,
3599       Arm_address address)
3600   {
3601     gold_assert(group >= 0 && group < 3);
3602     typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
3603     Valtype* wv = reinterpret_cast<Valtype*>(view);
3604     Valtype insn = elfcpp::Swap<32, big_endian>::readval(wv);
3605
3606     const int sign = (insn & 0x00800000) ? 1 : -1;
3607     int32_t addend = ((insn & 0xff) << 2) * sign;
3608     int32_t x = (psymval->value(object, addend) - address);
3609     // Calculate the relevant G(n-1) value to obtain this stage residual.
3610     Valtype residual =
3611       Arm_relocate_functions::calc_grp_residual(abs(x), group - 1);
3612     if ((residual & 0x3) != 0 || residual >= 0x400)
3613       return This::STATUS_OVERFLOW;
3614
3615     // Mask out the value and U bit.
3616     insn &= 0xff7fff00;
3617     // Set the U bit for non-negative values.
3618     if (x >= 0)
3619       insn |= 0x00800000;
3620     insn |= (residual >> 2);
3621
3622     elfcpp::Swap<32, big_endian>::writeval(wv, insn);
3623     return This::STATUS_OKAY;
3624   }
3625 };
3626
3627 // Relocate ARM long branches.  This handles relocation types
3628 // R_ARM_CALL, R_ARM_JUMP24, R_ARM_PLT32 and R_ARM_XPC25.
3629 // If IS_WEAK_UNDEFINED_WITH_PLT is true.  The target symbol is weakly
3630 // undefined and we do not use PLT in this relocation.  In such a case,
3631 // the branch is converted into an NOP.
3632
3633 template<bool big_endian>
3634 typename Arm_relocate_functions<big_endian>::Status
3635 Arm_relocate_functions<big_endian>::arm_branch_common(
3636     unsigned int r_type,
3637     const Relocate_info<32, big_endian>* relinfo,
3638     unsigned char *view,
3639     const Sized_symbol<32>* gsym,
3640     const Arm_relobj<big_endian>* object,
3641     unsigned int r_sym,
3642     const Symbol_value<32>* psymval,
3643     Arm_address address,
3644     Arm_address thumb_bit,
3645     bool is_weakly_undefined_without_plt)
3646 {
3647   typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
3648   Valtype* wv = reinterpret_cast<Valtype*>(view);
3649   Valtype val = elfcpp::Swap<32, big_endian>::readval(wv);
3650      
3651   bool insn_is_b = (((val >> 28) & 0xf) <= 0xe)
3652                     && ((val & 0x0f000000UL) == 0x0a000000UL);
3653   bool insn_is_uncond_bl = (val & 0xff000000UL) == 0xeb000000UL;
3654   bool insn_is_cond_bl = (((val >> 28) & 0xf) < 0xe)
3655                           && ((val & 0x0f000000UL) == 0x0b000000UL);
3656   bool insn_is_blx = (val & 0xfe000000UL) == 0xfa000000UL;
3657   bool insn_is_any_branch = (val & 0x0e000000UL) == 0x0a000000UL;
3658
3659   // Check that the instruction is valid.
3660   if (r_type == elfcpp::R_ARM_CALL)
3661     {
3662       if (!insn_is_uncond_bl && !insn_is_blx)
3663         return This::STATUS_BAD_RELOC;
3664     }
3665   else if (r_type == elfcpp::R_ARM_JUMP24)
3666     {
3667       if (!insn_is_b && !insn_is_cond_bl)
3668         return This::STATUS_BAD_RELOC;
3669     }
3670   else if (r_type == elfcpp::R_ARM_PLT32)
3671     {
3672       if (!insn_is_any_branch)
3673         return This::STATUS_BAD_RELOC;
3674     }
3675   else if (r_type == elfcpp::R_ARM_XPC25)
3676     {
3677       // FIXME: AAELF document IH0044C does not say much about it other
3678       // than it being obsolete.
3679       if (!insn_is_any_branch)
3680         return This::STATUS_BAD_RELOC;
3681     }
3682   else
3683     gold_unreachable();
3684
3685   // A branch to an undefined weak symbol is turned into a jump to
3686   // the next instruction unless a PLT entry will be created.
3687   // Do the same for local undefined symbols.
3688   // The jump to the next instruction is optimized as a NOP depending
3689   // on the architecture.
3690   const Target_arm<big_endian>* arm_target =
3691     Target_arm<big_endian>::default_target();
3692   if (is_weakly_undefined_without_plt)
3693     {
3694       Valtype cond = val & 0xf0000000U;
3695       if (arm_target->may_use_arm_nop())
3696         val = cond | 0x0320f000;
3697       else
3698         val = cond | 0x01a00000;        // Using pre-UAL nop: mov r0, r0.
3699       elfcpp::Swap<32, big_endian>::writeval(wv, val);
3700       return This::STATUS_OKAY;
3701     }
3702  
3703   Valtype addend = utils::sign_extend<26>(val << 2);
3704   Valtype branch_target = psymval->value(object, addend);
3705   int32_t branch_offset = branch_target - address;
3706
3707   // We need a stub if the branch offset is too large or if we need
3708   // to switch mode.
3709   bool may_use_blx = arm_target->may_use_blx();
3710   Reloc_stub* stub = NULL;
3711   if (utils::has_overflow<26>(branch_offset)
3712       || ((thumb_bit != 0) && !(may_use_blx && r_type == elfcpp::R_ARM_CALL)))
3713     {
3714       Valtype unadjusted_branch_target = psymval->value(object, 0);
3715
3716       Stub_type stub_type =
3717         Reloc_stub::stub_type_for_reloc(r_type, address,
3718                                         unadjusted_branch_target,
3719                                         (thumb_bit != 0));
3720       if (stub_type != arm_stub_none)
3721         {
3722           Stub_table<big_endian>* stub_table =
3723             object->stub_table(relinfo->data_shndx);
3724           gold_assert(stub_table != NULL);
3725
3726           Reloc_stub::Key stub_key(stub_type, gsym, object, r_sym, addend);
3727           stub = stub_table->find_reloc_stub(stub_key);
3728           gold_assert(stub != NULL);
3729           thumb_bit = stub->stub_template()->entry_in_thumb_mode() ? 1 : 0;
3730           branch_target = stub_table->address() + stub->offset() + addend;
3731           branch_offset = branch_target - address;
3732           gold_assert(!utils::has_overflow<26>(branch_offset));
3733         }
3734     }
3735
3736   // At this point, if we still need to switch mode, the instruction
3737   // must either be a BLX or a BL that can be converted to a BLX.
3738   if (thumb_bit != 0)
3739     {
3740       // Turn BL to BLX.
3741       gold_assert(may_use_blx && r_type == elfcpp::R_ARM_CALL);
3742       val = (val & 0xffffff) | 0xfa000000 | ((branch_offset & 2) << 23);
3743     }
3744
3745   val = utils::bit_select(val, (branch_offset >> 2), 0xffffffUL);
3746   elfcpp::Swap<32, big_endian>::writeval(wv, val);
3747   return (utils::has_overflow<26>(branch_offset)
3748           ? This::STATUS_OVERFLOW : This::STATUS_OKAY);
3749 }
3750
3751 // Relocate THUMB long branches.  This handles relocation types
3752 // R_ARM_THM_CALL, R_ARM_THM_JUMP24 and R_ARM_THM_XPC22.
3753 // If IS_WEAK_UNDEFINED_WITH_PLT is true.  The target symbol is weakly
3754 // undefined and we do not use PLT in this relocation.  In such a case,
3755 // the branch is converted into an NOP.
3756
3757 template<bool big_endian>
3758 typename Arm_relocate_functions<big_endian>::Status
3759 Arm_relocate_functions<big_endian>::thumb_branch_common(
3760     unsigned int r_type,
3761     const Relocate_info<32, big_endian>* relinfo,
3762     unsigned char *view,
3763     const Sized_symbol<32>* gsym,
3764     const Arm_relobj<big_endian>* object,
3765     unsigned int r_sym,
3766     const Symbol_value<32>* psymval,
3767     Arm_address address,
3768     Arm_address thumb_bit,
3769     bool is_weakly_undefined_without_plt)
3770 {
3771   typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
3772   Valtype* wv = reinterpret_cast<Valtype*>(view);
3773   uint32_t upper_insn = elfcpp::Swap<16, big_endian>::readval(wv);
3774   uint32_t lower_insn = elfcpp::Swap<16, big_endian>::readval(wv + 1);
3775
3776   // FIXME: These tests are too loose and do not take THUMB/THUMB-2 difference
3777   // into account.
3778   bool is_bl_insn = (lower_insn & 0x1000U) == 0x1000U;
3779   bool is_blx_insn = (lower_insn & 0x1000U) == 0x0000U;
3780      
3781   // Check that the instruction is valid.
3782   if (r_type == elfcpp::R_ARM_THM_CALL)
3783     {
3784       if (!is_bl_insn && !is_blx_insn)
3785         return This::STATUS_BAD_RELOC;
3786     }
3787   else if (r_type == elfcpp::R_ARM_THM_JUMP24)
3788     {
3789       // This cannot be a BLX.
3790       if (!is_bl_insn)
3791         return This::STATUS_BAD_RELOC;
3792     }
3793   else if (r_type == elfcpp::R_ARM_THM_XPC22)
3794     {
3795       // Check for Thumb to Thumb call.
3796       if (!is_blx_insn)
3797         return This::STATUS_BAD_RELOC;
3798       if (thumb_bit != 0)
3799         {
3800           gold_warning(_("%s: Thumb BLX instruction targets "
3801                          "thumb function '%s'."),
3802                          object->name().c_str(),
3803                          (gsym ? gsym->name() : "(local)")); 
3804           // Convert BLX to BL.
3805           lower_insn |= 0x1000U;
3806         }
3807     }
3808   else
3809     gold_unreachable();
3810
3811   // A branch to an undefined weak symbol is turned into a jump to
3812   // the next instruction unless a PLT entry will be created.
3813   // The jump to the next instruction is optimized as a NOP.W for
3814   // Thumb-2 enabled architectures.
3815   const Target_arm<big_endian>* arm_target =
3816     Target_arm<big_endian>::default_target();
3817   if (is_weakly_undefined_without_plt)
3818     {
3819       if (arm_target->may_use_thumb2_nop())
3820         {
3821           elfcpp::Swap<16, big_endian>::writeval(wv, 0xf3af);
3822           elfcpp::Swap<16, big_endian>::writeval(wv + 1, 0x8000);
3823         }
3824       else
3825         {
3826           elfcpp::Swap<16, big_endian>::writeval(wv, 0xe000);
3827           elfcpp::Swap<16, big_endian>::writeval(wv + 1, 0xbf00);
3828         }
3829       return This::STATUS_OKAY;
3830     }
3831  
3832   int32_t addend = This::thumb32_branch_offset(upper_insn, lower_insn);
3833   Arm_address branch_target = psymval->value(object, addend);
3834   int32_t branch_offset = branch_target - address;
3835
3836   // We need a stub if the branch offset is too large or if we need
3837   // to switch mode.
3838   bool may_use_blx = arm_target->may_use_blx();
3839   bool thumb2 = arm_target->using_thumb2();
3840   if ((!thumb2 && utils::has_overflow<23>(branch_offset))
3841       || (thumb2 && utils::has_overflow<25>(branch_offset))
3842       || ((thumb_bit == 0)
3843           && (((r_type == elfcpp::R_ARM_THM_CALL) && !may_use_blx)
3844               || r_type == elfcpp::R_ARM_THM_JUMP24)))
3845     {
3846       Arm_address unadjusted_branch_target = psymval->value(object, 0);
3847
3848       Stub_type stub_type =
3849         Reloc_stub::stub_type_for_reloc(r_type, address,
3850                                         unadjusted_branch_target,
3851                                         (thumb_bit != 0));
3852
3853       if (stub_type != arm_stub_none)
3854         {
3855           Stub_table<big_endian>* stub_table =
3856             object->stub_table(relinfo->data_shndx);
3857           gold_assert(stub_table != NULL);
3858
3859           Reloc_stub::Key stub_key(stub_type, gsym, object, r_sym, addend);
3860           Reloc_stub* stub = stub_table->find_reloc_stub(stub_key);
3861           gold_assert(stub != NULL);
3862           thumb_bit = stub->stub_template()->entry_in_thumb_mode() ? 1 : 0;
3863           branch_target = stub_table->address() + stub->offset() + addend;
3864           branch_offset = branch_target - address;
3865         }
3866     }
3867
3868   // At this point, if we still need to switch mode, the instruction
3869   // must either be a BLX or a BL that can be converted to a BLX.
3870   if (thumb_bit == 0)
3871     {
3872       gold_assert(may_use_blx
3873                   && (r_type == elfcpp::R_ARM_THM_CALL
3874                       || r_type == elfcpp::R_ARM_THM_XPC22));
3875       // Make sure this is a BLX.
3876       lower_insn &= ~0x1000U;
3877     }
3878   else
3879     {
3880       // Make sure this is a BL.
3881       lower_insn |= 0x1000U;
3882     }
3883
3884   if ((lower_insn & 0x5000U) == 0x4000U)
3885     // For a BLX instruction, make sure that the relocation is rounded up
3886     // to a word boundary.  This follows the semantics of the instruction
3887     // which specifies that bit 1 of the target address will come from bit
3888     // 1 of the base address.
3889     branch_offset = (branch_offset + 2) & ~3;
3890
3891   // Put BRANCH_OFFSET back into the insn.  Assumes two's complement.
3892   // We use the Thumb-2 encoding, which is safe even if dealing with
3893   // a Thumb-1 instruction by virtue of our overflow check above.  */
3894   upper_insn = This::thumb32_branch_upper(upper_insn, branch_offset);
3895   lower_insn = This::thumb32_branch_lower(lower_insn, branch_offset);
3896
3897   elfcpp::Swap<16, big_endian>::writeval(wv, upper_insn);
3898   elfcpp::Swap<16, big_endian>::writeval(wv + 1, lower_insn);
3899
3900   return ((thumb2
3901            ? utils::has_overflow<25>(branch_offset)
3902            : utils::has_overflow<23>(branch_offset))
3903           ? This::STATUS_OVERFLOW
3904           : This::STATUS_OKAY);
3905 }
3906
3907 // Relocate THUMB-2 long conditional branches.
3908 // If IS_WEAK_UNDEFINED_WITH_PLT is true.  The target symbol is weakly
3909 // undefined and we do not use PLT in this relocation.  In such a case,
3910 // the branch is converted into an NOP.
3911
3912 template<bool big_endian>
3913 typename Arm_relocate_functions<big_endian>::Status
3914 Arm_relocate_functions<big_endian>::thm_jump19(
3915     unsigned char *view,
3916     const Arm_relobj<big_endian>* object,
3917     const Symbol_value<32>* psymval,
3918     Arm_address address,
3919     Arm_address thumb_bit)
3920 {
3921   typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
3922   Valtype* wv = reinterpret_cast<Valtype*>(view);
3923   uint32_t upper_insn = elfcpp::Swap<16, big_endian>::readval(wv);
3924   uint32_t lower_insn = elfcpp::Swap<16, big_endian>::readval(wv + 1);
3925   int32_t addend = This::thumb32_cond_branch_offset(upper_insn, lower_insn);
3926
3927   Arm_address branch_target = psymval->value(object, addend);
3928   int32_t branch_offset = branch_target - address;
3929
3930   // ??? Should handle interworking?  GCC might someday try to
3931   // use this for tail calls.
3932   // FIXME: We do support thumb entry to PLT yet.
3933   if (thumb_bit == 0)
3934     {
3935       gold_error(_("conditional branch to PLT in THUMB-2 not supported yet."));
3936       return This::STATUS_BAD_RELOC;
3937     }
3938
3939   // Put RELOCATION back into the insn.
3940   upper_insn = This::thumb32_cond_branch_upper(upper_insn, branch_offset);
3941   lower_insn = This::thumb32_cond_branch_lower(lower_insn, branch_offset);
3942
3943   // Put the relocated value back in the object file:
3944   elfcpp::Swap<16, big_endian>::writeval(wv, upper_insn);
3945   elfcpp::Swap<16, big_endian>::writeval(wv + 1, lower_insn);
3946
3947   return (utils::has_overflow<21>(branch_offset)
3948           ? This::STATUS_OVERFLOW
3949           : This::STATUS_OKAY);
3950 }
3951
3952 // Get the GOT section, creating it if necessary.
3953
3954 template<bool big_endian>
3955 Arm_output_data_got<big_endian>*
3956 Target_arm<big_endian>::got_section(Symbol_table* symtab, Layout* layout)
3957 {
3958   if (this->got_ == NULL)
3959     {
3960       gold_assert(symtab != NULL && layout != NULL);
3961
3962       this->got_ = new Arm_output_data_got<big_endian>(symtab, layout);
3963
3964       Output_section* os;
3965       os = layout->add_output_section_data(".got", elfcpp::SHT_PROGBITS,
3966                                            (elfcpp::SHF_ALLOC
3967                                             | elfcpp::SHF_WRITE),
3968                                            this->got_, false, false, false,
3969                                            true);
3970       // The old GNU linker creates a .got.plt section.  We just
3971       // create another set of data in the .got section.  Note that we
3972       // always create a PLT if we create a GOT, although the PLT
3973       // might be empty.
3974       this->got_plt_ = new Output_data_space(4, "** GOT PLT");
3975       os = layout->add_output_section_data(".got", elfcpp::SHT_PROGBITS,
3976                                            (elfcpp::SHF_ALLOC
3977                                             | elfcpp::SHF_WRITE),
3978                                            this->got_plt_, false, false,
3979                                            false, false);
3980
3981       // The first three entries are reserved.
3982       this->got_plt_->set_current_data_size(3 * 4);
3983
3984       // Define _GLOBAL_OFFSET_TABLE_ at the start of the PLT.
3985       symtab->define_in_output_data("_GLOBAL_OFFSET_TABLE_", NULL,
3986                                     Symbol_table::PREDEFINED,
3987                                     this->got_plt_,
3988                                     0, 0, elfcpp::STT_OBJECT,
3989                                     elfcpp::STB_LOCAL,
3990                                     elfcpp::STV_HIDDEN, 0,
3991                                     false, false);
3992     }
3993   return this->got_;
3994 }
3995
3996 // Get the dynamic reloc section, creating it if necessary.
3997
3998 template<bool big_endian>
3999 typename Target_arm<big_endian>::Reloc_section*
4000 Target_arm<big_endian>::rel_dyn_section(Layout* layout)
4001 {
4002   if (this->rel_dyn_ == NULL)
4003     {
4004       gold_assert(layout != NULL);
4005       this->rel_dyn_ = new Reloc_section(parameters->options().combreloc());
4006       layout->add_output_section_data(".rel.dyn", elfcpp::SHT_REL,
4007                                       elfcpp::SHF_ALLOC, this->rel_dyn_, true,
4008                                       false, false, false);
4009     }
4010   return this->rel_dyn_;
4011 }
4012
4013 // Insn_template methods.
4014
4015 // Return byte size of an instruction template.
4016
4017 size_t
4018 Insn_template::size() const
4019 {
4020   switch (this->type())
4021     {
4022     case THUMB16_TYPE:
4023     case THUMB16_SPECIAL_TYPE:
4024       return 2;
4025     case ARM_TYPE:
4026     case THUMB32_TYPE:
4027     case DATA_TYPE:
4028       return 4;
4029     default:
4030       gold_unreachable();
4031     }
4032 }
4033
4034 // Return alignment of an instruction template.
4035
4036 unsigned
4037 Insn_template::alignment() const
4038 {
4039   switch (this->type())
4040     {
4041     case THUMB16_TYPE:
4042     case THUMB16_SPECIAL_TYPE:
4043     case THUMB32_TYPE:
4044       return 2;
4045     case ARM_TYPE:
4046     case DATA_TYPE:
4047       return 4;
4048     default:
4049       gold_unreachable();
4050     }
4051 }
4052
4053 // Stub_template methods.
4054
4055 Stub_template::Stub_template(
4056     Stub_type type, const Insn_template* insns,
4057      size_t insn_count)
4058   : type_(type), insns_(insns), insn_count_(insn_count), alignment_(1),
4059     entry_in_thumb_mode_(false), relocs_()
4060 {
4061   off_t offset = 0;
4062
4063   // Compute byte size and alignment of stub template.
4064   for (size_t i = 0; i < insn_count; i++)
4065     {
4066       unsigned insn_alignment = insns[i].alignment();
4067       size_t insn_size = insns[i].size();
4068       gold_assert((offset & (insn_alignment - 1)) == 0);
4069       this->alignment_ = std::max(this->alignment_, insn_alignment);
4070       switch (insns[i].type())
4071         {
4072         case Insn_template::THUMB16_TYPE:
4073         case Insn_template::THUMB16_SPECIAL_TYPE:
4074           if (i == 0)
4075             this->entry_in_thumb_mode_ = true;
4076           break;
4077
4078         case Insn_template::THUMB32_TYPE:
4079           if (insns[i].r_type() != elfcpp::R_ARM_NONE)
4080             this->relocs_.push_back(Reloc(i, offset));
4081           if (i == 0)
4082             this->entry_in_thumb_mode_ = true;
4083           break;
4084
4085         case Insn_template::ARM_TYPE:
4086           // Handle cases where the target is encoded within the
4087           // instruction.
4088           if (insns[i].r_type() == elfcpp::R_ARM_JUMP24)
4089             this->relocs_.push_back(Reloc(i, offset));
4090           break;
4091
4092         case Insn_template::DATA_TYPE:
4093           // Entry point cannot be data.
4094           gold_assert(i != 0);
4095           this->relocs_.push_back(Reloc(i, offset));
4096           break;
4097
4098         default:
4099           gold_unreachable();
4100         }
4101       offset += insn_size; 
4102     }
4103   this->size_ = offset;
4104 }
4105
4106 // Stub methods.
4107
4108 // Template to implement do_write for a specific target endianity.
4109
4110 template<bool big_endian>
4111 void inline
4112 Stub::do_fixed_endian_write(unsigned char* view, section_size_type view_size)
4113 {
4114   const Stub_template* stub_template = this->stub_template();
4115   const Insn_template* insns = stub_template->insns();
4116
4117   // FIXME:  We do not handle BE8 encoding yet.
4118   unsigned char* pov = view;
4119   for (size_t i = 0; i < stub_template->insn_count(); i++)
4120     {
4121       switch (insns[i].type())
4122         {
4123         case Insn_template::THUMB16_TYPE:
4124           elfcpp::Swap<16, big_endian>::writeval(pov, insns[i].data() & 0xffff);
4125           break;
4126         case Insn_template::THUMB16_SPECIAL_TYPE:
4127           elfcpp::Swap<16, big_endian>::writeval(
4128               pov,
4129               this->thumb16_special(i));
4130           break;
4131         case Insn_template::THUMB32_TYPE:
4132           {
4133             uint32_t hi = (insns[i].data() >> 16) & 0xffff;
4134             uint32_t lo = insns[i].data() & 0xffff;
4135             elfcpp::Swap<16, big_endian>::writeval(pov, hi);
4136             elfcpp::Swap<16, big_endian>::writeval(pov + 2, lo);
4137           }
4138           break;
4139         case Insn_template::ARM_TYPE:
4140         case Insn_template::DATA_TYPE:
4141           elfcpp::Swap<32, big_endian>::writeval(pov, insns[i].data());
4142           break;
4143         default:
4144           gold_unreachable();
4145         }
4146       pov += insns[i].size();
4147     }
4148   gold_assert(static_cast<section_size_type>(pov - view) == view_size);
4149
4150
4151 // Reloc_stub::Key methods.
4152
4153 // Dump a Key as a string for debugging.
4154
4155 std::string
4156 Reloc_stub::Key::name() const
4157 {
4158   if (this->r_sym_ == invalid_index)
4159     {
4160       // Global symbol key name
4161       // <stub-type>:<symbol name>:<addend>.
4162       const std::string sym_name = this->u_.symbol->name();
4163       // We need to print two hex number and two colons.  So just add 100 bytes
4164       // to the symbol name size.
4165       size_t len = sym_name.size() + 100;
4166       char* buffer = new char[len];
4167       int c = snprintf(buffer, len, "%d:%s:%x", this->stub_type_,
4168                        sym_name.c_str(), this->addend_);
4169       gold_assert(c > 0 && c < static_cast<int>(len));
4170       delete[] buffer;
4171       return std::string(buffer);
4172     }
4173   else
4174     {
4175       // local symbol key name
4176       // <stub-type>:<object>:<r_sym>:<addend>.
4177       const size_t len = 200;
4178       char buffer[len];
4179       int c = snprintf(buffer, len, "%d:%p:%u:%x", this->stub_type_,
4180                        this->u_.relobj, this->r_sym_, this->addend_);
4181       gold_assert(c > 0 && c < static_cast<int>(len));
4182       return std::string(buffer);
4183     }
4184 }
4185
4186 // Reloc_stub methods.
4187
4188 // Determine the type of stub needed, if any, for a relocation of R_TYPE at
4189 // LOCATION to DESTINATION.
4190 // This code is based on the arm_type_of_stub function in
4191 // bfd/elf32-arm.c.  We have changed the interface a liitle to keep the Stub
4192 // class simple.
4193
4194 Stub_type
4195 Reloc_stub::stub_type_for_reloc(
4196    unsigned int r_type,
4197    Arm_address location,
4198    Arm_address destination,
4199    bool target_is_thumb)
4200 {
4201   Stub_type stub_type = arm_stub_none;
4202
4203   // This is a bit ugly but we want to avoid using a templated class for
4204   // big and little endianities.
4205   bool may_use_blx;
4206   bool should_force_pic_veneer;
4207   bool thumb2;
4208   bool thumb_only;
4209   if (parameters->target().is_big_endian())
4210     {
4211       const Target_arm<true>* big_endian_target =
4212         Target_arm<true>::default_target();
4213       may_use_blx = big_endian_target->may_use_blx();
4214       should_force_pic_veneer = big_endian_target->should_force_pic_veneer();
4215       thumb2 = big_endian_target->using_thumb2();
4216       thumb_only = big_endian_target->using_thumb_only();
4217     }
4218   else
4219     {
4220       const Target_arm<false>* little_endian_target =
4221         Target_arm<false>::default_target();
4222       may_use_blx = little_endian_target->may_use_blx();
4223       should_force_pic_veneer = little_endian_target->should_force_pic_veneer();
4224       thumb2 = little_endian_target->using_thumb2();
4225       thumb_only = little_endian_target->using_thumb_only();
4226     }
4227
4228   int64_t branch_offset = (int64_t)destination - location;
4229
4230   if (r_type == elfcpp::R_ARM_THM_CALL || r_type == elfcpp::R_ARM_THM_JUMP24)
4231     {
4232       // Handle cases where:
4233       // - this call goes too far (different Thumb/Thumb2 max
4234       //   distance)
4235       // - it's a Thumb->Arm call and blx is not available, or it's a
4236       //   Thumb->Arm branch (not bl). A stub is needed in this case.
4237       if ((!thumb2
4238             && (branch_offset > THM_MAX_FWD_BRANCH_OFFSET
4239                 || (branch_offset < THM_MAX_BWD_BRANCH_OFFSET)))
4240           || (thumb2
4241               && (branch_offset > THM2_MAX_FWD_BRANCH_OFFSET
4242                   || (branch_offset < THM2_MAX_BWD_BRANCH_OFFSET)))
4243           || ((!target_is_thumb)
4244               && (((r_type == elfcpp::R_ARM_THM_CALL) && !may_use_blx)
4245                   || (r_type == elfcpp::R_ARM_THM_JUMP24))))
4246         {
4247           if (target_is_thumb)
4248             {
4249               // Thumb to thumb.
4250               if (!thumb_only)
4251                 {
4252                   stub_type = (parameters->options().shared()
4253                                || should_force_pic_veneer)
4254                     // PIC stubs.
4255                     ? ((may_use_blx
4256                         && (r_type == elfcpp::R_ARM_THM_CALL))
4257                        // V5T and above. Stub starts with ARM code, so
4258                        // we must be able to switch mode before
4259                        // reaching it, which is only possible for 'bl'
4260                        // (ie R_ARM_THM_CALL relocation).
4261                        ? arm_stub_long_branch_any_thumb_pic
4262                        // On V4T, use Thumb code only.
4263                        : arm_stub_long_branch_v4t_thumb_thumb_pic)
4264
4265                     // non-PIC stubs.
4266                     : ((may_use_blx
4267                         && (r_type == elfcpp::R_ARM_THM_CALL))
4268                        ? arm_stub_long_branch_any_any // V5T and above.
4269                        : arm_stub_long_branch_v4t_thumb_thumb); // V4T.
4270                 }
4271               else
4272                 {
4273                   stub_type = (parameters->options().shared()
4274                                || should_force_pic_veneer)
4275                     ? arm_stub_long_branch_thumb_only_pic       // PIC stub.
4276                     : arm_stub_long_branch_thumb_only;  // non-PIC stub.
4277                 }
4278             }
4279           else
4280             {
4281               // Thumb to arm.
4282              
4283               // FIXME: We should check that the input section is from an
4284               // object that has interwork enabled.
4285
4286               stub_type = (parameters->options().shared()
4287                            || should_force_pic_veneer)
4288                 // PIC stubs.
4289                 ? ((may_use_blx
4290                     && (r_type == elfcpp::R_ARM_THM_CALL))
4291                    ? arm_stub_long_branch_any_arm_pic   // V5T and above.
4292                    : arm_stub_long_branch_v4t_thumb_arm_pic)    // V4T.
4293
4294                 // non-PIC stubs.
4295                 : ((may_use_blx
4296                     && (r_type == elfcpp::R_ARM_THM_CALL))
4297                    ? arm_stub_long_branch_any_any       // V5T and above.
4298                    : arm_stub_long_branch_v4t_thumb_arm);       // V4T.
4299
4300               // Handle v4t short branches.
4301               if ((stub_type == arm_stub_long_branch_v4t_thumb_arm)
4302                   && (branch_offset <= THM_MAX_FWD_BRANCH_OFFSET)
4303                   && (branch_offset >= THM_MAX_BWD_BRANCH_OFFSET))
4304                 stub_type = arm_stub_short_branch_v4t_thumb_arm;
4305             }
4306         }
4307     }
4308   else if (r_type == elfcpp::R_ARM_CALL
4309            || r_type == elfcpp::R_ARM_JUMP24
4310            || r_type == elfcpp::R_ARM_PLT32)
4311     {
4312       if (target_is_thumb)
4313         {
4314           // Arm to thumb.
4315
4316           // FIXME: We should check that the input section is from an
4317           // object that has interwork enabled.
4318
4319           // We have an extra 2-bytes reach because of
4320           // the mode change (bit 24 (H) of BLX encoding).
4321           if (branch_offset > (ARM_MAX_FWD_BRANCH_OFFSET + 2)
4322               || (branch_offset < ARM_MAX_BWD_BRANCH_OFFSET)
4323               || ((r_type == elfcpp::R_ARM_CALL) && !may_use_blx)
4324               || (r_type == elfcpp::R_ARM_JUMP24)
4325               || (r_type == elfcpp::R_ARM_PLT32))
4326             {
4327               stub_type = (parameters->options().shared()
4328                            || should_force_pic_veneer)
4329                 // PIC stubs.
4330                 ? (may_use_blx
4331                    ? arm_stub_long_branch_any_thumb_pic// V5T and above.
4332                    : arm_stub_long_branch_v4t_arm_thumb_pic)    // V4T stub.
4333
4334                 // non-PIC stubs.
4335                 : (may_use_blx
4336                    ? arm_stub_long_branch_any_any       // V5T and above.
4337                    : arm_stub_long_branch_v4t_arm_thumb);       // V4T.
4338             }
4339         }
4340       else
4341         {
4342           // Arm to arm.
4343           if (branch_offset > ARM_MAX_FWD_BRANCH_OFFSET
4344               || (branch_offset < ARM_MAX_BWD_BRANCH_OFFSET))
4345             {
4346               stub_type = (parameters->options().shared()
4347                            || should_force_pic_veneer)
4348                 ? arm_stub_long_branch_any_arm_pic      // PIC stubs.
4349                 : arm_stub_long_branch_any_any;         /// non-PIC.
4350             }
4351         }
4352     }
4353
4354   return stub_type;
4355 }
4356
4357 // Cortex_a8_stub methods.
4358
4359 // Return the instruction for a THUMB16_SPECIAL_TYPE instruction template.
4360 // I is the position of the instruction template in the stub template.
4361
4362 uint16_t
4363 Cortex_a8_stub::do_thumb16_special(size_t i)
4364 {
4365   // The only use of this is to copy condition code from a conditional
4366   // branch being worked around to the corresponding conditional branch in
4367   // to the stub.
4368   gold_assert(this->stub_template()->type() == arm_stub_a8_veneer_b_cond
4369               && i == 0);
4370   uint16_t data = this->stub_template()->insns()[i].data();
4371   gold_assert((data & 0xff00U) == 0xd000U);
4372   data |= ((this->original_insn_ >> 22) & 0xf) << 8;
4373   return data;
4374 }
4375
4376 // Stub_factory methods.
4377
4378 Stub_factory::Stub_factory()
4379 {
4380   // The instruction template sequences are declared as static
4381   // objects and initialized first time the constructor runs.
4382  
4383   // Arm/Thumb -> Arm/Thumb long branch stub. On V5T and above, use blx
4384   // to reach the stub if necessary.
4385   static const Insn_template elf32_arm_stub_long_branch_any_any[] =
4386     {
4387       Insn_template::arm_insn(0xe51ff004),      // ldr   pc, [pc, #-4]
4388       Insn_template::data_word(0, elfcpp::R_ARM_ABS32, 0),
4389                                                 // dcd   R_ARM_ABS32(X)
4390     };
4391   
4392   // V4T Arm -> Thumb long branch stub. Used on V4T where blx is not
4393   // available.
4394   static const Insn_template elf32_arm_stub_long_branch_v4t_arm_thumb[] =
4395     {
4396       Insn_template::arm_insn(0xe59fc000),      // ldr   ip, [pc, #0]
4397       Insn_template::arm_insn(0xe12fff1c),      // bx    ip
4398       Insn_template::data_word(0, elfcpp::R_ARM_ABS32, 0),
4399                                                 // dcd   R_ARM_ABS32(X)
4400     };
4401   
4402   // Thumb -> Thumb long branch stub. Used on M-profile architectures.
4403   static const Insn_template elf32_arm_stub_long_branch_thumb_only[] =
4404     {
4405       Insn_template::thumb16_insn(0xb401),      // push {r0}
4406       Insn_template::thumb16_insn(0x4802),      // ldr  r0, [pc, #8]
4407       Insn_template::thumb16_insn(0x4684),      // mov  ip, r0
4408       Insn_template::thumb16_insn(0xbc01),      // pop  {r0}
4409       Insn_template::thumb16_insn(0x4760),      // bx   ip
4410       Insn_template::thumb16_insn(0xbf00),      // nop
4411       Insn_template::data_word(0, elfcpp::R_ARM_ABS32, 0),
4412                                                 // dcd  R_ARM_ABS32(X)
4413     };
4414   
4415   // V4T Thumb -> Thumb long branch stub. Using the stack is not
4416   // allowed.
4417   static const Insn_template elf32_arm_stub_long_branch_v4t_thumb_thumb[] =
4418     {
4419       Insn_template::thumb16_insn(0x4778),      // bx   pc
4420       Insn_template::thumb16_insn(0x46c0),      // nop
4421       Insn_template::arm_insn(0xe59fc000),      // ldr  ip, [pc, #0]
4422       Insn_template::arm_insn(0xe12fff1c),      // bx   ip
4423       Insn_template::data_word(0, elfcpp::R_ARM_ABS32, 0),
4424                                                 // dcd  R_ARM_ABS32(X)
4425     };
4426   
4427   // V4T Thumb -> ARM long branch stub. Used on V4T where blx is not
4428   // available.
4429   static const Insn_template elf32_arm_stub_long_branch_v4t_thumb_arm[] =
4430     {
4431       Insn_template::thumb16_insn(0x4778),      // bx   pc
4432       Insn_template::thumb16_insn(0x46c0),      // nop
4433       Insn_template::arm_insn(0xe51ff004),      // ldr   pc, [pc, #-4]
4434       Insn_template::data_word(0, elfcpp::R_ARM_ABS32, 0),
4435                                                 // dcd   R_ARM_ABS32(X)
4436     };
4437   
4438   // V4T Thumb -> ARM short branch stub. Shorter variant of the above
4439   // one, when the destination is close enough.
4440   static const Insn_template elf32_arm_stub_short_branch_v4t_thumb_arm[] =
4441     {
4442       Insn_template::thumb16_insn(0x4778),              // bx   pc
4443       Insn_template::thumb16_insn(0x46c0),              // nop
4444       Insn_template::arm_rel_insn(0xea000000, -8),      // b    (X-8)
4445     };
4446   
4447   // ARM/Thumb -> ARM long branch stub, PIC.  On V5T and above, use
4448   // blx to reach the stub if necessary.
4449   static const Insn_template elf32_arm_stub_long_branch_any_arm_pic[] =
4450     {
4451       Insn_template::arm_insn(0xe59fc000),      // ldr   r12, [pc]
4452       Insn_template::arm_insn(0xe08ff00c),      // add   pc, pc, ip
4453       Insn_template::data_word(0, elfcpp::R_ARM_REL32, -4),
4454                                                 // dcd   R_ARM_REL32(X-4)
4455     };
4456   
4457   // ARM/Thumb -> Thumb long branch stub, PIC.  On V5T and above, use
4458   // blx to reach the stub if necessary.  We can not add into pc;
4459   // it is not guaranteed to mode switch (different in ARMv6 and
4460   // ARMv7).
4461   static const Insn_template elf32_arm_stub_long_branch_any_thumb_pic[] =
4462     {
4463       Insn_template::arm_insn(0xe59fc004),      // ldr   r12, [pc, #4]
4464       Insn_template::arm_insn(0xe08fc00c),      // add   ip, pc, ip
4465       Insn_template::arm_insn(0xe12fff1c),      // bx    ip
4466       Insn_template::data_word(0, elfcpp::R_ARM_REL32, 0),
4467                                                 // dcd   R_ARM_REL32(X)
4468     };
4469   
4470   // V4T ARM -> ARM long branch stub, PIC.
4471   static const Insn_template elf32_arm_stub_long_branch_v4t_arm_thumb_pic[] =
4472     {
4473       Insn_template::arm_insn(0xe59fc004),      // ldr   ip, [pc, #4]
4474       Insn_template::arm_insn(0xe08fc00c),      // add   ip, pc, ip
4475       Insn_template::arm_insn(0xe12fff1c),      // bx    ip
4476       Insn_template::data_word(0, elfcpp::R_ARM_REL32, 0),
4477                                                 // dcd   R_ARM_REL32(X)
4478     };
4479   
4480   // V4T Thumb -> ARM long branch stub, PIC.
4481   static const Insn_template elf32_arm_stub_long_branch_v4t_thumb_arm_pic[] =
4482     {
4483       Insn_template::thumb16_insn(0x4778),      // bx   pc
4484       Insn_template::thumb16_insn(0x46c0),      // nop
4485       Insn_template::arm_insn(0xe59fc000),      // ldr  ip, [pc, #0]
4486       Insn_template::arm_insn(0xe08cf00f),      // add  pc, ip, pc
4487       Insn_template::data_word(0, elfcpp::R_ARM_REL32, -4),
4488                                                 // dcd  R_ARM_REL32(X)
4489     };
4490   
4491   // Thumb -> Thumb long branch stub, PIC. Used on M-profile
4492   // architectures.
4493   static const Insn_template elf32_arm_stub_long_branch_thumb_only_pic[] =
4494     {
4495       Insn_template::thumb16_insn(0xb401),      // push {r0}
4496       Insn_template::thumb16_insn(0x4802),      // ldr  r0, [pc, #8]
4497       Insn_template::thumb16_insn(0x46fc),      // mov  ip, pc
4498       Insn_template::thumb16_insn(0x4484),      // add  ip, r0
4499       Insn_template::thumb16_insn(0xbc01),      // pop  {r0}
4500       Insn_template::thumb16_insn(0x4760),      // bx   ip
4501       Insn_template::data_word(0, elfcpp::R_ARM_REL32, 4),
4502                                                 // dcd  R_ARM_REL32(X)
4503     };
4504   
4505   // V4T Thumb -> Thumb long branch stub, PIC. Using the stack is not
4506   // allowed.
4507   static const Insn_template elf32_arm_stub_long_branch_v4t_thumb_thumb_pic[] =
4508     {
4509       Insn_template::thumb16_insn(0x4778),      // bx   pc
4510       Insn_template::thumb16_insn(0x46c0),      // nop
4511       Insn_template::arm_insn(0xe59fc004),      // ldr  ip, [pc, #4]
4512       Insn_template::arm_insn(0xe08fc00c),      // add   ip, pc, ip
4513       Insn_template::arm_insn(0xe12fff1c),      // bx   ip
4514       Insn_template::data_word(0, elfcpp::R_ARM_REL32, 0),
4515                                                 // dcd  R_ARM_REL32(X)
4516     };
4517   
4518   // Cortex-A8 erratum-workaround stubs.
4519   
4520   // Stub used for conditional branches (which may be beyond +/-1MB away,
4521   // so we can't use a conditional branch to reach this stub).
4522   
4523   // original code:
4524   //
4525   //    b<cond> X
4526   // after:
4527   //
4528   static const Insn_template elf32_arm_stub_a8_veneer_b_cond[] =
4529     {
4530       Insn_template::thumb16_bcond_insn(0xd001),        //      b<cond>.n true
4531       Insn_template::thumb32_b_insn(0xf000b800, -4),    //      b.w after
4532       Insn_template::thumb32_b_insn(0xf000b800, -4)     // true:
4533                                                         //      b.w X
4534     };
4535   
4536   // Stub used for b.w and bl.w instructions.
4537   
4538   static const Insn_template elf32_arm_stub_a8_veneer_b[] =
4539     {
4540       Insn_template::thumb32_b_insn(0xf000b800, -4)     // b.w dest
4541     };
4542   
4543   static const Insn_template elf32_arm_stub_a8_veneer_bl[] =
4544     {
4545       Insn_template::thumb32_b_insn(0xf000b800, -4)     // b.w dest
4546     };
4547   
4548   // Stub used for Thumb-2 blx.w instructions.  We modified the original blx.w
4549   // instruction (which switches to ARM mode) to point to this stub.  Jump to
4550   // the real destination using an ARM-mode branch.
4551   static const Insn_template elf32_arm_stub_a8_veneer_blx[] =
4552     {
4553       Insn_template::arm_rel_insn(0xea000000, -8)       // b dest
4554     };
4555
4556   // Stub used to provide an interworking for R_ARM_V4BX relocation
4557   // (bx r[n] instruction).
4558   static const Insn_template elf32_arm_stub_v4_veneer_bx[] =
4559     {
4560       Insn_template::arm_insn(0xe3100001),              // tst   r<n>, #1
4561       Insn_template::arm_insn(0x01a0f000),              // moveq pc, r<n>
4562       Insn_template::arm_insn(0xe12fff10)               // bx    r<n>
4563     };
4564
4565   // Fill in the stub template look-up table.  Stub templates are constructed
4566   // per instance of Stub_factory for fast look-up without locking
4567   // in a thread-enabled environment.
4568
4569   this->stub_templates_[arm_stub_none] =
4570     new Stub_template(arm_stub_none, NULL, 0);
4571
4572 #define DEF_STUB(x)     \
4573   do \
4574     { \
4575       size_t array_size \
4576         = sizeof(elf32_arm_stub_##x) / sizeof(elf32_arm_stub_##x[0]); \
4577       Stub_type type = arm_stub_##x; \
4578       this->stub_templates_[type] = \
4579         new Stub_template(type, elf32_arm_stub_##x, array_size); \
4580     } \
4581   while (0);
4582
4583   DEF_STUBS
4584 #undef DEF_STUB
4585 }
4586
4587 // Stub_table methods.
4588
4589 // Removel all Cortex-A8 stub.
4590
4591 template<bool big_endian>
4592 void
4593 Stub_table<big_endian>::remove_all_cortex_a8_stubs()
4594 {
4595   for (Cortex_a8_stub_list::iterator p = this->cortex_a8_stubs_.begin();
4596        p != this->cortex_a8_stubs_.end();
4597        ++p)
4598     delete p->second;
4599   this->cortex_a8_stubs_.clear();
4600 }
4601
4602 // Relocate one stub.  This is a helper for Stub_table::relocate_stubs().
4603
4604 template<bool big_endian>
4605 void
4606 Stub_table<big_endian>::relocate_stub(
4607     Stub* stub,
4608     const Relocate_info<32, big_endian>* relinfo,
4609     Target_arm<big_endian>* arm_target,
4610     Output_section* output_section,
4611     unsigned char* view,
4612     Arm_address address,
4613     section_size_type view_size)
4614 {
4615   const Stub_template* stub_template = stub->stub_template();
4616   if (stub_template->reloc_count() != 0)
4617     {
4618       // Adjust view to cover the stub only.
4619       section_size_type offset = stub->offset();
4620       section_size_type stub_size = stub_template->size();
4621       gold_assert(offset + stub_size <= view_size);
4622
4623       arm_target->relocate_stub(stub, relinfo, output_section, view + offset,
4624                                 address + offset, stub_size);
4625     }
4626 }
4627
4628 // Relocate all stubs in this stub table.
4629
4630 template<bool big_endian>
4631 void
4632 Stub_table<big_endian>::relocate_stubs(
4633     const Relocate_info<32, big_endian>* relinfo,
4634     Target_arm<big_endian>* arm_target,
4635     Output_section* output_section,
4636     unsigned char* view,
4637     Arm_address address,
4638     section_size_type view_size)
4639 {
4640   // If we are passed a view bigger than the stub table's.  we need to
4641   // adjust the view.
4642   gold_assert(address == this->address()
4643               && (view_size
4644                   == static_cast<section_size_type>(this->data_size())));
4645
4646   // Relocate all relocation stubs.
4647   for (typename Reloc_stub_map::const_iterator p = this->reloc_stubs_.begin();
4648       p != this->reloc_stubs_.end();
4649       ++p)
4650     this->relocate_stub(p->second, relinfo, arm_target, output_section, view,
4651                         address, view_size);
4652
4653   // Relocate all Cortex-A8 stubs.
4654   for (Cortex_a8_stub_list::iterator p = this->cortex_a8_stubs_.begin();
4655        p != this->cortex_a8_stubs_.end();
4656        ++p)
4657     this->relocate_stub(p->second, relinfo, arm_target, output_section, view,
4658                         address, view_size);
4659
4660   // Relocate all ARM V4BX stubs.
4661   for (Arm_v4bx_stub_list::iterator p = this->arm_v4bx_stubs_.begin();
4662        p != this->arm_v4bx_stubs_.end();
4663        ++p)
4664     {
4665       if (*p != NULL)
4666         this->relocate_stub(*p, relinfo, arm_target, output_section, view,
4667                             address, view_size);
4668     }
4669 }
4670
4671 // Write out the stubs to file.
4672
4673 template<bool big_endian>
4674 void
4675 Stub_table<big_endian>::do_write(Output_file* of)
4676 {
4677   off_t offset = this->offset();
4678   const section_size_type oview_size =
4679     convert_to_section_size_type(this->data_size());
4680   unsigned char* const oview = of->get_output_view(offset, oview_size);
4681
4682   // Write relocation stubs.
4683   for (typename Reloc_stub_map::const_iterator p = this->reloc_stubs_.begin();
4684       p != this->reloc_stubs_.end();
4685       ++p)
4686     {
4687       Reloc_stub* stub = p->second;
4688       Arm_address address = this->address() + stub->offset();
4689       gold_assert(address
4690                   == align_address(address,
4691                                    stub->stub_template()->alignment()));
4692       stub->write(oview + stub->offset(), stub->stub_template()->size(),
4693                   big_endian);
4694     }
4695
4696   // Write Cortex-A8 stubs.
4697   for (Cortex_a8_stub_list::const_iterator p = this->cortex_a8_stubs_.begin();
4698        p != this->cortex_a8_stubs_.end();
4699        ++p)
4700     {
4701       Cortex_a8_stub* stub = p->second;
4702       Arm_address address = this->address() + stub->offset();
4703       gold_assert(address
4704                   == align_address(address,
4705                                    stub->stub_template()->alignment()));
4706       stub->write(oview + stub->offset(), stub->stub_template()->size(),
4707                   big_endian);
4708     }
4709
4710   // Write ARM V4BX relocation stubs.
4711   for (Arm_v4bx_stub_list::const_iterator p = this->arm_v4bx_stubs_.begin();
4712        p != this->arm_v4bx_stubs_.end();
4713        ++p)
4714     {
4715       if (*p == NULL)
4716         continue;
4717
4718       Arm_address address = this->address() + (*p)->offset();
4719       gold_assert(address
4720                   == align_address(address,
4721                                    (*p)->stub_template()->alignment()));
4722       (*p)->write(oview + (*p)->offset(), (*p)->stub_template()->size(),
4723                   big_endian);
4724     }
4725
4726   of->write_output_view(this->offset(), oview_size, oview);
4727 }
4728
4729 // Update the data size and address alignment of the stub table at the end
4730 // of a relaxation pass.   Return true if either the data size or the
4731 // alignment changed in this relaxation pass.
4732
4733 template<bool big_endian>
4734 bool
4735 Stub_table<big_endian>::update_data_size_and_addralign()
4736 {
4737   // Go over all stubs in table to compute data size and address alignment.
4738   off_t size = this->reloc_stubs_size_;
4739   unsigned addralign = this->reloc_stubs_addralign_;
4740
4741   for (Cortex_a8_stub_list::const_iterator p = this->cortex_a8_stubs_.begin();
4742        p != this->cortex_a8_stubs_.end();
4743        ++p)
4744     {
4745       const Stub_template* stub_template = p->second->stub_template();
4746       addralign = std::max(addralign, stub_template->alignment());
4747       size = (align_address(size, stub_template->alignment())
4748               + stub_template->size());
4749     }
4750
4751   for (Arm_v4bx_stub_list::const_iterator p = this->arm_v4bx_stubs_.begin();
4752        p != this->arm_v4bx_stubs_.end();
4753        ++p)
4754     {
4755       if (*p == NULL)
4756         continue;
4757
4758       const Stub_template* stub_template = (*p)->stub_template();
4759       addralign = std::max(addralign, stub_template->alignment());
4760       size = (align_address(size, stub_template->alignment())
4761               + stub_template->size());
4762     }
4763
4764   // Check if either data size or alignment changed in this pass.
4765   // Update prev_data_size_ and prev_addralign_.  These will be used
4766   // as the current data size and address alignment for the next pass.
4767   bool changed = size != this->prev_data_size_;
4768   this->prev_data_size_ = size; 
4769
4770   if (addralign != this->prev_addralign_)
4771     changed = true;
4772   this->prev_addralign_ = addralign;
4773
4774   return changed;
4775 }
4776
4777 // Finalize the stubs.  This sets the offsets of the stubs within the stub
4778 // table.  It also marks all input sections needing Cortex-A8 workaround.
4779
4780 template<bool big_endian>
4781 void
4782 Stub_table<big_endian>::finalize_stubs()
4783 {
4784   off_t off = this->reloc_stubs_size_;
4785   for (Cortex_a8_stub_list::const_iterator p = this->cortex_a8_stubs_.begin();
4786        p != this->cortex_a8_stubs_.end();
4787        ++p)
4788     {
4789       Cortex_a8_stub* stub = p->second;
4790       const Stub_template* stub_template = stub->stub_template();
4791       uint64_t stub_addralign = stub_template->alignment();
4792       off = align_address(off, stub_addralign);
4793       stub->set_offset(off);
4794       off += stub_template->size();
4795
4796       // Mark input section so that we can determine later if a code section
4797       // needs the Cortex-A8 workaround quickly.
4798       Arm_relobj<big_endian>* arm_relobj =
4799         Arm_relobj<big_endian>::as_arm_relobj(stub->relobj());
4800       arm_relobj->mark_section_for_cortex_a8_workaround(stub->shndx());
4801     }
4802
4803   for (Arm_v4bx_stub_list::const_iterator p = this->arm_v4bx_stubs_.begin();
4804       p != this->arm_v4bx_stubs_.end();
4805       ++p)
4806     {
4807       if (*p == NULL)
4808         continue;
4809
4810       const Stub_template* stub_template = (*p)->stub_template();
4811       uint64_t stub_addralign = stub_template->alignment();
4812       off = align_address(off, stub_addralign);
4813       (*p)->set_offset(off);
4814       off += stub_template->size();
4815     }
4816
4817   gold_assert(off <= this->prev_data_size_);
4818 }
4819
4820 // Apply Cortex-A8 workaround to an address range between VIEW_ADDRESS
4821 // and VIEW_ADDRESS + VIEW_SIZE - 1.  VIEW points to the mapped address
4822 // of the address range seen by the linker.
4823
4824 template<bool big_endian>
4825 void
4826 Stub_table<big_endian>::apply_cortex_a8_workaround_to_address_range(
4827     Target_arm<big_endian>* arm_target,
4828     unsigned char* view,
4829     Arm_address view_address,
4830     section_size_type view_size)
4831 {
4832   // Cortex-A8 stubs are sorted by addresses of branches being fixed up.
4833   for (Cortex_a8_stub_list::const_iterator p =
4834          this->cortex_a8_stubs_.lower_bound(view_address);
4835        ((p != this->cortex_a8_stubs_.end())
4836         && (p->first < (view_address + view_size)));
4837        ++p)
4838     {
4839       // We do not store the THUMB bit in the LSB of either the branch address
4840       // or the stub offset.  There is no need to strip the LSB.
4841       Arm_address branch_address = p->first;
4842       const Cortex_a8_stub* stub = p->second;
4843       Arm_address stub_address = this->address() + stub->offset();
4844
4845       // Offset of the branch instruction relative to this view.
4846       section_size_type offset =
4847         convert_to_section_size_type(branch_address - view_address);
4848       gold_assert((offset + 4) <= view_size);
4849
4850       arm_target->apply_cortex_a8_workaround(stub, stub_address,
4851                                              view + offset, branch_address);
4852     }
4853 }
4854
4855 // Arm_input_section methods.
4856
4857 // Initialize an Arm_input_section.
4858
4859 template<bool big_endian>
4860 void
4861 Arm_input_section<big_endian>::init()
4862 {
4863   Relobj* relobj = this->relobj();
4864   unsigned int shndx = this->shndx();
4865
4866   // Cache these to speed up size and alignment queries.  It is too slow
4867   // to call section_addraglin and section_size every time.
4868   this->original_addralign_ = relobj->section_addralign(shndx);
4869   this->original_size_ = relobj->section_size(shndx);
4870
4871   // We want to make this look like the original input section after
4872   // output sections are finalized.
4873   Output_section* os = relobj->output_section(shndx);
4874   off_t offset = relobj->output_section_offset(shndx);
4875   gold_assert(os != NULL && !relobj->is_output_section_offset_invalid(shndx));
4876   this->set_address(os->address() + offset);
4877   this->set_file_offset(os->offset() + offset);
4878
4879   this->set_current_data_size(this->original_size_);
4880   this->finalize_data_size();
4881 }
4882
4883 template<bool big_endian>
4884 void
4885 Arm_input_section<big_endian>::do_write(Output_file* of)
4886 {
4887   // We have to write out the original section content.
4888   section_size_type section_size;
4889   const unsigned char* section_contents =
4890     this->relobj()->section_contents(this->shndx(), &section_size, false); 
4891   of->write(this->offset(), section_contents, section_size); 
4892
4893   // If this owns a stub table and it is not empty, write it.
4894   if (this->is_stub_table_owner() && !this->stub_table_->empty())
4895     this->stub_table_->write(of);
4896 }
4897
4898 // Finalize data size.
4899
4900 template<bool big_endian>
4901 void
4902 Arm_input_section<big_endian>::set_final_data_size()
4903 {
4904   // If this owns a stub table, finalize its data size as well.
4905   if (this->is_stub_table_owner())
4906     {
4907       uint64_t address = this->address();
4908
4909       // The stub table comes after the original section contents.
4910       address += this->original_size_;
4911       address = align_address(address, this->stub_table_->addralign());
4912       off_t offset = this->offset() + (address - this->address());
4913       this->stub_table_->set_address_and_file_offset(address, offset);
4914       address += this->stub_table_->data_size();
4915       gold_assert(address == this->address() + this->current_data_size());
4916     }
4917
4918   this->set_data_size(this->current_data_size());
4919 }
4920
4921 // Reset address and file offset.
4922
4923 template<bool big_endian>
4924 void
4925 Arm_input_section<big_endian>::do_reset_address_and_file_offset()
4926 {
4927   // Size of the original input section contents.
4928   off_t off = convert_types<off_t, uint64_t>(this->original_size_);
4929
4930   // If this is a stub table owner, account for the stub table size.
4931   if (this->is_stub_table_owner())
4932     {
4933       Stub_table<big_endian>* stub_table = this->stub_table_;
4934
4935       // Reset the stub table's address and file offset.  The
4936       // current data size for child will be updated after that.
4937       stub_table_->reset_address_and_file_offset();
4938       off = align_address(off, stub_table_->addralign());
4939       off += stub_table->current_data_size();
4940     }
4941
4942   this->set_current_data_size(off);
4943 }
4944
4945 // Arm_exidx_cantunwind methods.
4946
4947 // Write this to Output file OF for a fixed endianity.
4948
4949 template<bool big_endian>
4950 void
4951 Arm_exidx_cantunwind::do_fixed_endian_write(Output_file* of)
4952 {
4953   off_t offset = this->offset();
4954   const section_size_type oview_size = 8;
4955   unsigned char* const oview = of->get_output_view(offset, oview_size);
4956   
4957   typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
4958   Valtype* wv = reinterpret_cast<Valtype*>(oview);
4959
4960   Output_section* os = this->relobj_->output_section(this->shndx_);
4961   gold_assert(os != NULL);
4962
4963   Arm_relobj<big_endian>* arm_relobj =
4964     Arm_relobj<big_endian>::as_arm_relobj(this->relobj_);
4965   Arm_address output_offset =
4966     arm_relobj->get_output_section_offset(this->shndx_);
4967   Arm_address section_start;
4968   if(output_offset != Arm_relobj<big_endian>::invalid_address)
4969     section_start = os->address() + output_offset;
4970   else
4971     {
4972       // Currently this only happens for a relaxed section.
4973       const Output_relaxed_input_section* poris =
4974         os->find_relaxed_input_section(this->relobj_, this->shndx_);
4975       gold_assert(poris != NULL);
4976       section_start = poris->address();
4977     }
4978
4979   // We always append this to the end of an EXIDX section.
4980   Arm_address output_address =
4981     section_start + this->relobj_->section_size(this->shndx_);
4982
4983   // Write out the entry.  The first word either points to the beginning
4984   // or after the end of a text section.  The second word is the special
4985   // EXIDX_CANTUNWIND value.
4986   uint32_t prel31_offset = output_address - this->address();
4987   if (utils::has_overflow<31>(offset))
4988     gold_error(_("PREL31 overflow in EXIDX_CANTUNWIND entry"));
4989   elfcpp::Swap<32, big_endian>::writeval(wv, prel31_offset & 0x7fffffffU);
4990   elfcpp::Swap<32, big_endian>::writeval(wv + 1, elfcpp::EXIDX_CANTUNWIND);
4991
4992   of->write_output_view(this->offset(), oview_size, oview);
4993 }
4994
4995 // Arm_exidx_merged_section methods.
4996
4997 // Constructor for Arm_exidx_merged_section.
4998 // EXIDX_INPUT_SECTION points to the unmodified EXIDX input section.
4999 // SECTION_OFFSET_MAP points to a section offset map describing how
5000 // parts of the input section are mapped to output.  DELETED_BYTES is
5001 // the number of bytes deleted from the EXIDX input section.
5002
5003 Arm_exidx_merged_section::Arm_exidx_merged_section(
5004     const Arm_exidx_input_section& exidx_input_section,
5005     const Arm_exidx_section_offset_map& section_offset_map,
5006     uint32_t deleted_bytes)
5007   : Output_relaxed_input_section(exidx_input_section.relobj(),
5008                                  exidx_input_section.shndx(),
5009                                  exidx_input_section.addralign()),
5010     exidx_input_section_(exidx_input_section),
5011     section_offset_map_(section_offset_map)
5012 {
5013   // Fix size here so that we do not need to implement set_final_data_size.
5014   this->set_data_size(exidx_input_section.size() - deleted_bytes);
5015   this->fix_data_size();
5016 }
5017
5018 // Given an input OBJECT, an input section index SHNDX within that
5019 // object, and an OFFSET relative to the start of that input
5020 // section, return whether or not the corresponding offset within
5021 // the output section is known.  If this function returns true, it
5022 // sets *POUTPUT to the output offset.  The value -1 indicates that
5023 // this input offset is being discarded.
5024
5025 bool
5026 Arm_exidx_merged_section::do_output_offset(
5027     const Relobj* relobj,
5028     unsigned int shndx,
5029     section_offset_type offset,
5030     section_offset_type* poutput) const
5031 {
5032   // We only handle offsets for the original EXIDX input section.
5033   if (relobj != this->exidx_input_section_.relobj()
5034       || shndx != this->exidx_input_section_.shndx())
5035     return false;
5036
5037   section_offset_type section_size =
5038     convert_types<section_offset_type>(this->exidx_input_section_.size());
5039   if (offset < 0 || offset >= section_size)
5040     // Input offset is out of valid range.
5041     *poutput = -1;
5042   else
5043     {
5044       // We need to look up the section offset map to determine the output
5045       // offset.  Find the reference point in map that is first offset
5046       // bigger than or equal to this offset.
5047       Arm_exidx_section_offset_map::const_iterator p =
5048         this->section_offset_map_.lower_bound(offset);
5049
5050       // The section offset maps are build such that this should not happen if
5051       // input offset is in the valid range.
5052       gold_assert(p != this->section_offset_map_.end());
5053
5054       // We need to check if this is dropped.
5055      section_offset_type ref = p->first;
5056      section_offset_type mapped_ref = p->second;
5057
5058       if (mapped_ref != Arm_exidx_input_section::invalid_offset)
5059         // Offset is present in output.
5060         *poutput = mapped_ref + (offset - ref);
5061       else
5062         // Offset is discarded owing to EXIDX entry merging.
5063         *poutput = -1;
5064     }
5065   
5066   return true;
5067 }
5068
5069 // Write this to output file OF.
5070
5071 void
5072 Arm_exidx_merged_section::do_write(Output_file* of)
5073 {
5074   // If we retain or discard the whole EXIDX input section,  we would
5075   // not be here.
5076   gold_assert(this->data_size() != this->exidx_input_section_.size()
5077               && this->data_size() != 0);
5078
5079   off_t offset = this->offset();
5080   const section_size_type oview_size = this->data_size();
5081   unsigned char* const oview = of->get_output_view(offset, oview_size);
5082   
5083   Output_section* os = this->relobj()->output_section(this->shndx());
5084   gold_assert(os != NULL);
5085
5086   // Get contents of EXIDX input section.
5087   section_size_type section_size;
5088   const unsigned char* section_contents =
5089     this->relobj()->section_contents(this->shndx(), &section_size, false); 
5090   gold_assert(section_size == this->exidx_input_section_.size());
5091
5092   // Go over spans of input offsets and write only those that are not
5093   // discarded.
5094   section_offset_type in_start = 0;
5095   section_offset_type out_start = 0;
5096   for(Arm_exidx_section_offset_map::const_iterator p =
5097         this->section_offset_map_.begin();
5098       p != this->section_offset_map_.end();
5099       ++p)
5100     {
5101       section_offset_type in_end = p->first;
5102       gold_assert(in_end >= in_start);
5103       section_offset_type out_end = p->second;
5104       size_t in_chunk_size = convert_types<size_t>(in_end - in_start + 1);
5105       if (out_end != -1)
5106         {
5107           size_t out_chunk_size =
5108             convert_types<size_t>(out_end - out_start + 1);
5109           gold_assert(out_chunk_size == in_chunk_size);
5110           memcpy(oview + out_start, section_contents + in_start,
5111                  out_chunk_size);
5112           out_start += out_chunk_size;
5113         }
5114       in_start += in_chunk_size;
5115     }
5116
5117   gold_assert(convert_to_section_size_type(out_start) == oview_size);
5118   of->write_output_view(this->offset(), oview_size, oview);
5119 }
5120
5121 // Arm_exidx_fixup methods.
5122
5123 // Append an EXIDX_CANTUNWIND in the current output section if the last entry
5124 // is not an EXIDX_CANTUNWIND entry already.  The new EXIDX_CANTUNWIND entry
5125 // points to the end of the last seen EXIDX section.
5126
5127 void
5128 Arm_exidx_fixup::add_exidx_cantunwind_as_needed()
5129 {
5130   if (this->last_unwind_type_ != UT_EXIDX_CANTUNWIND
5131       && this->last_input_section_ != NULL)
5132     {
5133       Relobj* relobj = this->last_input_section_->relobj();
5134       unsigned int text_shndx = this->last_input_section_->link();
5135       Arm_exidx_cantunwind* cantunwind =
5136         new Arm_exidx_cantunwind(relobj, text_shndx);
5137       this->exidx_output_section_->add_output_section_data(cantunwind);
5138       this->last_unwind_type_ = UT_EXIDX_CANTUNWIND;
5139     }
5140 }
5141
5142 // Process an EXIDX section entry in input.  Return whether this entry
5143 // can be deleted in the output.  SECOND_WORD in the second word of the
5144 // EXIDX entry.
5145
5146 bool
5147 Arm_exidx_fixup::process_exidx_entry(uint32_t second_word)
5148 {
5149   bool delete_entry;
5150   if (second_word == elfcpp::EXIDX_CANTUNWIND)
5151     {
5152       // Merge if previous entry is also an EXIDX_CANTUNWIND.
5153       delete_entry = this->last_unwind_type_ == UT_EXIDX_CANTUNWIND;
5154       this->last_unwind_type_ = UT_EXIDX_CANTUNWIND;
5155     }
5156   else if ((second_word & 0x80000000) != 0)
5157     {
5158       // Inlined unwinding data.  Merge if equal to previous.
5159       delete_entry = (this->last_unwind_type_ == UT_INLINED_ENTRY
5160                       && this->last_inlined_entry_ == second_word);
5161       this->last_unwind_type_ = UT_INLINED_ENTRY;
5162       this->last_inlined_entry_ = second_word;
5163     }
5164   else
5165     {
5166       // Normal table entry.  In theory we could merge these too,
5167       // but duplicate entries are likely to be much less common.
5168       delete_entry = false;
5169       this->last_unwind_type_ = UT_NORMAL_ENTRY;
5170     }
5171   return delete_entry;
5172 }
5173
5174 // Update the current section offset map during EXIDX section fix-up.
5175 // If there is no map, create one.  INPUT_OFFSET is the offset of a
5176 // reference point, DELETED_BYTES is the number of deleted by in the
5177 // section so far.  If DELETE_ENTRY is true, the reference point and
5178 // all offsets after the previous reference point are discarded.
5179
5180 void
5181 Arm_exidx_fixup::update_offset_map(
5182     section_offset_type input_offset,
5183     section_size_type deleted_bytes,
5184     bool delete_entry)
5185 {
5186   if (this->section_offset_map_ == NULL)
5187     this->section_offset_map_ = new Arm_exidx_section_offset_map();
5188   section_offset_type output_offset =
5189     (delete_entry
5190      ? Arm_exidx_input_section::invalid_offset
5191      : input_offset - deleted_bytes);
5192   (*this->section_offset_map_)[input_offset] = output_offset;
5193 }
5194
5195 // Process EXIDX_INPUT_SECTION for EXIDX entry merging.  Return the number of
5196 // bytes deleted.  If some entries are merged, also store a pointer to a newly
5197 // created Arm_exidx_section_offset_map object in *PSECTION_OFFSET_MAP.  The
5198 // caller owns the map and is responsible for releasing it after use.
5199
5200 template<bool big_endian>
5201 uint32_t
5202 Arm_exidx_fixup::process_exidx_section(
5203     const Arm_exidx_input_section* exidx_input_section,
5204     Arm_exidx_section_offset_map** psection_offset_map)
5205 {
5206   Relobj* relobj = exidx_input_section->relobj();
5207   unsigned shndx = exidx_input_section->shndx();
5208   section_size_type section_size;
5209   const unsigned char* section_contents =
5210     relobj->section_contents(shndx, &section_size, false);
5211
5212   if ((section_size % 8) != 0)
5213     {
5214       // Something is wrong with this section.  Better not touch it.
5215       gold_error(_("uneven .ARM.exidx section size in %s section %u"),
5216                  relobj->name().c_str(), shndx);
5217       this->last_input_section_ = exidx_input_section;
5218       this->last_unwind_type_ = UT_NONE;
5219       return 0;
5220     }
5221   
5222   uint32_t deleted_bytes = 0;
5223   bool prev_delete_entry = false;
5224   gold_assert(this->section_offset_map_ == NULL);
5225
5226   for (section_size_type i = 0; i < section_size; i += 8)
5227     {
5228       typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
5229       const Valtype* wv =
5230           reinterpret_cast<const Valtype*>(section_contents + i + 4);
5231       uint32_t second_word = elfcpp::Swap<32, big_endian>::readval(wv);
5232
5233       bool delete_entry = this->process_exidx_entry(second_word);
5234
5235       // Entry deletion causes changes in output offsets.  We use a std::map
5236       // to record these.  And entry (x, y) means input offset x
5237       // is mapped to output offset y.  If y is invalid_offset, then x is
5238       // dropped in the output.  Because of the way std::map::lower_bound
5239       // works, we record the last offset in a region w.r.t to keeping or
5240       // dropping.  If there is no entry (x0, y0) for an input offset x0,
5241       // the output offset y0 of it is determined by the output offset y1 of
5242       // the smallest input offset x1 > x0 that there is an (x1, y1) entry
5243       // in the map.  If y1 is not -1, then y0 = y1 + x0 - x1.  Othewise, y1
5244       // y0 is also -1.
5245       if (delete_entry != prev_delete_entry && i != 0)
5246         this->update_offset_map(i - 1, deleted_bytes, prev_delete_entry);
5247
5248       // Update total deleted bytes for this entry.
5249       if (delete_entry)
5250         deleted_bytes += 8;
5251
5252       prev_delete_entry = delete_entry;
5253     }
5254   
5255   // If section offset map is not NULL, make an entry for the end of
5256   // section.
5257   if (this->section_offset_map_ != NULL)
5258     update_offset_map(section_size - 1, deleted_bytes, prev_delete_entry);
5259
5260   *psection_offset_map = this->section_offset_map_;
5261   this->section_offset_map_ = NULL;
5262   this->last_input_section_ = exidx_input_section;
5263   
5264   // Set the first output text section so that we can link the EXIDX output
5265   // section to it.  Ignore any EXIDX input section that is completely merged.
5266   if (this->first_output_text_section_ == NULL
5267       && deleted_bytes != section_size)
5268     {
5269       unsigned int link = exidx_input_section->link();
5270       Output_section* os = relobj->output_section(link);
5271       gold_assert(os != NULL);
5272       this->first_output_text_section_ = os;
5273     }
5274
5275   return deleted_bytes;
5276 }
5277
5278 // Arm_output_section methods.
5279
5280 // Create a stub group for input sections from BEGIN to END.  OWNER
5281 // points to the input section to be the owner a new stub table.
5282
5283 template<bool big_endian>
5284 void
5285 Arm_output_section<big_endian>::create_stub_group(
5286   Input_section_list::const_iterator begin,
5287   Input_section_list::const_iterator end,
5288   Input_section_list::const_iterator owner,
5289   Target_arm<big_endian>* target,
5290   std::vector<Output_relaxed_input_section*>* new_relaxed_sections)
5291 {
5292   // We use a different kind of relaxed section in an EXIDX section.
5293   // The static casting from Output_relaxed_input_section to
5294   // Arm_input_section is invalid in an EXIDX section.  We are okay
5295   // because we should not be calling this for an EXIDX section. 
5296   gold_assert(this->type() != elfcpp::SHT_ARM_EXIDX);
5297
5298   // Currently we convert ordinary input sections into relaxed sections only
5299   // at this point but we may want to support creating relaxed input section
5300   // very early.  So we check here to see if owner is already a relaxed
5301   // section.
5302   
5303   Arm_input_section<big_endian>* arm_input_section;
5304   if (owner->is_relaxed_input_section())
5305     {
5306       arm_input_section =
5307         Arm_input_section<big_endian>::as_arm_input_section(
5308           owner->relaxed_input_section());
5309     }
5310   else
5311     {
5312       gold_assert(owner->is_input_section());
5313       // Create a new relaxed input section.
5314       arm_input_section =
5315         target->new_arm_input_section(owner->relobj(), owner->shndx());
5316       new_relaxed_sections->push_back(arm_input_section);
5317     }
5318
5319   // Create a stub table.
5320   Stub_table<big_endian>* stub_table =
5321     target->new_stub_table(arm_input_section);
5322
5323   arm_input_section->set_stub_table(stub_table);
5324   
5325   Input_section_list::const_iterator p = begin;
5326   Input_section_list::const_iterator prev_p;
5327
5328   // Look for input sections or relaxed input sections in [begin ... end].
5329   do
5330     {
5331       if (p->is_input_section() || p->is_relaxed_input_section())
5332         {
5333           // The stub table information for input sections live
5334           // in their objects.
5335           Arm_relobj<big_endian>* arm_relobj =
5336             Arm_relobj<big_endian>::as_arm_relobj(p->relobj());
5337           arm_relobj->set_stub_table(p->shndx(), stub_table);
5338         }
5339       prev_p = p++;
5340     }
5341   while (prev_p != end);
5342 }
5343
5344 // Group input sections for stub generation.  GROUP_SIZE is roughly the limit
5345 // of stub groups.  We grow a stub group by adding input section until the
5346 // size is just below GROUP_SIZE.  The last input section will be converted
5347 // into a stub table.  If STUB_ALWAYS_AFTER_BRANCH is false, we also add
5348 // input section after the stub table, effectively double the group size.
5349 // 
5350 // This is similar to the group_sections() function in elf32-arm.c but is
5351 // implemented differently.
5352
5353 template<bool big_endian>
5354 void
5355 Arm_output_section<big_endian>::group_sections(
5356     section_size_type group_size,
5357     bool stubs_always_after_branch,
5358     Target_arm<big_endian>* target)
5359 {
5360   // We only care about sections containing code.
5361   if ((this->flags() & elfcpp::SHF_EXECINSTR) == 0)
5362     return;
5363
5364   // States for grouping.
5365   typedef enum
5366   {
5367     // No group is being built.
5368     NO_GROUP,
5369     // A group is being built but the stub table is not found yet.
5370     // We keep group a stub group until the size is just under GROUP_SIZE.
5371     // The last input section in the group will be used as the stub table.
5372     FINDING_STUB_SECTION,
5373     // A group is being built and we have already found a stub table.
5374     // We enter this state to grow a stub group by adding input section
5375     // after the stub table.  This effectively doubles the group size.
5376     HAS_STUB_SECTION
5377   } State;
5378
5379   // Any newly created relaxed sections are stored here.
5380   std::vector<Output_relaxed_input_section*> new_relaxed_sections;
5381
5382   State state = NO_GROUP;
5383   section_size_type off = 0;
5384   section_size_type group_begin_offset = 0;
5385   section_size_type group_end_offset = 0;
5386   section_size_type stub_table_end_offset = 0;
5387   Input_section_list::const_iterator group_begin =
5388     this->input_sections().end();
5389   Input_section_list::const_iterator stub_table =
5390     this->input_sections().end();
5391   Input_section_list::const_iterator group_end = this->input_sections().end();
5392   for (Input_section_list::const_iterator p = this->input_sections().begin();
5393        p != this->input_sections().end();
5394        ++p)
5395     {
5396       section_size_type section_begin_offset =
5397         align_address(off, p->addralign());
5398       section_size_type section_end_offset =
5399         section_begin_offset + p->data_size(); 
5400       
5401       // Check to see if we should group the previously seens sections.
5402       switch (state)
5403         {
5404         case NO_GROUP:
5405           break;
5406
5407         case FINDING_STUB_SECTION:
5408           // Adding this section makes the group larger than GROUP_SIZE.
5409           if (section_end_offset - group_begin_offset >= group_size)
5410             {
5411               if (stubs_always_after_branch)
5412                 {       
5413                   gold_assert(group_end != this->input_sections().end());
5414                   this->create_stub_group(group_begin, group_end, group_end,
5415                                           target, &new_relaxed_sections);
5416                   state = NO_GROUP;
5417                 }
5418               else
5419                 {
5420                   // But wait, there's more!  Input sections up to
5421                   // stub_group_size bytes after the stub table can be
5422                   // handled by it too.
5423                   state = HAS_STUB_SECTION;
5424                   stub_table = group_end;
5425                   stub_table_end_offset = group_end_offset;
5426                 }
5427             }
5428             break;
5429
5430         case HAS_STUB_SECTION:
5431           // Adding this section makes the post stub-section group larger
5432           // than GROUP_SIZE.
5433           if (section_end_offset - stub_table_end_offset >= group_size)
5434            {
5435              gold_assert(group_end != this->input_sections().end());
5436              this->create_stub_group(group_begin, group_end, stub_table,
5437                                      target, &new_relaxed_sections);
5438              state = NO_GROUP;
5439            }
5440            break;
5441
5442           default:
5443             gold_unreachable();
5444         }       
5445
5446       // If we see an input section and currently there is no group, start
5447       // a new one.  Skip any empty sections.
5448       if ((p->is_input_section() || p->is_relaxed_input_section())
5449           && (p->relobj()->section_size(p->shndx()) != 0))
5450         {
5451           if (state == NO_GROUP)
5452             {
5453               state = FINDING_STUB_SECTION;
5454               group_begin = p;
5455               group_begin_offset = section_begin_offset;
5456             }
5457
5458           // Keep track of the last input section seen.
5459           group_end = p;
5460           group_end_offset = section_end_offset;
5461         }
5462
5463       off = section_end_offset;
5464     }
5465
5466   // Create a stub group for any ungrouped sections.
5467   if (state == FINDING_STUB_SECTION || state == HAS_STUB_SECTION)
5468     {
5469       gold_assert(group_end != this->input_sections().end());
5470       this->create_stub_group(group_begin, group_end,
5471                               (state == FINDING_STUB_SECTION
5472                                ? group_end
5473                                : stub_table),
5474                                target, &new_relaxed_sections);
5475     }
5476
5477   // Convert input section into relaxed input section in a batch.
5478   if (!new_relaxed_sections.empty())
5479     this->convert_input_sections_to_relaxed_sections(new_relaxed_sections);
5480
5481   // Update the section offsets
5482   for (size_t i = 0; i < new_relaxed_sections.size(); ++i)
5483     {
5484       Arm_relobj<big_endian>* arm_relobj =
5485         Arm_relobj<big_endian>::as_arm_relobj(
5486           new_relaxed_sections[i]->relobj());
5487       unsigned int shndx = new_relaxed_sections[i]->shndx();
5488       // Tell Arm_relobj that this input section is converted.
5489       arm_relobj->convert_input_section_to_relaxed_section(shndx);
5490     }
5491 }
5492
5493 // Append non empty text sections in this to LIST in ascending
5494 // order of their position in this.
5495
5496 template<bool big_endian>
5497 void
5498 Arm_output_section<big_endian>::append_text_sections_to_list(
5499     Text_section_list* list)
5500 {
5501   // We only care about text sections.
5502   if ((this->flags() & elfcpp::SHF_EXECINSTR) == 0)
5503     return;
5504
5505   gold_assert((this->flags() & elfcpp::SHF_ALLOC) != 0);
5506
5507   for (Input_section_list::const_iterator p = this->input_sections().begin();
5508        p != this->input_sections().end();
5509        ++p)
5510     {
5511       // We only care about plain or relaxed input sections.  We also
5512       // ignore any merged sections.
5513       if ((p->is_input_section() || p->is_relaxed_input_section())
5514           && p->data_size() != 0)
5515         list->push_back(Text_section_list::value_type(p->relobj(),
5516                                                       p->shndx()));
5517     }
5518 }
5519
5520 template<bool big_endian>
5521 void
5522 Arm_output_section<big_endian>::fix_exidx_coverage(
5523     Layout* layout,
5524     const Text_section_list& sorted_text_sections,
5525     Symbol_table* symtab)
5526 {
5527   // We should only do this for the EXIDX output section.
5528   gold_assert(this->type() == elfcpp::SHT_ARM_EXIDX);
5529
5530   // We don't want the relaxation loop to undo these changes, so we discard
5531   // the current saved states and take another one after the fix-up.
5532   this->discard_states();
5533
5534   // Remove all input sections.
5535   uint64_t address = this->address();
5536   typedef std::list<Simple_input_section> Simple_input_section_list;
5537   Simple_input_section_list input_sections;
5538   this->reset_address_and_file_offset();
5539   this->get_input_sections(address, std::string(""), &input_sections);
5540
5541   if (!this->input_sections().empty())
5542     gold_error(_("Found non-EXIDX input sections in EXIDX output section"));
5543   
5544   // Go through all the known input sections and record them.
5545   typedef Unordered_set<Section_id, Section_id_hash> Section_id_set;
5546   Section_id_set known_input_sections;
5547   for (Simple_input_section_list::const_iterator p = input_sections.begin();
5548        p != input_sections.end();
5549        ++p)
5550     {
5551       // This should never happen.  At this point, we should only see
5552       // plain EXIDX input sections.
5553       gold_assert(!p->is_relaxed_input_section());
5554       known_input_sections.insert(Section_id(p->relobj(), p->shndx()));
5555     }
5556
5557   Arm_exidx_fixup exidx_fixup(this);
5558
5559   // Go over the sorted text sections.
5560   Section_id_set processed_input_sections;
5561   for (Text_section_list::const_iterator p = sorted_text_sections.begin();
5562        p != sorted_text_sections.end();
5563        ++p)
5564     {
5565       Relobj* relobj = p->first;
5566       unsigned int shndx = p->second;
5567
5568       Arm_relobj<big_endian>* arm_relobj =
5569          Arm_relobj<big_endian>::as_arm_relobj(relobj);
5570       const Arm_exidx_input_section* exidx_input_section =
5571          arm_relobj->exidx_input_section_by_link(shndx);
5572
5573       // If this text section has no EXIDX section, force an EXIDX_CANTUNWIND
5574       // entry pointing to the end of the last seen EXIDX section.
5575       if (exidx_input_section == NULL)
5576         {
5577           exidx_fixup.add_exidx_cantunwind_as_needed();
5578           continue;
5579         }
5580
5581       Relobj* exidx_relobj = exidx_input_section->relobj();
5582       unsigned int exidx_shndx = exidx_input_section->shndx();
5583       Section_id sid(exidx_relobj, exidx_shndx);
5584       if (known_input_sections.find(sid) == known_input_sections.end())
5585         {
5586           // This is odd.  We have not seen this EXIDX input section before.
5587           // We cannot do fix-up.  If we saw a SECTIONS clause in a script,
5588           // issue a warning instead.  We assume the user knows what he
5589           // or she is doing.  Otherwise, this is an error.
5590           if (layout->script_options()->saw_sections_clause())
5591             gold_warning(_("unwinding may not work because EXIDX input section"
5592                            " %u of %s is not in EXIDX output section"),
5593                          exidx_shndx, exidx_relobj->name().c_str());
5594           else
5595             gold_error(_("unwinding may not work because EXIDX input section"
5596                          " %u of %s is not in EXIDX output section"),
5597                        exidx_shndx, exidx_relobj->name().c_str());
5598
5599           exidx_fixup.add_exidx_cantunwind_as_needed();
5600           continue;
5601         }
5602
5603       // Fix up coverage and append input section to output data list.
5604       Arm_exidx_section_offset_map* section_offset_map = NULL;
5605       uint32_t deleted_bytes =
5606         exidx_fixup.process_exidx_section<big_endian>(exidx_input_section,
5607                                                       &section_offset_map);
5608
5609       if (deleted_bytes == exidx_input_section->size())
5610         {
5611           // The whole EXIDX section got merged.  Remove it from output.
5612           gold_assert(section_offset_map == NULL);
5613           exidx_relobj->set_output_section(exidx_shndx, NULL);
5614
5615           // All local symbols defined in this input section will be dropped.
5616           // We need to adjust output local symbol count.
5617           arm_relobj->set_output_local_symbol_count_needs_update();
5618         }
5619       else if (deleted_bytes > 0)
5620         {
5621           // Some entries are merged.  We need to convert this EXIDX input
5622           // section into a relaxed section.
5623           gold_assert(section_offset_map != NULL);
5624           Arm_exidx_merged_section* merged_section =
5625             new Arm_exidx_merged_section(*exidx_input_section,
5626                                          *section_offset_map, deleted_bytes);
5627           this->add_relaxed_input_section(merged_section);
5628           arm_relobj->convert_input_section_to_relaxed_section(exidx_shndx);
5629
5630           // All local symbols defined in discarded portions of this input
5631           // section will be dropped.  We need to adjust output local symbol
5632           // count.
5633           arm_relobj->set_output_local_symbol_count_needs_update();
5634         }
5635       else
5636         {
5637           // Just add back the EXIDX input section.
5638           gold_assert(section_offset_map == NULL);
5639           Output_section::Simple_input_section sis(exidx_relobj, exidx_shndx);
5640           this->add_simple_input_section(sis, exidx_input_section->size(),
5641                                          exidx_input_section->addralign());
5642         }
5643
5644       processed_input_sections.insert(Section_id(exidx_relobj, exidx_shndx)); 
5645     }
5646
5647   // Insert an EXIDX_CANTUNWIND entry at the end of output if necessary.
5648   exidx_fixup.add_exidx_cantunwind_as_needed();
5649
5650   // Remove any known EXIDX input sections that are not processed.
5651   for (Simple_input_section_list::const_iterator p = input_sections.begin();
5652        p != input_sections.end();
5653        ++p)
5654     {
5655       if (processed_input_sections.find(Section_id(p->relobj(), p->shndx()))
5656           == processed_input_sections.end())
5657         {
5658           // We only discard a known EXIDX section because its linked
5659           // text section has been folded by ICF.
5660           Arm_relobj<big_endian>* arm_relobj =
5661             Arm_relobj<big_endian>::as_arm_relobj(p->relobj());
5662           const Arm_exidx_input_section* exidx_input_section =
5663             arm_relobj->exidx_input_section_by_shndx(p->shndx());
5664           gold_assert(exidx_input_section != NULL);
5665           unsigned int text_shndx = exidx_input_section->link();
5666           gold_assert(symtab->is_section_folded(p->relobj(), text_shndx));
5667
5668           // Remove this from link.
5669           p->relobj()->set_output_section(p->shndx(), NULL);
5670         }
5671     }
5672     
5673   // Link exidx output section to the first seen output section and
5674   // set correct entry size.
5675   this->set_link_section(exidx_fixup.first_output_text_section());
5676   this->set_entsize(8);
5677
5678   // Make changes permanent.
5679   this->save_states();
5680   this->set_section_offsets_need_adjustment();
5681 }
5682
5683 // Arm_relobj methods.
5684
5685 // Determine if an input section is scannable for stub processing.  SHDR is
5686 // the header of the section and SHNDX is the section index.  OS is the output
5687 // section for the input section and SYMTAB is the global symbol table used to
5688 // look up ICF information.
5689
5690 template<bool big_endian>
5691 bool
5692 Arm_relobj<big_endian>::section_is_scannable(
5693     const elfcpp::Shdr<32, big_endian>& shdr,
5694     unsigned int shndx,
5695     const Output_section* os,
5696     const Symbol_table *symtab)
5697 {
5698   // Skip any empty sections, unallocated sections or sections whose
5699   // type are not SHT_PROGBITS.
5700   if (shdr.get_sh_size() == 0
5701       || (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0
5702       || shdr.get_sh_type() != elfcpp::SHT_PROGBITS)
5703     return false;
5704
5705   // Skip any discarded or ICF'ed sections.
5706   if (os == NULL || symtab->is_section_folded(this, shndx))
5707     return false;
5708
5709   // If this requires special offset handling, check to see if it is
5710   // a relaxed section.  If this is not, then it is a merged section that
5711   // we cannot handle.
5712   if (this->is_output_section_offset_invalid(shndx))
5713     {
5714       const Output_relaxed_input_section* poris =
5715         os->find_relaxed_input_section(this, shndx);
5716       if (poris == NULL)
5717         return false;
5718     }
5719
5720   return true;
5721 }
5722
5723 // Determine if we want to scan the SHNDX-th section for relocation stubs.
5724 // This is a helper for Arm_relobj::scan_sections_for_stubs() below.
5725
5726 template<bool big_endian>
5727 bool
5728 Arm_relobj<big_endian>::section_needs_reloc_stub_scanning(
5729     const elfcpp::Shdr<32, big_endian>& shdr,
5730     const Relobj::Output_sections& out_sections,
5731     const Symbol_table *symtab,
5732     const unsigned char* pshdrs)
5733 {
5734   unsigned int sh_type = shdr.get_sh_type();
5735   if (sh_type != elfcpp::SHT_REL && sh_type != elfcpp::SHT_RELA)
5736     return false;
5737
5738   // Ignore empty section.
5739   off_t sh_size = shdr.get_sh_size();
5740   if (sh_size == 0)
5741     return false;
5742
5743   // Ignore reloc section with unexpected symbol table.  The
5744   // error will be reported in the final link.
5745   if (this->adjust_shndx(shdr.get_sh_link()) != this->symtab_shndx())
5746     return false;
5747
5748   unsigned int reloc_size;
5749   if (sh_type == elfcpp::SHT_REL)
5750     reloc_size = elfcpp::Elf_sizes<32>::rel_size;
5751   else
5752     reloc_size = elfcpp::Elf_sizes<32>::rela_size;
5753
5754   // Ignore reloc section with unexpected entsize or uneven size.
5755   // The error will be reported in the final link.
5756   if (reloc_size != shdr.get_sh_entsize() || sh_size % reloc_size != 0)
5757     return false;
5758
5759   // Ignore reloc section with bad info.  This error will be
5760   // reported in the final link.
5761   unsigned int index = this->adjust_shndx(shdr.get_sh_info());
5762   if (index >= this->shnum())
5763     return false;
5764
5765   const unsigned int shdr_size = elfcpp::Elf_sizes<32>::shdr_size;
5766   const elfcpp::Shdr<32, big_endian> text_shdr(pshdrs + index * shdr_size);
5767   return this->section_is_scannable(text_shdr, index,
5768                                    out_sections[index], symtab);
5769 }
5770
5771 // Return the output address of either a plain input section or a relaxed
5772 // input section.  SHNDX is the section index.  We define and use this
5773 // instead of calling Output_section::output_address because that is slow
5774 // for large output.
5775
5776 template<bool big_endian>
5777 Arm_address
5778 Arm_relobj<big_endian>::simple_input_section_output_address(
5779     unsigned int shndx,
5780     Output_section* os)
5781 {
5782   if (this->is_output_section_offset_invalid(shndx))
5783     {
5784       const Output_relaxed_input_section* poris =
5785         os->find_relaxed_input_section(this, shndx);
5786       // We do not handle merged sections here.
5787       gold_assert(poris != NULL);
5788       return poris->address();
5789     }
5790   else
5791     return os->address() + this->get_output_section_offset(shndx);
5792 }
5793
5794 // Determine if we want to scan the SHNDX-th section for non-relocation stubs.
5795 // This is a helper for Arm_relobj::scan_sections_for_stubs() below.
5796
5797 template<bool big_endian>
5798 bool
5799 Arm_relobj<big_endian>::section_needs_cortex_a8_stub_scanning(
5800     const elfcpp::Shdr<32, big_endian>& shdr,
5801     unsigned int shndx,
5802     Output_section* os,
5803     const Symbol_table* symtab)
5804 {
5805   if (!this->section_is_scannable(shdr, shndx, os, symtab))
5806     return false;
5807
5808   // If the section does not cross any 4K-boundaries, it does not need to
5809   // be scanned.
5810   Arm_address address = this->simple_input_section_output_address(shndx, os);
5811   if ((address & ~0xfffU) == ((address + shdr.get_sh_size() - 1) & ~0xfffU))
5812     return false;
5813
5814   return true;
5815 }
5816
5817 // Scan a section for Cortex-A8 workaround.
5818
5819 template<bool big_endian>
5820 void
5821 Arm_relobj<big_endian>::scan_section_for_cortex_a8_erratum(
5822     const elfcpp::Shdr<32, big_endian>& shdr,
5823     unsigned int shndx,
5824     Output_section* os,
5825     Target_arm<big_endian>* arm_target)
5826 {
5827   // Look for the first mapping symbol in this section.  It should be
5828   // at (shndx, 0).
5829   Mapping_symbol_position section_start(shndx, 0);
5830   typename Mapping_symbols_info::const_iterator p =
5831     this->mapping_symbols_info_.lower_bound(section_start);
5832
5833   // There are no mapping symbols for this section.  Treat it as a data-only
5834   // section.
5835   if (p == this->mapping_symbols_info_.end() || p->first.first != shndx)
5836     return;
5837
5838   Arm_address output_address =
5839     this->simple_input_section_output_address(shndx, os);
5840
5841   // Get the section contents.
5842   section_size_type input_view_size = 0;
5843   const unsigned char* input_view =
5844     this->section_contents(shndx, &input_view_size, false);
5845
5846   // We need to go through the mapping symbols to determine what to
5847   // scan.  There are two reasons.  First, we should look at THUMB code and
5848   // THUMB code only.  Second, we only want to look at the 4K-page boundary
5849   // to speed up the scanning.
5850   
5851   while (p != this->mapping_symbols_info_.end()
5852         && p->first.first == shndx)
5853     {
5854       typename Mapping_symbols_info::const_iterator next =
5855         this->mapping_symbols_info_.upper_bound(p->first);
5856
5857       // Only scan part of a section with THUMB code.
5858       if (p->second == 't')
5859         {
5860           // Determine the end of this range.
5861           section_size_type span_start =
5862             convert_to_section_size_type(p->first.second);
5863           section_size_type span_end;
5864           if (next != this->mapping_symbols_info_.end()
5865               && next->first.first == shndx)
5866             span_end = convert_to_section_size_type(next->first.second);
5867           else
5868             span_end = convert_to_section_size_type(shdr.get_sh_size());
5869           
5870           if (((span_start + output_address) & ~0xfffUL)
5871               != ((span_end + output_address - 1) & ~0xfffUL))
5872             {
5873               arm_target->scan_span_for_cortex_a8_erratum(this, shndx,
5874                                                           span_start, span_end,
5875                                                           input_view,
5876                                                           output_address);
5877             }
5878         }
5879
5880       p = next; 
5881     }
5882 }
5883
5884 // Scan relocations for stub generation.
5885
5886 template<bool big_endian>
5887 void
5888 Arm_relobj<big_endian>::scan_sections_for_stubs(
5889     Target_arm<big_endian>* arm_target,
5890     const Symbol_table* symtab,
5891     const Layout* layout)
5892 {
5893   unsigned int shnum = this->shnum();
5894   const unsigned int shdr_size = elfcpp::Elf_sizes<32>::shdr_size;
5895
5896   // Read the section headers.
5897   const unsigned char* pshdrs = this->get_view(this->elf_file()->shoff(),
5898                                                shnum * shdr_size,
5899                                                true, true);
5900
5901   // To speed up processing, we set up hash tables for fast lookup of
5902   // input offsets to output addresses.
5903   this->initialize_input_to_output_maps();
5904
5905   const Relobj::Output_sections& out_sections(this->output_sections());
5906
5907   Relocate_info<32, big_endian> relinfo;
5908   relinfo.symtab = symtab;
5909   relinfo.layout = layout;
5910   relinfo.object = this;
5911
5912   // Do relocation stubs scanning.
5913   const unsigned char* p = pshdrs + shdr_size;
5914   for (unsigned int i = 1; i < shnum; ++i, p += shdr_size)
5915     {
5916       const elfcpp::Shdr<32, big_endian> shdr(p);
5917       if (this->section_needs_reloc_stub_scanning(shdr, out_sections, symtab,
5918                                                   pshdrs))
5919         {
5920           unsigned int index = this->adjust_shndx(shdr.get_sh_info());
5921           Arm_address output_offset = this->get_output_section_offset(index);
5922           Arm_address output_address;
5923           if(output_offset != invalid_address)
5924             output_address = out_sections[index]->address() + output_offset;
5925           else
5926             {
5927               // Currently this only happens for a relaxed section.
5928               const Output_relaxed_input_section* poris =
5929               out_sections[index]->find_relaxed_input_section(this, index);
5930               gold_assert(poris != NULL);
5931               output_address = poris->address();
5932             }
5933
5934           // Get the relocations.
5935           const unsigned char* prelocs = this->get_view(shdr.get_sh_offset(),
5936                                                         shdr.get_sh_size(),
5937                                                         true, false);
5938
5939           // Get the section contents.  This does work for the case in which
5940           // we modify the contents of an input section.  We need to pass the
5941           // output view under such circumstances.
5942           section_size_type input_view_size = 0;
5943           const unsigned char* input_view =
5944             this->section_contents(index, &input_view_size, false);
5945
5946           relinfo.reloc_shndx = i;
5947           relinfo.data_shndx = index;
5948           unsigned int sh_type = shdr.get_sh_type();
5949           unsigned int reloc_size;
5950           if (sh_type == elfcpp::SHT_REL)
5951             reloc_size = elfcpp::Elf_sizes<32>::rel_size;
5952           else
5953             reloc_size = elfcpp::Elf_sizes<32>::rela_size;
5954
5955           Output_section* os = out_sections[index];
5956           arm_target->scan_section_for_stubs(&relinfo, sh_type, prelocs,
5957                                              shdr.get_sh_size() / reloc_size,
5958                                              os,
5959                                              output_offset == invalid_address,
5960                                              input_view, output_address,
5961                                              input_view_size);
5962         }
5963     }
5964
5965   // Do Cortex-A8 erratum stubs scanning.  This has to be done for a section
5966   // after its relocation section, if there is one, is processed for
5967   // relocation stubs.  Merging this loop with the one above would have been
5968   // complicated since we would have had to make sure that relocation stub
5969   // scanning is done first.
5970   if (arm_target->fix_cortex_a8())
5971     {
5972       const unsigned char* p = pshdrs + shdr_size;
5973       for (unsigned int i = 1; i < shnum; ++i, p += shdr_size)
5974         {
5975           const elfcpp::Shdr<32, big_endian> shdr(p);
5976           if (this->section_needs_cortex_a8_stub_scanning(shdr, i,
5977                                                           out_sections[i],
5978                                                           symtab))
5979             this->scan_section_for_cortex_a8_erratum(shdr, i, out_sections[i],
5980                                                      arm_target);
5981         }
5982     }
5983
5984   // After we've done the relocations, we release the hash tables,
5985   // since we no longer need them.
5986   this->free_input_to_output_maps();
5987 }
5988
5989 // Count the local symbols.  The ARM backend needs to know if a symbol
5990 // is a THUMB function or not.  For global symbols, it is easy because
5991 // the Symbol object keeps the ELF symbol type.  For local symbol it is
5992 // harder because we cannot access this information.   So we override the
5993 // do_count_local_symbol in parent and scan local symbols to mark
5994 // THUMB functions.  This is not the most efficient way but I do not want to
5995 // slow down other ports by calling a per symbol targer hook inside
5996 // Sized_relobj<size, big_endian>::do_count_local_symbols. 
5997
5998 template<bool big_endian>
5999 void
6000 Arm_relobj<big_endian>::do_count_local_symbols(
6001     Stringpool_template<char>* pool,
6002     Stringpool_template<char>* dynpool)
6003 {
6004   // We need to fix-up the values of any local symbols whose type are
6005   // STT_ARM_TFUNC.
6006   
6007   // Ask parent to count the local symbols.
6008   Sized_relobj<32, big_endian>::do_count_local_symbols(pool, dynpool);
6009   const unsigned int loccount = this->local_symbol_count();
6010   if (loccount == 0)
6011     return;
6012
6013   // Intialize the thumb function bit-vector.
6014   std::vector<bool> empty_vector(loccount, false);
6015   this->local_symbol_is_thumb_function_.swap(empty_vector);
6016
6017   // Read the symbol table section header.
6018   const unsigned int symtab_shndx = this->symtab_shndx();
6019   elfcpp::Shdr<32, big_endian>
6020       symtabshdr(this, this->elf_file()->section_header(symtab_shndx));
6021   gold_assert(symtabshdr.get_sh_type() == elfcpp::SHT_SYMTAB);
6022
6023   // Read the local symbols.
6024   const int sym_size =elfcpp::Elf_sizes<32>::sym_size;
6025   gold_assert(loccount == symtabshdr.get_sh_info());
6026   off_t locsize = loccount * sym_size;
6027   const unsigned char* psyms = this->get_view(symtabshdr.get_sh_offset(),
6028                                               locsize, true, true);
6029
6030   // For mapping symbol processing, we need to read the symbol names.
6031   unsigned int strtab_shndx = this->adjust_shndx(symtabshdr.get_sh_link());
6032   if (strtab_shndx >= this->shnum())
6033     {
6034       this->error(_("invalid symbol table name index: %u"), strtab_shndx);
6035       return;
6036     }
6037
6038   elfcpp::Shdr<32, big_endian>
6039     strtabshdr(this, this->elf_file()->section_header(strtab_shndx));
6040   if (strtabshdr.get_sh_type() != elfcpp::SHT_STRTAB)
6041     {
6042       this->error(_("symbol table name section has wrong type: %u"),
6043                   static_cast<unsigned int>(strtabshdr.get_sh_type()));
6044       return;
6045     }
6046   const char* pnames =
6047     reinterpret_cast<const char*>(this->get_view(strtabshdr.get_sh_offset(),
6048                                                  strtabshdr.get_sh_size(),
6049                                                  false, false));
6050
6051   // Loop over the local symbols and mark any local symbols pointing
6052   // to THUMB functions.
6053
6054   // Skip the first dummy symbol.
6055   psyms += sym_size;
6056   typename Sized_relobj<32, big_endian>::Local_values* plocal_values =
6057     this->local_values();
6058   for (unsigned int i = 1; i < loccount; ++i, psyms += sym_size)
6059     {
6060       elfcpp::Sym<32, big_endian> sym(psyms);
6061       elfcpp::STT st_type = sym.get_st_type();
6062       Symbol_value<32>& lv((*plocal_values)[i]);
6063       Arm_address input_value = lv.input_value();
6064
6065       // Check to see if this is a mapping symbol.
6066       const char* sym_name = pnames + sym.get_st_name();
6067       if (Target_arm<big_endian>::is_mapping_symbol_name(sym_name))
6068         {
6069           unsigned int input_shndx = sym.get_st_shndx();  
6070
6071           // Strip of LSB in case this is a THUMB symbol.
6072           Mapping_symbol_position msp(input_shndx, input_value & ~1U);
6073           this->mapping_symbols_info_[msp] = sym_name[1];
6074         }
6075
6076       if (st_type == elfcpp::STT_ARM_TFUNC
6077           || (st_type == elfcpp::STT_FUNC && ((input_value & 1) != 0)))
6078         {
6079           // This is a THUMB function.  Mark this and canonicalize the
6080           // symbol value by setting LSB.
6081           this->local_symbol_is_thumb_function_[i] = true;
6082           if ((input_value & 1) == 0)
6083             lv.set_input_value(input_value | 1);
6084         }
6085     }
6086 }
6087
6088 // Relocate sections.
6089 template<bool big_endian>
6090 void
6091 Arm_relobj<big_endian>::do_relocate_sections(
6092     const Symbol_table* symtab,
6093     const Layout* layout,
6094     const unsigned char* pshdrs,
6095     typename Sized_relobj<32, big_endian>::Views* pviews)
6096 {
6097   // Call parent to relocate sections.
6098   Sized_relobj<32, big_endian>::do_relocate_sections(symtab, layout, pshdrs,
6099                                                      pviews); 
6100
6101   // We do not generate stubs if doing a relocatable link.
6102   if (parameters->options().relocatable())
6103     return;
6104
6105   // Relocate stub tables.
6106   unsigned int shnum = this->shnum();
6107
6108   Target_arm<big_endian>* arm_target =
6109     Target_arm<big_endian>::default_target();
6110
6111   Relocate_info<32, big_endian> relinfo;
6112   relinfo.symtab = symtab;
6113   relinfo.layout = layout;
6114   relinfo.object = this;
6115
6116   for (unsigned int i = 1; i < shnum; ++i)
6117     {
6118       Arm_input_section<big_endian>* arm_input_section =
6119         arm_target->find_arm_input_section(this, i);
6120
6121       if (arm_input_section != NULL
6122           && arm_input_section->is_stub_table_owner()
6123           && !arm_input_section->stub_table()->empty())
6124         {
6125           // We cannot discard a section if it owns a stub table.
6126           Output_section* os = this->output_section(i);
6127           gold_assert(os != NULL);
6128
6129           relinfo.reloc_shndx = elfcpp::SHN_UNDEF;
6130           relinfo.reloc_shdr = NULL;
6131           relinfo.data_shndx = i;
6132           relinfo.data_shdr = pshdrs + i * elfcpp::Elf_sizes<32>::shdr_size;
6133
6134           gold_assert((*pviews)[i].view != NULL);
6135
6136           // We are passed the output section view.  Adjust it to cover the
6137           // stub table only.
6138           Stub_table<big_endian>* stub_table = arm_input_section->stub_table();
6139           gold_assert((stub_table->address() >= (*pviews)[i].address)
6140                       && ((stub_table->address() + stub_table->data_size())
6141                           <= (*pviews)[i].address + (*pviews)[i].view_size));
6142
6143           off_t offset = stub_table->address() - (*pviews)[i].address;
6144           unsigned char* view = (*pviews)[i].view + offset;
6145           Arm_address address = stub_table->address();
6146           section_size_type view_size = stub_table->data_size();
6147  
6148           stub_table->relocate_stubs(&relinfo, arm_target, os, view, address,
6149                                      view_size);
6150         }
6151
6152       // Apply Cortex A8 workaround if applicable.
6153       if (this->section_has_cortex_a8_workaround(i))
6154         {
6155           unsigned char* view = (*pviews)[i].view;
6156           Arm_address view_address = (*pviews)[i].address;
6157           section_size_type view_size = (*pviews)[i].view_size;
6158           Stub_table<big_endian>* stub_table = this->stub_tables_[i];
6159
6160           // Adjust view to cover section.
6161           Output_section* os = this->output_section(i);
6162           gold_assert(os != NULL);
6163           Arm_address section_address =
6164             this->simple_input_section_output_address(i, os);
6165           uint64_t section_size = this->section_size(i);
6166
6167           gold_assert(section_address >= view_address
6168                       && ((section_address + section_size)
6169                           <= (view_address + view_size)));
6170
6171           unsigned char* section_view = view + (section_address - view_address);
6172
6173           // Apply the Cortex-A8 workaround to the output address range
6174           // corresponding to this input section.
6175           stub_table->apply_cortex_a8_workaround_to_address_range(
6176               arm_target,
6177               section_view,
6178               section_address,
6179               section_size);
6180         }
6181     }
6182 }
6183
6184 // Find the linked text section of an EXIDX section by looking the the first
6185 // relocation.  4.4.1 of the EHABI specifications says that an EXIDX section
6186 // must be linked to to its associated code section via the sh_link field of
6187 // its section header.  However, some tools are broken and the link is not
6188 // always set.  LD just drops such an EXIDX section silently, causing the
6189 // associated code not unwindabled.   Here we try a little bit harder to
6190 // discover the linked code section.
6191 //
6192 // PSHDR points to the section header of a relocation section of an EXIDX
6193 // section.  If we can find a linked text section, return true and
6194 // store the text section index in the location PSHNDX.  Otherwise
6195 // return false.
6196
6197 template<bool big_endian>
6198 bool
6199 Arm_relobj<big_endian>::find_linked_text_section(
6200     const unsigned char* pshdr,
6201     const unsigned char* psyms,
6202     unsigned int* pshndx)
6203 {
6204   elfcpp::Shdr<32, big_endian> shdr(pshdr);
6205   
6206   // If there is no relocation, we cannot find the linked text section.
6207   size_t reloc_size;
6208   if (shdr.get_sh_type() == elfcpp::SHT_REL)
6209       reloc_size = elfcpp::Elf_sizes<32>::rel_size;
6210   else
6211       reloc_size = elfcpp::Elf_sizes<32>::rela_size;
6212   size_t reloc_count = shdr.get_sh_size() / reloc_size;
6213  
6214   // Get the relocations.
6215   const unsigned char* prelocs =
6216       this->get_view(shdr.get_sh_offset(), shdr.get_sh_size(), true, false); 
6217
6218   // Find the REL31 relocation for the first word of the first EXIDX entry.
6219   for (size_t i = 0; i < reloc_count; ++i, prelocs += reloc_size)
6220     {
6221       Arm_address r_offset;
6222       typename elfcpp::Elf_types<32>::Elf_WXword r_info;
6223       if (shdr.get_sh_type() == elfcpp::SHT_REL)
6224         {
6225           typename elfcpp::Rel<32, big_endian> reloc(prelocs);
6226           r_info = reloc.get_r_info();
6227           r_offset = reloc.get_r_offset();
6228         }
6229       else
6230         {
6231           typename elfcpp::Rela<32, big_endian> reloc(prelocs);
6232           r_info = reloc.get_r_info();
6233           r_offset = reloc.get_r_offset();
6234         }
6235
6236       unsigned int r_type = elfcpp::elf_r_type<32>(r_info);
6237       if (r_type != elfcpp::R_ARM_PREL31 && r_type != elfcpp::R_ARM_SBREL31)
6238         continue;
6239
6240       unsigned int r_sym = elfcpp::elf_r_sym<32>(r_info);
6241       if (r_sym == 0
6242           || r_sym >= this->local_symbol_count()
6243           || r_offset != 0)
6244         continue;
6245
6246       // This is the relocation for the first word of the first EXIDX entry.
6247       // We expect to see a local section symbol.
6248       const int sym_size = elfcpp::Elf_sizes<32>::sym_size;
6249       elfcpp::Sym<32, big_endian> sym(psyms + r_sym * sym_size);
6250       if (sym.get_st_type() == elfcpp::STT_SECTION)
6251         {
6252           *pshndx = this->adjust_shndx(sym.get_st_shndx());
6253           return true;
6254         }
6255       else
6256         return false;
6257     }
6258
6259   return false;
6260 }
6261
6262 // Make an EXIDX input section object for an EXIDX section whose index is
6263 // SHNDX.  SHDR is the section header of the EXIDX section and TEXT_SHNDX
6264 // is the section index of the linked text section.
6265
6266 template<bool big_endian>
6267 void
6268 Arm_relobj<big_endian>::make_exidx_input_section(
6269     unsigned int shndx,
6270     const elfcpp::Shdr<32, big_endian>& shdr,
6271     unsigned int text_shndx)
6272 {
6273   // Issue an error and ignore this EXIDX section if it points to a text
6274   // section already has an EXIDX section.
6275   if (this->exidx_section_map_[text_shndx] != NULL)
6276     {
6277       gold_error(_("EXIDX sections %u and %u both link to text section %u "
6278                    "in %s"),
6279                  shndx, this->exidx_section_map_[text_shndx]->shndx(),
6280                  text_shndx, this->name().c_str());
6281       return;
6282     }
6283
6284   // Create an Arm_exidx_input_section object for this EXIDX section.
6285   Arm_exidx_input_section* exidx_input_section =
6286     new Arm_exidx_input_section(this, shndx, text_shndx, shdr.get_sh_size(),
6287                                 shdr.get_sh_addralign());
6288   this->exidx_section_map_[text_shndx] = exidx_input_section;
6289
6290   // Also map the EXIDX section index to this.
6291   gold_assert(this->exidx_section_map_[shndx] == NULL);
6292   this->exidx_section_map_[shndx] = exidx_input_section;
6293 }
6294
6295 // Read the symbol information.
6296
6297 template<bool big_endian>
6298 void
6299 Arm_relobj<big_endian>::do_read_symbols(Read_symbols_data* sd)
6300 {
6301   // Call parent class to read symbol information.
6302   Sized_relobj<32, big_endian>::do_read_symbols(sd);
6303
6304   // Read processor-specific flags in ELF file header.
6305   const unsigned char* pehdr = this->get_view(elfcpp::file_header_offset,
6306                                               elfcpp::Elf_sizes<32>::ehdr_size,
6307                                               true, false);
6308   elfcpp::Ehdr<32, big_endian> ehdr(pehdr);
6309   this->processor_specific_flags_ = ehdr.get_e_flags();
6310
6311   // Go over the section headers and look for .ARM.attributes and .ARM.exidx
6312   // sections.
6313   std::vector<unsigned int> deferred_exidx_sections;
6314   const size_t shdr_size = elfcpp::Elf_sizes<32>::shdr_size;
6315   const unsigned char* pshdrs = sd->section_headers->data();
6316   const unsigned char *ps = pshdrs + shdr_size;
6317   for (unsigned int i = 1; i < this->shnum(); ++i, ps += shdr_size)
6318     {
6319       elfcpp::Shdr<32, big_endian> shdr(ps);
6320       if (shdr.get_sh_type() == elfcpp::SHT_ARM_ATTRIBUTES)
6321         {
6322           gold_assert(this->attributes_section_data_ == NULL);
6323           section_offset_type section_offset = shdr.get_sh_offset();
6324           section_size_type section_size =
6325             convert_to_section_size_type(shdr.get_sh_size());
6326           File_view* view = this->get_lasting_view(section_offset,
6327                                                    section_size, true, false);
6328           this->attributes_section_data_ =
6329             new Attributes_section_data(view->data(), section_size);
6330         }
6331       else if (shdr.get_sh_type() == elfcpp::SHT_ARM_EXIDX)
6332         {
6333           unsigned int text_shndx = this->adjust_shndx(shdr.get_sh_link());
6334           if (text_shndx >= this->shnum())
6335             gold_error(_("EXIDX section %u linked to invalid section %u"),
6336                        i, text_shndx);
6337           else if (text_shndx == elfcpp::SHN_UNDEF)
6338             deferred_exidx_sections.push_back(i);
6339           else
6340             this->make_exidx_input_section(i, shdr, text_shndx);
6341         }
6342     }
6343
6344   // Some tools are broken and they do not set the link of EXIDX sections. 
6345   // We look at the first relocation to figure out the linked sections.
6346   if (!deferred_exidx_sections.empty())
6347     {
6348       // We need to go over the section headers again to find the mapping
6349       // from sections being relocated to their relocation sections.  This is
6350       // a bit inefficient as we could do that in the loop above.  However,
6351       // we do not expect any deferred EXIDX sections normally.  So we do not
6352       // want to slow down the most common path.
6353       typedef Unordered_map<unsigned int, unsigned int> Reloc_map;
6354       Reloc_map reloc_map;
6355       ps = pshdrs + shdr_size;
6356       for (unsigned int i = 1; i < this->shnum(); ++i, ps += shdr_size)
6357         {
6358           elfcpp::Shdr<32, big_endian> shdr(ps);
6359           elfcpp::Elf_Word sh_type = shdr.get_sh_type();
6360           if (sh_type == elfcpp::SHT_REL || sh_type == elfcpp::SHT_RELA)
6361             {
6362               unsigned int info_shndx = this->adjust_shndx(shdr.get_sh_info());
6363               if (info_shndx >= this->shnum())
6364                 gold_error(_("relocation section %u has invalid info %u"),
6365                            i, info_shndx);
6366               Reloc_map::value_type value(info_shndx, i);
6367               std::pair<Reloc_map::iterator, bool> result =
6368                 reloc_map.insert(value);
6369               if (!result.second)
6370                 gold_error(_("section %u has multiple relocation sections "
6371                              "%u and %u"),
6372                            info_shndx, i, reloc_map[info_shndx]);
6373             }
6374         }
6375
6376       // Read the symbol table section header.
6377       const unsigned int symtab_shndx = this->symtab_shndx();
6378       elfcpp::Shdr<32, big_endian>
6379           symtabshdr(this, this->elf_file()->section_header(symtab_shndx));
6380       gold_assert(symtabshdr.get_sh_type() == elfcpp::SHT_SYMTAB);
6381
6382       // Read the local symbols.
6383       const int sym_size =elfcpp::Elf_sizes<32>::sym_size;
6384       const unsigned int loccount = this->local_symbol_count();
6385       gold_assert(loccount == symtabshdr.get_sh_info());
6386       off_t locsize = loccount * sym_size;
6387       const unsigned char* psyms = this->get_view(symtabshdr.get_sh_offset(),
6388                                                   locsize, true, true);
6389
6390       // Process the deferred EXIDX sections. 
6391       for(unsigned int i = 0; i < deferred_exidx_sections.size(); ++i)
6392         {
6393           unsigned int shndx = deferred_exidx_sections[i];
6394           elfcpp::Shdr<32, big_endian> shdr(pshdrs + shndx * shdr_size);
6395           unsigned int text_shndx;
6396           Reloc_map::const_iterator it = reloc_map.find(shndx);
6397           if (it != reloc_map.end()
6398               && find_linked_text_section(pshdrs + it->second * shdr_size,
6399                                           psyms, &text_shndx))
6400             this->make_exidx_input_section(shndx, shdr, text_shndx);
6401           else
6402             gold_error(_("EXIDX section %u has no linked text section."),
6403                        shndx);
6404         }
6405     }
6406 }
6407
6408 // Process relocations for garbage collection.  The ARM target uses .ARM.exidx
6409 // sections for unwinding.  These sections are referenced implicitly by 
6410 // text sections linked in the section headers.  If we ignore these implict
6411 // references, the .ARM.exidx sections and any .ARM.extab sections they use
6412 // will be garbage-collected incorrectly.  Hence we override the same function
6413 // in the base class to handle these implicit references.
6414
6415 template<bool big_endian>
6416 void
6417 Arm_relobj<big_endian>::do_gc_process_relocs(Symbol_table* symtab,
6418                                              Layout* layout,
6419                                              Read_relocs_data* rd)
6420 {
6421   // First, call base class method to process relocations in this object.
6422   Sized_relobj<32, big_endian>::do_gc_process_relocs(symtab, layout, rd);
6423
6424   // If --gc-sections is not specified, there is nothing more to do.
6425   // This happens when --icf is used but --gc-sections is not.
6426   if (!parameters->options().gc_sections())
6427     return;
6428   
6429   unsigned int shnum = this->shnum();
6430   const unsigned int shdr_size = elfcpp::Elf_sizes<32>::shdr_size;
6431   const unsigned char* pshdrs = this->get_view(this->elf_file()->shoff(),
6432                                                shnum * shdr_size,
6433                                                true, true);
6434
6435   // Scan section headers for sections of type SHT_ARM_EXIDX.  Add references
6436   // to these from the linked text sections.
6437   const unsigned char* ps = pshdrs + shdr_size;
6438   for (unsigned int i = 1; i < shnum; ++i, ps += shdr_size)
6439     {
6440       elfcpp::Shdr<32, big_endian> shdr(ps);
6441       if (shdr.get_sh_type() == elfcpp::SHT_ARM_EXIDX)
6442         {
6443           // Found an .ARM.exidx section, add it to the set of reachable
6444           // sections from its linked text section.
6445           unsigned int text_shndx = this->adjust_shndx(shdr.get_sh_link());
6446           symtab->gc()->add_reference(this, text_shndx, this, i);
6447         }
6448     }
6449 }
6450
6451 // Update output local symbol count.  Owing to EXIDX entry merging, some local
6452 // symbols  will be removed in output.  Adjust output local symbol count
6453 // accordingly.  We can only changed the static output local symbol count.  It
6454 // is too late to change the dynamic symbols.
6455
6456 template<bool big_endian>
6457 void
6458 Arm_relobj<big_endian>::update_output_local_symbol_count()
6459 {
6460   // Caller should check that this needs updating.  We want caller checking
6461   // because output_local_symbol_count_needs_update() is most likely inlined.
6462   gold_assert(this->output_local_symbol_count_needs_update_);
6463
6464   gold_assert(this->symtab_shndx() != -1U);
6465   if (this->symtab_shndx() == 0)
6466     {
6467       // This object has no symbols.  Weird but legal.
6468       return;
6469     }
6470
6471   // Read the symbol table section header.
6472   const unsigned int symtab_shndx = this->symtab_shndx();
6473   elfcpp::Shdr<32, big_endian>
6474     symtabshdr(this, this->elf_file()->section_header(symtab_shndx));
6475   gold_assert(symtabshdr.get_sh_type() == elfcpp::SHT_SYMTAB);
6476
6477   // Read the local symbols.
6478   const int sym_size = elfcpp::Elf_sizes<32>::sym_size;
6479   const unsigned int loccount = this->local_symbol_count();
6480   gold_assert(loccount == symtabshdr.get_sh_info());
6481   off_t locsize = loccount * sym_size;
6482   const unsigned char* psyms = this->get_view(symtabshdr.get_sh_offset(),
6483                                               locsize, true, true);
6484
6485   // Loop over the local symbols.
6486
6487   typedef typename Sized_relobj<32, big_endian>::Output_sections
6488      Output_sections;
6489   const Output_sections& out_sections(this->output_sections());
6490   unsigned int shnum = this->shnum();
6491   unsigned int count = 0;
6492   // Skip the first, dummy, symbol.
6493   psyms += sym_size;
6494   for (unsigned int i = 1; i < loccount; ++i, psyms += sym_size)
6495     {
6496       elfcpp::Sym<32, big_endian> sym(psyms);
6497
6498       Symbol_value<32>& lv((*this->local_values())[i]);
6499
6500       // This local symbol was already discarded by do_count_local_symbols.
6501       if (lv.is_output_symtab_index_set() && !lv.has_output_symtab_entry())
6502         continue;
6503
6504       bool is_ordinary;
6505       unsigned int shndx = this->adjust_sym_shndx(i, sym.get_st_shndx(),
6506                                                   &is_ordinary);
6507
6508       if (shndx < shnum)
6509         {
6510           Output_section* os = out_sections[shndx];
6511
6512           // This local symbol no longer has an output section.  Discard it.
6513           if (os == NULL)
6514             {
6515               lv.set_no_output_symtab_entry();
6516               continue;
6517             }
6518
6519           // Currently we only discard parts of EXIDX input sections.
6520           // We explicitly check for a merged EXIDX input section to avoid
6521           // calling Output_section_data::output_offset unless necessary.
6522           if ((this->get_output_section_offset(shndx) == invalid_address)
6523               && (this->exidx_input_section_by_shndx(shndx) != NULL))
6524             {
6525               section_offset_type output_offset =
6526                 os->output_offset(this, shndx, lv.input_value());
6527               if (output_offset == -1)
6528                 {
6529                   // This symbol is defined in a part of an EXIDX input section
6530                   // that is discarded due to entry merging.
6531                   lv.set_no_output_symtab_entry();
6532                   continue;
6533                 }       
6534             }
6535         }
6536
6537       ++count;
6538     }
6539
6540   this->set_output_local_symbol_count(count);
6541   this->output_local_symbol_count_needs_update_ = false;
6542 }
6543
6544 // Arm_dynobj methods.
6545
6546 // Read the symbol information.
6547
6548 template<bool big_endian>
6549 void
6550 Arm_dynobj<big_endian>::do_read_symbols(Read_symbols_data* sd)
6551 {
6552   // Call parent class to read symbol information.
6553   Sized_dynobj<32, big_endian>::do_read_symbols(sd);
6554
6555   // Read processor-specific flags in ELF file header.
6556   const unsigned char* pehdr = this->get_view(elfcpp::file_header_offset,
6557                                               elfcpp::Elf_sizes<32>::ehdr_size,
6558                                               true, false);
6559   elfcpp::Ehdr<32, big_endian> ehdr(pehdr);
6560   this->processor_specific_flags_ = ehdr.get_e_flags();
6561
6562   // Read the attributes section if there is one.
6563   // We read from the end because gas seems to put it near the end of
6564   // the section headers.
6565   const size_t shdr_size = elfcpp::Elf_sizes<32>::shdr_size;
6566   const unsigned char *ps =
6567     sd->section_headers->data() + shdr_size * (this->shnum() - 1);
6568   for (unsigned int i = this->shnum(); i > 0; --i, ps -= shdr_size)
6569     {
6570       elfcpp::Shdr<32, big_endian> shdr(ps);
6571       if (shdr.get_sh_type() == elfcpp::SHT_ARM_ATTRIBUTES)
6572         {
6573           section_offset_type section_offset = shdr.get_sh_offset();
6574           section_size_type section_size =
6575             convert_to_section_size_type(shdr.get_sh_size());
6576           File_view* view = this->get_lasting_view(section_offset,
6577                                                    section_size, true, false);
6578           this->attributes_section_data_ =
6579             new Attributes_section_data(view->data(), section_size);
6580           break;
6581         }
6582     }
6583 }
6584
6585 // Stub_addend_reader methods.
6586
6587 // Read the addend of a REL relocation of type R_TYPE at VIEW.
6588
6589 template<bool big_endian>
6590 elfcpp::Elf_types<32>::Elf_Swxword
6591 Stub_addend_reader<elfcpp::SHT_REL, big_endian>::operator()(
6592     unsigned int r_type,
6593     const unsigned char* view,
6594     const typename Reloc_types<elfcpp::SHT_REL, 32, big_endian>::Reloc&) const
6595 {
6596   typedef struct Arm_relocate_functions<big_endian> RelocFuncs;
6597   
6598   switch (r_type)
6599     {
6600     case elfcpp::R_ARM_CALL:
6601     case elfcpp::R_ARM_JUMP24:
6602     case elfcpp::R_ARM_PLT32:
6603       {
6604         typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
6605         const Valtype* wv = reinterpret_cast<const Valtype*>(view);
6606         Valtype val = elfcpp::Swap<32, big_endian>::readval(wv);
6607         return utils::sign_extend<26>(val << 2);
6608       }
6609
6610     case elfcpp::R_ARM_THM_CALL:
6611     case elfcpp::R_ARM_THM_JUMP24:
6612     case elfcpp::R_ARM_THM_XPC22:
6613       {
6614         typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
6615         const Valtype* wv = reinterpret_cast<const Valtype*>(view);
6616         Valtype upper_insn = elfcpp::Swap<16, big_endian>::readval(wv);
6617         Valtype lower_insn = elfcpp::Swap<16, big_endian>::readval(wv + 1);
6618         return RelocFuncs::thumb32_branch_offset(upper_insn, lower_insn);
6619       }
6620
6621     case elfcpp::R_ARM_THM_JUMP19:
6622       {
6623         typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
6624         const Valtype* wv = reinterpret_cast<const Valtype*>(view);
6625         Valtype upper_insn = elfcpp::Swap<16, big_endian>::readval(wv);
6626         Valtype lower_insn = elfcpp::Swap<16, big_endian>::readval(wv + 1);
6627         return RelocFuncs::thumb32_cond_branch_offset(upper_insn, lower_insn);
6628       }
6629
6630     default:
6631       gold_unreachable();
6632     }
6633 }
6634
6635 // Arm_output_data_got methods.
6636
6637 // Add a GOT pair for R_ARM_TLS_GD32.  The creates a pair of GOT entries.
6638 // The first one is initialized to be 1, which is the module index for
6639 // the main executable and the second one 0.  A reloc of the type
6640 // R_ARM_TLS_DTPOFF32 will be created for the second GOT entry and will
6641 // be applied by gold.  GSYM is a global symbol.
6642 //
6643 template<bool big_endian>
6644 void
6645 Arm_output_data_got<big_endian>::add_tls_gd32_with_static_reloc(
6646     unsigned int got_type,
6647     Symbol* gsym)
6648 {
6649   if (gsym->has_got_offset(got_type))
6650     return;
6651
6652   // We are doing a static link.  Just mark it as belong to module 1,
6653   // the executable.
6654   unsigned int got_offset = this->add_constant(1);
6655   gsym->set_got_offset(got_type, got_offset); 
6656   got_offset = this->add_constant(0);
6657   this->static_relocs_.push_back(Static_reloc(got_offset,
6658                                               elfcpp::R_ARM_TLS_DTPOFF32,
6659                                               gsym));
6660 }
6661
6662 // Same as the above but for a local symbol.
6663
6664 template<bool big_endian>
6665 void
6666 Arm_output_data_got<big_endian>::add_tls_gd32_with_static_reloc(
6667   unsigned int got_type,
6668   Sized_relobj<32, big_endian>* object,
6669   unsigned int index)
6670 {
6671   if (object->local_has_got_offset(index, got_type))
6672     return;
6673
6674   // We are doing a static link.  Just mark it as belong to module 1,
6675   // the executable.
6676   unsigned int got_offset = this->add_constant(1);
6677   object->set_local_got_offset(index, got_type, got_offset);
6678   got_offset = this->add_constant(0);
6679   this->static_relocs_.push_back(Static_reloc(got_offset, 
6680                                               elfcpp::R_ARM_TLS_DTPOFF32, 
6681                                               object, index));
6682 }
6683
6684 template<bool big_endian>
6685 void
6686 Arm_output_data_got<big_endian>::do_write(Output_file* of)
6687 {
6688   // Call parent to write out GOT.
6689   Output_data_got<32, big_endian>::do_write(of);
6690
6691   // We are done if there is no fix up.
6692   if (this->static_relocs_.empty())
6693     return;
6694
6695   gold_assert(parameters->doing_static_link());
6696
6697   const off_t offset = this->offset();
6698   const section_size_type oview_size =
6699     convert_to_section_size_type(this->data_size());
6700   unsigned char* const oview = of->get_output_view(offset, oview_size);
6701
6702   Output_segment* tls_segment = this->layout_->tls_segment();
6703   gold_assert(tls_segment != NULL);
6704   
6705   // The thread pointer $tp points to the TCB, which is followed by the
6706   // TLS.  So we need to adjust $tp relative addressing by this amount.
6707   Arm_address aligned_tcb_size =
6708     align_address(ARM_TCB_SIZE, tls_segment->maximum_alignment());
6709
6710   for (size_t i = 0; i < this->static_relocs_.size(); ++i)
6711     {
6712       Static_reloc& reloc(this->static_relocs_[i]);
6713       
6714       Arm_address value;
6715       if (!reloc.symbol_is_global())
6716         {
6717           Sized_relobj<32, big_endian>* object = reloc.relobj();
6718           const Symbol_value<32>* psymval =
6719             reloc.relobj()->local_symbol(reloc.index());
6720
6721           // We are doing static linking.  Issue an error and skip this
6722           // relocation if the symbol is undefined or in a discarded_section.
6723           bool is_ordinary;
6724           unsigned int shndx = psymval->input_shndx(&is_ordinary);
6725           if ((shndx == elfcpp::SHN_UNDEF)
6726               || (is_ordinary
6727                   && shndx != elfcpp::SHN_UNDEF
6728                   && !object->is_section_included(shndx)
6729                   && !this->symbol_table_->is_section_folded(object, shndx)))
6730             {
6731               gold_error(_("undefined or discarded local symbol %u from "
6732                            " object %s in GOT"),
6733                          reloc.index(), reloc.relobj()->name().c_str());
6734               continue;
6735             }
6736           
6737           value = psymval->value(object, 0);
6738         }
6739       else
6740         {
6741           const Symbol* gsym = reloc.symbol();
6742           gold_assert(gsym != NULL);
6743           if (gsym->is_forwarder())
6744             gsym = this->symbol_table_->resolve_forwards(gsym);
6745
6746           // We are doing static linking.  Issue an error and skip this
6747           // relocation if the symbol is undefined or in a discarded_section
6748           // unless it is a weakly_undefined symbol.
6749           if ((gsym->is_defined_in_discarded_section()
6750                || gsym->is_undefined())
6751               && !gsym->is_weak_undefined())
6752             {
6753               gold_error(_("undefined or discarded symbol %s in GOT"),
6754                          gsym->name());
6755               continue;
6756             }
6757
6758           if (!gsym->is_weak_undefined())
6759             {
6760               const Sized_symbol<32>* sym =
6761                 static_cast<const Sized_symbol<32>*>(gsym);
6762               value = sym->value();
6763             }
6764           else
6765               value = 0;
6766         }
6767
6768       unsigned got_offset = reloc.got_offset();
6769       gold_assert(got_offset < oview_size);
6770
6771       typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
6772       Valtype* wv = reinterpret_cast<Valtype*>(oview + got_offset);
6773       Valtype x;
6774       switch (reloc.r_type())
6775         {
6776         case elfcpp::R_ARM_TLS_DTPOFF32:
6777           x = value;
6778           break;
6779         case elfcpp::R_ARM_TLS_TPOFF32:
6780           x = value + aligned_tcb_size;
6781           break;
6782         default:
6783           gold_unreachable();
6784         }
6785       elfcpp::Swap<32, big_endian>::writeval(wv, x);
6786     }
6787
6788   of->write_output_view(offset, oview_size, oview);
6789 }
6790
6791 // A class to handle the PLT data.
6792
6793 template<bool big_endian>
6794 class Output_data_plt_arm : public Output_section_data
6795 {
6796  public:
6797   typedef Output_data_reloc<elfcpp::SHT_REL, true, 32, big_endian>
6798     Reloc_section;
6799
6800   Output_data_plt_arm(Layout*, Output_data_space*);
6801
6802   // Add an entry to the PLT.
6803   void
6804   add_entry(Symbol* gsym);
6805
6806   // Return the .rel.plt section data.
6807   const Reloc_section*
6808   rel_plt() const
6809   { return this->rel_; }
6810
6811  protected:
6812   void
6813   do_adjust_output_section(Output_section* os);
6814
6815   // Write to a map file.
6816   void
6817   do_print_to_mapfile(Mapfile* mapfile) const
6818   { mapfile->print_output_data(this, _("** PLT")); }
6819
6820  private:
6821   // Template for the first PLT entry.
6822   static const uint32_t first_plt_entry[5];
6823
6824   // Template for subsequent PLT entries. 
6825   static const uint32_t plt_entry[3];
6826
6827   // Set the final size.
6828   void
6829   set_final_data_size()
6830   {
6831     this->set_data_size(sizeof(first_plt_entry)
6832                         + this->count_ * sizeof(plt_entry));
6833   }
6834
6835   // Write out the PLT data.
6836   void
6837   do_write(Output_file*);
6838
6839   // The reloc section.
6840   Reloc_section* rel_;
6841   // The .got.plt section.
6842   Output_data_space* got_plt_;
6843   // The number of PLT entries.
6844   unsigned int count_;
6845 };
6846
6847 // Create the PLT section.  The ordinary .got section is an argument,
6848 // since we need to refer to the start.  We also create our own .got
6849 // section just for PLT entries.
6850
6851 template<bool big_endian>
6852 Output_data_plt_arm<big_endian>::Output_data_plt_arm(Layout* layout,
6853                                                      Output_data_space* got_plt)
6854   : Output_section_data(4), got_plt_(got_plt), count_(0)
6855 {
6856   this->rel_ = new Reloc_section(false);
6857   layout->add_output_section_data(".rel.plt", elfcpp::SHT_REL,
6858                                   elfcpp::SHF_ALLOC, this->rel_, true, false,
6859                                   false, false);
6860 }
6861
6862 template<bool big_endian>
6863 void
6864 Output_data_plt_arm<big_endian>::do_adjust_output_section(Output_section* os)
6865 {
6866   os->set_entsize(0);
6867 }
6868
6869 // Add an entry to the PLT.
6870
6871 template<bool big_endian>
6872 void
6873 Output_data_plt_arm<big_endian>::add_entry(Symbol* gsym)
6874 {
6875   gold_assert(!gsym->has_plt_offset());
6876
6877   // Note that when setting the PLT offset we skip the initial
6878   // reserved PLT entry.
6879   gsym->set_plt_offset((this->count_) * sizeof(plt_entry)
6880                        + sizeof(first_plt_entry));
6881
6882   ++this->count_;
6883
6884   section_offset_type got_offset = this->got_plt_->current_data_size();
6885
6886   // Every PLT entry needs a GOT entry which points back to the PLT
6887   // entry (this will be changed by the dynamic linker, normally
6888   // lazily when the function is called).
6889   this->got_plt_->set_current_data_size(got_offset + 4);
6890
6891   // Every PLT entry needs a reloc.
6892   gsym->set_needs_dynsym_entry();
6893   this->rel_->add_global(gsym, elfcpp::R_ARM_JUMP_SLOT, this->got_plt_,
6894                          got_offset);
6895
6896   // Note that we don't need to save the symbol.  The contents of the
6897   // PLT are independent of which symbols are used.  The symbols only
6898   // appear in the relocations.
6899 }
6900
6901 // ARM PLTs.
6902 // FIXME:  This is not very flexible.  Right now this has only been tested
6903 // on armv5te.  If we are to support additional architecture features like
6904 // Thumb-2 or BE8, we need to make this more flexible like GNU ld.
6905
6906 // The first entry in the PLT.
6907 template<bool big_endian>
6908 const uint32_t Output_data_plt_arm<big_endian>::first_plt_entry[5] =
6909 {
6910   0xe52de004,   // str   lr, [sp, #-4]!
6911   0xe59fe004,   // ldr   lr, [pc, #4]
6912   0xe08fe00e,   // add   lr, pc, lr 
6913   0xe5bef008,   // ldr   pc, [lr, #8]!
6914   0x00000000,   // &GOT[0] - .
6915 };
6916
6917 // Subsequent entries in the PLT.
6918
6919 template<bool big_endian>
6920 const uint32_t Output_data_plt_arm<big_endian>::plt_entry[3] =
6921 {
6922   0xe28fc600,   // add   ip, pc, #0xNN00000
6923   0xe28cca00,   // add   ip, ip, #0xNN000
6924   0xe5bcf000,   // ldr   pc, [ip, #0xNNN]!
6925 };
6926
6927 // Write out the PLT.  This uses the hand-coded instructions above,
6928 // and adjusts them as needed.  This is all specified by the arm ELF
6929 // Processor Supplement.
6930
6931 template<bool big_endian>
6932 void
6933 Output_data_plt_arm<big_endian>::do_write(Output_file* of)
6934 {
6935   const off_t offset = this->offset();
6936   const section_size_type oview_size =
6937     convert_to_section_size_type(this->data_size());
6938   unsigned char* const oview = of->get_output_view(offset, oview_size);
6939
6940   const off_t got_file_offset = this->got_plt_->offset();
6941   const section_size_type got_size =
6942     convert_to_section_size_type(this->got_plt_->data_size());
6943   unsigned char* const got_view = of->get_output_view(got_file_offset,
6944                                                       got_size);
6945   unsigned char* pov = oview;
6946
6947   Arm_address plt_address = this->address();
6948   Arm_address got_address = this->got_plt_->address();
6949
6950   // Write first PLT entry.  All but the last word are constants.
6951   const size_t num_first_plt_words = (sizeof(first_plt_entry)
6952                                       / sizeof(plt_entry[0]));
6953   for (size_t i = 0; i < num_first_plt_words - 1; i++)
6954     elfcpp::Swap<32, big_endian>::writeval(pov + i * 4, first_plt_entry[i]);
6955   // Last word in first PLT entry is &GOT[0] - .
6956   elfcpp::Swap<32, big_endian>::writeval(pov + 16,
6957                                          got_address - (plt_address + 16));
6958   pov += sizeof(first_plt_entry);
6959
6960   unsigned char* got_pov = got_view;
6961
6962   memset(got_pov, 0, 12);
6963   got_pov += 12;
6964
6965   const int rel_size = elfcpp::Elf_sizes<32>::rel_size;
6966   unsigned int plt_offset = sizeof(first_plt_entry);
6967   unsigned int plt_rel_offset = 0;
6968   unsigned int got_offset = 12;
6969   const unsigned int count = this->count_;
6970   for (unsigned int i = 0;
6971        i < count;
6972        ++i,
6973          pov += sizeof(plt_entry),
6974          got_pov += 4,
6975          plt_offset += sizeof(plt_entry),
6976          plt_rel_offset += rel_size,
6977          got_offset += 4)
6978     {
6979       // Set and adjust the PLT entry itself.
6980       int32_t offset = ((got_address + got_offset)
6981                          - (plt_address + plt_offset + 8));
6982
6983       gold_assert(offset >= 0 && offset < 0x0fffffff);
6984       uint32_t plt_insn0 = plt_entry[0] | ((offset >> 20) & 0xff);
6985       elfcpp::Swap<32, big_endian>::writeval(pov, plt_insn0);
6986       uint32_t plt_insn1 = plt_entry[1] | ((offset >> 12) & 0xff);
6987       elfcpp::Swap<32, big_endian>::writeval(pov + 4, plt_insn1);
6988       uint32_t plt_insn2 = plt_entry[2] | (offset & 0xfff);
6989       elfcpp::Swap<32, big_endian>::writeval(pov + 8, plt_insn2);
6990
6991       // Set the entry in the GOT.
6992       elfcpp::Swap<32, big_endian>::writeval(got_pov, plt_address);
6993     }
6994
6995   gold_assert(static_cast<section_size_type>(pov - oview) == oview_size);
6996   gold_assert(static_cast<section_size_type>(got_pov - got_view) == got_size);
6997
6998   of->write_output_view(offset, oview_size, oview);
6999   of->write_output_view(got_file_offset, got_size, got_view);
7000 }
7001
7002 // Create a PLT entry for a global symbol.
7003
7004 template<bool big_endian>
7005 void
7006 Target_arm<big_endian>::make_plt_entry(Symbol_table* symtab, Layout* layout,
7007                                        Symbol* gsym)
7008 {
7009   if (gsym->has_plt_offset())
7010     return;
7011
7012   if (this->plt_ == NULL)
7013     {
7014       // Create the GOT sections first.
7015       this->got_section(symtab, layout);
7016
7017       this->plt_ = new Output_data_plt_arm<big_endian>(layout, this->got_plt_);
7018       layout->add_output_section_data(".plt", elfcpp::SHT_PROGBITS,
7019                                       (elfcpp::SHF_ALLOC
7020                                        | elfcpp::SHF_EXECINSTR),
7021                                       this->plt_, false, false, false, false);
7022     }
7023   this->plt_->add_entry(gsym);
7024 }
7025
7026 // Get the section to use for TLS_DESC relocations.
7027
7028 template<bool big_endian>
7029 typename Target_arm<big_endian>::Reloc_section*
7030 Target_arm<big_endian>::rel_tls_desc_section(Layout* layout) const
7031 {
7032   return this->plt_section()->rel_tls_desc(layout);
7033 }
7034
7035 // Define the _TLS_MODULE_BASE_ symbol in the TLS segment.
7036
7037 template<bool big_endian>
7038 void
7039 Target_arm<big_endian>::define_tls_base_symbol(
7040     Symbol_table* symtab,
7041     Layout* layout)
7042 {
7043   if (this->tls_base_symbol_defined_)
7044     return;
7045
7046   Output_segment* tls_segment = layout->tls_segment();
7047   if (tls_segment != NULL)
7048     {
7049       bool is_exec = parameters->options().output_is_executable();
7050       symtab->define_in_output_segment("_TLS_MODULE_BASE_", NULL,
7051                                        Symbol_table::PREDEFINED,
7052                                        tls_segment, 0, 0,
7053                                        elfcpp::STT_TLS,
7054                                        elfcpp::STB_LOCAL,
7055                                        elfcpp::STV_HIDDEN, 0,
7056                                        (is_exec
7057                                         ? Symbol::SEGMENT_END
7058                                         : Symbol::SEGMENT_START),
7059                                        true);
7060     }
7061   this->tls_base_symbol_defined_ = true;
7062 }
7063
7064 // Create a GOT entry for the TLS module index.
7065
7066 template<bool big_endian>
7067 unsigned int
7068 Target_arm<big_endian>::got_mod_index_entry(
7069     Symbol_table* symtab,
7070     Layout* layout,
7071     Sized_relobj<32, big_endian>* object)
7072 {
7073   if (this->got_mod_index_offset_ == -1U)
7074     {
7075       gold_assert(symtab != NULL && layout != NULL && object != NULL);
7076       Arm_output_data_got<big_endian>* got = this->got_section(symtab, layout);
7077       unsigned int got_offset;
7078       if (!parameters->doing_static_link())
7079         {
7080           got_offset = got->add_constant(0);
7081           Reloc_section* rel_dyn = this->rel_dyn_section(layout);
7082           rel_dyn->add_local(object, 0, elfcpp::R_ARM_TLS_DTPMOD32, got,
7083                              got_offset);
7084         }
7085       else
7086         {
7087           // We are doing a static link.  Just mark it as belong to module 1,
7088           // the executable.
7089           got_offset = got->add_constant(1);
7090         }
7091
7092       got->add_constant(0);
7093       this->got_mod_index_offset_ = got_offset;
7094     }
7095   return this->got_mod_index_offset_;
7096 }
7097
7098 // Optimize the TLS relocation type based on what we know about the
7099 // symbol.  IS_FINAL is true if the final address of this symbol is
7100 // known at link time.
7101
7102 template<bool big_endian>
7103 tls::Tls_optimization
7104 Target_arm<big_endian>::optimize_tls_reloc(bool, int)
7105 {
7106   // FIXME: Currently we do not do any TLS optimization.
7107   return tls::TLSOPT_NONE;
7108 }
7109
7110 // Report an unsupported relocation against a local symbol.
7111
7112 template<bool big_endian>
7113 void
7114 Target_arm<big_endian>::Scan::unsupported_reloc_local(
7115     Sized_relobj<32, big_endian>* object,
7116     unsigned int r_type)
7117 {
7118   gold_error(_("%s: unsupported reloc %u against local symbol"),
7119              object->name().c_str(), r_type);
7120 }
7121
7122 // We are about to emit a dynamic relocation of type R_TYPE.  If the
7123 // dynamic linker does not support it, issue an error.  The GNU linker
7124 // only issues a non-PIC error for an allocated read-only section.
7125 // Here we know the section is allocated, but we don't know that it is
7126 // read-only.  But we check for all the relocation types which the
7127 // glibc dynamic linker supports, so it seems appropriate to issue an
7128 // error even if the section is not read-only.
7129
7130 template<bool big_endian>
7131 void
7132 Target_arm<big_endian>::Scan::check_non_pic(Relobj* object,
7133                                             unsigned int r_type)
7134 {
7135   switch (r_type)
7136     {
7137     // These are the relocation types supported by glibc for ARM.
7138     case elfcpp::R_ARM_RELATIVE:
7139     case elfcpp::R_ARM_COPY:
7140     case elfcpp::R_ARM_GLOB_DAT:
7141     case elfcpp::R_ARM_JUMP_SLOT:
7142     case elfcpp::R_ARM_ABS32:
7143     case elfcpp::R_ARM_ABS32_NOI:
7144     case elfcpp::R_ARM_PC24:
7145     // FIXME: The following 3 types are not supported by Android's dynamic
7146     // linker.
7147     case elfcpp::R_ARM_TLS_DTPMOD32:
7148     case elfcpp::R_ARM_TLS_DTPOFF32:
7149     case elfcpp::R_ARM_TLS_TPOFF32:
7150       return;
7151
7152     default:
7153       {
7154         // This prevents us from issuing more than one error per reloc
7155         // section.  But we can still wind up issuing more than one
7156         // error per object file.
7157         if (this->issued_non_pic_error_)
7158           return;
7159         const Arm_reloc_property* reloc_property =
7160           arm_reloc_property_table->get_reloc_property(r_type);
7161         gold_assert(reloc_property != NULL);
7162         object->error(_("requires unsupported dynamic reloc %s; "
7163                       "recompile with -fPIC"),
7164                       reloc_property->name().c_str());
7165         this->issued_non_pic_error_ = true;
7166         return;
7167       }
7168
7169     case elfcpp::R_ARM_NONE:
7170       gold_unreachable();
7171     }
7172 }
7173
7174 // Scan a relocation for a local symbol.
7175 // FIXME: This only handles a subset of relocation types used by Android
7176 // on ARM v5te devices.
7177
7178 template<bool big_endian>
7179 inline void
7180 Target_arm<big_endian>::Scan::local(Symbol_table* symtab,
7181                                     Layout* layout,
7182                                     Target_arm* target,
7183                                     Sized_relobj<32, big_endian>* object,
7184                                     unsigned int data_shndx,
7185                                     Output_section* output_section,
7186                                     const elfcpp::Rel<32, big_endian>& reloc,
7187                                     unsigned int r_type,
7188                                     const elfcpp::Sym<32, big_endian>& lsym)
7189 {
7190   r_type = get_real_reloc_type(r_type);
7191   switch (r_type)
7192     {
7193     case elfcpp::R_ARM_NONE:
7194     case elfcpp::R_ARM_V4BX:
7195     case elfcpp::R_ARM_GNU_VTENTRY:
7196     case elfcpp::R_ARM_GNU_VTINHERIT:
7197       break;
7198
7199     case elfcpp::R_ARM_ABS32:
7200     case elfcpp::R_ARM_ABS32_NOI:
7201       // If building a shared library (or a position-independent
7202       // executable), we need to create a dynamic relocation for
7203       // this location. The relocation applied at link time will
7204       // apply the link-time value, so we flag the location with
7205       // an R_ARM_RELATIVE relocation so the dynamic loader can
7206       // relocate it easily.
7207       if (parameters->options().output_is_position_independent())
7208         {
7209           Reloc_section* rel_dyn = target->rel_dyn_section(layout);
7210           unsigned int r_sym = elfcpp::elf_r_sym<32>(reloc.get_r_info());
7211           // If we are to add more other reloc types than R_ARM_ABS32,
7212           // we need to add check_non_pic(object, r_type) here.
7213           rel_dyn->add_local_relative(object, r_sym, elfcpp::R_ARM_RELATIVE,
7214                                       output_section, data_shndx,
7215                                       reloc.get_r_offset());
7216         }
7217       break;
7218
7219     case elfcpp::R_ARM_ABS16:
7220     case elfcpp::R_ARM_ABS12:
7221     case elfcpp::R_ARM_THM_ABS5:
7222     case elfcpp::R_ARM_ABS8:
7223     case elfcpp::R_ARM_BASE_ABS:
7224     case elfcpp::R_ARM_MOVW_ABS_NC:
7225     case elfcpp::R_ARM_MOVT_ABS:
7226     case elfcpp::R_ARM_THM_MOVW_ABS_NC:
7227     case elfcpp::R_ARM_THM_MOVT_ABS:
7228       // If building a shared library (or a position-independent
7229       // executable), we need to create a dynamic relocation for
7230       // this location. Because the addend needs to remain in the
7231       // data section, we need to be careful not to apply this
7232       // relocation statically.
7233       if (parameters->options().output_is_position_independent())
7234         {
7235           check_non_pic(object, r_type);
7236           Reloc_section* rel_dyn = target->rel_dyn_section(layout);
7237           unsigned int r_sym = elfcpp::elf_r_sym<32>(reloc.get_r_info());
7238           if (lsym.get_st_type() != elfcpp::STT_SECTION)
7239             rel_dyn->add_local(object, r_sym, r_type, output_section,
7240                                data_shndx, reloc.get_r_offset());
7241           else
7242             {
7243               gold_assert(lsym.get_st_value() == 0);
7244               unsigned int shndx = lsym.get_st_shndx();
7245               bool is_ordinary;
7246               shndx = object->adjust_sym_shndx(r_sym, shndx,
7247                                                &is_ordinary);
7248               if (!is_ordinary)
7249                 object->error(_("section symbol %u has bad shndx %u"),
7250                               r_sym, shndx);
7251               else
7252                 rel_dyn->add_local_section(object, shndx,
7253                                            r_type, output_section,
7254                                            data_shndx, reloc.get_r_offset());
7255             }
7256         }
7257       break;
7258
7259     case elfcpp::R_ARM_PC24:
7260     case elfcpp::R_ARM_REL32:
7261     case elfcpp::R_ARM_LDR_PC_G0:
7262     case elfcpp::R_ARM_SBREL32:
7263     case elfcpp::R_ARM_THM_CALL:
7264     case elfcpp::R_ARM_THM_PC8:
7265     case elfcpp::R_ARM_BASE_PREL:
7266     case elfcpp::R_ARM_PLT32:
7267     case elfcpp::R_ARM_CALL:
7268     case elfcpp::R_ARM_JUMP24:
7269     case elfcpp::R_ARM_THM_JUMP24:
7270     case elfcpp::R_ARM_LDR_SBREL_11_0_NC:
7271     case elfcpp::R_ARM_ALU_SBREL_19_12_NC:
7272     case elfcpp::R_ARM_ALU_SBREL_27_20_CK:
7273     case elfcpp::R_ARM_SBREL31:
7274     case elfcpp::R_ARM_PREL31:
7275     case elfcpp::R_ARM_MOVW_PREL_NC:
7276     case elfcpp::R_ARM_MOVT_PREL:
7277     case elfcpp::R_ARM_THM_MOVW_PREL_NC:
7278     case elfcpp::R_ARM_THM_MOVT_PREL:
7279     case elfcpp::R_ARM_THM_JUMP19:
7280     case elfcpp::R_ARM_THM_JUMP6:
7281     case elfcpp::R_ARM_THM_ALU_PREL_11_0:
7282     case elfcpp::R_ARM_THM_PC12:
7283     case elfcpp::R_ARM_REL32_NOI:
7284     case elfcpp::R_ARM_ALU_PC_G0_NC:
7285     case elfcpp::R_ARM_ALU_PC_G0:
7286     case elfcpp::R_ARM_ALU_PC_G1_NC:
7287     case elfcpp::R_ARM_ALU_PC_G1:
7288     case elfcpp::R_ARM_ALU_PC_G2:
7289     case elfcpp::R_ARM_LDR_PC_G1:
7290     case elfcpp::R_ARM_LDR_PC_G2:
7291     case elfcpp::R_ARM_LDRS_PC_G0:
7292     case elfcpp::R_ARM_LDRS_PC_G1:
7293     case elfcpp::R_ARM_LDRS_PC_G2:
7294     case elfcpp::R_ARM_LDC_PC_G0:
7295     case elfcpp::R_ARM_LDC_PC_G1:
7296     case elfcpp::R_ARM_LDC_PC_G2:
7297     case elfcpp::R_ARM_ALU_SB_G0_NC:
7298     case elfcpp::R_ARM_ALU_SB_G0:
7299     case elfcpp::R_ARM_ALU_SB_G1_NC:
7300     case elfcpp::R_ARM_ALU_SB_G1:
7301     case elfcpp::R_ARM_ALU_SB_G2:
7302     case elfcpp::R_ARM_LDR_SB_G0:
7303     case elfcpp::R_ARM_LDR_SB_G1:
7304     case elfcpp::R_ARM_LDR_SB_G2:
7305     case elfcpp::R_ARM_LDRS_SB_G0:
7306     case elfcpp::R_ARM_LDRS_SB_G1:
7307     case elfcpp::R_ARM_LDRS_SB_G2:
7308     case elfcpp::R_ARM_LDC_SB_G0:
7309     case elfcpp::R_ARM_LDC_SB_G1:
7310     case elfcpp::R_ARM_LDC_SB_G2:
7311     case elfcpp::R_ARM_MOVW_BREL_NC:
7312     case elfcpp::R_ARM_MOVT_BREL:
7313     case elfcpp::R_ARM_MOVW_BREL:
7314     case elfcpp::R_ARM_THM_MOVW_BREL_NC:
7315     case elfcpp::R_ARM_THM_MOVT_BREL:
7316     case elfcpp::R_ARM_THM_MOVW_BREL:
7317     case elfcpp::R_ARM_THM_JUMP11:
7318     case elfcpp::R_ARM_THM_JUMP8:
7319       // We don't need to do anything for a relative addressing relocation
7320       // against a local symbol if it does not reference the GOT.
7321       break;
7322
7323     case elfcpp::R_ARM_GOTOFF32:
7324     case elfcpp::R_ARM_GOTOFF12:
7325       // We need a GOT section:
7326       target->got_section(symtab, layout);
7327       break;
7328
7329     case elfcpp::R_ARM_GOT_BREL:
7330     case elfcpp::R_ARM_GOT_PREL:
7331       {
7332         // The symbol requires a GOT entry.
7333         Arm_output_data_got<big_endian>* got =
7334           target->got_section(symtab, layout);
7335         unsigned int r_sym = elfcpp::elf_r_sym<32>(reloc.get_r_info());
7336         if (got->add_local(object, r_sym, GOT_TYPE_STANDARD))
7337           {
7338             // If we are generating a shared object, we need to add a
7339             // dynamic RELATIVE relocation for this symbol's GOT entry.
7340             if (parameters->options().output_is_position_independent())
7341               {
7342                 Reloc_section* rel_dyn = target->rel_dyn_section(layout);
7343                 unsigned int r_sym = elfcpp::elf_r_sym<32>(reloc.get_r_info());
7344                 rel_dyn->add_local_relative(
7345                     object, r_sym, elfcpp::R_ARM_RELATIVE, got,
7346                     object->local_got_offset(r_sym, GOT_TYPE_STANDARD));
7347               }
7348           }
7349       }
7350       break;
7351
7352     case elfcpp::R_ARM_TARGET1:
7353     case elfcpp::R_ARM_TARGET2:
7354       // This should have been mapped to another type already.
7355       // Fall through.
7356     case elfcpp::R_ARM_COPY:
7357     case elfcpp::R_ARM_GLOB_DAT:
7358     case elfcpp::R_ARM_JUMP_SLOT:
7359     case elfcpp::R_ARM_RELATIVE:
7360       // These are relocations which should only be seen by the
7361       // dynamic linker, and should never be seen here.
7362       gold_error(_("%s: unexpected reloc %u in object file"),
7363                  object->name().c_str(), r_type);
7364       break;
7365
7366
7367       // These are initial TLS relocs, which are expected when
7368       // linking.
7369     case elfcpp::R_ARM_TLS_GD32:        // Global-dynamic
7370     case elfcpp::R_ARM_TLS_LDM32:       // Local-dynamic
7371     case elfcpp::R_ARM_TLS_LDO32:       // Alternate local-dynamic
7372     case elfcpp::R_ARM_TLS_IE32:        // Initial-exec
7373     case elfcpp::R_ARM_TLS_LE32:        // Local-exec
7374       {
7375         bool output_is_shared = parameters->options().shared();
7376         const tls::Tls_optimization optimized_type
7377             = Target_arm<big_endian>::optimize_tls_reloc(!output_is_shared,
7378                                                          r_type);
7379         switch (r_type)
7380           {
7381           case elfcpp::R_ARM_TLS_GD32:          // Global-dynamic
7382             if (optimized_type == tls::TLSOPT_NONE)
7383               {
7384                 // Create a pair of GOT entries for the module index and
7385                 // dtv-relative offset.
7386                 Arm_output_data_got<big_endian>* got
7387                     = target->got_section(symtab, layout);
7388                 unsigned int r_sym = elfcpp::elf_r_sym<32>(reloc.get_r_info());
7389                 unsigned int shndx = lsym.get_st_shndx();
7390                 bool is_ordinary;
7391                 shndx = object->adjust_sym_shndx(r_sym, shndx, &is_ordinary);
7392                 if (!is_ordinary)
7393                   {
7394                     object->error(_("local symbol %u has bad shndx %u"),
7395                                   r_sym, shndx);
7396                     break;
7397                   }
7398
7399                 if (!parameters->doing_static_link())
7400                   got->add_local_pair_with_rel(object, r_sym, shndx,
7401                                                GOT_TYPE_TLS_PAIR,
7402                                                target->rel_dyn_section(layout),
7403                                                elfcpp::R_ARM_TLS_DTPMOD32, 0);
7404                 else
7405                   got->add_tls_gd32_with_static_reloc(GOT_TYPE_TLS_PAIR,
7406                                                       object, r_sym);
7407               }
7408             else
7409               // FIXME: TLS optimization not supported yet.
7410               gold_unreachable();
7411             break;
7412
7413           case elfcpp::R_ARM_TLS_LDM32:         // Local-dynamic
7414             if (optimized_type == tls::TLSOPT_NONE)
7415               {
7416                 // Create a GOT entry for the module index.
7417                 target->got_mod_index_entry(symtab, layout, object);
7418               }
7419             else
7420               // FIXME: TLS optimization not supported yet.
7421               gold_unreachable();
7422             break;
7423
7424           case elfcpp::R_ARM_TLS_LDO32:         // Alternate local-dynamic
7425             break;
7426
7427           case elfcpp::R_ARM_TLS_IE32:          // Initial-exec
7428             layout->set_has_static_tls();
7429             if (optimized_type == tls::TLSOPT_NONE)
7430               {
7431                 // Create a GOT entry for the tp-relative offset.
7432                 Arm_output_data_got<big_endian>* got
7433                   = target->got_section(symtab, layout);
7434                 unsigned int r_sym =
7435                    elfcpp::elf_r_sym<32>(reloc.get_r_info());
7436                 if (!parameters->doing_static_link())
7437                     got->add_local_with_rel(object, r_sym, GOT_TYPE_TLS_OFFSET,
7438                                             target->rel_dyn_section(layout),
7439                                             elfcpp::R_ARM_TLS_TPOFF32);
7440                 else if (!object->local_has_got_offset(r_sym,
7441                                                        GOT_TYPE_TLS_OFFSET))
7442                   {
7443                     got->add_local(object, r_sym, GOT_TYPE_TLS_OFFSET);
7444                     unsigned int got_offset =
7445                       object->local_got_offset(r_sym, GOT_TYPE_TLS_OFFSET);
7446                     got->add_static_reloc(got_offset,
7447                                           elfcpp::R_ARM_TLS_TPOFF32, object,
7448                                           r_sym);
7449                   }
7450               }
7451             else
7452               // FIXME: TLS optimization not supported yet.
7453               gold_unreachable();
7454             break;
7455
7456           case elfcpp::R_ARM_TLS_LE32:          // Local-exec
7457             layout->set_has_static_tls();
7458             if (output_is_shared)
7459               {
7460                 // We need to create a dynamic relocation.
7461                 gold_assert(lsym.get_st_type() != elfcpp::STT_SECTION);
7462                 unsigned int r_sym = elfcpp::elf_r_sym<32>(reloc.get_r_info());
7463                 Reloc_section* rel_dyn = target->rel_dyn_section(layout);
7464                 rel_dyn->add_local(object, r_sym, elfcpp::R_ARM_TLS_TPOFF32,
7465                                    output_section, data_shndx,
7466                                    reloc.get_r_offset());
7467               }
7468             break;
7469
7470           default:
7471             gold_unreachable();
7472           }
7473       }
7474       break;
7475
7476     default:
7477       unsupported_reloc_local(object, r_type);
7478       break;
7479     }
7480 }
7481
7482 // Report an unsupported relocation against a global symbol.
7483
7484 template<bool big_endian>
7485 void
7486 Target_arm<big_endian>::Scan::unsupported_reloc_global(
7487     Sized_relobj<32, big_endian>* object,
7488     unsigned int r_type,
7489     Symbol* gsym)
7490 {
7491   gold_error(_("%s: unsupported reloc %u against global symbol %s"),
7492              object->name().c_str(), r_type, gsym->demangled_name().c_str());
7493 }
7494
7495 // Scan a relocation for a global symbol.
7496
7497 template<bool big_endian>
7498 inline void
7499 Target_arm<big_endian>::Scan::global(Symbol_table* symtab,
7500                                      Layout* layout,
7501                                      Target_arm* target,
7502                                      Sized_relobj<32, big_endian>* object,
7503                                      unsigned int data_shndx,
7504                                      Output_section* output_section,
7505                                      const elfcpp::Rel<32, big_endian>& reloc,
7506                                      unsigned int r_type,
7507                                      Symbol* gsym)
7508 {
7509   // A reference to _GLOBAL_OFFSET_TABLE_ implies that we need a got
7510   // section.  We check here to avoid creating a dynamic reloc against
7511   // _GLOBAL_OFFSET_TABLE_.
7512   if (!target->has_got_section()
7513       && strcmp(gsym->name(), "_GLOBAL_OFFSET_TABLE_") == 0)
7514     target->got_section(symtab, layout);
7515
7516   r_type = get_real_reloc_type(r_type);
7517   switch (r_type)
7518     {
7519     case elfcpp::R_ARM_NONE:
7520     case elfcpp::R_ARM_V4BX:
7521     case elfcpp::R_ARM_GNU_VTENTRY:
7522     case elfcpp::R_ARM_GNU_VTINHERIT:
7523       break;
7524
7525     case elfcpp::R_ARM_ABS32:
7526     case elfcpp::R_ARM_ABS16:
7527     case elfcpp::R_ARM_ABS12:
7528     case elfcpp::R_ARM_THM_ABS5:
7529     case elfcpp::R_ARM_ABS8:
7530     case elfcpp::R_ARM_BASE_ABS:
7531     case elfcpp::R_ARM_MOVW_ABS_NC:
7532     case elfcpp::R_ARM_MOVT_ABS:
7533     case elfcpp::R_ARM_THM_MOVW_ABS_NC:
7534     case elfcpp::R_ARM_THM_MOVT_ABS:
7535     case elfcpp::R_ARM_ABS32_NOI:
7536       // Absolute addressing relocations.
7537       {
7538         // Make a PLT entry if necessary.
7539         if (this->symbol_needs_plt_entry(gsym))
7540           {
7541             target->make_plt_entry(symtab, layout, gsym);
7542             // Since this is not a PC-relative relocation, we may be
7543             // taking the address of a function. In that case we need to
7544             // set the entry in the dynamic symbol table to the address of
7545             // the PLT entry.
7546             if (gsym->is_from_dynobj() && !parameters->options().shared())
7547               gsym->set_needs_dynsym_value();
7548           }
7549         // Make a dynamic relocation if necessary.
7550         if (gsym->needs_dynamic_reloc(Symbol::ABSOLUTE_REF))
7551           {
7552             if (gsym->may_need_copy_reloc())
7553               {
7554                 target->copy_reloc(symtab, layout, object,
7555                                    data_shndx, output_section, gsym, reloc);
7556               }
7557             else if ((r_type == elfcpp::R_ARM_ABS32
7558                       || r_type == elfcpp::R_ARM_ABS32_NOI)
7559                      && gsym->can_use_relative_reloc(false))
7560               {
7561                 Reloc_section* rel_dyn = target->rel_dyn_section(layout);
7562                 rel_dyn->add_global_relative(gsym, elfcpp::R_ARM_RELATIVE,
7563                                              output_section, object,
7564                                              data_shndx, reloc.get_r_offset());
7565               }
7566             else
7567               {
7568                 check_non_pic(object, r_type);
7569                 Reloc_section* rel_dyn = target->rel_dyn_section(layout);
7570                 rel_dyn->add_global(gsym, r_type, output_section, object,
7571                                     data_shndx, reloc.get_r_offset());
7572               }
7573           }
7574       }
7575       break;
7576
7577     case elfcpp::R_ARM_GOTOFF32:
7578     case elfcpp::R_ARM_GOTOFF12:
7579       // We need a GOT section.
7580       target->got_section(symtab, layout);
7581       break;
7582       
7583     case elfcpp::R_ARM_REL32:
7584     case elfcpp::R_ARM_LDR_PC_G0:
7585     case elfcpp::R_ARM_SBREL32:
7586     case elfcpp::R_ARM_THM_PC8:
7587     case elfcpp::R_ARM_BASE_PREL:
7588     case elfcpp::R_ARM_LDR_SBREL_11_0_NC:
7589     case elfcpp::R_ARM_ALU_SBREL_19_12_NC:
7590     case elfcpp::R_ARM_ALU_SBREL_27_20_CK:
7591     case elfcpp::R_ARM_MOVW_PREL_NC:
7592     case elfcpp::R_ARM_MOVT_PREL:
7593     case elfcpp::R_ARM_THM_MOVW_PREL_NC:
7594     case elfcpp::R_ARM_THM_MOVT_PREL:
7595     case elfcpp::R_ARM_THM_ALU_PREL_11_0:
7596     case elfcpp::R_ARM_THM_PC12:
7597     case elfcpp::R_ARM_REL32_NOI:
7598     case elfcpp::R_ARM_ALU_PC_G0_NC:
7599     case elfcpp::R_ARM_ALU_PC_G0:
7600     case elfcpp::R_ARM_ALU_PC_G1_NC:
7601     case elfcpp::R_ARM_ALU_PC_G1:
7602     case elfcpp::R_ARM_ALU_PC_G2:
7603     case elfcpp::R_ARM_LDR_PC_G1:
7604     case elfcpp::R_ARM_LDR_PC_G2:
7605     case elfcpp::R_ARM_LDRS_PC_G0:
7606     case elfcpp::R_ARM_LDRS_PC_G1:
7607     case elfcpp::R_ARM_LDRS_PC_G2:
7608     case elfcpp::R_ARM_LDC_PC_G0:
7609     case elfcpp::R_ARM_LDC_PC_G1:
7610     case elfcpp::R_ARM_LDC_PC_G2:
7611     case elfcpp::R_ARM_ALU_SB_G0_NC:
7612     case elfcpp::R_ARM_ALU_SB_G0:
7613     case elfcpp::R_ARM_ALU_SB_G1_NC:
7614     case elfcpp::R_ARM_ALU_SB_G1:
7615     case elfcpp::R_ARM_ALU_SB_G2:
7616     case elfcpp::R_ARM_LDR_SB_G0:
7617     case elfcpp::R_ARM_LDR_SB_G1:
7618     case elfcpp::R_ARM_LDR_SB_G2:
7619     case elfcpp::R_ARM_LDRS_SB_G0:
7620     case elfcpp::R_ARM_LDRS_SB_G1:
7621     case elfcpp::R_ARM_LDRS_SB_G2:
7622     case elfcpp::R_ARM_LDC_SB_G0:
7623     case elfcpp::R_ARM_LDC_SB_G1:
7624     case elfcpp::R_ARM_LDC_SB_G2:
7625     case elfcpp::R_ARM_MOVW_BREL_NC:
7626     case elfcpp::R_ARM_MOVT_BREL:
7627     case elfcpp::R_ARM_MOVW_BREL:
7628     case elfcpp::R_ARM_THM_MOVW_BREL_NC:
7629     case elfcpp::R_ARM_THM_MOVT_BREL:
7630     case elfcpp::R_ARM_THM_MOVW_BREL:
7631       // Relative addressing relocations.
7632       {
7633         // Make a dynamic relocation if necessary.
7634         int flags = Symbol::NON_PIC_REF;
7635         if (gsym->needs_dynamic_reloc(flags))
7636           {
7637             if (target->may_need_copy_reloc(gsym))
7638               {
7639                 target->copy_reloc(symtab, layout, object,
7640                                    data_shndx, output_section, gsym, reloc);
7641               }
7642             else
7643               {
7644                 check_non_pic(object, r_type);
7645                 Reloc_section* rel_dyn = target->rel_dyn_section(layout);
7646                 rel_dyn->add_global(gsym, r_type, output_section, object,
7647                                     data_shndx, reloc.get_r_offset());
7648               }
7649           }
7650       }
7651       break;
7652
7653     case elfcpp::R_ARM_PC24:
7654     case elfcpp::R_ARM_THM_CALL:
7655     case elfcpp::R_ARM_PLT32:
7656     case elfcpp::R_ARM_CALL:
7657     case elfcpp::R_ARM_JUMP24:
7658     case elfcpp::R_ARM_THM_JUMP24:
7659     case elfcpp::R_ARM_SBREL31:
7660     case elfcpp::R_ARM_PREL31:
7661     case elfcpp::R_ARM_THM_JUMP19:
7662     case elfcpp::R_ARM_THM_JUMP6:
7663     case elfcpp::R_ARM_THM_JUMP11:
7664     case elfcpp::R_ARM_THM_JUMP8:
7665       // All the relocation above are branches except for the PREL31 ones.
7666       // A PREL31 relocation can point to a personality function in a shared
7667       // library.  In that case we want to use a PLT because we want to
7668       // call the personality routine and the dyanmic linkers we care about
7669       // do not support dynamic PREL31 relocations. An REL31 relocation may
7670       // point to a function whose unwinding behaviour is being described but
7671       // we will not mistakenly generate a PLT for that because we should use
7672       // a local section symbol.
7673
7674       // If the symbol is fully resolved, this is just a relative
7675       // local reloc.  Otherwise we need a PLT entry.
7676       if (gsym->final_value_is_known())
7677         break;
7678       // If building a shared library, we can also skip the PLT entry
7679       // if the symbol is defined in the output file and is protected
7680       // or hidden.
7681       if (gsym->is_defined()
7682           && !gsym->is_from_dynobj()
7683           && !gsym->is_preemptible())
7684         break;
7685       target->make_plt_entry(symtab, layout, gsym);
7686       break;
7687
7688     case elfcpp::R_ARM_GOT_BREL:
7689     case elfcpp::R_ARM_GOT_ABS:
7690     case elfcpp::R_ARM_GOT_PREL:
7691       {
7692         // The symbol requires a GOT entry.
7693         Arm_output_data_got<big_endian>* got =
7694           target->got_section(symtab, layout);
7695         if (gsym->final_value_is_known())
7696           got->add_global(gsym, GOT_TYPE_STANDARD);
7697         else
7698           {
7699             // If this symbol is not fully resolved, we need to add a
7700             // GOT entry with a dynamic relocation.
7701             Reloc_section* rel_dyn = target->rel_dyn_section(layout);
7702             if (gsym->is_from_dynobj()
7703                 || gsym->is_undefined()
7704                 || gsym->is_preemptible())
7705               got->add_global_with_rel(gsym, GOT_TYPE_STANDARD,
7706                                        rel_dyn, elfcpp::R_ARM_GLOB_DAT);
7707             else
7708               {
7709                 if (got->add_global(gsym, GOT_TYPE_STANDARD))
7710                   rel_dyn->add_global_relative(
7711                       gsym, elfcpp::R_ARM_RELATIVE, got,
7712                       gsym->got_offset(GOT_TYPE_STANDARD));
7713               }
7714           }
7715       }
7716       break;
7717
7718     case elfcpp::R_ARM_TARGET1:
7719     case elfcpp::R_ARM_TARGET2:
7720       // These should have been mapped to other types already.
7721       // Fall through.
7722     case elfcpp::R_ARM_COPY:
7723     case elfcpp::R_ARM_GLOB_DAT:
7724     case elfcpp::R_ARM_JUMP_SLOT:
7725     case elfcpp::R_ARM_RELATIVE:
7726       // These are relocations which should only be seen by the
7727       // dynamic linker, and should never be seen here.
7728       gold_error(_("%s: unexpected reloc %u in object file"),
7729                  object->name().c_str(), r_type);
7730       break;
7731
7732       // These are initial tls relocs, which are expected when
7733       // linking.
7734     case elfcpp::R_ARM_TLS_GD32:        // Global-dynamic
7735     case elfcpp::R_ARM_TLS_LDM32:       // Local-dynamic
7736     case elfcpp::R_ARM_TLS_LDO32:       // Alternate local-dynamic
7737     case elfcpp::R_ARM_TLS_IE32:        // Initial-exec
7738     case elfcpp::R_ARM_TLS_LE32:        // Local-exec
7739       {
7740         const bool is_final = gsym->final_value_is_known();
7741         const tls::Tls_optimization optimized_type
7742             = Target_arm<big_endian>::optimize_tls_reloc(is_final, r_type);
7743         switch (r_type)
7744           {
7745           case elfcpp::R_ARM_TLS_GD32:          // Global-dynamic
7746             if (optimized_type == tls::TLSOPT_NONE)
7747               {
7748                 // Create a pair of GOT entries for the module index and
7749                 // dtv-relative offset.
7750                 Arm_output_data_got<big_endian>* got
7751                     = target->got_section(symtab, layout);
7752                 if (!parameters->doing_static_link())
7753                   got->add_global_pair_with_rel(gsym, GOT_TYPE_TLS_PAIR,
7754                                                 target->rel_dyn_section(layout),
7755                                                 elfcpp::R_ARM_TLS_DTPMOD32,
7756                                                 elfcpp::R_ARM_TLS_DTPOFF32);
7757                 else
7758                   got->add_tls_gd32_with_static_reloc(GOT_TYPE_TLS_PAIR, gsym);
7759               }
7760             else
7761               // FIXME: TLS optimization not supported yet.
7762               gold_unreachable();
7763             break;
7764
7765           case elfcpp::R_ARM_TLS_LDM32:         // Local-dynamic
7766             if (optimized_type == tls::TLSOPT_NONE)
7767               {
7768                 // Create a GOT entry for the module index.
7769                 target->got_mod_index_entry(symtab, layout, object);
7770               }
7771             else
7772               // FIXME: TLS optimization not supported yet.
7773               gold_unreachable();
7774             break;
7775
7776           case elfcpp::R_ARM_TLS_LDO32:         // Alternate local-dynamic
7777             break;
7778
7779           case elfcpp::R_ARM_TLS_IE32:          // Initial-exec
7780             layout->set_has_static_tls();
7781             if (optimized_type == tls::TLSOPT_NONE)
7782               {
7783                 // Create a GOT entry for the tp-relative offset.
7784                 Arm_output_data_got<big_endian>* got
7785                   = target->got_section(symtab, layout);
7786                 if (!parameters->doing_static_link())
7787                   got->add_global_with_rel(gsym, GOT_TYPE_TLS_OFFSET,
7788                                            target->rel_dyn_section(layout),
7789                                            elfcpp::R_ARM_TLS_TPOFF32);
7790                 else if (!gsym->has_got_offset(GOT_TYPE_TLS_OFFSET))
7791                   {
7792                     got->add_global(gsym, GOT_TYPE_TLS_OFFSET);
7793                     unsigned int got_offset =
7794                        gsym->got_offset(GOT_TYPE_TLS_OFFSET);
7795                     got->add_static_reloc(got_offset,
7796                                           elfcpp::R_ARM_TLS_TPOFF32, gsym);
7797                   }
7798               }
7799             else
7800               // FIXME: TLS optimization not supported yet.
7801               gold_unreachable();
7802             break;
7803
7804           case elfcpp::R_ARM_TLS_LE32:  // Local-exec
7805             layout->set_has_static_tls();
7806             if (parameters->options().shared())
7807               {
7808                 // We need to create a dynamic relocation.
7809                 Reloc_section* rel_dyn = target->rel_dyn_section(layout);
7810                 rel_dyn->add_global(gsym, elfcpp::R_ARM_TLS_TPOFF32,
7811                                     output_section, object,
7812                                     data_shndx, reloc.get_r_offset());
7813               }
7814             break;
7815
7816           default:
7817             gold_unreachable();
7818           }
7819       }
7820       break;
7821
7822     default:
7823       unsupported_reloc_global(object, r_type, gsym);
7824       break;
7825     }
7826 }
7827
7828 // Process relocations for gc.
7829
7830 template<bool big_endian>
7831 void
7832 Target_arm<big_endian>::gc_process_relocs(Symbol_table* symtab,
7833                                           Layout* layout,
7834                                           Sized_relobj<32, big_endian>* object,
7835                                           unsigned int data_shndx,
7836                                           unsigned int,
7837                                           const unsigned char* prelocs,
7838                                           size_t reloc_count,
7839                                           Output_section* output_section,
7840                                           bool needs_special_offset_handling,
7841                                           size_t local_symbol_count,
7842                                           const unsigned char* plocal_symbols)
7843 {
7844   typedef Target_arm<big_endian> Arm;
7845   typedef typename Target_arm<big_endian>::Scan Scan;
7846
7847   gold::gc_process_relocs<32, big_endian, Arm, elfcpp::SHT_REL, Scan>(
7848     symtab,
7849     layout,
7850     this,
7851     object,
7852     data_shndx,
7853     prelocs,
7854     reloc_count,
7855     output_section,
7856     needs_special_offset_handling,
7857     local_symbol_count,
7858     plocal_symbols);
7859 }
7860
7861 // Scan relocations for a section.
7862
7863 template<bool big_endian>
7864 void
7865 Target_arm<big_endian>::scan_relocs(Symbol_table* symtab,
7866                                     Layout* layout,
7867                                     Sized_relobj<32, big_endian>* object,
7868                                     unsigned int data_shndx,
7869                                     unsigned int sh_type,
7870                                     const unsigned char* prelocs,
7871                                     size_t reloc_count,
7872                                     Output_section* output_section,
7873                                     bool needs_special_offset_handling,
7874                                     size_t local_symbol_count,
7875                                     const unsigned char* plocal_symbols)
7876 {
7877   typedef typename Target_arm<big_endian>::Scan Scan;
7878   if (sh_type == elfcpp::SHT_RELA)
7879     {
7880       gold_error(_("%s: unsupported RELA reloc section"),
7881                  object->name().c_str());
7882       return;
7883     }
7884
7885   gold::scan_relocs<32, big_endian, Target_arm, elfcpp::SHT_REL, Scan>(
7886     symtab,
7887     layout,
7888     this,
7889     object,
7890     data_shndx,
7891     prelocs,
7892     reloc_count,
7893     output_section,
7894     needs_special_offset_handling,
7895     local_symbol_count,
7896     plocal_symbols);
7897 }
7898
7899 // Finalize the sections.
7900
7901 template<bool big_endian>
7902 void
7903 Target_arm<big_endian>::do_finalize_sections(
7904     Layout* layout,
7905     const Input_objects* input_objects,
7906     Symbol_table* symtab)
7907 {
7908   // Create an empty uninitialized attribute section if we still don't have it
7909   // at this moment.
7910   if (this->attributes_section_data_ == NULL)
7911     this->attributes_section_data_ = new Attributes_section_data(NULL, 0);
7912
7913   // Merge processor-specific flags.
7914   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
7915        p != input_objects->relobj_end();
7916        ++p)
7917     {
7918       // If this input file is a binary file, it has no processor
7919       // specific flags and attributes section.
7920       Input_file::Format format = (*p)->input_file()->format();
7921       if (format != Input_file::FORMAT_ELF)
7922         {
7923           gold_assert(format == Input_file::FORMAT_BINARY);
7924           continue;
7925         }
7926
7927       Arm_relobj<big_endian>* arm_relobj =
7928         Arm_relobj<big_endian>::as_arm_relobj(*p);
7929       this->merge_processor_specific_flags(
7930           arm_relobj->name(),
7931           arm_relobj->processor_specific_flags());
7932       this->merge_object_attributes(arm_relobj->name().c_str(),
7933                                     arm_relobj->attributes_section_data());
7934
7935     } 
7936
7937   for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
7938        p != input_objects->dynobj_end();
7939        ++p)
7940     {
7941       Arm_dynobj<big_endian>* arm_dynobj =
7942         Arm_dynobj<big_endian>::as_arm_dynobj(*p);
7943       this->merge_processor_specific_flags(
7944           arm_dynobj->name(),
7945           arm_dynobj->processor_specific_flags());
7946       this->merge_object_attributes(arm_dynobj->name().c_str(),
7947                                     arm_dynobj->attributes_section_data());
7948     }
7949
7950   // Check BLX use.
7951   const Object_attribute* cpu_arch_attr =
7952     this->get_aeabi_object_attribute(elfcpp::Tag_CPU_arch);
7953   if (cpu_arch_attr->int_value() > elfcpp::TAG_CPU_ARCH_V4)
7954     this->set_may_use_blx(true);
7955  
7956   // Check if we need to use Cortex-A8 workaround.
7957   if (parameters->options().user_set_fix_cortex_a8())
7958     this->fix_cortex_a8_ = parameters->options().fix_cortex_a8();
7959   else
7960     {
7961       // If neither --fix-cortex-a8 nor --no-fix-cortex-a8 is used, turn on
7962       // Cortex-A8 erratum workaround for ARMv7-A or ARMv7 with unknown
7963       // profile.  
7964       const Object_attribute* cpu_arch_profile_attr =
7965         this->get_aeabi_object_attribute(elfcpp::Tag_CPU_arch_profile);
7966       this->fix_cortex_a8_ =
7967         (cpu_arch_attr->int_value() == elfcpp::TAG_CPU_ARCH_V7
7968          && (cpu_arch_profile_attr->int_value() == 'A'
7969              || cpu_arch_profile_attr->int_value() == 0));
7970     }
7971   
7972   // Check if we can use V4BX interworking.
7973   // The V4BX interworking stub contains BX instruction,
7974   // which is not specified for some profiles.
7975   if (this->fix_v4bx() == General_options::FIX_V4BX_INTERWORKING
7976       && !this->may_use_blx())
7977     gold_error(_("unable to provide V4BX reloc interworking fix up; "
7978                  "the target profile does not support BX instruction"));
7979
7980   // Fill in some more dynamic tags.
7981   const Reloc_section* rel_plt = (this->plt_ == NULL
7982                                   ? NULL
7983                                   : this->plt_->rel_plt());
7984   layout->add_target_dynamic_tags(true, this->got_plt_, rel_plt,
7985                                   this->rel_dyn_, true, false);
7986
7987   // Emit any relocs we saved in an attempt to avoid generating COPY
7988   // relocs.
7989   if (this->copy_relocs_.any_saved_relocs())
7990     this->copy_relocs_.emit(this->rel_dyn_section(layout));
7991
7992   // Handle the .ARM.exidx section.
7993   Output_section* exidx_section = layout->find_output_section(".ARM.exidx");
7994   if (exidx_section != NULL
7995       && exidx_section->type() == elfcpp::SHT_ARM_EXIDX
7996       && !parameters->options().relocatable())
7997     {
7998       // Create __exidx_start and __exdix_end symbols.
7999       symtab->define_in_output_data("__exidx_start", NULL,
8000                                     Symbol_table::PREDEFINED,
8001                                     exidx_section, 0, 0, elfcpp::STT_OBJECT,
8002                                     elfcpp::STB_GLOBAL, elfcpp::STV_HIDDEN, 0,
8003                                     false, true);
8004       symtab->define_in_output_data("__exidx_end", NULL,
8005                                     Symbol_table::PREDEFINED,
8006                                     exidx_section, 0, 0, elfcpp::STT_OBJECT,
8007                                     elfcpp::STB_GLOBAL, elfcpp::STV_HIDDEN, 0,
8008                                     true, true);
8009
8010       // For the ARM target, we need to add a PT_ARM_EXIDX segment for
8011       // the .ARM.exidx section.
8012       if (!layout->script_options()->saw_phdrs_clause())
8013         {
8014           gold_assert(layout->find_output_segment(elfcpp::PT_ARM_EXIDX, 0, 0)
8015                       == NULL);
8016           Output_segment*  exidx_segment =
8017             layout->make_output_segment(elfcpp::PT_ARM_EXIDX, elfcpp::PF_R);
8018           exidx_segment->add_output_section(exidx_section, elfcpp::PF_R,
8019                                             false);
8020         }
8021     }
8022
8023   // Create an .ARM.attributes section if there is not one already.
8024   Output_attributes_section_data* attributes_section =
8025     new Output_attributes_section_data(*this->attributes_section_data_);
8026   layout->add_output_section_data(".ARM.attributes",
8027                                   elfcpp::SHT_ARM_ATTRIBUTES, 0,
8028                                   attributes_section, false, false, false,
8029                                   false);
8030 }
8031
8032 // Return whether a direct absolute static relocation needs to be applied.
8033 // In cases where Scan::local() or Scan::global() has created
8034 // a dynamic relocation other than R_ARM_RELATIVE, the addend
8035 // of the relocation is carried in the data, and we must not
8036 // apply the static relocation.
8037
8038 template<bool big_endian>
8039 inline bool
8040 Target_arm<big_endian>::Relocate::should_apply_static_reloc(
8041     const Sized_symbol<32>* gsym,
8042     int ref_flags,
8043     bool is_32bit,
8044     Output_section* output_section)
8045 {
8046   // If the output section is not allocated, then we didn't call
8047   // scan_relocs, we didn't create a dynamic reloc, and we must apply
8048   // the reloc here.
8049   if ((output_section->flags() & elfcpp::SHF_ALLOC) == 0)
8050       return true;
8051
8052   // For local symbols, we will have created a non-RELATIVE dynamic
8053   // relocation only if (a) the output is position independent,
8054   // (b) the relocation is absolute (not pc- or segment-relative), and
8055   // (c) the relocation is not 32 bits wide.
8056   if (gsym == NULL)
8057     return !(parameters->options().output_is_position_independent()
8058              && (ref_flags & Symbol::ABSOLUTE_REF)
8059              && !is_32bit);
8060
8061   // For global symbols, we use the same helper routines used in the
8062   // scan pass.  If we did not create a dynamic relocation, or if we
8063   // created a RELATIVE dynamic relocation, we should apply the static
8064   // relocation.
8065   bool has_dyn = gsym->needs_dynamic_reloc(ref_flags);
8066   bool is_rel = (ref_flags & Symbol::ABSOLUTE_REF)
8067                  && gsym->can_use_relative_reloc(ref_flags
8068                                                  & Symbol::FUNCTION_CALL);
8069   return !has_dyn || is_rel;
8070 }
8071
8072 // Perform a relocation.
8073
8074 template<bool big_endian>
8075 inline bool
8076 Target_arm<big_endian>::Relocate::relocate(
8077     const Relocate_info<32, big_endian>* relinfo,
8078     Target_arm* target,
8079     Output_section *output_section,
8080     size_t relnum,
8081     const elfcpp::Rel<32, big_endian>& rel,
8082     unsigned int r_type,
8083     const Sized_symbol<32>* gsym,
8084     const Symbol_value<32>* psymval,
8085     unsigned char* view,
8086     Arm_address address,
8087     section_size_type view_size)
8088 {
8089   typedef Arm_relocate_functions<big_endian> Arm_relocate_functions;
8090
8091   r_type = get_real_reloc_type(r_type);
8092   const Arm_reloc_property* reloc_property =
8093     arm_reloc_property_table->get_implemented_static_reloc_property(r_type);
8094   if (reloc_property == NULL)
8095     {
8096       std::string reloc_name =
8097         arm_reloc_property_table->reloc_name_in_error_message(r_type);
8098       gold_error_at_location(relinfo, relnum, rel.get_r_offset(),
8099                              _("cannot relocate %s in object file"),
8100                              reloc_name.c_str());
8101       return true;
8102     }
8103
8104   const Arm_relobj<big_endian>* object =
8105     Arm_relobj<big_endian>::as_arm_relobj(relinfo->object);
8106
8107   // If the final branch target of a relocation is THUMB instruction, this
8108   // is 1.  Otherwise it is 0.
8109   Arm_address thumb_bit = 0;
8110   Symbol_value<32> symval;
8111   bool is_weakly_undefined_without_plt = false;
8112   if (relnum != Target_arm<big_endian>::fake_relnum_for_stubs)
8113     {
8114       if (gsym != NULL)
8115         {
8116           // This is a global symbol.  Determine if we use PLT and if the
8117           // final target is THUMB.
8118           if (gsym->use_plt_offset(reloc_is_non_pic(r_type)))
8119             {
8120               // This uses a PLT, change the symbol value.
8121               symval.set_output_value(target->plt_section()->address()
8122                                       + gsym->plt_offset());
8123               psymval = &symval;
8124             }
8125           else if (gsym->is_weak_undefined())
8126             {
8127               // This is a weakly undefined symbol and we do not use PLT
8128               // for this relocation.  A branch targeting this symbol will
8129               // be converted into an NOP.
8130               is_weakly_undefined_without_plt = true;
8131             }
8132           else
8133             {
8134               // Set thumb bit if symbol:
8135               // -Has type STT_ARM_TFUNC or
8136               // -Has type STT_FUNC, is defined and with LSB in value set.
8137               thumb_bit =
8138                 (((gsym->type() == elfcpp::STT_ARM_TFUNC)
8139                  || (gsym->type() == elfcpp::STT_FUNC
8140                      && !gsym->is_undefined()
8141                      && ((psymval->value(object, 0) & 1) != 0)))
8142                 ? 1
8143                 : 0);
8144             }
8145         }
8146       else
8147         {
8148           // This is a local symbol.  Determine if the final target is THUMB.
8149           // We saved this information when all the local symbols were read.
8150           elfcpp::Elf_types<32>::Elf_WXword r_info = rel.get_r_info();
8151           unsigned int r_sym = elfcpp::elf_r_sym<32>(r_info);
8152           thumb_bit = object->local_symbol_is_thumb_function(r_sym) ? 1 : 0;
8153         }
8154     }
8155   else
8156     {
8157       // This is a fake relocation synthesized for a stub.  It does not have
8158       // a real symbol.  We just look at the LSB of the symbol value to
8159       // determine if the target is THUMB or not.
8160       thumb_bit = ((psymval->value(object, 0) & 1) != 0);
8161     }
8162
8163   // Strip LSB if this points to a THUMB target.
8164   if (thumb_bit != 0
8165       && reloc_property->uses_thumb_bit() 
8166       && ((psymval->value(object, 0) & 1) != 0))
8167     {
8168       Arm_address stripped_value =
8169         psymval->value(object, 0) & ~static_cast<Arm_address>(1);
8170       symval.set_output_value(stripped_value);
8171       psymval = &symval;
8172     } 
8173
8174   // Get the GOT offset if needed.
8175   // The GOT pointer points to the end of the GOT section.
8176   // We need to subtract the size of the GOT section to get
8177   // the actual offset to use in the relocation.
8178   bool have_got_offset = false;
8179   unsigned int got_offset = 0;
8180   switch (r_type)
8181     {
8182     case elfcpp::R_ARM_GOT_BREL:
8183     case elfcpp::R_ARM_GOT_PREL:
8184       if (gsym != NULL)
8185         {
8186           gold_assert(gsym->has_got_offset(GOT_TYPE_STANDARD));
8187           got_offset = (gsym->got_offset(GOT_TYPE_STANDARD)
8188                         - target->got_size());
8189         }
8190       else
8191         {
8192           unsigned int r_sym = elfcpp::elf_r_sym<32>(rel.get_r_info());
8193           gold_assert(object->local_has_got_offset(r_sym, GOT_TYPE_STANDARD));
8194           got_offset = (object->local_got_offset(r_sym, GOT_TYPE_STANDARD)
8195                         - target->got_size());
8196         }
8197       have_got_offset = true;
8198       break;
8199
8200     default:
8201       break;
8202     }
8203
8204   // To look up relocation stubs, we need to pass the symbol table index of
8205   // a local symbol.
8206   unsigned int r_sym = elfcpp::elf_r_sym<32>(rel.get_r_info());
8207
8208   // Get the addressing origin of the output segment defining the
8209   // symbol gsym if needed (AAELF 4.6.1.2 Relocation types).
8210   Arm_address sym_origin = 0;
8211   if (reloc_property->uses_symbol_base())
8212     {
8213       if (r_type == elfcpp::R_ARM_BASE_ABS && gsym == NULL)
8214         // R_ARM_BASE_ABS with the NULL symbol will give the
8215         // absolute address of the GOT origin (GOT_ORG) (see ARM IHI
8216         // 0044C (AAELF): 4.6.1.8 Proxy generating relocations).
8217         sym_origin = target->got_plt_section()->address();
8218       else if (gsym == NULL)
8219         sym_origin = 0;
8220       else if (gsym->source() == Symbol::IN_OUTPUT_SEGMENT)
8221         sym_origin = gsym->output_segment()->vaddr();
8222       else if (gsym->source() == Symbol::IN_OUTPUT_DATA)
8223         sym_origin = gsym->output_data()->address();
8224
8225       // TODO: Assumes the segment base to be zero for the global symbols
8226       // till the proper support for the segment-base-relative addressing
8227       // will be implemented.  This is consistent with GNU ld.
8228     }
8229
8230   // For relative addressing relocation, find out the relative address base.
8231   Arm_address relative_address_base = 0;
8232   switch(reloc_property->relative_address_base())
8233     {
8234     case Arm_reloc_property::RAB_NONE:
8235     // Relocations with relative address bases RAB_TLS and RAB_tp are
8236     // handled by relocate_tls.  So we do not need to do anything here.
8237     case Arm_reloc_property::RAB_TLS:
8238     case Arm_reloc_property::RAB_tp:
8239       break;
8240     case Arm_reloc_property::RAB_B_S:
8241       relative_address_base = sym_origin;
8242       break;
8243     case Arm_reloc_property::RAB_GOT_ORG:
8244       relative_address_base = target->got_plt_section()->address();
8245       break;
8246     case Arm_reloc_property::RAB_P:
8247       relative_address_base = address;
8248       break;
8249     case Arm_reloc_property::RAB_Pa:
8250       relative_address_base = address & 0xfffffffcU;
8251       break;
8252     default:
8253       gold_unreachable(); 
8254     }
8255     
8256   typename Arm_relocate_functions::Status reloc_status =
8257         Arm_relocate_functions::STATUS_OKAY;
8258   bool check_overflow = reloc_property->checks_overflow();
8259   switch (r_type)
8260     {
8261     case elfcpp::R_ARM_NONE:
8262       break;
8263
8264     case elfcpp::R_ARM_ABS8:
8265       if (should_apply_static_reloc(gsym, Symbol::ABSOLUTE_REF, false,
8266                                     output_section))
8267         reloc_status = Arm_relocate_functions::abs8(view, object, psymval);
8268       break;
8269
8270     case elfcpp::R_ARM_ABS12:
8271       if (should_apply_static_reloc(gsym, Symbol::ABSOLUTE_REF, false,
8272                                     output_section))
8273         reloc_status = Arm_relocate_functions::abs12(view, object, psymval);
8274       break;
8275
8276     case elfcpp::R_ARM_ABS16:
8277       if (should_apply_static_reloc(gsym, Symbol::ABSOLUTE_REF, false,
8278                                     output_section))
8279         reloc_status = Arm_relocate_functions::abs16(view, object, psymval);
8280       break;
8281
8282     case elfcpp::R_ARM_ABS32:
8283       if (should_apply_static_reloc(gsym, Symbol::ABSOLUTE_REF, true,
8284                                     output_section))
8285         reloc_status = Arm_relocate_functions::abs32(view, object, psymval,
8286                                                      thumb_bit);
8287       break;
8288
8289     case elfcpp::R_ARM_ABS32_NOI:
8290       if (should_apply_static_reloc(gsym, Symbol::ABSOLUTE_REF, true,
8291                                     output_section))
8292         // No thumb bit for this relocation: (S + A)
8293         reloc_status = Arm_relocate_functions::abs32(view, object, psymval,
8294                                                      0);
8295       break;
8296
8297     case elfcpp::R_ARM_MOVW_ABS_NC:
8298       if (should_apply_static_reloc(gsym, Symbol::ABSOLUTE_REF, false,
8299                                     output_section))
8300         reloc_status = Arm_relocate_functions::movw(view, object, psymval,
8301                                                     0, thumb_bit,
8302                                                     check_overflow);
8303       break;
8304
8305     case elfcpp::R_ARM_MOVT_ABS:
8306       if (should_apply_static_reloc(gsym, Symbol::ABSOLUTE_REF, false,
8307                                     output_section))
8308         reloc_status = Arm_relocate_functions::movt(view, object, psymval, 0);
8309       break;
8310
8311     case elfcpp::R_ARM_THM_MOVW_ABS_NC:
8312       if (should_apply_static_reloc(gsym, Symbol::ABSOLUTE_REF, false,
8313                                     output_section))
8314         reloc_status = Arm_relocate_functions::thm_movw(view, object, psymval,
8315                                                         0, thumb_bit, false);
8316       break;
8317
8318     case elfcpp::R_ARM_THM_MOVT_ABS:
8319       if (should_apply_static_reloc(gsym, Symbol::ABSOLUTE_REF, false,
8320                                     output_section))
8321         reloc_status = Arm_relocate_functions::thm_movt(view, object,
8322                                                         psymval, 0);
8323       break;
8324
8325     case elfcpp::R_ARM_MOVW_PREL_NC:
8326     case elfcpp::R_ARM_MOVW_BREL_NC:
8327     case elfcpp::R_ARM_MOVW_BREL:
8328       reloc_status =
8329         Arm_relocate_functions::movw(view, object, psymval,
8330                                      relative_address_base, thumb_bit,
8331                                      check_overflow);
8332       break;
8333
8334     case elfcpp::R_ARM_MOVT_PREL:
8335     case elfcpp::R_ARM_MOVT_BREL:
8336       reloc_status =
8337         Arm_relocate_functions::movt(view, object, psymval,
8338                                      relative_address_base);
8339       break;
8340
8341     case elfcpp::R_ARM_THM_MOVW_PREL_NC:
8342     case elfcpp::R_ARM_THM_MOVW_BREL_NC:
8343     case elfcpp::R_ARM_THM_MOVW_BREL:
8344       reloc_status =
8345         Arm_relocate_functions::thm_movw(view, object, psymval,
8346                                          relative_address_base,
8347                                          thumb_bit, check_overflow);
8348       break;
8349
8350     case elfcpp::R_ARM_THM_MOVT_PREL:
8351     case elfcpp::R_ARM_THM_MOVT_BREL:
8352       reloc_status =
8353         Arm_relocate_functions::thm_movt(view, object, psymval,
8354                                          relative_address_base);
8355       break;
8356         
8357     case elfcpp::R_ARM_REL32:
8358       reloc_status = Arm_relocate_functions::rel32(view, object, psymval,
8359                                                    address, thumb_bit);
8360       break;
8361
8362     case elfcpp::R_ARM_THM_ABS5:
8363       if (should_apply_static_reloc(gsym, Symbol::ABSOLUTE_REF, false,
8364                                     output_section))
8365         reloc_status = Arm_relocate_functions::thm_abs5(view, object, psymval);
8366       break;
8367
8368     // Thumb long branches.
8369     case elfcpp::R_ARM_THM_CALL:
8370     case elfcpp::R_ARM_THM_XPC22:
8371     case elfcpp::R_ARM_THM_JUMP24:
8372       reloc_status =
8373         Arm_relocate_functions::thumb_branch_common(
8374             r_type, relinfo, view, gsym, object, r_sym, psymval, address,
8375             thumb_bit, is_weakly_undefined_without_plt);
8376       break;
8377
8378     case elfcpp::R_ARM_GOTOFF32:
8379       {
8380         Arm_address got_origin;
8381         got_origin = target->got_plt_section()->address();
8382         reloc_status = Arm_relocate_functions::rel32(view, object, psymval,
8383                                                      got_origin, thumb_bit);
8384       }
8385       break;
8386
8387     case elfcpp::R_ARM_BASE_PREL:
8388       gold_assert(gsym != NULL);
8389       reloc_status =
8390           Arm_relocate_functions::base_prel(view, sym_origin, address);
8391       break;
8392
8393     case elfcpp::R_ARM_BASE_ABS:
8394       {
8395         if (!should_apply_static_reloc(gsym, Symbol::ABSOLUTE_REF, false,
8396                                       output_section))
8397           break;
8398
8399         reloc_status = Arm_relocate_functions::base_abs(view, sym_origin);
8400       }
8401       break;
8402
8403     case elfcpp::R_ARM_GOT_BREL:
8404       gold_assert(have_got_offset);
8405       reloc_status = Arm_relocate_functions::got_brel(view, got_offset);
8406       break;
8407
8408     case elfcpp::R_ARM_GOT_PREL:
8409       gold_assert(have_got_offset);
8410       // Get the address origin for GOT PLT, which is allocated right
8411       // after the GOT section, to calculate an absolute address of
8412       // the symbol GOT entry (got_origin + got_offset).
8413       Arm_address got_origin;
8414       got_origin = target->got_plt_section()->address();
8415       reloc_status = Arm_relocate_functions::got_prel(view,
8416                                                       got_origin + got_offset,
8417                                                       address);
8418       break;
8419
8420     case elfcpp::R_ARM_PLT32:
8421     case elfcpp::R_ARM_CALL:
8422     case elfcpp::R_ARM_JUMP24:
8423     case elfcpp::R_ARM_XPC25:
8424       gold_assert(gsym == NULL
8425                   || gsym->has_plt_offset()
8426                   || gsym->final_value_is_known()
8427                   || (gsym->is_defined()
8428                       && !gsym->is_from_dynobj()
8429                       && !gsym->is_preemptible()));
8430       reloc_status =
8431         Arm_relocate_functions::arm_branch_common(
8432             r_type, relinfo, view, gsym, object, r_sym, psymval, address,
8433             thumb_bit, is_weakly_undefined_without_plt);
8434       break;
8435
8436     case elfcpp::R_ARM_THM_JUMP19:
8437       reloc_status =
8438         Arm_relocate_functions::thm_jump19(view, object, psymval, address,
8439                                            thumb_bit);
8440       break;
8441
8442     case elfcpp::R_ARM_THM_JUMP6:
8443       reloc_status =
8444         Arm_relocate_functions::thm_jump6(view, object, psymval, address);
8445       break;
8446
8447     case elfcpp::R_ARM_THM_JUMP8:
8448       reloc_status =
8449         Arm_relocate_functions::thm_jump8(view, object, psymval, address);
8450       break;
8451
8452     case elfcpp::R_ARM_THM_JUMP11:
8453       reloc_status =
8454         Arm_relocate_functions::thm_jump11(view, object, psymval, address);
8455       break;
8456
8457     case elfcpp::R_ARM_PREL31:
8458       reloc_status = Arm_relocate_functions::prel31(view, object, psymval,
8459                                                     address, thumb_bit);
8460       break;
8461
8462     case elfcpp::R_ARM_V4BX:
8463       if (target->fix_v4bx() > General_options::FIX_V4BX_NONE)
8464         {
8465           const bool is_v4bx_interworking =
8466               (target->fix_v4bx() == General_options::FIX_V4BX_INTERWORKING);
8467           reloc_status =
8468             Arm_relocate_functions::v4bx(relinfo, view, object, address,
8469                                          is_v4bx_interworking);
8470         }
8471       break;
8472
8473     case elfcpp::R_ARM_THM_PC8:
8474       reloc_status =
8475         Arm_relocate_functions::thm_pc8(view, object, psymval, address);
8476       break;
8477
8478     case elfcpp::R_ARM_THM_PC12:
8479       reloc_status =
8480         Arm_relocate_functions::thm_pc12(view, object, psymval, address);
8481       break;
8482
8483     case elfcpp::R_ARM_THM_ALU_PREL_11_0:
8484       reloc_status =
8485         Arm_relocate_functions::thm_alu11(view, object, psymval, address,
8486                                           thumb_bit);
8487       break;
8488
8489     case elfcpp::R_ARM_ALU_PC_G0_NC:
8490     case elfcpp::R_ARM_ALU_PC_G0:
8491     case elfcpp::R_ARM_ALU_PC_G1_NC:
8492     case elfcpp::R_ARM_ALU_PC_G1:
8493     case elfcpp::R_ARM_ALU_PC_G2:
8494     case elfcpp::R_ARM_ALU_SB_G0_NC:
8495     case elfcpp::R_ARM_ALU_SB_G0:
8496     case elfcpp::R_ARM_ALU_SB_G1_NC:
8497     case elfcpp::R_ARM_ALU_SB_G1:
8498     case elfcpp::R_ARM_ALU_SB_G2:
8499       reloc_status =
8500         Arm_relocate_functions::arm_grp_alu(view, object, psymval,
8501                                             reloc_property->group_index(),
8502                                             relative_address_base,
8503                                             thumb_bit, check_overflow);
8504       break;
8505
8506     case elfcpp::R_ARM_LDR_PC_G0:
8507     case elfcpp::R_ARM_LDR_PC_G1:
8508     case elfcpp::R_ARM_LDR_PC_G2:
8509     case elfcpp::R_ARM_LDR_SB_G0:
8510     case elfcpp::R_ARM_LDR_SB_G1:
8511     case elfcpp::R_ARM_LDR_SB_G2:
8512       reloc_status =
8513           Arm_relocate_functions::arm_grp_ldr(view, object, psymval,
8514                                               reloc_property->group_index(),
8515                                               relative_address_base);
8516       break;
8517
8518     case elfcpp::R_ARM_LDRS_PC_G0:
8519     case elfcpp::R_ARM_LDRS_PC_G1:
8520     case elfcpp::R_ARM_LDRS_PC_G2:
8521     case elfcpp::R_ARM_LDRS_SB_G0:
8522     case elfcpp::R_ARM_LDRS_SB_G1:
8523     case elfcpp::R_ARM_LDRS_SB_G2:
8524       reloc_status =
8525           Arm_relocate_functions::arm_grp_ldrs(view, object, psymval,
8526                                                reloc_property->group_index(),
8527                                                relative_address_base);
8528       break;
8529
8530     case elfcpp::R_ARM_LDC_PC_G0:
8531     case elfcpp::R_ARM_LDC_PC_G1:
8532     case elfcpp::R_ARM_LDC_PC_G2:
8533     case elfcpp::R_ARM_LDC_SB_G0:
8534     case elfcpp::R_ARM_LDC_SB_G1:
8535     case elfcpp::R_ARM_LDC_SB_G2:
8536       reloc_status =
8537           Arm_relocate_functions::arm_grp_ldc(view, object, psymval,
8538                                               reloc_property->group_index(),
8539                                               relative_address_base);
8540       break;
8541
8542       // These are initial tls relocs, which are expected when
8543       // linking.
8544     case elfcpp::R_ARM_TLS_GD32:        // Global-dynamic
8545     case elfcpp::R_ARM_TLS_LDM32:       // Local-dynamic
8546     case elfcpp::R_ARM_TLS_LDO32:       // Alternate local-dynamic
8547     case elfcpp::R_ARM_TLS_IE32:        // Initial-exec
8548     case elfcpp::R_ARM_TLS_LE32:        // Local-exec
8549       reloc_status =
8550         this->relocate_tls(relinfo, target, relnum, rel, r_type, gsym, psymval,
8551                            view, address, view_size);
8552       break;
8553
8554     default:
8555       gold_unreachable();
8556     }
8557
8558   // Report any errors.
8559   switch (reloc_status)
8560     {
8561     case Arm_relocate_functions::STATUS_OKAY:
8562       break;
8563     case Arm_relocate_functions::STATUS_OVERFLOW:
8564       gold_error_at_location(relinfo, relnum, rel.get_r_offset(),
8565                              _("relocation overflow in relocation %u"),
8566                              r_type);
8567       break;
8568     case Arm_relocate_functions::STATUS_BAD_RELOC:
8569       gold_error_at_location(
8570         relinfo,
8571         relnum,
8572         rel.get_r_offset(),
8573         _("unexpected opcode while processing relocation %u"),
8574         r_type);
8575       break;
8576     default:
8577       gold_unreachable();
8578     }
8579
8580   return true;
8581 }
8582
8583 // Perform a TLS relocation.
8584
8585 template<bool big_endian>
8586 inline typename Arm_relocate_functions<big_endian>::Status
8587 Target_arm<big_endian>::Relocate::relocate_tls(
8588     const Relocate_info<32, big_endian>* relinfo,
8589     Target_arm<big_endian>* target,
8590     size_t relnum,
8591     const elfcpp::Rel<32, big_endian>& rel,
8592     unsigned int r_type,
8593     const Sized_symbol<32>* gsym,
8594     const Symbol_value<32>* psymval,
8595     unsigned char* view,
8596     elfcpp::Elf_types<32>::Elf_Addr address,
8597     section_size_type /*view_size*/ )
8598 {
8599   typedef Arm_relocate_functions<big_endian> ArmRelocFuncs;
8600   typedef Relocate_functions<32, big_endian> RelocFuncs;
8601   Output_segment* tls_segment = relinfo->layout->tls_segment();
8602
8603   const Sized_relobj<32, big_endian>* object = relinfo->object;
8604
8605   elfcpp::Elf_types<32>::Elf_Addr value = psymval->value(object, 0);
8606
8607   const bool is_final = (gsym == NULL
8608                          ? !parameters->options().shared()
8609                          : gsym->final_value_is_known());
8610   const tls::Tls_optimization optimized_type
8611       = Target_arm<big_endian>::optimize_tls_reloc(is_final, r_type);
8612   switch (r_type)
8613     {
8614     case elfcpp::R_ARM_TLS_GD32:        // Global-dynamic
8615         {
8616           unsigned int got_type = GOT_TYPE_TLS_PAIR;
8617           unsigned int got_offset;
8618           if (gsym != NULL)
8619             {
8620               gold_assert(gsym->has_got_offset(got_type));
8621               got_offset = gsym->got_offset(got_type) - target->got_size();
8622             }
8623           else
8624             {
8625               unsigned int r_sym = elfcpp::elf_r_sym<32>(rel.get_r_info());
8626               gold_assert(object->local_has_got_offset(r_sym, got_type));
8627               got_offset = (object->local_got_offset(r_sym, got_type)
8628                             - target->got_size());
8629             }
8630           if (optimized_type == tls::TLSOPT_NONE)
8631             {
8632               Arm_address got_entry =
8633                 target->got_plt_section()->address() + got_offset;
8634               
8635               // Relocate the field with the PC relative offset of the pair of
8636               // GOT entries.
8637               RelocFuncs::pcrel32(view, got_entry, address);
8638               return ArmRelocFuncs::STATUS_OKAY;
8639             }
8640         }
8641       break;
8642
8643     case elfcpp::R_ARM_TLS_LDM32:       // Local-dynamic
8644       if (optimized_type == tls::TLSOPT_NONE)
8645         {
8646           // Relocate the field with the offset of the GOT entry for
8647           // the module index.
8648           unsigned int got_offset;
8649           got_offset = (target->got_mod_index_entry(NULL, NULL, NULL)
8650                         - target->got_size());
8651           Arm_address got_entry =
8652             target->got_plt_section()->address() + got_offset;
8653
8654           // Relocate the field with the PC relative offset of the pair of
8655           // GOT entries.
8656           RelocFuncs::pcrel32(view, got_entry, address);
8657           return ArmRelocFuncs::STATUS_OKAY;
8658         }
8659       break;
8660
8661     case elfcpp::R_ARM_TLS_LDO32:       // Alternate local-dynamic
8662       RelocFuncs::rel32(view, value);
8663       return ArmRelocFuncs::STATUS_OKAY;
8664
8665     case elfcpp::R_ARM_TLS_IE32:        // Initial-exec
8666       if (optimized_type == tls::TLSOPT_NONE)
8667         {
8668           // Relocate the field with the offset of the GOT entry for
8669           // the tp-relative offset of the symbol.
8670           unsigned int got_type = GOT_TYPE_TLS_OFFSET;
8671           unsigned int got_offset;
8672           if (gsym != NULL)
8673             {
8674               gold_assert(gsym->has_got_offset(got_type));
8675               got_offset = gsym->got_offset(got_type);
8676             }
8677           else
8678             {
8679               unsigned int r_sym = elfcpp::elf_r_sym<32>(rel.get_r_info());
8680               gold_assert(object->local_has_got_offset(r_sym, got_type));
8681               got_offset = object->local_got_offset(r_sym, got_type);
8682             }
8683
8684           // All GOT offsets are relative to the end of the GOT.
8685           got_offset -= target->got_size();
8686
8687           Arm_address got_entry =
8688             target->got_plt_section()->address() + got_offset;
8689
8690           // Relocate the field with the PC relative offset of the GOT entry.
8691           RelocFuncs::pcrel32(view, got_entry, address);
8692           return ArmRelocFuncs::STATUS_OKAY;
8693         }
8694       break;
8695
8696     case elfcpp::R_ARM_TLS_LE32:        // Local-exec
8697       // If we're creating a shared library, a dynamic relocation will
8698       // have been created for this location, so do not apply it now.
8699       if (!parameters->options().shared())
8700         {
8701           gold_assert(tls_segment != NULL);
8702
8703           // $tp points to the TCB, which is followed by the TLS, so we
8704           // need to add TCB size to the offset.
8705           Arm_address aligned_tcb_size =
8706             align_address(ARM_TCB_SIZE, tls_segment->maximum_alignment());
8707           RelocFuncs::rel32(view, value + aligned_tcb_size);
8708
8709         }
8710       return ArmRelocFuncs::STATUS_OKAY;
8711     
8712     default:
8713       gold_unreachable();
8714     }
8715
8716   gold_error_at_location(relinfo, relnum, rel.get_r_offset(),
8717                          _("unsupported reloc %u"),
8718                          r_type);
8719   return ArmRelocFuncs::STATUS_BAD_RELOC;
8720 }
8721
8722 // Relocate section data.
8723
8724 template<bool big_endian>
8725 void
8726 Target_arm<big_endian>::relocate_section(
8727     const Relocate_info<32, big_endian>* relinfo,
8728     unsigned int sh_type,
8729     const unsigned char* prelocs,
8730     size_t reloc_count,
8731     Output_section* output_section,
8732     bool needs_special_offset_handling,
8733     unsigned char* view,
8734     Arm_address address,
8735     section_size_type view_size,
8736     const Reloc_symbol_changes* reloc_symbol_changes)
8737 {
8738   typedef typename Target_arm<big_endian>::Relocate Arm_relocate;
8739   gold_assert(sh_type == elfcpp::SHT_REL);
8740
8741   // See if we are relocating a relaxed input section.  If so, the view
8742   // covers the whole output section and we need to adjust accordingly.
8743   if (needs_special_offset_handling)
8744     {
8745       const Output_relaxed_input_section* poris =
8746         output_section->find_relaxed_input_section(relinfo->object,
8747                                                    relinfo->data_shndx);
8748       if (poris != NULL)
8749         {
8750           Arm_address section_address = poris->address();
8751           section_size_type section_size = poris->data_size();
8752
8753           gold_assert((section_address >= address)
8754                       && ((section_address + section_size)
8755                           <= (address + view_size)));
8756
8757           off_t offset = section_address - address;
8758           view += offset;
8759           address += offset;
8760           view_size = section_size;
8761         }
8762     }
8763
8764   gold::relocate_section<32, big_endian, Target_arm, elfcpp::SHT_REL,
8765                          Arm_relocate>(
8766     relinfo,
8767     this,
8768     prelocs,
8769     reloc_count,
8770     output_section,
8771     needs_special_offset_handling,
8772     view,
8773     address,
8774     view_size,
8775     reloc_symbol_changes);
8776 }
8777
8778 // Return the size of a relocation while scanning during a relocatable
8779 // link.
8780
8781 template<bool big_endian>
8782 unsigned int
8783 Target_arm<big_endian>::Relocatable_size_for_reloc::get_size_for_reloc(
8784     unsigned int r_type,
8785     Relobj* object)
8786 {
8787   r_type = get_real_reloc_type(r_type);
8788   const Arm_reloc_property* arp =
8789       arm_reloc_property_table->get_implemented_static_reloc_property(r_type);
8790   if (arp != NULL)
8791     return arp->size();
8792   else
8793     {
8794       std::string reloc_name =
8795         arm_reloc_property_table->reloc_name_in_error_message(r_type);
8796       gold_error(_("%s: unexpected %s in object file"),
8797                  object->name().c_str(), reloc_name.c_str());
8798       return 0;
8799     }
8800 }
8801
8802 // Scan the relocs during a relocatable link.
8803
8804 template<bool big_endian>
8805 void
8806 Target_arm<big_endian>::scan_relocatable_relocs(
8807     Symbol_table* symtab,
8808     Layout* layout,
8809     Sized_relobj<32, big_endian>* object,
8810     unsigned int data_shndx,
8811     unsigned int sh_type,
8812     const unsigned char* prelocs,
8813     size_t reloc_count,
8814     Output_section* output_section,
8815     bool needs_special_offset_handling,
8816     size_t local_symbol_count,
8817     const unsigned char* plocal_symbols,
8818     Relocatable_relocs* rr)
8819 {
8820   gold_assert(sh_type == elfcpp::SHT_REL);
8821
8822   typedef gold::Default_scan_relocatable_relocs<elfcpp::SHT_REL,
8823     Relocatable_size_for_reloc> Scan_relocatable_relocs;
8824
8825   gold::scan_relocatable_relocs<32, big_endian, elfcpp::SHT_REL,
8826       Scan_relocatable_relocs>(
8827     symtab,
8828     layout,
8829     object,
8830     data_shndx,
8831     prelocs,
8832     reloc_count,
8833     output_section,
8834     needs_special_offset_handling,
8835     local_symbol_count,
8836     plocal_symbols,
8837     rr);
8838 }
8839
8840 // Relocate a section during a relocatable link.
8841
8842 template<bool big_endian>
8843 void
8844 Target_arm<big_endian>::relocate_for_relocatable(
8845     const Relocate_info<32, big_endian>* relinfo,
8846     unsigned int sh_type,
8847     const unsigned char* prelocs,
8848     size_t reloc_count,
8849     Output_section* output_section,
8850     off_t offset_in_output_section,
8851     const Relocatable_relocs* rr,
8852     unsigned char* view,
8853     Arm_address view_address,
8854     section_size_type view_size,
8855     unsigned char* reloc_view,
8856     section_size_type reloc_view_size)
8857 {
8858   gold_assert(sh_type == elfcpp::SHT_REL);
8859
8860   gold::relocate_for_relocatable<32, big_endian, elfcpp::SHT_REL>(
8861     relinfo,
8862     prelocs,
8863     reloc_count,
8864     output_section,
8865     offset_in_output_section,
8866     rr,
8867     view,
8868     view_address,
8869     view_size,
8870     reloc_view,
8871     reloc_view_size);
8872 }
8873
8874 // Return the value to use for a dynamic symbol which requires special
8875 // treatment.  This is how we support equality comparisons of function
8876 // pointers across shared library boundaries, as described in the
8877 // processor specific ABI supplement.
8878
8879 template<bool big_endian>
8880 uint64_t
8881 Target_arm<big_endian>::do_dynsym_value(const Symbol* gsym) const
8882 {
8883   gold_assert(gsym->is_from_dynobj() && gsym->has_plt_offset());
8884   return this->plt_section()->address() + gsym->plt_offset();
8885 }
8886
8887 // Map platform-specific relocs to real relocs
8888 //
8889 template<bool big_endian>
8890 unsigned int
8891 Target_arm<big_endian>::get_real_reloc_type (unsigned int r_type)
8892 {
8893   switch (r_type)
8894     {
8895     case elfcpp::R_ARM_TARGET1:
8896       // This is either R_ARM_ABS32 or R_ARM_REL32;
8897       return elfcpp::R_ARM_ABS32;
8898
8899     case elfcpp::R_ARM_TARGET2:
8900       // This can be any reloc type but ususally is R_ARM_GOT_PREL
8901       return elfcpp::R_ARM_GOT_PREL;
8902
8903     default:
8904       return r_type;
8905     }
8906 }
8907
8908 // Whether if two EABI versions V1 and V2 are compatible.
8909
8910 template<bool big_endian>
8911 bool
8912 Target_arm<big_endian>::are_eabi_versions_compatible(
8913     elfcpp::Elf_Word v1,
8914     elfcpp::Elf_Word v2)
8915 {
8916   // v4 and v5 are the same spec before and after it was released,
8917   // so allow mixing them.
8918   if ((v1 == elfcpp::EF_ARM_EABI_VER4 && v2 == elfcpp::EF_ARM_EABI_VER5)
8919       || (v1 == elfcpp::EF_ARM_EABI_VER5 && v2 == elfcpp::EF_ARM_EABI_VER4))
8920     return true;
8921
8922   return v1 == v2;
8923 }
8924
8925 // Combine FLAGS from an input object called NAME and the processor-specific
8926 // flags in the ELF header of the output.  Much of this is adapted from the
8927 // processor-specific flags merging code in elf32_arm_merge_private_bfd_data
8928 // in bfd/elf32-arm.c.
8929
8930 template<bool big_endian>
8931 void
8932 Target_arm<big_endian>::merge_processor_specific_flags(
8933     const std::string& name,
8934     elfcpp::Elf_Word flags)
8935 {
8936   if (this->are_processor_specific_flags_set())
8937     {
8938       elfcpp::Elf_Word out_flags = this->processor_specific_flags();
8939
8940       // Nothing to merge if flags equal to those in output.
8941       if (flags == out_flags)
8942         return;
8943
8944       // Complain about various flag mismatches.
8945       elfcpp::Elf_Word version1 = elfcpp::arm_eabi_version(flags);
8946       elfcpp::Elf_Word version2 = elfcpp::arm_eabi_version(out_flags);
8947       if (!this->are_eabi_versions_compatible(version1, version2))
8948         gold_error(_("Source object %s has EABI version %d but output has "
8949                      "EABI version %d."),
8950                    name.c_str(),
8951                    (flags & elfcpp::EF_ARM_EABIMASK) >> 24,
8952                    (out_flags & elfcpp::EF_ARM_EABIMASK) >> 24);
8953     }
8954   else
8955     {
8956       // If the input is the default architecture and had the default
8957       // flags then do not bother setting the flags for the output
8958       // architecture, instead allow future merges to do this.  If no
8959       // future merges ever set these flags then they will retain their
8960       // uninitialised values, which surprise surprise, correspond
8961       // to the default values.
8962       if (flags == 0)
8963         return;
8964
8965       // This is the first time, just copy the flags.
8966       // We only copy the EABI version for now.
8967       this->set_processor_specific_flags(flags & elfcpp::EF_ARM_EABIMASK);
8968     }
8969 }
8970
8971 // Adjust ELF file header.
8972 template<bool big_endian>
8973 void
8974 Target_arm<big_endian>::do_adjust_elf_header(
8975     unsigned char* view,
8976     int len) const
8977 {
8978   gold_assert(len == elfcpp::Elf_sizes<32>::ehdr_size);
8979
8980   elfcpp::Ehdr<32, big_endian> ehdr(view);
8981   unsigned char e_ident[elfcpp::EI_NIDENT];
8982   memcpy(e_ident, ehdr.get_e_ident(), elfcpp::EI_NIDENT);
8983
8984   if (elfcpp::arm_eabi_version(this->processor_specific_flags())
8985       == elfcpp::EF_ARM_EABI_UNKNOWN)
8986     e_ident[elfcpp::EI_OSABI] = elfcpp::ELFOSABI_ARM;
8987   else
8988     e_ident[elfcpp::EI_OSABI] = 0;
8989   e_ident[elfcpp::EI_ABIVERSION] = 0;
8990
8991   // FIXME: Do EF_ARM_BE8 adjustment.
8992
8993   elfcpp::Ehdr_write<32, big_endian> oehdr(view);
8994   oehdr.put_e_ident(e_ident);
8995 }
8996
8997 // do_make_elf_object to override the same function in the base class.
8998 // We need to use a target-specific sub-class of Sized_relobj<32, big_endian>
8999 // to store ARM specific information.  Hence we need to have our own
9000 // ELF object creation.
9001
9002 template<bool big_endian>
9003 Object*
9004 Target_arm<big_endian>::do_make_elf_object(
9005     const std::string& name,
9006     Input_file* input_file,
9007     off_t offset, const elfcpp::Ehdr<32, big_endian>& ehdr)
9008 {
9009   int et = ehdr.get_e_type();
9010   if (et == elfcpp::ET_REL)
9011     {
9012       Arm_relobj<big_endian>* obj =
9013         new Arm_relobj<big_endian>(name, input_file, offset, ehdr);
9014       obj->setup();
9015       return obj;
9016     }
9017   else if (et == elfcpp::ET_DYN)
9018     {
9019       Sized_dynobj<32, big_endian>* obj =
9020         new Arm_dynobj<big_endian>(name, input_file, offset, ehdr);
9021       obj->setup();
9022       return obj;
9023     }
9024   else
9025     {
9026       gold_error(_("%s: unsupported ELF file type %d"),
9027                  name.c_str(), et);
9028       return NULL;
9029     }
9030 }
9031
9032 // Read the architecture from the Tag_also_compatible_with attribute, if any.
9033 // Returns -1 if no architecture could be read.
9034 // This is adapted from get_secondary_compatible_arch() in bfd/elf32-arm.c.
9035
9036 template<bool big_endian>
9037 int
9038 Target_arm<big_endian>::get_secondary_compatible_arch(
9039     const Attributes_section_data* pasd)
9040 {
9041   const Object_attribute *known_attributes =
9042     pasd->known_attributes(Object_attribute::OBJ_ATTR_PROC);
9043
9044   // Note: the tag and its argument below are uleb128 values, though
9045   // currently-defined values fit in one byte for each.
9046   const std::string& sv =
9047     known_attributes[elfcpp::Tag_also_compatible_with].string_value();
9048   if (sv.size() == 2
9049       && sv.data()[0] == elfcpp::Tag_CPU_arch
9050       && (sv.data()[1] & 128) != 128)
9051    return sv.data()[1];
9052
9053   // This tag is "safely ignorable", so don't complain if it looks funny.
9054   return -1;
9055 }
9056
9057 // Set, or unset, the architecture of the Tag_also_compatible_with attribute.
9058 // The tag is removed if ARCH is -1.
9059 // This is adapted from set_secondary_compatible_arch() in bfd/elf32-arm.c.
9060
9061 template<bool big_endian>
9062 void
9063 Target_arm<big_endian>::set_secondary_compatible_arch(
9064     Attributes_section_data* pasd,
9065     int arch)
9066 {
9067   Object_attribute *known_attributes =
9068     pasd->known_attributes(Object_attribute::OBJ_ATTR_PROC);
9069
9070   if (arch == -1)
9071     {
9072       known_attributes[elfcpp::Tag_also_compatible_with].set_string_value("");
9073       return;
9074     }
9075
9076   // Note: the tag and its argument below are uleb128 values, though
9077   // currently-defined values fit in one byte for each.
9078   char sv[3];
9079   sv[0] = elfcpp::Tag_CPU_arch;
9080   gold_assert(arch != 0);
9081   sv[1] = arch;
9082   sv[2] = '\0';
9083
9084   known_attributes[elfcpp::Tag_also_compatible_with].set_string_value(sv);
9085 }
9086
9087 // Combine two values for Tag_CPU_arch, taking secondary compatibility tags
9088 // into account.
9089 // This is adapted from tag_cpu_arch_combine() in bfd/elf32-arm.c.
9090
9091 template<bool big_endian>
9092 int
9093 Target_arm<big_endian>::tag_cpu_arch_combine(
9094     const char* name,
9095     int oldtag,
9096     int* secondary_compat_out,
9097     int newtag,
9098     int secondary_compat)
9099 {
9100 #define T(X) elfcpp::TAG_CPU_ARCH_##X
9101   static const int v6t2[] =
9102     {
9103       T(V6T2),   // PRE_V4.
9104       T(V6T2),   // V4.
9105       T(V6T2),   // V4T.
9106       T(V6T2),   // V5T.
9107       T(V6T2),   // V5TE.
9108       T(V6T2),   // V5TEJ.
9109       T(V6T2),   // V6.
9110       T(V7),     // V6KZ.
9111       T(V6T2)    // V6T2.
9112     };
9113   static const int v6k[] =
9114     {
9115       T(V6K),    // PRE_V4.
9116       T(V6K),    // V4.
9117       T(V6K),    // V4T.
9118       T(V6K),    // V5T.
9119       T(V6K),    // V5TE.
9120       T(V6K),    // V5TEJ.
9121       T(V6K),    // V6.
9122       T(V6KZ),   // V6KZ.
9123       T(V7),     // V6T2.
9124       T(V6K)     // V6K.
9125     };
9126   static const int v7[] =
9127     {
9128       T(V7),     // PRE_V4.
9129       T(V7),     // V4.
9130       T(V7),     // V4T.
9131       T(V7),     // V5T.
9132       T(V7),     // V5TE.
9133       T(V7),     // V5TEJ.
9134       T(V7),     // V6.
9135       T(V7),     // V6KZ.
9136       T(V7),     // V6T2.
9137       T(V7),     // V6K.
9138       T(V7)      // V7.
9139     };
9140   static const int v6_m[] =
9141     {
9142       -1,        // PRE_V4.
9143       -1,        // V4.
9144       T(V6K),    // V4T.
9145       T(V6K),    // V5T.
9146       T(V6K),    // V5TE.
9147       T(V6K),    // V5TEJ.
9148       T(V6K),    // V6.
9149       T(V6KZ),   // V6KZ.
9150       T(V7),     // V6T2.
9151       T(V6K),    // V6K.
9152       T(V7),     // V7.
9153       T(V6_M)    // V6_M.
9154     };
9155   static const int v6s_m[] =
9156     {
9157       -1,        // PRE_V4.
9158       -1,        // V4.
9159       T(V6K),    // V4T.
9160       T(V6K),    // V5T.
9161       T(V6K),    // V5TE.
9162       T(V6K),    // V5TEJ.
9163       T(V6K),    // V6.
9164       T(V6KZ),   // V6KZ.
9165       T(V7),     // V6T2.
9166       T(V6K),    // V6K.
9167       T(V7),     // V7.
9168       T(V6S_M),  // V6_M.
9169       T(V6S_M)   // V6S_M.
9170     };
9171   static const int v7e_m[] =
9172     {
9173       -1,       // PRE_V4.
9174       -1,       // V4.
9175       T(V7E_M), // V4T.
9176       T(V7E_M), // V5T.
9177       T(V7E_M), // V5TE.
9178       T(V7E_M), // V5TEJ.
9179       T(V7E_M), // V6.
9180       T(V7E_M), // V6KZ.
9181       T(V7E_M), // V6T2.
9182       T(V7E_M), // V6K.
9183       T(V7E_M), // V7.
9184       T(V7E_M), // V6_M.
9185       T(V7E_M), // V6S_M.
9186       T(V7E_M)  // V7E_M.
9187     };
9188   static const int v4t_plus_v6_m[] =
9189     {
9190       -1,               // PRE_V4.
9191       -1,               // V4.
9192       T(V4T),           // V4T.
9193       T(V5T),           // V5T.
9194       T(V5TE),          // V5TE.
9195       T(V5TEJ),         // V5TEJ.
9196       T(V6),            // V6.
9197       T(V6KZ),          // V6KZ.
9198       T(V6T2),          // V6T2.
9199       T(V6K),           // V6K.
9200       T(V7),            // V7.
9201       T(V6_M),          // V6_M.
9202       T(V6S_M),         // V6S_M.
9203       T(V7E_M),         // V7E_M.
9204       T(V4T_PLUS_V6_M)  // V4T plus V6_M.
9205     };
9206   static const int *comb[] =
9207     {
9208       v6t2,
9209       v6k,
9210       v7,
9211       v6_m,
9212       v6s_m,
9213       v7e_m,
9214       // Pseudo-architecture.
9215       v4t_plus_v6_m
9216     };
9217
9218   // Check we've not got a higher architecture than we know about.
9219
9220   if (oldtag >= elfcpp::MAX_TAG_CPU_ARCH || newtag >= elfcpp::MAX_TAG_CPU_ARCH)
9221     {
9222       gold_error(_("%s: unknown CPU architecture"), name);
9223       return -1;
9224     }
9225
9226   // Override old tag if we have a Tag_also_compatible_with on the output.
9227
9228   if ((oldtag == T(V6_M) && *secondary_compat_out == T(V4T))
9229       || (oldtag == T(V4T) && *secondary_compat_out == T(V6_M)))
9230     oldtag = T(V4T_PLUS_V6_M);
9231
9232   // And override the new tag if we have a Tag_also_compatible_with on the
9233   // input.
9234
9235   if ((newtag == T(V6_M) && secondary_compat == T(V4T))
9236       || (newtag == T(V4T) && secondary_compat == T(V6_M)))
9237     newtag = T(V4T_PLUS_V6_M);
9238
9239   // Architectures before V6KZ add features monotonically.
9240   int tagh = std::max(oldtag, newtag);
9241   if (tagh <= elfcpp::TAG_CPU_ARCH_V6KZ)
9242     return tagh;
9243
9244   int tagl = std::min(oldtag, newtag);
9245   int result = comb[tagh - T(V6T2)][tagl];
9246
9247   // Use Tag_CPU_arch == V4T and Tag_also_compatible_with (Tag_CPU_arch V6_M)
9248   // as the canonical version.
9249   if (result == T(V4T_PLUS_V6_M))
9250     {
9251       result = T(V4T);
9252       *secondary_compat_out = T(V6_M);
9253     }
9254   else
9255     *secondary_compat_out = -1;
9256
9257   if (result == -1)
9258     {
9259       gold_error(_("%s: conflicting CPU architectures %d/%d"),
9260                  name, oldtag, newtag);
9261       return -1;
9262     }
9263
9264   return result;
9265 #undef T
9266 }
9267
9268 // Helper to print AEABI enum tag value.
9269
9270 template<bool big_endian>
9271 std::string
9272 Target_arm<big_endian>::aeabi_enum_name(unsigned int value)
9273 {
9274   static const char *aeabi_enum_names[] =
9275     { "", "variable-size", "32-bit", "" };
9276   const size_t aeabi_enum_names_size =
9277     sizeof(aeabi_enum_names) / sizeof(aeabi_enum_names[0]);
9278
9279   if (value < aeabi_enum_names_size)
9280     return std::string(aeabi_enum_names[value]);
9281   else
9282     {
9283       char buffer[100];
9284       sprintf(buffer, "<unknown value %u>", value);
9285       return std::string(buffer);
9286     }
9287 }
9288
9289 // Return the string value to store in TAG_CPU_name.
9290
9291 template<bool big_endian>
9292 std::string
9293 Target_arm<big_endian>::tag_cpu_name_value(unsigned int value)
9294 {
9295   static const char *name_table[] = {
9296     // These aren't real CPU names, but we can't guess
9297     // that from the architecture version alone.
9298    "Pre v4",
9299    "ARM v4",
9300    "ARM v4T",
9301    "ARM v5T",
9302    "ARM v5TE",
9303    "ARM v5TEJ",
9304    "ARM v6",
9305    "ARM v6KZ",
9306    "ARM v6T2",
9307    "ARM v6K",
9308    "ARM v7",
9309    "ARM v6-M",
9310    "ARM v6S-M",
9311    "ARM v7E-M"
9312  };
9313  const size_t name_table_size = sizeof(name_table) / sizeof(name_table[0]);
9314
9315   if (value < name_table_size)
9316     return std::string(name_table[value]);
9317   else
9318     {
9319       char buffer[100];
9320       sprintf(buffer, "<unknown CPU value %u>", value);
9321       return std::string(buffer);
9322     } 
9323 }
9324
9325 // Merge object attributes from input file called NAME with those of the
9326 // output.  The input object attributes are in the object pointed by PASD.
9327
9328 template<bool big_endian>
9329 void
9330 Target_arm<big_endian>::merge_object_attributes(
9331     const char* name,
9332     const Attributes_section_data* pasd)
9333 {
9334   // Return if there is no attributes section data.
9335   if (pasd == NULL)
9336     return;
9337
9338   // If output has no object attributes, just copy.
9339   if (this->attributes_section_data_ == NULL)
9340     {
9341       this->attributes_section_data_ = new Attributes_section_data(*pasd);
9342       return;
9343     }
9344
9345   const int vendor = Object_attribute::OBJ_ATTR_PROC;
9346   const Object_attribute* in_attr = pasd->known_attributes(vendor);
9347   Object_attribute* out_attr =
9348     this->attributes_section_data_->known_attributes(vendor);
9349
9350   // This needs to happen before Tag_ABI_FP_number_model is merged.  */
9351   if (in_attr[elfcpp::Tag_ABI_VFP_args].int_value()
9352       != out_attr[elfcpp::Tag_ABI_VFP_args].int_value())
9353     {
9354       // Ignore mismatches if the object doesn't use floating point.  */
9355       if (out_attr[elfcpp::Tag_ABI_FP_number_model].int_value() == 0)
9356         out_attr[elfcpp::Tag_ABI_VFP_args].set_int_value(
9357             in_attr[elfcpp::Tag_ABI_VFP_args].int_value());
9358       else if (in_attr[elfcpp::Tag_ABI_FP_number_model].int_value() != 0)
9359         gold_error(_("%s uses VFP register arguments, output does not"),
9360                    name);
9361     }
9362
9363   for (int i = 4; i < Vendor_object_attributes::NUM_KNOWN_ATTRIBUTES; ++i)
9364     {
9365       // Merge this attribute with existing attributes.
9366       switch (i)
9367         {
9368         case elfcpp::Tag_CPU_raw_name:
9369         case elfcpp::Tag_CPU_name:
9370           // These are merged after Tag_CPU_arch.
9371           break;
9372
9373         case elfcpp::Tag_ABI_optimization_goals:
9374         case elfcpp::Tag_ABI_FP_optimization_goals:
9375           // Use the first value seen.
9376           break;
9377
9378         case elfcpp::Tag_CPU_arch:
9379           {
9380             unsigned int saved_out_attr = out_attr->int_value();
9381             // Merge Tag_CPU_arch and Tag_also_compatible_with.
9382             int secondary_compat =
9383               this->get_secondary_compatible_arch(pasd);
9384             int secondary_compat_out =
9385               this->get_secondary_compatible_arch(
9386                   this->attributes_section_data_);
9387             out_attr[i].set_int_value(
9388                 tag_cpu_arch_combine(name, out_attr[i].int_value(),
9389                                      &secondary_compat_out,
9390                                      in_attr[i].int_value(),
9391                                      secondary_compat));
9392             this->set_secondary_compatible_arch(this->attributes_section_data_,
9393                                                 secondary_compat_out);
9394
9395             // Merge Tag_CPU_name and Tag_CPU_raw_name.
9396             if (out_attr[i].int_value() == saved_out_attr)
9397               ; // Leave the names alone.
9398             else if (out_attr[i].int_value() == in_attr[i].int_value())
9399               {
9400                 // The output architecture has been changed to match the
9401                 // input architecture.  Use the input names.
9402                 out_attr[elfcpp::Tag_CPU_name].set_string_value(
9403                     in_attr[elfcpp::Tag_CPU_name].string_value());
9404                 out_attr[elfcpp::Tag_CPU_raw_name].set_string_value(
9405                     in_attr[elfcpp::Tag_CPU_raw_name].string_value());
9406               }
9407             else
9408               {
9409                 out_attr[elfcpp::Tag_CPU_name].set_string_value("");
9410                 out_attr[elfcpp::Tag_CPU_raw_name].set_string_value("");
9411               }
9412
9413             // If we still don't have a value for Tag_CPU_name,
9414             // make one up now.  Tag_CPU_raw_name remains blank.
9415             if (out_attr[elfcpp::Tag_CPU_name].string_value() == "")
9416               {
9417                 const std::string cpu_name =
9418                   this->tag_cpu_name_value(out_attr[i].int_value());
9419                 // FIXME:  If we see an unknown CPU, this will be set
9420                 // to "<unknown CPU n>", where n is the attribute value.
9421                 // This is different from BFD, which leaves the name alone.
9422                 out_attr[elfcpp::Tag_CPU_name].set_string_value(cpu_name);
9423               }
9424           }
9425           break;
9426
9427         case elfcpp::Tag_ARM_ISA_use:
9428         case elfcpp::Tag_THUMB_ISA_use:
9429         case elfcpp::Tag_WMMX_arch:
9430         case elfcpp::Tag_Advanced_SIMD_arch:
9431           // ??? Do Advanced_SIMD (NEON) and WMMX conflict?
9432         case elfcpp::Tag_ABI_FP_rounding:
9433         case elfcpp::Tag_ABI_FP_exceptions:
9434         case elfcpp::Tag_ABI_FP_user_exceptions:
9435         case elfcpp::Tag_ABI_FP_number_model:
9436         case elfcpp::Tag_VFP_HP_extension:
9437         case elfcpp::Tag_CPU_unaligned_access:
9438         case elfcpp::Tag_T2EE_use:
9439         case elfcpp::Tag_Virtualization_use:
9440         case elfcpp::Tag_MPextension_use:
9441           // Use the largest value specified.
9442           if (in_attr[i].int_value() > out_attr[i].int_value())
9443             out_attr[i].set_int_value(in_attr[i].int_value());
9444           break;
9445
9446         case elfcpp::Tag_ABI_align8_preserved:
9447         case elfcpp::Tag_ABI_PCS_RO_data:
9448           // Use the smallest value specified.
9449           if (in_attr[i].int_value() < out_attr[i].int_value())
9450             out_attr[i].set_int_value(in_attr[i].int_value());
9451           break;
9452
9453         case elfcpp::Tag_ABI_align8_needed:
9454           if ((in_attr[i].int_value() > 0 || out_attr[i].int_value() > 0)
9455               && (in_attr[elfcpp::Tag_ABI_align8_preserved].int_value() == 0
9456                   || (out_attr[elfcpp::Tag_ABI_align8_preserved].int_value()
9457                       == 0)))
9458             {
9459               // This error message should be enabled once all non-conformant
9460               // binaries in the toolchain have had the attributes set
9461               // properly.
9462               // gold_error(_("output 8-byte data alignment conflicts with %s"),
9463               //            name);
9464             }
9465           // Fall through.
9466         case elfcpp::Tag_ABI_FP_denormal:
9467         case elfcpp::Tag_ABI_PCS_GOT_use:
9468           {
9469             // These tags have 0 = don't care, 1 = strong requirement,
9470             // 2 = weak requirement.
9471             static const int order_021[3] = {0, 2, 1};
9472
9473             // Use the "greatest" from the sequence 0, 2, 1, or the largest
9474             // value if greater than 2 (for future-proofing).
9475             if ((in_attr[i].int_value() > 2
9476                  && in_attr[i].int_value() > out_attr[i].int_value())
9477                 || (in_attr[i].int_value() <= 2
9478                     && out_attr[i].int_value() <= 2
9479                     && (order_021[in_attr[i].int_value()]
9480                         > order_021[out_attr[i].int_value()])))
9481               out_attr[i].set_int_value(in_attr[i].int_value());
9482           }
9483           break;
9484
9485         case elfcpp::Tag_CPU_arch_profile:
9486           if (out_attr[i].int_value() != in_attr[i].int_value())
9487             {
9488               // 0 will merge with anything.
9489               // 'A' and 'S' merge to 'A'.
9490               // 'R' and 'S' merge to 'R'.
9491               // 'M' and 'A|R|S' is an error.
9492               if (out_attr[i].int_value() == 0
9493                   || (out_attr[i].int_value() == 'S'
9494                       && (in_attr[i].int_value() == 'A'
9495                           || in_attr[i].int_value() == 'R')))
9496                 out_attr[i].set_int_value(in_attr[i].int_value());
9497               else if (in_attr[i].int_value() == 0
9498                        || (in_attr[i].int_value() == 'S'
9499                            && (out_attr[i].int_value() == 'A'
9500                                || out_attr[i].int_value() == 'R')))
9501                 ; // Do nothing.
9502               else
9503                 {
9504                   gold_error
9505                     (_("conflicting architecture profiles %c/%c"),
9506                      in_attr[i].int_value() ? in_attr[i].int_value() : '0',
9507                      out_attr[i].int_value() ? out_attr[i].int_value() : '0');
9508                 }
9509             }
9510           break;
9511         case elfcpp::Tag_VFP_arch:
9512             {
9513               static const struct
9514               {
9515                   int ver;
9516                   int regs;
9517               } vfp_versions[7] =
9518                 {
9519                   {0, 0},
9520                   {1, 16},
9521                   {2, 16},
9522                   {3, 32},
9523                   {3, 16},
9524                   {4, 32},
9525                   {4, 16}
9526                 };
9527
9528               // Values greater than 6 aren't defined, so just pick the
9529               // biggest.
9530               if (in_attr[i].int_value() > 6
9531                   && in_attr[i].int_value() > out_attr[i].int_value())
9532                 {
9533                   *out_attr = *in_attr;
9534                   break;
9535                 }
9536               // The output uses the superset of input features
9537               // (ISA version) and registers.
9538               int ver = std::max(vfp_versions[in_attr[i].int_value()].ver,
9539                                  vfp_versions[out_attr[i].int_value()].ver);
9540               int regs = std::max(vfp_versions[in_attr[i].int_value()].regs,
9541                                   vfp_versions[out_attr[i].int_value()].regs);
9542               // This assumes all possible supersets are also a valid
9543               // options.
9544               int newval;
9545               for (newval = 6; newval > 0; newval--)
9546                 {
9547                   if (regs == vfp_versions[newval].regs
9548                       && ver == vfp_versions[newval].ver)
9549                     break;
9550                 }
9551               out_attr[i].set_int_value(newval);
9552             }
9553           break;
9554         case elfcpp::Tag_PCS_config:
9555           if (out_attr[i].int_value() == 0)
9556             out_attr[i].set_int_value(in_attr[i].int_value());
9557           else if (in_attr[i].int_value() != 0 && out_attr[i].int_value() != 0)
9558             {
9559               // It's sometimes ok to mix different configs, so this is only
9560               // a warning.
9561               gold_warning(_("%s: conflicting platform configuration"), name);
9562             }
9563           break;
9564         case elfcpp::Tag_ABI_PCS_R9_use:
9565           if (in_attr[i].int_value() != out_attr[i].int_value()
9566               && out_attr[i].int_value() != elfcpp::AEABI_R9_unused
9567               && in_attr[i].int_value() != elfcpp::AEABI_R9_unused)
9568             {
9569               gold_error(_("%s: conflicting use of R9"), name);
9570             }
9571           if (out_attr[i].int_value() == elfcpp::AEABI_R9_unused)
9572             out_attr[i].set_int_value(in_attr[i].int_value());
9573           break;
9574         case elfcpp::Tag_ABI_PCS_RW_data:
9575           if (in_attr[i].int_value() == elfcpp::AEABI_PCS_RW_data_SBrel
9576               && (in_attr[elfcpp::Tag_ABI_PCS_R9_use].int_value()
9577                   != elfcpp::AEABI_R9_SB)
9578               && (out_attr[elfcpp::Tag_ABI_PCS_R9_use].int_value()
9579                   != elfcpp::AEABI_R9_unused))
9580             {
9581               gold_error(_("%s: SB relative addressing conflicts with use "
9582                            "of R9"),
9583                          name);
9584             }
9585           // Use the smallest value specified.
9586           if (in_attr[i].int_value() < out_attr[i].int_value())
9587             out_attr[i].set_int_value(in_attr[i].int_value());
9588           break;
9589         case elfcpp::Tag_ABI_PCS_wchar_t:
9590           // FIXME: Make it possible to turn off this warning.
9591           if (out_attr[i].int_value()
9592               && in_attr[i].int_value()
9593               && out_attr[i].int_value() != in_attr[i].int_value())
9594             {
9595               gold_warning(_("%s uses %u-byte wchar_t yet the output is to "
9596                              "use %u-byte wchar_t; use of wchar_t values "
9597                              "across objects may fail"),
9598                            name, in_attr[i].int_value(),
9599                            out_attr[i].int_value());
9600             }
9601           else if (in_attr[i].int_value() && !out_attr[i].int_value())
9602             out_attr[i].set_int_value(in_attr[i].int_value());
9603           break;
9604         case elfcpp::Tag_ABI_enum_size:
9605           if (in_attr[i].int_value() != elfcpp::AEABI_enum_unused)
9606             {
9607               if (out_attr[i].int_value() == elfcpp::AEABI_enum_unused
9608                   || out_attr[i].int_value() == elfcpp::AEABI_enum_forced_wide)
9609                 {
9610                   // The existing object is compatible with anything.
9611                   // Use whatever requirements the new object has.
9612                   out_attr[i].set_int_value(in_attr[i].int_value());
9613                 }
9614               // FIXME: Make it possible to turn off this warning.
9615               else if (in_attr[i].int_value() != elfcpp::AEABI_enum_forced_wide
9616                        && out_attr[i].int_value() != in_attr[i].int_value())
9617                 {
9618                   unsigned int in_value = in_attr[i].int_value();
9619                   unsigned int out_value = out_attr[i].int_value();
9620                   gold_warning(_("%s uses %s enums yet the output is to use "
9621                                  "%s enums; use of enum values across objects "
9622                                  "may fail"),
9623                                name,
9624                                this->aeabi_enum_name(in_value).c_str(),
9625                                this->aeabi_enum_name(out_value).c_str());
9626                 }
9627             }
9628           break;
9629         case elfcpp::Tag_ABI_VFP_args:
9630           // Aready done.
9631           break;
9632         case elfcpp::Tag_ABI_WMMX_args:
9633           if (in_attr[i].int_value() != out_attr[i].int_value())
9634             {
9635               gold_error(_("%s uses iWMMXt register arguments, output does "
9636                            "not"),
9637                          name);
9638             }
9639           break;
9640         case Object_attribute::Tag_compatibility:
9641           // Merged in target-independent code.
9642           break;
9643         case elfcpp::Tag_ABI_HardFP_use:
9644           // 1 (SP) and 2 (DP) conflict, so combine to 3 (SP & DP).
9645           if ((in_attr[i].int_value() == 1 && out_attr[i].int_value() == 2)
9646               || (in_attr[i].int_value() == 2 && out_attr[i].int_value() == 1))
9647             out_attr[i].set_int_value(3);
9648           else if (in_attr[i].int_value() > out_attr[i].int_value())
9649             out_attr[i].set_int_value(in_attr[i].int_value());
9650           break;
9651         case elfcpp::Tag_ABI_FP_16bit_format:
9652           if (in_attr[i].int_value() != 0 && out_attr[i].int_value() != 0)
9653             {
9654               if (in_attr[i].int_value() != out_attr[i].int_value())
9655                 gold_error(_("fp16 format mismatch between %s and output"),
9656                            name);
9657             }
9658           if (in_attr[i].int_value() != 0)
9659             out_attr[i].set_int_value(in_attr[i].int_value());
9660           break;
9661
9662         case elfcpp::Tag_nodefaults:
9663           // This tag is set if it exists, but the value is unused (and is
9664           // typically zero).  We don't actually need to do anything here -
9665           // the merge happens automatically when the type flags are merged
9666           // below.
9667           break;
9668         case elfcpp::Tag_also_compatible_with:
9669           // Already done in Tag_CPU_arch.
9670           break;
9671         case elfcpp::Tag_conformance:
9672           // Keep the attribute if it matches.  Throw it away otherwise.
9673           // No attribute means no claim to conform.
9674           if (in_attr[i].string_value() != out_attr[i].string_value())
9675             out_attr[i].set_string_value("");
9676           break;
9677
9678         default:
9679           {
9680             const char* err_object = NULL;
9681
9682             // The "known_obj_attributes" table does contain some undefined
9683             // attributes.  Ensure that there are unused.
9684             if (out_attr[i].int_value() != 0
9685                 || out_attr[i].string_value() != "")
9686               err_object = "output";
9687             else if (in_attr[i].int_value() != 0
9688                      || in_attr[i].string_value() != "")
9689               err_object = name;
9690
9691             if (err_object != NULL)
9692               {
9693                 // Attribute numbers >=64 (mod 128) can be safely ignored.
9694                 if ((i & 127) < 64)
9695                   gold_error(_("%s: unknown mandatory EABI object attribute "
9696                                "%d"),
9697                              err_object, i);
9698                 else
9699                   gold_warning(_("%s: unknown EABI object attribute %d"),
9700                                err_object, i);
9701               }
9702
9703             // Only pass on attributes that match in both inputs.
9704             if (!in_attr[i].matches(out_attr[i]))
9705               {
9706                 out_attr[i].set_int_value(0);
9707                 out_attr[i].set_string_value("");
9708               }
9709           }
9710         }
9711
9712       // If out_attr was copied from in_attr then it won't have a type yet.
9713       if (in_attr[i].type() && !out_attr[i].type())
9714         out_attr[i].set_type(in_attr[i].type());
9715     }
9716
9717   // Merge Tag_compatibility attributes and any common GNU ones.
9718   this->attributes_section_data_->merge(name, pasd);
9719
9720   // Check for any attributes not known on ARM.
9721   typedef Vendor_object_attributes::Other_attributes Other_attributes;
9722   const Other_attributes* in_other_attributes = pasd->other_attributes(vendor);
9723   Other_attributes::const_iterator in_iter = in_other_attributes->begin();
9724   Other_attributes* out_other_attributes =
9725     this->attributes_section_data_->other_attributes(vendor);
9726   Other_attributes::iterator out_iter = out_other_attributes->begin();
9727
9728   while (in_iter != in_other_attributes->end()
9729          || out_iter != out_other_attributes->end())
9730     {
9731       const char* err_object = NULL;
9732       int err_tag = 0;
9733
9734       // The tags for each list are in numerical order.
9735       // If the tags are equal, then merge.
9736       if (out_iter != out_other_attributes->end()
9737           && (in_iter == in_other_attributes->end()
9738               || in_iter->first > out_iter->first))
9739         {
9740           // This attribute only exists in output.  We can't merge, and we
9741           // don't know what the tag means, so delete it.
9742           err_object = "output";
9743           err_tag = out_iter->first;
9744           int saved_tag = out_iter->first;
9745           delete out_iter->second;
9746           out_other_attributes->erase(out_iter); 
9747           out_iter = out_other_attributes->upper_bound(saved_tag);
9748         }
9749       else if (in_iter != in_other_attributes->end()
9750                && (out_iter != out_other_attributes->end()
9751                    || in_iter->first < out_iter->first))
9752         {
9753           // This attribute only exists in input. We can't merge, and we
9754           // don't know what the tag means, so ignore it.
9755           err_object = name;
9756           err_tag = in_iter->first;
9757           ++in_iter;
9758         }
9759       else // The tags are equal.
9760         {
9761           // As present, all attributes in the list are unknown, and
9762           // therefore can't be merged meaningfully.
9763           err_object = "output";
9764           err_tag = out_iter->first;
9765
9766           //  Only pass on attributes that match in both inputs.
9767           if (!in_iter->second->matches(*(out_iter->second)))
9768             {
9769               // No match.  Delete the attribute.
9770               int saved_tag = out_iter->first;
9771               delete out_iter->second;
9772               out_other_attributes->erase(out_iter);
9773               out_iter = out_other_attributes->upper_bound(saved_tag);
9774             }
9775           else
9776             {
9777               // Matched.  Keep the attribute and move to the next.
9778               ++out_iter;
9779               ++in_iter;
9780             }
9781         }
9782
9783       if (err_object)
9784         {
9785           // Attribute numbers >=64 (mod 128) can be safely ignored.  */
9786           if ((err_tag & 127) < 64)
9787             {
9788               gold_error(_("%s: unknown mandatory EABI object attribute %d"),
9789                          err_object, err_tag);
9790             }
9791           else
9792             {
9793               gold_warning(_("%s: unknown EABI object attribute %d"),
9794                            err_object, err_tag);
9795             }
9796         }
9797     }
9798 }
9799
9800 // Stub-generation methods for Target_arm.
9801
9802 // Make a new Arm_input_section object.
9803
9804 template<bool big_endian>
9805 Arm_input_section<big_endian>*
9806 Target_arm<big_endian>::new_arm_input_section(
9807     Relobj* relobj,
9808     unsigned int shndx)
9809 {
9810   Section_id sid(relobj, shndx);
9811
9812   Arm_input_section<big_endian>* arm_input_section =
9813     new Arm_input_section<big_endian>(relobj, shndx);
9814   arm_input_section->init();
9815
9816   // Register new Arm_input_section in map for look-up.
9817   std::pair<typename Arm_input_section_map::iterator, bool> ins =
9818     this->arm_input_section_map_.insert(std::make_pair(sid, arm_input_section));
9819
9820   // Make sure that it we have not created another Arm_input_section
9821   // for this input section already.
9822   gold_assert(ins.second);
9823
9824   return arm_input_section; 
9825 }
9826
9827 // Find the Arm_input_section object corresponding to the SHNDX-th input
9828 // section of RELOBJ.
9829
9830 template<bool big_endian>
9831 Arm_input_section<big_endian>*
9832 Target_arm<big_endian>::find_arm_input_section(
9833     Relobj* relobj,
9834     unsigned int shndx) const
9835 {
9836   Section_id sid(relobj, shndx);
9837   typename Arm_input_section_map::const_iterator p =
9838     this->arm_input_section_map_.find(sid);
9839   return (p != this->arm_input_section_map_.end()) ? p->second : NULL;
9840 }
9841
9842 // Make a new stub table.
9843
9844 template<bool big_endian>
9845 Stub_table<big_endian>*
9846 Target_arm<big_endian>::new_stub_table(Arm_input_section<big_endian>* owner)
9847 {
9848   Stub_table<big_endian>* stub_table =
9849     new Stub_table<big_endian>(owner);
9850   this->stub_tables_.push_back(stub_table);
9851
9852   stub_table->set_address(owner->address() + owner->data_size());
9853   stub_table->set_file_offset(owner->offset() + owner->data_size());
9854   stub_table->finalize_data_size();
9855
9856   return stub_table;
9857 }
9858
9859 // Scan a relocation for stub generation.
9860
9861 template<bool big_endian>
9862 void
9863 Target_arm<big_endian>::scan_reloc_for_stub(
9864     const Relocate_info<32, big_endian>* relinfo,
9865     unsigned int r_type,
9866     const Sized_symbol<32>* gsym,
9867     unsigned int r_sym,
9868     const Symbol_value<32>* psymval,
9869     elfcpp::Elf_types<32>::Elf_Swxword addend,
9870     Arm_address address)
9871 {
9872   typedef typename Target_arm<big_endian>::Relocate Relocate;
9873
9874   const Arm_relobj<big_endian>* arm_relobj =
9875     Arm_relobj<big_endian>::as_arm_relobj(relinfo->object);
9876
9877   bool target_is_thumb;
9878   Symbol_value<32> symval;
9879   if (gsym != NULL)
9880     {
9881       // This is a global symbol.  Determine if we use PLT and if the
9882       // final target is THUMB.
9883       if (gsym->use_plt_offset(Relocate::reloc_is_non_pic(r_type)))
9884         {
9885           // This uses a PLT, change the symbol value.
9886           symval.set_output_value(this->plt_section()->address()
9887                                   + gsym->plt_offset());
9888           psymval = &symval;
9889           target_is_thumb = false;
9890         }
9891       else if (gsym->is_undefined())
9892         // There is no need to generate a stub symbol is undefined.
9893         return;
9894       else
9895         {
9896           target_is_thumb =
9897             ((gsym->type() == elfcpp::STT_ARM_TFUNC)
9898              || (gsym->type() == elfcpp::STT_FUNC
9899                  && !gsym->is_undefined()
9900                  && ((psymval->value(arm_relobj, 0) & 1) != 0)));
9901         }
9902     }
9903   else
9904     {
9905       // This is a local symbol.  Determine if the final target is THUMB.
9906       target_is_thumb = arm_relobj->local_symbol_is_thumb_function(r_sym);
9907     }
9908
9909   // Strip LSB if this points to a THUMB target.
9910   const Arm_reloc_property* reloc_property =
9911     arm_reloc_property_table->get_implemented_static_reloc_property(r_type);
9912   gold_assert(reloc_property != NULL);
9913   if (target_is_thumb
9914       && reloc_property->uses_thumb_bit()
9915       && ((psymval->value(arm_relobj, 0) & 1) != 0))
9916     {
9917       Arm_address stripped_value =
9918         psymval->value(arm_relobj, 0) & ~static_cast<Arm_address>(1);
9919       symval.set_output_value(stripped_value);
9920       psymval = &symval;
9921     } 
9922
9923   // Get the symbol value.
9924   Symbol_value<32>::Value value = psymval->value(arm_relobj, 0);
9925
9926   // Owing to pipelining, the PC relative branches below actually skip
9927   // two instructions when the branch offset is 0.
9928   Arm_address destination;
9929   switch (r_type)
9930     {
9931     case elfcpp::R_ARM_CALL:
9932     case elfcpp::R_ARM_JUMP24:
9933     case elfcpp::R_ARM_PLT32:
9934       // ARM branches.
9935       destination = value + addend + 8;
9936       break;
9937     case elfcpp::R_ARM_THM_CALL:
9938     case elfcpp::R_ARM_THM_XPC22:
9939     case elfcpp::R_ARM_THM_JUMP24:
9940     case elfcpp::R_ARM_THM_JUMP19:
9941       // THUMB branches.
9942       destination = value + addend + 4;
9943       break;
9944     default:
9945       gold_unreachable();
9946     }
9947
9948   Reloc_stub* stub = NULL;
9949   Stub_type stub_type =
9950     Reloc_stub::stub_type_for_reloc(r_type, address, destination,
9951                                     target_is_thumb);
9952   if (stub_type != arm_stub_none)
9953     {
9954       // Try looking up an existing stub from a stub table.
9955       Stub_table<big_endian>* stub_table = 
9956         arm_relobj->stub_table(relinfo->data_shndx);
9957       gold_assert(stub_table != NULL);
9958    
9959       // Locate stub by destination.
9960       Reloc_stub::Key stub_key(stub_type, gsym, arm_relobj, r_sym, addend);
9961
9962       // Create a stub if there is not one already
9963       stub = stub_table->find_reloc_stub(stub_key);
9964       if (stub == NULL)
9965         {
9966           // create a new stub and add it to stub table.
9967           stub = this->stub_factory().make_reloc_stub(stub_type);
9968           stub_table->add_reloc_stub(stub, stub_key);
9969         }
9970
9971       // Record the destination address.
9972       stub->set_destination_address(destination
9973                                     | (target_is_thumb ? 1 : 0));
9974     }
9975
9976   // For Cortex-A8, we need to record a relocation at 4K page boundary.
9977   if (this->fix_cortex_a8_
9978       && (r_type == elfcpp::R_ARM_THM_JUMP24
9979           || r_type == elfcpp::R_ARM_THM_JUMP19
9980           || r_type == elfcpp::R_ARM_THM_CALL
9981           || r_type == elfcpp::R_ARM_THM_XPC22)
9982       && (address & 0xfffU) == 0xffeU)
9983     {
9984       // Found a candidate.  Note we haven't checked the destination is
9985       // within 4K here: if we do so (and don't create a record) we can't
9986       // tell that a branch should have been relocated when scanning later.
9987       this->cortex_a8_relocs_info_[address] =
9988         new Cortex_a8_reloc(stub, r_type,
9989                             destination | (target_is_thumb ? 1 : 0));
9990     }
9991 }
9992
9993 // This function scans a relocation sections for stub generation.
9994 // The template parameter Relocate must be a class type which provides
9995 // a single function, relocate(), which implements the machine
9996 // specific part of a relocation.
9997
9998 // BIG_ENDIAN is the endianness of the data.  SH_TYPE is the section type:
9999 // SHT_REL or SHT_RELA.
10000
10001 // PRELOCS points to the relocation data.  RELOC_COUNT is the number
10002 // of relocs.  OUTPUT_SECTION is the output section.
10003 // NEEDS_SPECIAL_OFFSET_HANDLING is true if input offsets need to be
10004 // mapped to output offsets.
10005
10006 // VIEW is the section data, VIEW_ADDRESS is its memory address, and
10007 // VIEW_SIZE is the size.  These refer to the input section, unless
10008 // NEEDS_SPECIAL_OFFSET_HANDLING is true, in which case they refer to
10009 // the output section.
10010
10011 template<bool big_endian>
10012 template<int sh_type>
10013 void inline
10014 Target_arm<big_endian>::scan_reloc_section_for_stubs(
10015     const Relocate_info<32, big_endian>* relinfo,
10016     const unsigned char* prelocs,
10017     size_t reloc_count,
10018     Output_section* output_section,
10019     bool needs_special_offset_handling,
10020     const unsigned char* view,
10021     elfcpp::Elf_types<32>::Elf_Addr view_address,
10022     section_size_type)
10023 {
10024   typedef typename Reloc_types<sh_type, 32, big_endian>::Reloc Reltype;
10025   const int reloc_size =
10026     Reloc_types<sh_type, 32, big_endian>::reloc_size;
10027
10028   Arm_relobj<big_endian>* arm_object =
10029     Arm_relobj<big_endian>::as_arm_relobj(relinfo->object);
10030   unsigned int local_count = arm_object->local_symbol_count();
10031
10032   Comdat_behavior comdat_behavior = CB_UNDETERMINED;
10033
10034   for (size_t i = 0; i < reloc_count; ++i, prelocs += reloc_size)
10035     {
10036       Reltype reloc(prelocs);
10037
10038       typename elfcpp::Elf_types<32>::Elf_WXword r_info = reloc.get_r_info();
10039       unsigned int r_sym = elfcpp::elf_r_sym<32>(r_info);
10040       unsigned int r_type = elfcpp::elf_r_type<32>(r_info);
10041
10042       r_type = this->get_real_reloc_type(r_type);
10043
10044       // Only a few relocation types need stubs.
10045       if ((r_type != elfcpp::R_ARM_CALL)
10046          && (r_type != elfcpp::R_ARM_JUMP24)
10047          && (r_type != elfcpp::R_ARM_PLT32)
10048          && (r_type != elfcpp::R_ARM_THM_CALL)
10049          && (r_type != elfcpp::R_ARM_THM_XPC22)
10050          && (r_type != elfcpp::R_ARM_THM_JUMP24)
10051          && (r_type != elfcpp::R_ARM_THM_JUMP19)
10052          && (r_type != elfcpp::R_ARM_V4BX))
10053         continue;
10054
10055       section_offset_type offset =
10056         convert_to_section_size_type(reloc.get_r_offset());
10057
10058       if (needs_special_offset_handling)
10059         {
10060           offset = output_section->output_offset(relinfo->object,
10061                                                  relinfo->data_shndx,
10062                                                  offset);
10063           if (offset == -1)
10064             continue;
10065         }
10066
10067       // Create a v4bx stub if --fix-v4bx-interworking is used.
10068       if (r_type == elfcpp::R_ARM_V4BX)
10069         {
10070           if (this->fix_v4bx() == General_options::FIX_V4BX_INTERWORKING)
10071             {
10072               // Get the BX instruction.
10073               typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
10074               const Valtype* wv =
10075                 reinterpret_cast<const Valtype*>(view + offset);
10076               elfcpp::Elf_types<32>::Elf_Swxword insn =
10077                 elfcpp::Swap<32, big_endian>::readval(wv);
10078               const uint32_t reg = (insn & 0xf);
10079
10080               if (reg < 0xf)
10081                 {
10082                   // Try looking up an existing stub from a stub table.
10083                   Stub_table<big_endian>* stub_table =
10084                     arm_object->stub_table(relinfo->data_shndx);
10085                   gold_assert(stub_table != NULL);
10086
10087                   if (stub_table->find_arm_v4bx_stub(reg) == NULL)
10088                     {
10089                       // create a new stub and add it to stub table.
10090                       Arm_v4bx_stub* stub =
10091                         this->stub_factory().make_arm_v4bx_stub(reg);
10092                       gold_assert(stub != NULL);
10093                       stub_table->add_arm_v4bx_stub(stub);
10094                     }
10095                 }
10096             }
10097           continue;
10098         }
10099
10100       // Get the addend.
10101       Stub_addend_reader<sh_type, big_endian> stub_addend_reader;
10102       elfcpp::Elf_types<32>::Elf_Swxword addend =
10103         stub_addend_reader(r_type, view + offset, reloc);
10104
10105       const Sized_symbol<32>* sym;
10106
10107       Symbol_value<32> symval;
10108       const Symbol_value<32> *psymval;
10109       if (r_sym < local_count)
10110         {
10111           sym = NULL;
10112           psymval = arm_object->local_symbol(r_sym);
10113
10114           // If the local symbol belongs to a section we are discarding,
10115           // and that section is a debug section, try to find the
10116           // corresponding kept section and map this symbol to its
10117           // counterpart in the kept section.  The symbol must not 
10118           // correspond to a section we are folding.
10119           bool is_ordinary;
10120           unsigned int shndx = psymval->input_shndx(&is_ordinary);
10121           if (is_ordinary
10122               && shndx != elfcpp::SHN_UNDEF
10123               && !arm_object->is_section_included(shndx) 
10124               && !(relinfo->symtab->is_section_folded(arm_object, shndx)))
10125             {
10126               if (comdat_behavior == CB_UNDETERMINED)
10127                 {
10128                   std::string name =
10129                     arm_object->section_name(relinfo->data_shndx);
10130                   comdat_behavior = get_comdat_behavior(name.c_str());
10131                 }
10132               if (comdat_behavior == CB_PRETEND)
10133                 {
10134                   bool found;
10135                   typename elfcpp::Elf_types<32>::Elf_Addr value =
10136                     arm_object->map_to_kept_section(shndx, &found);
10137                   if (found)
10138                     symval.set_output_value(value + psymval->input_value());
10139                   else
10140                     symval.set_output_value(0);
10141                 }
10142               else
10143                 {
10144                   symval.set_output_value(0);
10145                 }
10146               symval.set_no_output_symtab_entry();
10147               psymval = &symval;
10148             }
10149         }
10150       else
10151         {
10152           const Symbol* gsym = arm_object->global_symbol(r_sym);
10153           gold_assert(gsym != NULL);
10154           if (gsym->is_forwarder())
10155             gsym = relinfo->symtab->resolve_forwards(gsym);
10156
10157           sym = static_cast<const Sized_symbol<32>*>(gsym);
10158           if (sym->has_symtab_index())
10159             symval.set_output_symtab_index(sym->symtab_index());
10160           else
10161             symval.set_no_output_symtab_entry();
10162
10163           // We need to compute the would-be final value of this global
10164           // symbol.
10165           const Symbol_table* symtab = relinfo->symtab;
10166           const Sized_symbol<32>* sized_symbol =
10167             symtab->get_sized_symbol<32>(gsym);
10168           Symbol_table::Compute_final_value_status status;
10169           Arm_address value =
10170             symtab->compute_final_value<32>(sized_symbol, &status);
10171
10172           // Skip this if the symbol has not output section.
10173           if (status == Symbol_table::CFVS_NO_OUTPUT_SECTION)
10174             continue;
10175
10176           symval.set_output_value(value);
10177           psymval = &symval;
10178         }
10179
10180       // If symbol is a section symbol, we don't know the actual type of
10181       // destination.  Give up.
10182       if (psymval->is_section_symbol())
10183         continue;
10184
10185       this->scan_reloc_for_stub(relinfo, r_type, sym, r_sym, psymval,
10186                                 addend, view_address + offset);
10187     }
10188 }
10189
10190 // Scan an input section for stub generation.
10191
10192 template<bool big_endian>
10193 void
10194 Target_arm<big_endian>::scan_section_for_stubs(
10195     const Relocate_info<32, big_endian>* relinfo,
10196     unsigned int sh_type,
10197     const unsigned char* prelocs,
10198     size_t reloc_count,
10199     Output_section* output_section,
10200     bool needs_special_offset_handling,
10201     const unsigned char* view,
10202     Arm_address view_address,
10203     section_size_type view_size)
10204 {
10205   if (sh_type == elfcpp::SHT_REL)
10206     this->scan_reloc_section_for_stubs<elfcpp::SHT_REL>(
10207         relinfo,
10208         prelocs,
10209         reloc_count,
10210         output_section,
10211         needs_special_offset_handling,
10212         view,
10213         view_address,
10214         view_size);
10215   else if (sh_type == elfcpp::SHT_RELA)
10216     // We do not support RELA type relocations yet.  This is provided for
10217     // completeness.
10218     this->scan_reloc_section_for_stubs<elfcpp::SHT_RELA>(
10219         relinfo,
10220         prelocs,
10221         reloc_count,
10222         output_section,
10223         needs_special_offset_handling,
10224         view,
10225         view_address,
10226         view_size);
10227   else
10228     gold_unreachable();
10229 }
10230
10231 // Group input sections for stub generation.
10232 //
10233 // We goup input sections in an output sections so that the total size,
10234 // including any padding space due to alignment is smaller than GROUP_SIZE
10235 // unless the only input section in group is bigger than GROUP_SIZE already.
10236 // Then an ARM stub table is created to follow the last input section
10237 // in group.  For each group an ARM stub table is created an is placed
10238 // after the last group.  If STUB_ALWATS_AFTER_BRANCH is false, we further
10239 // extend the group after the stub table.
10240
10241 template<bool big_endian>
10242 void
10243 Target_arm<big_endian>::group_sections(
10244     Layout* layout,
10245     section_size_type group_size,
10246     bool stubs_always_after_branch)
10247 {
10248   // Group input sections and insert stub table
10249   Layout::Section_list section_list;
10250   layout->get_allocated_sections(&section_list);
10251   for (Layout::Section_list::const_iterator p = section_list.begin();
10252        p != section_list.end();
10253        ++p)
10254     {
10255       Arm_output_section<big_endian>* output_section =
10256         Arm_output_section<big_endian>::as_arm_output_section(*p);
10257       output_section->group_sections(group_size, stubs_always_after_branch,
10258                                      this);
10259     }
10260 }
10261
10262 // Relaxation hook.  This is where we do stub generation.
10263
10264 template<bool big_endian>
10265 bool
10266 Target_arm<big_endian>::do_relax(
10267     int pass,
10268     const Input_objects* input_objects,
10269     Symbol_table* symtab,
10270     Layout* layout)
10271 {
10272   // No need to generate stubs if this is a relocatable link.
10273   gold_assert(!parameters->options().relocatable());
10274
10275   // If this is the first pass, we need to group input sections into
10276   // stub groups.
10277   bool done_exidx_fixup = false;
10278   if (pass == 1)
10279     {
10280       // Determine the stub group size.  The group size is the absolute
10281       // value of the parameter --stub-group-size.  If --stub-group-size
10282       // is passed a negative value, we restict stubs to be always after
10283       // the stubbed branches.
10284       int32_t stub_group_size_param =
10285         parameters->options().stub_group_size();
10286       bool stubs_always_after_branch = stub_group_size_param < 0;
10287       section_size_type stub_group_size = abs(stub_group_size_param);
10288
10289       // The Cortex-A8 erratum fix depends on stubs not being in the same 4K
10290       // page as the first half of a 32-bit branch straddling two 4K pages.
10291       // This is a crude way of enforcing that.
10292       if (this->fix_cortex_a8_)
10293         stubs_always_after_branch = true;
10294
10295       if (stub_group_size == 1)
10296         {
10297           // Default value.
10298           // Thumb branch range is +-4MB has to be used as the default
10299           // maximum size (a given section can contain both ARM and Thumb
10300           // code, so the worst case has to be taken into account).
10301           //
10302           // This value is 24K less than that, which allows for 2025
10303           // 12-byte stubs.  If we exceed that, then we will fail to link.
10304           // The user will have to relink with an explicit group size
10305           // option.
10306           stub_group_size = 4170000;
10307         }
10308
10309       group_sections(layout, stub_group_size, stubs_always_after_branch);
10310      
10311       // Also fix .ARM.exidx section coverage.
10312       Output_section* os = layout->find_output_section(".ARM.exidx");
10313       if (os != NULL && os->type() == elfcpp::SHT_ARM_EXIDX)
10314         {
10315           Arm_output_section<big_endian>* exidx_output_section =
10316             Arm_output_section<big_endian>::as_arm_output_section(os);
10317           this->fix_exidx_coverage(layout, exidx_output_section, symtab);
10318           done_exidx_fixup = true;
10319         }
10320     }
10321
10322   // The Cortex-A8 stubs are sensitive to layout of code sections.  At the
10323   // beginning of each relaxation pass, just blow away all the stubs.
10324   // Alternatively, we could selectively remove only the stubs and reloc
10325   // information for code sections that have moved since the last pass.
10326   // That would require more book-keeping.
10327   typedef typename Stub_table_list::iterator Stub_table_iterator;
10328   if (this->fix_cortex_a8_)
10329     {
10330       // Clear all Cortex-A8 reloc information.
10331       for (typename Cortex_a8_relocs_info::const_iterator p =
10332              this->cortex_a8_relocs_info_.begin();
10333            p != this->cortex_a8_relocs_info_.end();
10334            ++p)
10335         delete p->second;
10336       this->cortex_a8_relocs_info_.clear();
10337
10338       // Remove all Cortex-A8 stubs.
10339       for (Stub_table_iterator sp = this->stub_tables_.begin();
10340            sp != this->stub_tables_.end();
10341            ++sp)
10342         (*sp)->remove_all_cortex_a8_stubs();
10343     }
10344   
10345   // Scan relocs for relocation stubs
10346   for (Input_objects::Relobj_iterator op = input_objects->relobj_begin();
10347        op != input_objects->relobj_end();
10348        ++op)
10349     {
10350       Arm_relobj<big_endian>* arm_relobj =
10351         Arm_relobj<big_endian>::as_arm_relobj(*op);
10352       arm_relobj->scan_sections_for_stubs(this, symtab, layout);
10353     }
10354
10355   // Check all stub tables to see if any of them have their data sizes
10356   // or addresses alignments changed.  These are the only things that
10357   // matter.
10358   bool any_stub_table_changed = false;
10359   Unordered_set<const Output_section*> sections_needing_adjustment;
10360   for (Stub_table_iterator sp = this->stub_tables_.begin();
10361        (sp != this->stub_tables_.end()) && !any_stub_table_changed;
10362        ++sp)
10363     {
10364       if ((*sp)->update_data_size_and_addralign())
10365         {
10366           // Update data size of stub table owner.
10367           Arm_input_section<big_endian>* owner = (*sp)->owner();
10368           uint64_t address = owner->address();
10369           off_t offset = owner->offset();
10370           owner->reset_address_and_file_offset();
10371           owner->set_address_and_file_offset(address, offset);
10372
10373           sections_needing_adjustment.insert(owner->output_section());
10374           any_stub_table_changed = true;
10375         }
10376     }
10377
10378   // Output_section_data::output_section() returns a const pointer but we
10379   // need to update output sections, so we record all output sections needing
10380   // update above and scan the sections here to find out what sections need
10381   // to be updated.
10382   for(Layout::Section_list::const_iterator p = layout->section_list().begin();
10383       p != layout->section_list().end();
10384       ++p)
10385     {
10386       if (sections_needing_adjustment.find(*p)
10387           != sections_needing_adjustment.end())
10388         (*p)->set_section_offsets_need_adjustment();
10389     }
10390
10391   // Stop relaxation if no EXIDX fix-up and no stub table change.
10392   bool continue_relaxation = done_exidx_fixup || any_stub_table_changed;
10393
10394   // Finalize the stubs in the last relaxation pass.
10395   if (!continue_relaxation)
10396     {
10397       for (Stub_table_iterator sp = this->stub_tables_.begin();
10398            (sp != this->stub_tables_.end()) && !any_stub_table_changed;
10399             ++sp)
10400         (*sp)->finalize_stubs();
10401
10402       // Update output local symbol counts of objects if necessary.
10403       for (Input_objects::Relobj_iterator op = input_objects->relobj_begin();
10404            op != input_objects->relobj_end();
10405            ++op)
10406         {
10407           Arm_relobj<big_endian>* arm_relobj =
10408             Arm_relobj<big_endian>::as_arm_relobj(*op);
10409
10410           // Update output local symbol counts.  We need to discard local
10411           // symbols defined in parts of input sections that are discarded by
10412           // relaxation.
10413           if (arm_relobj->output_local_symbol_count_needs_update())
10414             arm_relobj->update_output_local_symbol_count();
10415         }
10416     }
10417
10418   return continue_relaxation;
10419 }
10420
10421 // Relocate a stub.
10422
10423 template<bool big_endian>
10424 void
10425 Target_arm<big_endian>::relocate_stub(
10426     Stub* stub,
10427     const Relocate_info<32, big_endian>* relinfo,
10428     Output_section* output_section,
10429     unsigned char* view,
10430     Arm_address address,
10431     section_size_type view_size)
10432 {
10433   Relocate relocate;
10434   const Stub_template* stub_template = stub->stub_template();
10435   for (size_t i = 0; i < stub_template->reloc_count(); i++)
10436     {
10437       size_t reloc_insn_index = stub_template->reloc_insn_index(i);
10438       const Insn_template* insn = &stub_template->insns()[reloc_insn_index];
10439
10440       unsigned int r_type = insn->r_type();
10441       section_size_type reloc_offset = stub_template->reloc_offset(i);
10442       section_size_type reloc_size = insn->size();
10443       gold_assert(reloc_offset + reloc_size <= view_size);
10444
10445       // This is the address of the stub destination.
10446       Arm_address target = stub->reloc_target(i) + insn->reloc_addend();
10447       Symbol_value<32> symval;
10448       symval.set_output_value(target);
10449
10450       // Synthesize a fake reloc just in case.  We don't have a symbol so
10451       // we use 0.
10452       unsigned char reloc_buffer[elfcpp::Elf_sizes<32>::rel_size];
10453       memset(reloc_buffer, 0, sizeof(reloc_buffer));
10454       elfcpp::Rel_write<32, big_endian> reloc_write(reloc_buffer);
10455       reloc_write.put_r_offset(reloc_offset);
10456       reloc_write.put_r_info(elfcpp::elf_r_info<32>(0, r_type));
10457       elfcpp::Rel<32, big_endian> rel(reloc_buffer);
10458
10459       relocate.relocate(relinfo, this, output_section,
10460                         this->fake_relnum_for_stubs, rel, r_type,
10461                         NULL, &symval, view + reloc_offset,
10462                         address + reloc_offset, reloc_size);
10463     }
10464 }
10465
10466 // Determine whether an object attribute tag takes an integer, a
10467 // string or both.
10468
10469 template<bool big_endian>
10470 int
10471 Target_arm<big_endian>::do_attribute_arg_type(int tag) const
10472 {
10473   if (tag == Object_attribute::Tag_compatibility)
10474     return (Object_attribute::ATTR_TYPE_FLAG_INT_VAL
10475             | Object_attribute::ATTR_TYPE_FLAG_STR_VAL);
10476   else if (tag == elfcpp::Tag_nodefaults)
10477     return (Object_attribute::ATTR_TYPE_FLAG_INT_VAL
10478             | Object_attribute::ATTR_TYPE_FLAG_NO_DEFAULT);
10479   else if (tag == elfcpp::Tag_CPU_raw_name || tag == elfcpp::Tag_CPU_name)
10480     return Object_attribute::ATTR_TYPE_FLAG_STR_VAL;
10481   else if (tag < 32)
10482     return Object_attribute::ATTR_TYPE_FLAG_INT_VAL;
10483   else
10484     return ((tag & 1) != 0
10485             ? Object_attribute::ATTR_TYPE_FLAG_STR_VAL
10486             : Object_attribute::ATTR_TYPE_FLAG_INT_VAL);
10487 }
10488
10489 // Reorder attributes.
10490 //
10491 // The ABI defines that Tag_conformance should be emitted first, and that
10492 // Tag_nodefaults should be second (if either is defined).  This sets those
10493 // two positions, and bumps up the position of all the remaining tags to
10494 // compensate.
10495
10496 template<bool big_endian>
10497 int
10498 Target_arm<big_endian>::do_attributes_order(int num) const
10499 {
10500   // Reorder the known object attributes in output.  We want to move
10501   // Tag_conformance to position 4 and Tag_conformance to position 5
10502   // and shift eveything between 4 .. Tag_conformance - 1 to make room.
10503   if (num == 4)
10504     return elfcpp::Tag_conformance;
10505   if (num == 5)
10506     return elfcpp::Tag_nodefaults;
10507   if ((num - 2) < elfcpp::Tag_nodefaults)
10508     return num - 2;
10509   if ((num - 1) < elfcpp::Tag_conformance)
10510     return num - 1;
10511   return num;
10512 }
10513
10514 // Scan a span of THUMB code for Cortex-A8 erratum.
10515
10516 template<bool big_endian>
10517 void
10518 Target_arm<big_endian>::scan_span_for_cortex_a8_erratum(
10519     Arm_relobj<big_endian>* arm_relobj,
10520     unsigned int shndx,
10521     section_size_type span_start,
10522     section_size_type span_end,
10523     const unsigned char* view,
10524     Arm_address address)
10525 {
10526   // Scan for 32-bit Thumb-2 branches which span two 4K regions, where:
10527   //
10528   // The opcode is BLX.W, BL.W, B.W, Bcc.W
10529   // The branch target is in the same 4KB region as the
10530   // first half of the branch.
10531   // The instruction before the branch is a 32-bit
10532   // length non-branch instruction.
10533   section_size_type i = span_start;
10534   bool last_was_32bit = false;
10535   bool last_was_branch = false;
10536   while (i < span_end)
10537     {
10538       typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
10539       const Valtype* wv = reinterpret_cast<const Valtype*>(view + i);
10540       uint32_t insn = elfcpp::Swap<16, big_endian>::readval(wv);
10541       bool is_blx = false, is_b = false;
10542       bool is_bl = false, is_bcc = false;
10543
10544       bool insn_32bit = (insn & 0xe000) == 0xe000 && (insn & 0x1800) != 0x0000;
10545       if (insn_32bit)
10546         {
10547           // Load the rest of the insn (in manual-friendly order).
10548           insn = (insn << 16) | elfcpp::Swap<16, big_endian>::readval(wv + 1);
10549
10550           // Encoding T4: B<c>.W.
10551           is_b = (insn & 0xf800d000U) == 0xf0009000U;
10552           // Encoding T1: BL<c>.W.
10553           is_bl = (insn & 0xf800d000U) == 0xf000d000U;
10554           // Encoding T2: BLX<c>.W.
10555           is_blx = (insn & 0xf800d000U) == 0xf000c000U;
10556           // Encoding T3: B<c>.W (not permitted in IT block).
10557           is_bcc = ((insn & 0xf800d000U) == 0xf0008000U
10558                     && (insn & 0x07f00000U) != 0x03800000U);
10559         }
10560
10561       bool is_32bit_branch = is_b || is_bl || is_blx || is_bcc;
10562                            
10563       // If this instruction is a 32-bit THUMB branch that crosses a 4K
10564       // page boundary and it follows 32-bit non-branch instruction,
10565       // we need to work around.
10566       if (is_32bit_branch
10567           && ((address + i) & 0xfffU) == 0xffeU
10568           && last_was_32bit
10569           && !last_was_branch)
10570         {
10571           // Check to see if there is a relocation stub for this branch.
10572           bool force_target_arm = false;
10573           bool force_target_thumb = false;
10574           const Cortex_a8_reloc* cortex_a8_reloc = NULL;
10575           Cortex_a8_relocs_info::const_iterator p =
10576             this->cortex_a8_relocs_info_.find(address + i);
10577
10578           if (p != this->cortex_a8_relocs_info_.end())
10579             {
10580               cortex_a8_reloc = p->second;
10581               bool target_is_thumb = (cortex_a8_reloc->destination() & 1) != 0;
10582
10583               if (cortex_a8_reloc->r_type() == elfcpp::R_ARM_THM_CALL
10584                   && !target_is_thumb)
10585                 force_target_arm = true;
10586               else if (cortex_a8_reloc->r_type() == elfcpp::R_ARM_THM_CALL
10587                        && target_is_thumb)
10588                 force_target_thumb = true;
10589             }
10590
10591           off_t offset;
10592           Stub_type stub_type = arm_stub_none;
10593
10594           // Check if we have an offending branch instruction.
10595           uint16_t upper_insn = (insn >> 16) & 0xffffU;
10596           uint16_t lower_insn = insn & 0xffffU;
10597           typedef struct Arm_relocate_functions<big_endian> RelocFuncs;
10598
10599           if (cortex_a8_reloc != NULL
10600               && cortex_a8_reloc->reloc_stub() != NULL)
10601             // We've already made a stub for this instruction, e.g.
10602             // it's a long branch or a Thumb->ARM stub.  Assume that
10603             // stub will suffice to work around the A8 erratum (see
10604             // setting of always_after_branch above).
10605             ;
10606           else if (is_bcc)
10607             {
10608               offset = RelocFuncs::thumb32_cond_branch_offset(upper_insn,
10609                                                               lower_insn);
10610               stub_type = arm_stub_a8_veneer_b_cond;
10611             }
10612           else if (is_b || is_bl || is_blx)
10613             {
10614               offset = RelocFuncs::thumb32_branch_offset(upper_insn,
10615                                                          lower_insn);
10616               if (is_blx)
10617                 offset &= ~3;
10618
10619               stub_type = (is_blx
10620                            ? arm_stub_a8_veneer_blx
10621                            : (is_bl
10622                               ? arm_stub_a8_veneer_bl
10623                               : arm_stub_a8_veneer_b));
10624             }
10625
10626           if (stub_type != arm_stub_none)
10627             {
10628               Arm_address pc_for_insn = address + i + 4;
10629
10630               // The original instruction is a BL, but the target is
10631               // an ARM instruction.  If we were not making a stub,
10632               // the BL would have been converted to a BLX.  Use the
10633               // BLX stub instead in that case.
10634               if (this->may_use_blx() && force_target_arm
10635                   && stub_type == arm_stub_a8_veneer_bl)
10636                 {
10637                   stub_type = arm_stub_a8_veneer_blx;
10638                   is_blx = true;
10639                   is_bl = false;
10640                 }
10641               // Conversely, if the original instruction was
10642               // BLX but the target is Thumb mode, use the BL stub.
10643               else if (force_target_thumb
10644                        && stub_type == arm_stub_a8_veneer_blx)
10645                 {
10646                   stub_type = arm_stub_a8_veneer_bl;
10647                   is_blx = false;
10648                   is_bl = true;
10649                 }
10650
10651               if (is_blx)
10652                 pc_for_insn &= ~3;
10653
10654               // If we found a relocation, use the proper destination,
10655               // not the offset in the (unrelocated) instruction.
10656               // Note this is always done if we switched the stub type above.
10657               if (cortex_a8_reloc != NULL)
10658                 offset = (off_t) (cortex_a8_reloc->destination() - pc_for_insn);
10659
10660               Arm_address target = (pc_for_insn + offset) | (is_blx ? 0 : 1);
10661
10662               // Add a new stub if destination address in in the same page.
10663               if (((address + i) & ~0xfffU) == (target & ~0xfffU))
10664                 {
10665                   Cortex_a8_stub* stub =
10666                     this->stub_factory_.make_cortex_a8_stub(stub_type,
10667                                                             arm_relobj, shndx,
10668                                                             address + i,
10669                                                             target, insn);
10670                   Stub_table<big_endian>* stub_table =
10671                     arm_relobj->stub_table(shndx);
10672                   gold_assert(stub_table != NULL);
10673                   stub_table->add_cortex_a8_stub(address + i, stub);
10674                 }
10675             }
10676         }
10677
10678       i += insn_32bit ? 4 : 2;
10679       last_was_32bit = insn_32bit;
10680       last_was_branch = is_32bit_branch;
10681     }
10682 }
10683
10684 // Apply the Cortex-A8 workaround.
10685
10686 template<bool big_endian>
10687 void
10688 Target_arm<big_endian>::apply_cortex_a8_workaround(
10689     const Cortex_a8_stub* stub,
10690     Arm_address stub_address,
10691     unsigned char* insn_view,
10692     Arm_address insn_address)
10693 {
10694   typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
10695   Valtype* wv = reinterpret_cast<Valtype*>(insn_view);
10696   Valtype upper_insn = elfcpp::Swap<16, big_endian>::readval(wv);
10697   Valtype lower_insn = elfcpp::Swap<16, big_endian>::readval(wv + 1);
10698   off_t branch_offset = stub_address - (insn_address + 4);
10699
10700   typedef struct Arm_relocate_functions<big_endian> RelocFuncs;
10701   switch (stub->stub_template()->type())
10702     {
10703     case arm_stub_a8_veneer_b_cond:
10704       gold_assert(!utils::has_overflow<21>(branch_offset));
10705       upper_insn = RelocFuncs::thumb32_cond_branch_upper(upper_insn,
10706                                                          branch_offset);
10707       lower_insn = RelocFuncs::thumb32_cond_branch_lower(lower_insn,
10708                                                          branch_offset);
10709       break;
10710
10711     case arm_stub_a8_veneer_b:
10712     case arm_stub_a8_veneer_bl:
10713     case arm_stub_a8_veneer_blx:
10714       if ((lower_insn & 0x5000U) == 0x4000U)
10715         // For a BLX instruction, make sure that the relocation is
10716         // rounded up to a word boundary.  This follows the semantics of
10717         // the instruction which specifies that bit 1 of the target
10718         // address will come from bit 1 of the base address.
10719         branch_offset = (branch_offset + 2) & ~3;
10720
10721       // Put BRANCH_OFFSET back into the insn.
10722       gold_assert(!utils::has_overflow<25>(branch_offset));
10723       upper_insn = RelocFuncs::thumb32_branch_upper(upper_insn, branch_offset);
10724       lower_insn = RelocFuncs::thumb32_branch_lower(lower_insn, branch_offset);
10725       break;
10726
10727     default:
10728       gold_unreachable();
10729     }
10730
10731   // Put the relocated value back in the object file:
10732   elfcpp::Swap<16, big_endian>::writeval(wv, upper_insn);
10733   elfcpp::Swap<16, big_endian>::writeval(wv + 1, lower_insn);
10734 }
10735
10736 template<bool big_endian>
10737 class Target_selector_arm : public Target_selector
10738 {
10739  public:
10740   Target_selector_arm()
10741     : Target_selector(elfcpp::EM_ARM, 32, big_endian,
10742                       (big_endian ? "elf32-bigarm" : "elf32-littlearm"))
10743   { }
10744
10745   Target*
10746   do_instantiate_target()
10747   { return new Target_arm<big_endian>(); }
10748 };
10749
10750 // Fix .ARM.exidx section coverage.
10751
10752 template<bool big_endian>
10753 void
10754 Target_arm<big_endian>::fix_exidx_coverage(
10755     Layout* layout,
10756     Arm_output_section<big_endian>* exidx_section,
10757     Symbol_table* symtab)
10758 {
10759   // We need to look at all the input sections in output in ascending
10760   // order of of output address.  We do that by building a sorted list
10761   // of output sections by addresses.  Then we looks at the output sections
10762   // in order.  The input sections in an output section are already sorted
10763   // by addresses within the output section.
10764
10765   typedef std::set<Output_section*, output_section_address_less_than>
10766       Sorted_output_section_list;
10767   Sorted_output_section_list sorted_output_sections;
10768   Layout::Section_list section_list;
10769   layout->get_allocated_sections(&section_list);
10770   for (Layout::Section_list::const_iterator p = section_list.begin();
10771        p != section_list.end();
10772        ++p)
10773     {
10774       // We only care about output sections that contain executable code.
10775       if (((*p)->flags() & elfcpp::SHF_EXECINSTR) != 0)
10776         sorted_output_sections.insert(*p);
10777     }
10778
10779   // Go over the output sections in ascending order of output addresses.
10780   typedef typename Arm_output_section<big_endian>::Text_section_list
10781       Text_section_list;
10782   Text_section_list sorted_text_sections;
10783   for(typename Sorted_output_section_list::iterator p =
10784         sorted_output_sections.begin();
10785       p != sorted_output_sections.end();
10786       ++p)
10787     {
10788       Arm_output_section<big_endian>* arm_output_section =
10789         Arm_output_section<big_endian>::as_arm_output_section(*p);
10790       arm_output_section->append_text_sections_to_list(&sorted_text_sections);
10791     } 
10792
10793   exidx_section->fix_exidx_coverage(layout, sorted_text_sections, symtab);
10794 }
10795
10796 Target_selector_arm<false> target_selector_arm;
10797 Target_selector_arm<true> target_selector_armbe;
10798
10799 } // End anonymous namespace.