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