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