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