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