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