bfd/
[platform/upstream/binutils.git] / bfd / elfxx-mips.c
1 /* MIPS-specific support for ELF
2    Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
4    Free Software Foundation, Inc.
5
6    Most of the information added by Ian Lance Taylor, Cygnus Support,
7    <ian@cygnus.com>.
8    N32/64 ABI support added by Mark Mitchell, CodeSourcery, LLC.
9    <mark@codesourcery.com>
10    Traditional MIPS targets support added by Koundinya.K, Dansk Data
11    Elektronik & Operations Research Group. <kk@ddeorg.soft.net>
12
13    This file is part of BFD, the Binary File Descriptor library.
14
15    This program is free software; you can redistribute it and/or modify
16    it under the terms of the GNU General Public License as published by
17    the Free Software Foundation; either version 3 of the License, or
18    (at your option) any later version.
19
20    This program is distributed in the hope that it will be useful,
21    but WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23    GNU General Public License for more details.
24
25    You should have received a copy of the GNU General Public License
26    along with this program; if not, write to the Free Software
27    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
28    MA 02110-1301, USA.  */
29
30
31 /* This file handles functionality common to the different MIPS ABI's.  */
32
33 #include "sysdep.h"
34 #include "bfd.h"
35 #include "libbfd.h"
36 #include "libiberty.h"
37 #include "elf-bfd.h"
38 #include "elfxx-mips.h"
39 #include "elf/mips.h"
40 #include "elf-vxworks.h"
41
42 /* Get the ECOFF swapping routines.  */
43 #include "coff/sym.h"
44 #include "coff/symconst.h"
45 #include "coff/ecoff.h"
46 #include "coff/mips.h"
47
48 #include "hashtab.h"
49
50 /* This structure is used to hold information about one GOT entry.
51    There are four types of entry:
52
53       (1) an absolute address
54             requires: abfd == NULL
55             fields: d.address
56
57       (2) a SYMBOL + OFFSET address, where SYMBOL is local to an input bfd
58             requires: abfd != NULL, symndx >= 0, tls_type != GOT_TLS_LDM
59             fields: abfd, symndx, d.addend, tls_type
60
61       (3) a SYMBOL address, where SYMBOL is not local to an input bfd
62             requires: abfd != NULL, symndx == -1
63             fields: d.h, tls_type
64
65       (4) a TLS LDM slot
66             requires: abfd != NULL, symndx == 0, tls_type == GOT_TLS_LDM
67             fields: none; there's only one of these per GOT.  */
68 struct mips_got_entry
69 {
70   /* One input bfd that needs the GOT entry.  */
71   bfd *abfd;
72   /* The index of the symbol, as stored in the relocation r_info, if
73      we have a local symbol; -1 otherwise.  */
74   long symndx;
75   union
76   {
77     /* If abfd == NULL, an address that must be stored in the got.  */
78     bfd_vma address;
79     /* If abfd != NULL && symndx != -1, the addend of the relocation
80        that should be added to the symbol value.  */
81     bfd_vma addend;
82     /* If abfd != NULL && symndx == -1, the hash table entry
83        corresponding to a symbol in the GOT.  The symbol's entry
84        is in the local area if h->global_got_area is GGA_NONE,
85        otherwise it is in the global area.  */
86     struct mips_elf_link_hash_entry *h;
87   } d;
88
89   /* The TLS type of this GOT entry: GOT_NORMAL, GOT_TLS_IE, GOT_TLS_GD
90      or GOT_TLS_LDM.  An LDM GOT entry will be a local symbol entry with
91      r_symndx == 0.  */
92   unsigned char tls_type;
93
94   /* The offset from the beginning of the .got section to the entry
95      corresponding to this symbol+addend.  If it's a global symbol
96      whose offset is yet to be decided, it's going to be -1.  */
97   long gotidx;
98 };
99
100 /* This structure describes a range of addends: [MIN_ADDEND, MAX_ADDEND].
101    The structures form a non-overlapping list that is sorted by increasing
102    MIN_ADDEND.  */
103 struct mips_got_page_range
104 {
105   struct mips_got_page_range *next;
106   bfd_signed_vma min_addend;
107   bfd_signed_vma max_addend;
108 };
109
110 /* This structure describes the range of addends that are applied to page
111    relocations against a given symbol.  */
112 struct mips_got_page_entry
113 {
114   /* The input bfd in which the symbol is defined.  */
115   bfd *abfd;
116   /* The index of the symbol, as stored in the relocation r_info.  */
117   long symndx;
118   /* The ranges for this page entry.  */
119   struct mips_got_page_range *ranges;
120   /* The maximum number of page entries needed for RANGES.  */
121   bfd_vma num_pages;
122 };
123
124 /* This structure is used to hold .got information when linking.  */
125
126 struct mips_got_info
127 {
128   /* The number of global .got entries.  */
129   unsigned int global_gotno;
130   /* The number of global .got entries that are in the GGA_RELOC_ONLY area.  */
131   unsigned int reloc_only_gotno;
132   /* The number of .got slots used for TLS.  */
133   unsigned int tls_gotno;
134   /* The first unused TLS .got entry.  Used only during
135      mips_elf_initialize_tls_index.  */
136   unsigned int tls_assigned_gotno;
137   /* The number of local .got entries, eventually including page entries.  */
138   unsigned int local_gotno;
139   /* The maximum number of page entries needed.  */
140   unsigned int page_gotno;
141   /* The number of relocations needed for the GOT entries.  */
142   unsigned int relocs;
143   /* The number of local .got entries we have used.  */
144   unsigned int assigned_gotno;
145   /* A hash table holding members of the got.  */
146   struct htab *got_entries;
147   /* A hash table of mips_got_page_entry structures.  */
148   struct htab *got_page_entries;
149   /* In multi-got links, a pointer to the next got (err, rather, most
150      of the time, it points to the previous got).  */
151   struct mips_got_info *next;
152   /* This is the GOT index of the TLS LDM entry for the GOT, MINUS_ONE
153      for none, or MINUS_TWO for not yet assigned.  This is needed
154      because a single-GOT link may have multiple hash table entries
155      for the LDM.  It does not get initialized in multi-GOT mode.  */
156   bfd_vma tls_ldm_offset;
157 };
158
159 /* Structure passed when merging bfds' gots.  */
160
161 struct mips_elf_got_per_bfd_arg
162 {
163   /* The output bfd.  */
164   bfd *obfd;
165   /* The link information.  */
166   struct bfd_link_info *info;
167   /* A pointer to the primary got, i.e., the one that's going to get
168      the implicit relocations from DT_MIPS_LOCAL_GOTNO and
169      DT_MIPS_GOTSYM.  */
170   struct mips_got_info *primary;
171   /* A non-primary got we're trying to merge with other input bfd's
172      gots.  */
173   struct mips_got_info *current;
174   /* The maximum number of got entries that can be addressed with a
175      16-bit offset.  */
176   unsigned int max_count;
177   /* The maximum number of page entries needed by each got.  */
178   unsigned int max_pages;
179   /* The total number of global entries which will live in the
180      primary got and be automatically relocated.  This includes
181      those not referenced by the primary GOT but included in
182      the "master" GOT.  */
183   unsigned int global_count;
184 };
185
186 /* A structure used to pass information to htab_traverse callbacks
187    when laying out the GOT.  */
188
189 struct mips_elf_traverse_got_arg
190 {
191   struct bfd_link_info *info;
192   struct mips_got_info *g;
193   int value;
194 };
195
196 struct _mips_elf_section_data
197 {
198   struct bfd_elf_section_data elf;
199   union
200   {
201     bfd_byte *tdata;
202   } u;
203 };
204
205 #define mips_elf_section_data(sec) \
206   ((struct _mips_elf_section_data *) elf_section_data (sec))
207
208 #define is_mips_elf(bfd)                                \
209   (bfd_get_flavour (bfd) == bfd_target_elf_flavour      \
210    && elf_tdata (bfd) != NULL                           \
211    && elf_object_id (bfd) == MIPS_ELF_DATA)
212
213 /* The ABI says that every symbol used by dynamic relocations must have
214    a global GOT entry.  Among other things, this provides the dynamic
215    linker with a free, directly-indexed cache.  The GOT can therefore
216    contain symbols that are not referenced by GOT relocations themselves
217    (in other words, it may have symbols that are not referenced by things
218    like R_MIPS_GOT16 and R_MIPS_GOT_PAGE).
219
220    GOT relocations are less likely to overflow if we put the associated
221    GOT entries towards the beginning.  We therefore divide the global
222    GOT entries into two areas: "normal" and "reloc-only".  Entries in
223    the first area can be used for both dynamic relocations and GP-relative
224    accesses, while those in the "reloc-only" area are for dynamic
225    relocations only.
226
227    These GGA_* ("Global GOT Area") values are organised so that lower
228    values are more general than higher values.  Also, non-GGA_NONE
229    values are ordered by the position of the area in the GOT.  */
230 #define GGA_NORMAL 0
231 #define GGA_RELOC_ONLY 1
232 #define GGA_NONE 2
233
234 /* Information about a non-PIC interface to a PIC function.  There are
235    two ways of creating these interfaces.  The first is to add:
236
237         lui     $25,%hi(func)
238         addiu   $25,$25,%lo(func)
239
240    immediately before a PIC function "func".  The second is to add:
241
242         lui     $25,%hi(func)
243         j       func
244         addiu   $25,$25,%lo(func)
245
246    to a separate trampoline section.
247
248    Stubs of the first kind go in a new section immediately before the
249    target function.  Stubs of the second kind go in a single section
250    pointed to by the hash table's "strampoline" field.  */
251 struct mips_elf_la25_stub {
252   /* The generated section that contains this stub.  */
253   asection *stub_section;
254
255   /* The offset of the stub from the start of STUB_SECTION.  */
256   bfd_vma offset;
257
258   /* One symbol for the original function.  Its location is available
259      in H->root.root.u.def.  */
260   struct mips_elf_link_hash_entry *h;
261 };
262
263 /* Macros for populating a mips_elf_la25_stub.  */
264
265 #define LA25_LUI(VAL) (0x3c190000 | (VAL))      /* lui t9,VAL */
266 #define LA25_J(VAL) (0x08000000 | (((VAL) >> 2) & 0x3ffffff)) /* j VAL */
267 #define LA25_ADDIU(VAL) (0x27390000 | (VAL))    /* addiu t9,t9,VAL */
268 #define LA25_LUI_MICROMIPS(VAL)                                         \
269   (0x41b90000 | (VAL))                          /* lui t9,VAL */
270 #define LA25_J_MICROMIPS(VAL)                                           \
271   (0xd4000000 | (((VAL) >> 1) & 0x3ffffff))     /* j VAL */
272 #define LA25_ADDIU_MICROMIPS(VAL)                                       \
273   (0x33390000 | (VAL))                          /* addiu t9,t9,VAL */
274
275 /* This structure is passed to mips_elf_sort_hash_table_f when sorting
276    the dynamic symbols.  */
277
278 struct mips_elf_hash_sort_data
279 {
280   /* The symbol in the global GOT with the lowest dynamic symbol table
281      index.  */
282   struct elf_link_hash_entry *low;
283   /* The least dynamic symbol table index corresponding to a non-TLS
284      symbol with a GOT entry.  */
285   long min_got_dynindx;
286   /* The greatest dynamic symbol table index corresponding to a symbol
287      with a GOT entry that is not referenced (e.g., a dynamic symbol
288      with dynamic relocations pointing to it from non-primary GOTs).  */
289   long max_unref_got_dynindx;
290   /* The greatest dynamic symbol table index not corresponding to a
291      symbol without a GOT entry.  */
292   long max_non_got_dynindx;
293 };
294
295 /* The MIPS ELF linker needs additional information for each symbol in
296    the global hash table.  */
297
298 struct mips_elf_link_hash_entry
299 {
300   struct elf_link_hash_entry root;
301
302   /* External symbol information.  */
303   EXTR esym;
304
305   /* The la25 stub we have created for ths symbol, if any.  */
306   struct mips_elf_la25_stub *la25_stub;
307
308   /* Number of R_MIPS_32, R_MIPS_REL32, or R_MIPS_64 relocs against
309      this symbol.  */
310   unsigned int possibly_dynamic_relocs;
311
312   /* If there is a stub that 32 bit functions should use to call this
313      16 bit function, this points to the section containing the stub.  */
314   asection *fn_stub;
315
316   /* If there is a stub that 16 bit functions should use to call this
317      32 bit function, this points to the section containing the stub.  */
318   asection *call_stub;
319
320   /* This is like the call_stub field, but it is used if the function
321      being called returns a floating point value.  */
322   asection *call_fp_stub;
323
324 #define GOT_NORMAL      0
325 #define GOT_TLS_GD      1
326 #define GOT_TLS_LDM     2
327 #define GOT_TLS_IE      4
328 #define GOT_TLS_TYPE    7
329 #define GOT_TLS_OFFSET_DONE    0x40
330 #define GOT_TLS_DONE    0x80
331   unsigned char tls_ie_type;
332   unsigned char tls_gd_type;
333
334   /* These fields are only used in single-GOT mode; in multi-GOT mode there
335      is one mips_got_entry per GOT entry, so the offset is stored
336      there.  In single-GOT mode there may be many mips_got_entry
337      structures all referring to the same GOT slot.  */
338   bfd_vma tls_ie_got_offset;
339   bfd_vma tls_gd_got_offset;
340
341   /* The highest GGA_* value that satisfies all references to this symbol.  */
342   unsigned int global_got_area : 2;
343
344   /* True if all GOT relocations against this symbol are for calls.  This is
345      a looser condition than no_fn_stub below, because there may be other
346      non-call non-GOT relocations against the symbol.  */
347   unsigned int got_only_for_calls : 1;
348
349   /* True if one of the relocations described by possibly_dynamic_relocs
350      is against a readonly section.  */
351   unsigned int readonly_reloc : 1;
352
353   /* True if there is a relocation against this symbol that must be
354      resolved by the static linker (in other words, if the relocation
355      cannot possibly be made dynamic).  */
356   unsigned int has_static_relocs : 1;
357
358   /* True if we must not create a .MIPS.stubs entry for this symbol.
359      This is set, for example, if there are relocations related to
360      taking the function's address, i.e. any but R_MIPS_CALL*16 ones.
361      See "MIPS ABI Supplement, 3rd Edition", p. 4-20.  */
362   unsigned int no_fn_stub : 1;
363
364   /* Whether we need the fn_stub; this is true if this symbol appears
365      in any relocs other than a 16 bit call.  */
366   unsigned int need_fn_stub : 1;
367
368   /* True if this symbol is referenced by branch relocations from
369      any non-PIC input file.  This is used to determine whether an
370      la25 stub is required.  */
371   unsigned int has_nonpic_branches : 1;
372
373   /* Does this symbol need a traditional MIPS lazy-binding stub
374      (as opposed to a PLT entry)?  */
375   unsigned int needs_lazy_stub : 1;
376 };
377
378 /* MIPS ELF linker hash table.  */
379
380 struct mips_elf_link_hash_table
381 {
382   struct elf_link_hash_table root;
383
384   /* The number of .rtproc entries.  */
385   bfd_size_type procedure_count;
386
387   /* The size of the .compact_rel section (if SGI_COMPAT).  */
388   bfd_size_type compact_rel_size;
389
390   /* This flag indicates that the value of DT_MIPS_RLD_MAP dynamic entry
391      is set to the address of __rld_obj_head as in IRIX5 and IRIX6.  */
392   bfd_boolean use_rld_obj_head;
393
394   /* The  __rld_map or __rld_obj_head symbol. */
395   struct elf_link_hash_entry *rld_symbol;
396
397   /* This is set if we see any mips16 stub sections.  */
398   bfd_boolean mips16_stubs_seen;
399
400   /* True if we can generate copy relocs and PLTs.  */
401   bfd_boolean use_plts_and_copy_relocs;
402
403   /* True if we're generating code for VxWorks.  */
404   bfd_boolean is_vxworks;
405
406   /* True if we already reported the small-data section overflow.  */
407   bfd_boolean small_data_overflow_reported;
408
409   /* Shortcuts to some dynamic sections, or NULL if they are not
410      being used.  */
411   asection *srelbss;
412   asection *sdynbss;
413   asection *srelplt;
414   asection *srelplt2;
415   asection *sgotplt;
416   asection *splt;
417   asection *sstubs;
418   asection *sgot;
419
420   /* The master GOT information.  */
421   struct mips_got_info *got_info;
422
423   /* The global symbol in the GOT with the lowest index in the dynamic
424      symbol table.  */
425   struct elf_link_hash_entry *global_gotsym;
426
427   /* The size of the PLT header in bytes.  */
428   bfd_vma plt_header_size;
429
430   /* The size of a PLT entry in bytes.  */
431   bfd_vma plt_entry_size;
432
433   /* The number of functions that need a lazy-binding stub.  */
434   bfd_vma lazy_stub_count;
435
436   /* The size of a function stub entry in bytes.  */
437   bfd_vma function_stub_size;
438
439   /* The number of reserved entries at the beginning of the GOT.  */
440   unsigned int reserved_gotno;
441
442   /* The section used for mips_elf_la25_stub trampolines.
443      See the comment above that structure for details.  */
444   asection *strampoline;
445
446   /* A table of mips_elf_la25_stubs, indexed by (input_section, offset)
447      pairs.  */
448   htab_t la25_stubs;
449
450   /* A function FN (NAME, IS, OS) that creates a new input section
451      called NAME and links it to output section OS.  If IS is nonnull,
452      the new section should go immediately before it, otherwise it
453      should go at the (current) beginning of OS.
454
455      The function returns the new section on success, otherwise it
456      returns null.  */
457   asection *(*add_stub_section) (const char *, asection *, asection *);
458 };
459
460 /* Get the MIPS ELF linker hash table from a link_info structure.  */
461
462 #define mips_elf_hash_table(p) \
463   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
464   == MIPS_ELF_DATA ? ((struct mips_elf_link_hash_table *) ((p)->hash)) : NULL)
465
466 /* A structure used to communicate with htab_traverse callbacks.  */
467 struct mips_htab_traverse_info
468 {
469   /* The usual link-wide information.  */
470   struct bfd_link_info *info;
471   bfd *output_bfd;
472
473   /* Starts off FALSE and is set to TRUE if the link should be aborted.  */
474   bfd_boolean error;
475 };
476
477 /* MIPS ELF private object data.  */
478
479 struct mips_elf_obj_tdata
480 {
481   /* Generic ELF private object data.  */
482   struct elf_obj_tdata root;
483
484   /* Input BFD providing Tag_GNU_MIPS_ABI_FP attribute for output.  */
485   bfd *abi_fp_bfd;
486
487   /* The GOT requirements of input bfds.  */
488   struct mips_got_info *got;
489 };
490
491 /* Get MIPS ELF private object data from BFD's tdata.  */
492
493 #define mips_elf_tdata(bfd) \
494   ((struct mips_elf_obj_tdata *) (bfd)->tdata.any)
495
496 #define TLS_RELOC_P(r_type) \
497   (r_type == R_MIPS_TLS_DTPMOD32                \
498    || r_type == R_MIPS_TLS_DTPMOD64             \
499    || r_type == R_MIPS_TLS_DTPREL32             \
500    || r_type == R_MIPS_TLS_DTPREL64             \
501    || r_type == R_MIPS_TLS_GD                   \
502    || r_type == R_MIPS_TLS_LDM                  \
503    || r_type == R_MIPS_TLS_DTPREL_HI16          \
504    || r_type == R_MIPS_TLS_DTPREL_LO16          \
505    || r_type == R_MIPS_TLS_GOTTPREL             \
506    || r_type == R_MIPS_TLS_TPREL32              \
507    || r_type == R_MIPS_TLS_TPREL64              \
508    || r_type == R_MIPS_TLS_TPREL_HI16           \
509    || r_type == R_MIPS_TLS_TPREL_LO16           \
510    || r_type == R_MIPS16_TLS_GD                 \
511    || r_type == R_MIPS16_TLS_LDM                \
512    || r_type == R_MIPS16_TLS_DTPREL_HI16        \
513    || r_type == R_MIPS16_TLS_DTPREL_LO16        \
514    || r_type == R_MIPS16_TLS_GOTTPREL           \
515    || r_type == R_MIPS16_TLS_TPREL_HI16         \
516    || r_type == R_MIPS16_TLS_TPREL_LO16         \
517    || r_type == R_MICROMIPS_TLS_GD              \
518    || r_type == R_MICROMIPS_TLS_LDM             \
519    || r_type == R_MICROMIPS_TLS_DTPREL_HI16     \
520    || r_type == R_MICROMIPS_TLS_DTPREL_LO16     \
521    || r_type == R_MICROMIPS_TLS_GOTTPREL        \
522    || r_type == R_MICROMIPS_TLS_TPREL_HI16      \
523    || r_type == R_MICROMIPS_TLS_TPREL_LO16)
524
525 /* Structure used to pass information to mips_elf_output_extsym.  */
526
527 struct extsym_info
528 {
529   bfd *abfd;
530   struct bfd_link_info *info;
531   struct ecoff_debug_info *debug;
532   const struct ecoff_debug_swap *swap;
533   bfd_boolean failed;
534 };
535
536 /* The names of the runtime procedure table symbols used on IRIX5.  */
537
538 static const char * const mips_elf_dynsym_rtproc_names[] =
539 {
540   "_procedure_table",
541   "_procedure_string_table",
542   "_procedure_table_size",
543   NULL
544 };
545
546 /* These structures are used to generate the .compact_rel section on
547    IRIX5.  */
548
549 typedef struct
550 {
551   unsigned long id1;            /* Always one?  */
552   unsigned long num;            /* Number of compact relocation entries.  */
553   unsigned long id2;            /* Always two?  */
554   unsigned long offset;         /* The file offset of the first relocation.  */
555   unsigned long reserved0;      /* Zero?  */
556   unsigned long reserved1;      /* Zero?  */
557 } Elf32_compact_rel;
558
559 typedef struct
560 {
561   bfd_byte id1[4];
562   bfd_byte num[4];
563   bfd_byte id2[4];
564   bfd_byte offset[4];
565   bfd_byte reserved0[4];
566   bfd_byte reserved1[4];
567 } Elf32_External_compact_rel;
568
569 typedef struct
570 {
571   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
572   unsigned int rtype : 4;       /* Relocation types. See below.  */
573   unsigned int dist2to : 8;
574   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
575   unsigned long konst;          /* KONST field. See below.  */
576   unsigned long vaddr;          /* VADDR to be relocated.  */
577 } Elf32_crinfo;
578
579 typedef struct
580 {
581   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
582   unsigned int rtype : 4;       /* Relocation types. See below.  */
583   unsigned int dist2to : 8;
584   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
585   unsigned long konst;          /* KONST field. See below.  */
586 } Elf32_crinfo2;
587
588 typedef struct
589 {
590   bfd_byte info[4];
591   bfd_byte konst[4];
592   bfd_byte vaddr[4];
593 } Elf32_External_crinfo;
594
595 typedef struct
596 {
597   bfd_byte info[4];
598   bfd_byte konst[4];
599 } Elf32_External_crinfo2;
600
601 /* These are the constants used to swap the bitfields in a crinfo.  */
602
603 #define CRINFO_CTYPE (0x1)
604 #define CRINFO_CTYPE_SH (31)
605 #define CRINFO_RTYPE (0xf)
606 #define CRINFO_RTYPE_SH (27)
607 #define CRINFO_DIST2TO (0xff)
608 #define CRINFO_DIST2TO_SH (19)
609 #define CRINFO_RELVADDR (0x7ffff)
610 #define CRINFO_RELVADDR_SH (0)
611
612 /* A compact relocation info has long (3 words) or short (2 words)
613    formats.  A short format doesn't have VADDR field and relvaddr
614    fields contains ((VADDR - vaddr of the previous entry) >> 2).  */
615 #define CRF_MIPS_LONG                   1
616 #define CRF_MIPS_SHORT                  0
617
618 /* There are 4 types of compact relocation at least. The value KONST
619    has different meaning for each type:
620
621    (type)               (konst)
622    CT_MIPS_REL32        Address in data
623    CT_MIPS_WORD         Address in word (XXX)
624    CT_MIPS_GPHI_LO      GP - vaddr
625    CT_MIPS_JMPAD        Address to jump
626    */
627
628 #define CRT_MIPS_REL32                  0xa
629 #define CRT_MIPS_WORD                   0xb
630 #define CRT_MIPS_GPHI_LO                0xc
631 #define CRT_MIPS_JMPAD                  0xd
632
633 #define mips_elf_set_cr_format(x,format)        ((x).ctype = (format))
634 #define mips_elf_set_cr_type(x,type)            ((x).rtype = (type))
635 #define mips_elf_set_cr_dist2to(x,v)            ((x).dist2to = (v))
636 #define mips_elf_set_cr_relvaddr(x,d)           ((x).relvaddr = (d)<<2)
637 \f
638 /* The structure of the runtime procedure descriptor created by the
639    loader for use by the static exception system.  */
640
641 typedef struct runtime_pdr {
642         bfd_vma adr;            /* Memory address of start of procedure.  */
643         long    regmask;        /* Save register mask.  */
644         long    regoffset;      /* Save register offset.  */
645         long    fregmask;       /* Save floating point register mask.  */
646         long    fregoffset;     /* Save floating point register offset.  */
647         long    frameoffset;    /* Frame size.  */
648         short   framereg;       /* Frame pointer register.  */
649         short   pcreg;          /* Offset or reg of return pc.  */
650         long    irpss;          /* Index into the runtime string table.  */
651         long    reserved;
652         struct exception_info *exception_info;/* Pointer to exception array.  */
653 } RPDR, *pRPDR;
654 #define cbRPDR sizeof (RPDR)
655 #define rpdNil ((pRPDR) 0)
656 \f
657 static struct mips_got_entry *mips_elf_create_local_got_entry
658   (bfd *, struct bfd_link_info *, bfd *, bfd_vma, unsigned long,
659    struct mips_elf_link_hash_entry *, int);
660 static bfd_boolean mips_elf_sort_hash_table_f
661   (struct mips_elf_link_hash_entry *, void *);
662 static bfd_vma mips_elf_high
663   (bfd_vma);
664 static bfd_boolean mips_elf_create_dynamic_relocation
665   (bfd *, struct bfd_link_info *, const Elf_Internal_Rela *,
666    struct mips_elf_link_hash_entry *, asection *, bfd_vma,
667    bfd_vma *, asection *);
668 static bfd_vma mips_elf_adjust_gp
669   (bfd *, struct mips_got_info *, bfd *);
670
671 /* This will be used when we sort the dynamic relocation records.  */
672 static bfd *reldyn_sorting_bfd;
673
674 /* True if ABFD is for CPUs with load interlocking that include
675    non-MIPS1 CPUs and R3900.  */
676 #define LOAD_INTERLOCKS_P(abfd) \
677   (   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) != E_MIPS_ARCH_1) \
678    || ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_3900))
679
680 /* True if ABFD is for CPUs that are faster if JAL is converted to BAL.
681    This should be safe for all architectures.  We enable this predicate
682    for RM9000 for now.  */
683 #define JAL_TO_BAL_P(abfd) \
684   ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_9000)
685
686 /* True if ABFD is for CPUs that are faster if JALR is converted to BAL.
687    This should be safe for all architectures.  We enable this predicate for
688    all CPUs.  */
689 #define JALR_TO_BAL_P(abfd) 1
690
691 /* True if ABFD is for CPUs that are faster if JR is converted to B.
692    This should be safe for all architectures.  We enable this predicate for
693    all CPUs.  */
694 #define JR_TO_B_P(abfd) 1
695
696 /* True if ABFD is a PIC object.  */
697 #define PIC_OBJECT_P(abfd) \
698   ((elf_elfheader (abfd)->e_flags & EF_MIPS_PIC) != 0)
699
700 /* Nonzero if ABFD is using the N32 ABI.  */
701 #define ABI_N32_P(abfd) \
702   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI2) != 0)
703
704 /* Nonzero if ABFD is using the N64 ABI.  */
705 #define ABI_64_P(abfd) \
706   (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS64)
707
708 /* Nonzero if ABFD is using NewABI conventions.  */
709 #define NEWABI_P(abfd) (ABI_N32_P (abfd) || ABI_64_P (abfd))
710
711 /* The IRIX compatibility level we are striving for.  */
712 #define IRIX_COMPAT(abfd) \
713   (get_elf_backend_data (abfd)->elf_backend_mips_irix_compat (abfd))
714
715 /* Whether we are trying to be compatible with IRIX at all.  */
716 #define SGI_COMPAT(abfd) \
717   (IRIX_COMPAT (abfd) != ict_none)
718
719 /* The name of the options section.  */
720 #define MIPS_ELF_OPTIONS_SECTION_NAME(abfd) \
721   (NEWABI_P (abfd) ? ".MIPS.options" : ".options")
722
723 /* True if NAME is the recognized name of any SHT_MIPS_OPTIONS section.
724    Some IRIX system files do not use MIPS_ELF_OPTIONS_SECTION_NAME.  */
725 #define MIPS_ELF_OPTIONS_SECTION_NAME_P(NAME) \
726   (strcmp (NAME, ".MIPS.options") == 0 || strcmp (NAME, ".options") == 0)
727
728 /* Whether the section is readonly.  */
729 #define MIPS_ELF_READONLY_SECTION(sec) \
730   ((sec->flags & (SEC_ALLOC | SEC_LOAD | SEC_READONLY))         \
731    == (SEC_ALLOC | SEC_LOAD | SEC_READONLY))
732
733 /* The name of the stub section.  */
734 #define MIPS_ELF_STUB_SECTION_NAME(abfd) ".MIPS.stubs"
735
736 /* The size of an external REL relocation.  */
737 #define MIPS_ELF_REL_SIZE(abfd) \
738   (get_elf_backend_data (abfd)->s->sizeof_rel)
739
740 /* The size of an external RELA relocation.  */
741 #define MIPS_ELF_RELA_SIZE(abfd) \
742   (get_elf_backend_data (abfd)->s->sizeof_rela)
743
744 /* The size of an external dynamic table entry.  */
745 #define MIPS_ELF_DYN_SIZE(abfd) \
746   (get_elf_backend_data (abfd)->s->sizeof_dyn)
747
748 /* The size of a GOT entry.  */
749 #define MIPS_ELF_GOT_SIZE(abfd) \
750   (get_elf_backend_data (abfd)->s->arch_size / 8)
751
752 /* The size of the .rld_map section. */
753 #define MIPS_ELF_RLD_MAP_SIZE(abfd) \
754   (get_elf_backend_data (abfd)->s->arch_size / 8)
755
756 /* The size of a symbol-table entry.  */
757 #define MIPS_ELF_SYM_SIZE(abfd) \
758   (get_elf_backend_data (abfd)->s->sizeof_sym)
759
760 /* The default alignment for sections, as a power of two.  */
761 #define MIPS_ELF_LOG_FILE_ALIGN(abfd)                           \
762   (get_elf_backend_data (abfd)->s->log_file_align)
763
764 /* Get word-sized data.  */
765 #define MIPS_ELF_GET_WORD(abfd, ptr) \
766   (ABI_64_P (abfd) ? bfd_get_64 (abfd, ptr) : bfd_get_32 (abfd, ptr))
767
768 /* Put out word-sized data.  */
769 #define MIPS_ELF_PUT_WORD(abfd, val, ptr)       \
770   (ABI_64_P (abfd)                              \
771    ? bfd_put_64 (abfd, val, ptr)                \
772    : bfd_put_32 (abfd, val, ptr))
773
774 /* The opcode for word-sized loads (LW or LD).  */
775 #define MIPS_ELF_LOAD_WORD(abfd) \
776   (ABI_64_P (abfd) ? 0xdc000000 : 0x8c000000)
777
778 /* Add a dynamic symbol table-entry.  */
779 #define MIPS_ELF_ADD_DYNAMIC_ENTRY(info, tag, val)      \
780   _bfd_elf_add_dynamic_entry (info, tag, val)
781
782 #define MIPS_ELF_RTYPE_TO_HOWTO(abfd, rtype, rela)                      \
783   (get_elf_backend_data (abfd)->elf_backend_mips_rtype_to_howto (rtype, rela))
784
785 /* The name of the dynamic relocation section.  */
786 #define MIPS_ELF_REL_DYN_NAME(INFO) \
787   (mips_elf_hash_table (INFO)->is_vxworks ? ".rela.dyn" : ".rel.dyn")
788
789 /* In case we're on a 32-bit machine, construct a 64-bit "-1" value
790    from smaller values.  Start with zero, widen, *then* decrement.  */
791 #define MINUS_ONE       (((bfd_vma)0) - 1)
792 #define MINUS_TWO       (((bfd_vma)0) - 2)
793
794 /* The value to write into got[1] for SVR4 targets, to identify it is
795    a GNU object.  The dynamic linker can then use got[1] to store the
796    module pointer.  */
797 #define MIPS_ELF_GNU_GOT1_MASK(abfd) \
798   ((bfd_vma) 1 << (ABI_64_P (abfd) ? 63 : 31))
799
800 /* The offset of $gp from the beginning of the .got section.  */
801 #define ELF_MIPS_GP_OFFSET(INFO) \
802   (mips_elf_hash_table (INFO)->is_vxworks ? 0x0 : 0x7ff0)
803
804 /* The maximum size of the GOT for it to be addressable using 16-bit
805    offsets from $gp.  */
806 #define MIPS_ELF_GOT_MAX_SIZE(INFO) (ELF_MIPS_GP_OFFSET (INFO) + 0x7fff)
807
808 /* Instructions which appear in a stub.  */
809 #define STUB_LW(abfd)                                                   \
810   ((ABI_64_P (abfd)                                                     \
811     ? 0xdf998010                                /* ld t9,0x8010(gp) */  \
812     : 0x8f998010))                              /* lw t9,0x8010(gp) */
813 #define STUB_MOVE(abfd)                                                 \
814    ((ABI_64_P (abfd)                                                    \
815      ? 0x03e0782d                               /* daddu t7,ra */       \
816      : 0x03e07821))                             /* addu t7,ra */
817 #define STUB_LUI(VAL) (0x3c180000 + (VAL))      /* lui t8,VAL */
818 #define STUB_JALR 0x0320f809                    /* jalr t9,ra */
819 #define STUB_ORI(VAL) (0x37180000 + (VAL))      /* ori t8,t8,VAL */
820 #define STUB_LI16U(VAL) (0x34180000 + (VAL))    /* ori t8,zero,VAL unsigned */
821 #define STUB_LI16S(abfd, VAL)                                           \
822    ((ABI_64_P (abfd)                                                    \
823     ? (0x64180000 + (VAL))      /* daddiu t8,zero,VAL sign extended */  \
824     : (0x24180000 + (VAL))))    /* addiu t8,zero,VAL sign extended */
825
826 #define MIPS_FUNCTION_STUB_NORMAL_SIZE 16
827 #define MIPS_FUNCTION_STUB_BIG_SIZE 20
828
829 /* The name of the dynamic interpreter.  This is put in the .interp
830    section.  */
831
832 #define ELF_DYNAMIC_INTERPRETER(abfd)           \
833    (ABI_N32_P (abfd) ? "/usr/lib32/libc.so.1"   \
834     : ABI_64_P (abfd) ? "/usr/lib64/libc.so.1"  \
835     : "/usr/lib/libc.so.1")
836
837 #ifdef BFD64
838 #define MNAME(bfd,pre,pos) \
839   (ABI_64_P (bfd) ? CONCAT4 (pre,64,_,pos) : CONCAT4 (pre,32,_,pos))
840 #define ELF_R_SYM(bfd, i)                                       \
841   (ABI_64_P (bfd) ? ELF64_R_SYM (i) : ELF32_R_SYM (i))
842 #define ELF_R_TYPE(bfd, i)                                      \
843   (ABI_64_P (bfd) ? ELF64_MIPS_R_TYPE (i) : ELF32_R_TYPE (i))
844 #define ELF_R_INFO(bfd, s, t)                                   \
845   (ABI_64_P (bfd) ? ELF64_R_INFO (s, t) : ELF32_R_INFO (s, t))
846 #else
847 #define MNAME(bfd,pre,pos) CONCAT4 (pre,32,_,pos)
848 #define ELF_R_SYM(bfd, i)                                       \
849   (ELF32_R_SYM (i))
850 #define ELF_R_TYPE(bfd, i)                                      \
851   (ELF32_R_TYPE (i))
852 #define ELF_R_INFO(bfd, s, t)                                   \
853   (ELF32_R_INFO (s, t))
854 #endif
855 \f
856   /* The mips16 compiler uses a couple of special sections to handle
857      floating point arguments.
858
859      Section names that look like .mips16.fn.FNNAME contain stubs that
860      copy floating point arguments from the fp regs to the gp regs and
861      then jump to FNNAME.  If any 32 bit function calls FNNAME, the
862      call should be redirected to the stub instead.  If no 32 bit
863      function calls FNNAME, the stub should be discarded.  We need to
864      consider any reference to the function, not just a call, because
865      if the address of the function is taken we will need the stub,
866      since the address might be passed to a 32 bit function.
867
868      Section names that look like .mips16.call.FNNAME contain stubs
869      that copy floating point arguments from the gp regs to the fp
870      regs and then jump to FNNAME.  If FNNAME is a 32 bit function,
871      then any 16 bit function that calls FNNAME should be redirected
872      to the stub instead.  If FNNAME is not a 32 bit function, the
873      stub should be discarded.
874
875      .mips16.call.fp.FNNAME sections are similar, but contain stubs
876      which call FNNAME and then copy the return value from the fp regs
877      to the gp regs.  These stubs store the return value in $18 while
878      calling FNNAME; any function which might call one of these stubs
879      must arrange to save $18 around the call.  (This case is not
880      needed for 32 bit functions that call 16 bit functions, because
881      16 bit functions always return floating point values in both
882      $f0/$f1 and $2/$3.)
883
884      Note that in all cases FNNAME might be defined statically.
885      Therefore, FNNAME is not used literally.  Instead, the relocation
886      information will indicate which symbol the section is for.
887
888      We record any stubs that we find in the symbol table.  */
889
890 #define FN_STUB ".mips16.fn."
891 #define CALL_STUB ".mips16.call."
892 #define CALL_FP_STUB ".mips16.call.fp."
893
894 #define FN_STUB_P(name) CONST_STRNEQ (name, FN_STUB)
895 #define CALL_STUB_P(name) CONST_STRNEQ (name, CALL_STUB)
896 #define CALL_FP_STUB_P(name) CONST_STRNEQ (name, CALL_FP_STUB)
897 \f
898 /* The format of the first PLT entry in an O32 executable.  */
899 static const bfd_vma mips_o32_exec_plt0_entry[] =
900 {
901   0x3c1c0000,   /* lui $28, %hi(&GOTPLT[0])                             */
902   0x8f990000,   /* lw $25, %lo(&GOTPLT[0])($28)                         */
903   0x279c0000,   /* addiu $28, $28, %lo(&GOTPLT[0])                      */
904   0x031cc023,   /* subu $24, $24, $28                                   */
905   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
906   0x0018c082,   /* srl $24, $24, 2                                      */
907   0x0320f809,   /* jalr $25                                             */
908   0x2718fffe    /* subu $24, $24, 2                                     */
909 };
910
911 /* The format of the first PLT entry in an N32 executable.  Different
912    because gp ($28) is not available; we use t2 ($14) instead.  */
913 static const bfd_vma mips_n32_exec_plt0_entry[] =
914 {
915   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
916   0x8dd90000,   /* lw $25, %lo(&GOTPLT[0])($14)                         */
917   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
918   0x030ec023,   /* subu $24, $24, $14                                   */
919   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
920   0x0018c082,   /* srl $24, $24, 2                                      */
921   0x0320f809,   /* jalr $25                                             */
922   0x2718fffe    /* subu $24, $24, 2                                     */
923 };
924
925 /* The format of the first PLT entry in an N64 executable.  Different
926    from N32 because of the increased size of GOT entries.  */
927 static const bfd_vma mips_n64_exec_plt0_entry[] =
928 {
929   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
930   0xddd90000,   /* ld $25, %lo(&GOTPLT[0])($14)                         */
931   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
932   0x030ec023,   /* subu $24, $24, $14                                   */
933   0x03e0782d,   /* move $15, $31        # 64-bit move (daddu)           */
934   0x0018c0c2,   /* srl $24, $24, 3                                      */
935   0x0320f809,   /* jalr $25                                             */
936   0x2718fffe    /* subu $24, $24, 2                                     */
937 };
938
939 /* The format of subsequent PLT entries.  */
940 static const bfd_vma mips_exec_plt_entry[] =
941 {
942   0x3c0f0000,   /* lui $15, %hi(.got.plt entry)                 */
943   0x01f90000,   /* l[wd] $25, %lo(.got.plt entry)($15)          */
944   0x25f80000,   /* addiu $24, $15, %lo(.got.plt entry)          */
945   0x03200008    /* jr $25                                       */
946 };
947
948 /* The format of the first PLT entry in a VxWorks executable.  */
949 static const bfd_vma mips_vxworks_exec_plt0_entry[] =
950 {
951   0x3c190000,   /* lui t9, %hi(_GLOBAL_OFFSET_TABLE_)           */
952   0x27390000,   /* addiu t9, t9, %lo(_GLOBAL_OFFSET_TABLE_)     */
953   0x8f390008,   /* lw t9, 8(t9)                                 */
954   0x00000000,   /* nop                                          */
955   0x03200008,   /* jr t9                                        */
956   0x00000000    /* nop                                          */
957 };
958
959 /* The format of subsequent PLT entries.  */
960 static const bfd_vma mips_vxworks_exec_plt_entry[] =
961 {
962   0x10000000,   /* b .PLT_resolver                      */
963   0x24180000,   /* li t8, <pltindex>                    */
964   0x3c190000,   /* lui t9, %hi(<.got.plt slot>)         */
965   0x27390000,   /* addiu t9, t9, %lo(<.got.plt slot>)   */
966   0x8f390000,   /* lw t9, 0(t9)                         */
967   0x00000000,   /* nop                                  */
968   0x03200008,   /* jr t9                                */
969   0x00000000    /* nop                                  */
970 };
971
972 /* The format of the first PLT entry in a VxWorks shared object.  */
973 static const bfd_vma mips_vxworks_shared_plt0_entry[] =
974 {
975   0x8f990008,   /* lw t9, 8(gp)         */
976   0x00000000,   /* nop                  */
977   0x03200008,   /* jr t9                */
978   0x00000000,   /* nop                  */
979   0x00000000,   /* nop                  */
980   0x00000000    /* nop                  */
981 };
982
983 /* The format of subsequent PLT entries.  */
984 static const bfd_vma mips_vxworks_shared_plt_entry[] =
985 {
986   0x10000000,   /* b .PLT_resolver      */
987   0x24180000    /* li t8, <pltindex>    */
988 };
989 \f
990 /* microMIPS 32-bit opcode helper installer.  */
991
992 static void
993 bfd_put_micromips_32 (const bfd *abfd, bfd_vma opcode, bfd_byte *ptr)
994 {
995   bfd_put_16 (abfd, (opcode >> 16) & 0xffff, ptr);
996   bfd_put_16 (abfd,  opcode        & 0xffff, ptr + 2);
997 }
998
999 /* microMIPS 32-bit opcode helper retriever.  */
1000
1001 static bfd_vma
1002 bfd_get_micromips_32 (const bfd *abfd, const bfd_byte *ptr)
1003 {
1004   return (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
1005 }
1006 \f
1007 /* Look up an entry in a MIPS ELF linker hash table.  */
1008
1009 #define mips_elf_link_hash_lookup(table, string, create, copy, follow)  \
1010   ((struct mips_elf_link_hash_entry *)                                  \
1011    elf_link_hash_lookup (&(table)->root, (string), (create),            \
1012                          (copy), (follow)))
1013
1014 /* Traverse a MIPS ELF linker hash table.  */
1015
1016 #define mips_elf_link_hash_traverse(table, func, info)                  \
1017   (elf_link_hash_traverse                                               \
1018    (&(table)->root,                                                     \
1019     (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func),    \
1020     (info)))
1021
1022 /* Find the base offsets for thread-local storage in this object,
1023    for GD/LD and IE/LE respectively.  */
1024
1025 #define TP_OFFSET 0x7000
1026 #define DTP_OFFSET 0x8000
1027
1028 static bfd_vma
1029 dtprel_base (struct bfd_link_info *info)
1030 {
1031   /* If tls_sec is NULL, we should have signalled an error already.  */
1032   if (elf_hash_table (info)->tls_sec == NULL)
1033     return 0;
1034   return elf_hash_table (info)->tls_sec->vma + DTP_OFFSET;
1035 }
1036
1037 static bfd_vma
1038 tprel_base (struct bfd_link_info *info)
1039 {
1040   /* If tls_sec is NULL, we should have signalled an error already.  */
1041   if (elf_hash_table (info)->tls_sec == NULL)
1042     return 0;
1043   return elf_hash_table (info)->tls_sec->vma + TP_OFFSET;
1044 }
1045
1046 /* Create an entry in a MIPS ELF linker hash table.  */
1047
1048 static struct bfd_hash_entry *
1049 mips_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
1050                             struct bfd_hash_table *table, const char *string)
1051 {
1052   struct mips_elf_link_hash_entry *ret =
1053     (struct mips_elf_link_hash_entry *) entry;
1054
1055   /* Allocate the structure if it has not already been allocated by a
1056      subclass.  */
1057   if (ret == NULL)
1058     ret = bfd_hash_allocate (table, sizeof (struct mips_elf_link_hash_entry));
1059   if (ret == NULL)
1060     return (struct bfd_hash_entry *) ret;
1061
1062   /* Call the allocation method of the superclass.  */
1063   ret = ((struct mips_elf_link_hash_entry *)
1064          _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret,
1065                                      table, string));
1066   if (ret != NULL)
1067     {
1068       /* Set local fields.  */
1069       memset (&ret->esym, 0, sizeof (EXTR));
1070       /* We use -2 as a marker to indicate that the information has
1071          not been set.  -1 means there is no associated ifd.  */
1072       ret->esym.ifd = -2;
1073       ret->la25_stub = 0;
1074       ret->possibly_dynamic_relocs = 0;
1075       ret->fn_stub = NULL;
1076       ret->call_stub = NULL;
1077       ret->call_fp_stub = NULL;
1078       ret->tls_ie_type = GOT_NORMAL;
1079       ret->tls_gd_type = GOT_NORMAL;
1080       ret->global_got_area = GGA_NONE;
1081       ret->got_only_for_calls = TRUE;
1082       ret->readonly_reloc = FALSE;
1083       ret->has_static_relocs = FALSE;
1084       ret->no_fn_stub = FALSE;
1085       ret->need_fn_stub = FALSE;
1086       ret->has_nonpic_branches = FALSE;
1087       ret->needs_lazy_stub = FALSE;
1088     }
1089
1090   return (struct bfd_hash_entry *) ret;
1091 }
1092
1093 /* Allocate MIPS ELF private object data.  */
1094
1095 bfd_boolean
1096 _bfd_mips_elf_mkobject (bfd *abfd)
1097 {
1098   return bfd_elf_allocate_object (abfd, sizeof (struct mips_elf_obj_tdata),
1099                                   MIPS_ELF_DATA);
1100 }
1101
1102 bfd_boolean
1103 _bfd_mips_elf_new_section_hook (bfd *abfd, asection *sec)
1104 {
1105   if (!sec->used_by_bfd)
1106     {
1107       struct _mips_elf_section_data *sdata;
1108       bfd_size_type amt = sizeof (*sdata);
1109
1110       sdata = bfd_zalloc (abfd, amt);
1111       if (sdata == NULL)
1112         return FALSE;
1113       sec->used_by_bfd = sdata;
1114     }
1115
1116   return _bfd_elf_new_section_hook (abfd, sec);
1117 }
1118 \f
1119 /* Read ECOFF debugging information from a .mdebug section into a
1120    ecoff_debug_info structure.  */
1121
1122 bfd_boolean
1123 _bfd_mips_elf_read_ecoff_info (bfd *abfd, asection *section,
1124                                struct ecoff_debug_info *debug)
1125 {
1126   HDRR *symhdr;
1127   const struct ecoff_debug_swap *swap;
1128   char *ext_hdr;
1129
1130   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1131   memset (debug, 0, sizeof (*debug));
1132
1133   ext_hdr = bfd_malloc (swap->external_hdr_size);
1134   if (ext_hdr == NULL && swap->external_hdr_size != 0)
1135     goto error_return;
1136
1137   if (! bfd_get_section_contents (abfd, section, ext_hdr, 0,
1138                                   swap->external_hdr_size))
1139     goto error_return;
1140
1141   symhdr = &debug->symbolic_header;
1142   (*swap->swap_hdr_in) (abfd, ext_hdr, symhdr);
1143
1144   /* The symbolic header contains absolute file offsets and sizes to
1145      read.  */
1146 #define READ(ptr, offset, count, size, type)                            \
1147   if (symhdr->count == 0)                                               \
1148     debug->ptr = NULL;                                                  \
1149   else                                                                  \
1150     {                                                                   \
1151       bfd_size_type amt = (bfd_size_type) size * symhdr->count;         \
1152       debug->ptr = bfd_malloc (amt);                                    \
1153       if (debug->ptr == NULL)                                           \
1154         goto error_return;                                              \
1155       if (bfd_seek (abfd, symhdr->offset, SEEK_SET) != 0                \
1156           || bfd_bread (debug->ptr, amt, abfd) != amt)                  \
1157         goto error_return;                                              \
1158     }
1159
1160   READ (line, cbLineOffset, cbLine, sizeof (unsigned char), unsigned char *);
1161   READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *);
1162   READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *);
1163   READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *);
1164   READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *);
1165   READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext),
1166         union aux_ext *);
1167   READ (ss, cbSsOffset, issMax, sizeof (char), char *);
1168   READ (ssext, cbSsExtOffset, issExtMax, sizeof (char), char *);
1169   READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *);
1170   READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *);
1171   READ (external_ext, cbExtOffset, iextMax, swap->external_ext_size, void *);
1172 #undef READ
1173
1174   debug->fdr = NULL;
1175
1176   return TRUE;
1177
1178  error_return:
1179   if (ext_hdr != NULL)
1180     free (ext_hdr);
1181   if (debug->line != NULL)
1182     free (debug->line);
1183   if (debug->external_dnr != NULL)
1184     free (debug->external_dnr);
1185   if (debug->external_pdr != NULL)
1186     free (debug->external_pdr);
1187   if (debug->external_sym != NULL)
1188     free (debug->external_sym);
1189   if (debug->external_opt != NULL)
1190     free (debug->external_opt);
1191   if (debug->external_aux != NULL)
1192     free (debug->external_aux);
1193   if (debug->ss != NULL)
1194     free (debug->ss);
1195   if (debug->ssext != NULL)
1196     free (debug->ssext);
1197   if (debug->external_fdr != NULL)
1198     free (debug->external_fdr);
1199   if (debug->external_rfd != NULL)
1200     free (debug->external_rfd);
1201   if (debug->external_ext != NULL)
1202     free (debug->external_ext);
1203   return FALSE;
1204 }
1205 \f
1206 /* Swap RPDR (runtime procedure table entry) for output.  */
1207
1208 static void
1209 ecoff_swap_rpdr_out (bfd *abfd, const RPDR *in, struct rpdr_ext *ex)
1210 {
1211   H_PUT_S32 (abfd, in->adr, ex->p_adr);
1212   H_PUT_32 (abfd, in->regmask, ex->p_regmask);
1213   H_PUT_32 (abfd, in->regoffset, ex->p_regoffset);
1214   H_PUT_32 (abfd, in->fregmask, ex->p_fregmask);
1215   H_PUT_32 (abfd, in->fregoffset, ex->p_fregoffset);
1216   H_PUT_32 (abfd, in->frameoffset, ex->p_frameoffset);
1217
1218   H_PUT_16 (abfd, in->framereg, ex->p_framereg);
1219   H_PUT_16 (abfd, in->pcreg, ex->p_pcreg);
1220
1221   H_PUT_32 (abfd, in->irpss, ex->p_irpss);
1222 }
1223
1224 /* Create a runtime procedure table from the .mdebug section.  */
1225
1226 static bfd_boolean
1227 mips_elf_create_procedure_table (void *handle, bfd *abfd,
1228                                  struct bfd_link_info *info, asection *s,
1229                                  struct ecoff_debug_info *debug)
1230 {
1231   const struct ecoff_debug_swap *swap;
1232   HDRR *hdr = &debug->symbolic_header;
1233   RPDR *rpdr, *rp;
1234   struct rpdr_ext *erp;
1235   void *rtproc;
1236   struct pdr_ext *epdr;
1237   struct sym_ext *esym;
1238   char *ss, **sv;
1239   char *str;
1240   bfd_size_type size;
1241   bfd_size_type count;
1242   unsigned long sindex;
1243   unsigned long i;
1244   PDR pdr;
1245   SYMR sym;
1246   const char *no_name_func = _("static procedure (no name)");
1247
1248   epdr = NULL;
1249   rpdr = NULL;
1250   esym = NULL;
1251   ss = NULL;
1252   sv = NULL;
1253
1254   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1255
1256   sindex = strlen (no_name_func) + 1;
1257   count = hdr->ipdMax;
1258   if (count > 0)
1259     {
1260       size = swap->external_pdr_size;
1261
1262       epdr = bfd_malloc (size * count);
1263       if (epdr == NULL)
1264         goto error_return;
1265
1266       if (! _bfd_ecoff_get_accumulated_pdr (handle, (bfd_byte *) epdr))
1267         goto error_return;
1268
1269       size = sizeof (RPDR);
1270       rp = rpdr = bfd_malloc (size * count);
1271       if (rpdr == NULL)
1272         goto error_return;
1273
1274       size = sizeof (char *);
1275       sv = bfd_malloc (size * count);
1276       if (sv == NULL)
1277         goto error_return;
1278
1279       count = hdr->isymMax;
1280       size = swap->external_sym_size;
1281       esym = bfd_malloc (size * count);
1282       if (esym == NULL)
1283         goto error_return;
1284
1285       if (! _bfd_ecoff_get_accumulated_sym (handle, (bfd_byte *) esym))
1286         goto error_return;
1287
1288       count = hdr->issMax;
1289       ss = bfd_malloc (count);
1290       if (ss == NULL)
1291         goto error_return;
1292       if (! _bfd_ecoff_get_accumulated_ss (handle, (bfd_byte *) ss))
1293         goto error_return;
1294
1295       count = hdr->ipdMax;
1296       for (i = 0; i < (unsigned long) count; i++, rp++)
1297         {
1298           (*swap->swap_pdr_in) (abfd, epdr + i, &pdr);
1299           (*swap->swap_sym_in) (abfd, &esym[pdr.isym], &sym);
1300           rp->adr = sym.value;
1301           rp->regmask = pdr.regmask;
1302           rp->regoffset = pdr.regoffset;
1303           rp->fregmask = pdr.fregmask;
1304           rp->fregoffset = pdr.fregoffset;
1305           rp->frameoffset = pdr.frameoffset;
1306           rp->framereg = pdr.framereg;
1307           rp->pcreg = pdr.pcreg;
1308           rp->irpss = sindex;
1309           sv[i] = ss + sym.iss;
1310           sindex += strlen (sv[i]) + 1;
1311         }
1312     }
1313
1314   size = sizeof (struct rpdr_ext) * (count + 2) + sindex;
1315   size = BFD_ALIGN (size, 16);
1316   rtproc = bfd_alloc (abfd, size);
1317   if (rtproc == NULL)
1318     {
1319       mips_elf_hash_table (info)->procedure_count = 0;
1320       goto error_return;
1321     }
1322
1323   mips_elf_hash_table (info)->procedure_count = count + 2;
1324
1325   erp = rtproc;
1326   memset (erp, 0, sizeof (struct rpdr_ext));
1327   erp++;
1328   str = (char *) rtproc + sizeof (struct rpdr_ext) * (count + 2);
1329   strcpy (str, no_name_func);
1330   str += strlen (no_name_func) + 1;
1331   for (i = 0; i < count; i++)
1332     {
1333       ecoff_swap_rpdr_out (abfd, rpdr + i, erp + i);
1334       strcpy (str, sv[i]);
1335       str += strlen (sv[i]) + 1;
1336     }
1337   H_PUT_S32 (abfd, -1, (erp + count)->p_adr);
1338
1339   /* Set the size and contents of .rtproc section.  */
1340   s->size = size;
1341   s->contents = rtproc;
1342
1343   /* Skip this section later on (I don't think this currently
1344      matters, but someday it might).  */
1345   s->map_head.link_order = NULL;
1346
1347   if (epdr != NULL)
1348     free (epdr);
1349   if (rpdr != NULL)
1350     free (rpdr);
1351   if (esym != NULL)
1352     free (esym);
1353   if (ss != NULL)
1354     free (ss);
1355   if (sv != NULL)
1356     free (sv);
1357
1358   return TRUE;
1359
1360  error_return:
1361   if (epdr != NULL)
1362     free (epdr);
1363   if (rpdr != NULL)
1364     free (rpdr);
1365   if (esym != NULL)
1366     free (esym);
1367   if (ss != NULL)
1368     free (ss);
1369   if (sv != NULL)
1370     free (sv);
1371   return FALSE;
1372 }
1373 \f
1374 /* We're going to create a stub for H.  Create a symbol for the stub's
1375    value and size, to help make the disassembly easier to read.  */
1376
1377 static bfd_boolean
1378 mips_elf_create_stub_symbol (struct bfd_link_info *info,
1379                              struct mips_elf_link_hash_entry *h,
1380                              const char *prefix, asection *s, bfd_vma value,
1381                              bfd_vma size)
1382 {
1383   struct bfd_link_hash_entry *bh;
1384   struct elf_link_hash_entry *elfh;
1385   const char *name;
1386
1387   if (ELF_ST_IS_MICROMIPS (h->root.other))
1388     value |= 1;
1389
1390   /* Create a new symbol.  */
1391   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1392   bh = NULL;
1393   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1394                                          BSF_LOCAL, s, value, NULL,
1395                                          TRUE, FALSE, &bh))
1396     return FALSE;
1397
1398   /* Make it a local function.  */
1399   elfh = (struct elf_link_hash_entry *) bh;
1400   elfh->type = ELF_ST_INFO (STB_LOCAL, STT_FUNC);
1401   elfh->size = size;
1402   elfh->forced_local = 1;
1403   return TRUE;
1404 }
1405
1406 /* We're about to redefine H.  Create a symbol to represent H's
1407    current value and size, to help make the disassembly easier
1408    to read.  */
1409
1410 static bfd_boolean
1411 mips_elf_create_shadow_symbol (struct bfd_link_info *info,
1412                                struct mips_elf_link_hash_entry *h,
1413                                const char *prefix)
1414 {
1415   struct bfd_link_hash_entry *bh;
1416   struct elf_link_hash_entry *elfh;
1417   const char *name;
1418   asection *s;
1419   bfd_vma value;
1420
1421   /* Read the symbol's value.  */
1422   BFD_ASSERT (h->root.root.type == bfd_link_hash_defined
1423               || h->root.root.type == bfd_link_hash_defweak);
1424   s = h->root.root.u.def.section;
1425   value = h->root.root.u.def.value;
1426
1427   /* Create a new symbol.  */
1428   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1429   bh = NULL;
1430   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1431                                          BSF_LOCAL, s, value, NULL,
1432                                          TRUE, FALSE, &bh))
1433     return FALSE;
1434
1435   /* Make it local and copy the other attributes from H.  */
1436   elfh = (struct elf_link_hash_entry *) bh;
1437   elfh->type = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (h->root.type));
1438   elfh->other = h->root.other;
1439   elfh->size = h->root.size;
1440   elfh->forced_local = 1;
1441   return TRUE;
1442 }
1443
1444 /* Return TRUE if relocations in SECTION can refer directly to a MIPS16
1445    function rather than to a hard-float stub.  */
1446
1447 static bfd_boolean
1448 section_allows_mips16_refs_p (asection *section)
1449 {
1450   const char *name;
1451
1452   name = bfd_get_section_name (section->owner, section);
1453   return (FN_STUB_P (name)
1454           || CALL_STUB_P (name)
1455           || CALL_FP_STUB_P (name)
1456           || strcmp (name, ".pdr") == 0);
1457 }
1458
1459 /* [RELOCS, RELEND) are the relocations against SEC, which is a MIPS16
1460    stub section of some kind.  Return the R_SYMNDX of the target
1461    function, or 0 if we can't decide which function that is.  */
1462
1463 static unsigned long
1464 mips16_stub_symndx (const struct elf_backend_data *bed,
1465                     asection *sec ATTRIBUTE_UNUSED,
1466                     const Elf_Internal_Rela *relocs,
1467                     const Elf_Internal_Rela *relend)
1468 {
1469   int int_rels_per_ext_rel = bed->s->int_rels_per_ext_rel;
1470   const Elf_Internal_Rela *rel;
1471
1472   /* Trust the first R_MIPS_NONE relocation, if any, but not a subsequent
1473      one in a compound relocation.  */
1474   for (rel = relocs; rel < relend; rel += int_rels_per_ext_rel)
1475     if (ELF_R_TYPE (sec->owner, rel->r_info) == R_MIPS_NONE)
1476       return ELF_R_SYM (sec->owner, rel->r_info);
1477
1478   /* Otherwise trust the first relocation, whatever its kind.  This is
1479      the traditional behavior.  */
1480   if (relocs < relend)
1481     return ELF_R_SYM (sec->owner, relocs->r_info);
1482
1483   return 0;
1484 }
1485
1486 /* Check the mips16 stubs for a particular symbol, and see if we can
1487    discard them.  */
1488
1489 static void
1490 mips_elf_check_mips16_stubs (struct bfd_link_info *info,
1491                              struct mips_elf_link_hash_entry *h)
1492 {
1493   /* Dynamic symbols must use the standard call interface, in case other
1494      objects try to call them.  */
1495   if (h->fn_stub != NULL
1496       && h->root.dynindx != -1)
1497     {
1498       mips_elf_create_shadow_symbol (info, h, ".mips16.");
1499       h->need_fn_stub = TRUE;
1500     }
1501
1502   if (h->fn_stub != NULL
1503       && ! h->need_fn_stub)
1504     {
1505       /* We don't need the fn_stub; the only references to this symbol
1506          are 16 bit calls.  Clobber the size to 0 to prevent it from
1507          being included in the link.  */
1508       h->fn_stub->size = 0;
1509       h->fn_stub->flags &= ~SEC_RELOC;
1510       h->fn_stub->reloc_count = 0;
1511       h->fn_stub->flags |= SEC_EXCLUDE;
1512     }
1513
1514   if (h->call_stub != NULL
1515       && ELF_ST_IS_MIPS16 (h->root.other))
1516     {
1517       /* We don't need the call_stub; this is a 16 bit function, so
1518          calls from other 16 bit functions are OK.  Clobber the size
1519          to 0 to prevent it from being included in the link.  */
1520       h->call_stub->size = 0;
1521       h->call_stub->flags &= ~SEC_RELOC;
1522       h->call_stub->reloc_count = 0;
1523       h->call_stub->flags |= SEC_EXCLUDE;
1524     }
1525
1526   if (h->call_fp_stub != NULL
1527       && ELF_ST_IS_MIPS16 (h->root.other))
1528     {
1529       /* We don't need the call_stub; this is a 16 bit function, so
1530          calls from other 16 bit functions are OK.  Clobber the size
1531          to 0 to prevent it from being included in the link.  */
1532       h->call_fp_stub->size = 0;
1533       h->call_fp_stub->flags &= ~SEC_RELOC;
1534       h->call_fp_stub->reloc_count = 0;
1535       h->call_fp_stub->flags |= SEC_EXCLUDE;
1536     }
1537 }
1538
1539 /* Hashtable callbacks for mips_elf_la25_stubs.  */
1540
1541 static hashval_t
1542 mips_elf_la25_stub_hash (const void *entry_)
1543 {
1544   const struct mips_elf_la25_stub *entry;
1545
1546   entry = (struct mips_elf_la25_stub *) entry_;
1547   return entry->h->root.root.u.def.section->id
1548     + entry->h->root.root.u.def.value;
1549 }
1550
1551 static int
1552 mips_elf_la25_stub_eq (const void *entry1_, const void *entry2_)
1553 {
1554   const struct mips_elf_la25_stub *entry1, *entry2;
1555
1556   entry1 = (struct mips_elf_la25_stub *) entry1_;
1557   entry2 = (struct mips_elf_la25_stub *) entry2_;
1558   return ((entry1->h->root.root.u.def.section
1559            == entry2->h->root.root.u.def.section)
1560           && (entry1->h->root.root.u.def.value
1561               == entry2->h->root.root.u.def.value));
1562 }
1563
1564 /* Called by the linker to set up the la25 stub-creation code.  FN is
1565    the linker's implementation of add_stub_function.  Return true on
1566    success.  */
1567
1568 bfd_boolean
1569 _bfd_mips_elf_init_stubs (struct bfd_link_info *info,
1570                           asection *(*fn) (const char *, asection *,
1571                                            asection *))
1572 {
1573   struct mips_elf_link_hash_table *htab;
1574
1575   htab = mips_elf_hash_table (info);
1576   if (htab == NULL)
1577     return FALSE;
1578
1579   htab->add_stub_section = fn;
1580   htab->la25_stubs = htab_try_create (1, mips_elf_la25_stub_hash,
1581                                       mips_elf_la25_stub_eq, NULL);
1582   if (htab->la25_stubs == NULL)
1583     return FALSE;
1584
1585   return TRUE;
1586 }
1587
1588 /* Return true if H is a locally-defined PIC function, in the sense
1589    that it or its fn_stub might need $25 to be valid on entry.
1590    Note that MIPS16 functions set up $gp using PC-relative instructions,
1591    so they themselves never need $25 to be valid.  Only non-MIPS16
1592    entry points are of interest here.  */
1593
1594 static bfd_boolean
1595 mips_elf_local_pic_function_p (struct mips_elf_link_hash_entry *h)
1596 {
1597   return ((h->root.root.type == bfd_link_hash_defined
1598            || h->root.root.type == bfd_link_hash_defweak)
1599           && h->root.def_regular
1600           && !bfd_is_abs_section (h->root.root.u.def.section)
1601           && (!ELF_ST_IS_MIPS16 (h->root.other)
1602               || (h->fn_stub && h->need_fn_stub))
1603           && (PIC_OBJECT_P (h->root.root.u.def.section->owner)
1604               || ELF_ST_IS_MIPS_PIC (h->root.other)));
1605 }
1606
1607 /* Set *SEC to the input section that contains the target of STUB.
1608    Return the offset of the target from the start of that section.  */
1609
1610 static bfd_vma
1611 mips_elf_get_la25_target (struct mips_elf_la25_stub *stub,
1612                           asection **sec)
1613 {
1614   if (ELF_ST_IS_MIPS16 (stub->h->root.other))
1615     {
1616       BFD_ASSERT (stub->h->need_fn_stub);
1617       *sec = stub->h->fn_stub;
1618       return 0;
1619     }
1620   else
1621     {
1622       *sec = stub->h->root.root.u.def.section;
1623       return stub->h->root.root.u.def.value;
1624     }
1625 }
1626
1627 /* STUB describes an la25 stub that we have decided to implement
1628    by inserting an LUI/ADDIU pair before the target function.
1629    Create the section and redirect the function symbol to it.  */
1630
1631 static bfd_boolean
1632 mips_elf_add_la25_intro (struct mips_elf_la25_stub *stub,
1633                          struct bfd_link_info *info)
1634 {
1635   struct mips_elf_link_hash_table *htab;
1636   char *name;
1637   asection *s, *input_section;
1638   unsigned int align;
1639
1640   htab = mips_elf_hash_table (info);
1641   if (htab == NULL)
1642     return FALSE;
1643
1644   /* Create a unique name for the new section.  */
1645   name = bfd_malloc (11 + sizeof (".text.stub."));
1646   if (name == NULL)
1647     return FALSE;
1648   sprintf (name, ".text.stub.%d", (int) htab_elements (htab->la25_stubs));
1649
1650   /* Create the section.  */
1651   mips_elf_get_la25_target (stub, &input_section);
1652   s = htab->add_stub_section (name, input_section,
1653                               input_section->output_section);
1654   if (s == NULL)
1655     return FALSE;
1656
1657   /* Make sure that any padding goes before the stub.  */
1658   align = input_section->alignment_power;
1659   if (!bfd_set_section_alignment (s->owner, s, align))
1660     return FALSE;
1661   if (align > 3)
1662     s->size = (1 << align) - 8;
1663
1664   /* Create a symbol for the stub.  */
1665   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 8);
1666   stub->stub_section = s;
1667   stub->offset = s->size;
1668
1669   /* Allocate room for it.  */
1670   s->size += 8;
1671   return TRUE;
1672 }
1673
1674 /* STUB describes an la25 stub that we have decided to implement
1675    with a separate trampoline.  Allocate room for it and redirect
1676    the function symbol to it.  */
1677
1678 static bfd_boolean
1679 mips_elf_add_la25_trampoline (struct mips_elf_la25_stub *stub,
1680                               struct bfd_link_info *info)
1681 {
1682   struct mips_elf_link_hash_table *htab;
1683   asection *s;
1684
1685   htab = mips_elf_hash_table (info);
1686   if (htab == NULL)
1687     return FALSE;
1688
1689   /* Create a trampoline section, if we haven't already.  */
1690   s = htab->strampoline;
1691   if (s == NULL)
1692     {
1693       asection *input_section = stub->h->root.root.u.def.section;
1694       s = htab->add_stub_section (".text", NULL,
1695                                   input_section->output_section);
1696       if (s == NULL || !bfd_set_section_alignment (s->owner, s, 4))
1697         return FALSE;
1698       htab->strampoline = s;
1699     }
1700
1701   /* Create a symbol for the stub.  */
1702   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 16);
1703   stub->stub_section = s;
1704   stub->offset = s->size;
1705
1706   /* Allocate room for it.  */
1707   s->size += 16;
1708   return TRUE;
1709 }
1710
1711 /* H describes a symbol that needs an la25 stub.  Make sure that an
1712    appropriate stub exists and point H at it.  */
1713
1714 static bfd_boolean
1715 mips_elf_add_la25_stub (struct bfd_link_info *info,
1716                         struct mips_elf_link_hash_entry *h)
1717 {
1718   struct mips_elf_link_hash_table *htab;
1719   struct mips_elf_la25_stub search, *stub;
1720   bfd_boolean use_trampoline_p;
1721   asection *s;
1722   bfd_vma value;
1723   void **slot;
1724
1725   /* Describe the stub we want.  */
1726   search.stub_section = NULL;
1727   search.offset = 0;
1728   search.h = h;
1729
1730   /* See if we've already created an equivalent stub.  */
1731   htab = mips_elf_hash_table (info);
1732   if (htab == NULL)
1733     return FALSE;
1734
1735   slot = htab_find_slot (htab->la25_stubs, &search, INSERT);
1736   if (slot == NULL)
1737     return FALSE;
1738
1739   stub = (struct mips_elf_la25_stub *) *slot;
1740   if (stub != NULL)
1741     {
1742       /* We can reuse the existing stub.  */
1743       h->la25_stub = stub;
1744       return TRUE;
1745     }
1746
1747   /* Create a permanent copy of ENTRY and add it to the hash table.  */
1748   stub = bfd_malloc (sizeof (search));
1749   if (stub == NULL)
1750     return FALSE;
1751   *stub = search;
1752   *slot = stub;
1753
1754   /* Prefer to use LUI/ADDIU stubs if the function is at the beginning
1755      of the section and if we would need no more than 2 nops.  */
1756   value = mips_elf_get_la25_target (stub, &s);
1757   use_trampoline_p = (value != 0 || s->alignment_power > 4);
1758
1759   h->la25_stub = stub;
1760   return (use_trampoline_p
1761           ? mips_elf_add_la25_trampoline (stub, info)
1762           : mips_elf_add_la25_intro (stub, info));
1763 }
1764
1765 /* A mips_elf_link_hash_traverse callback that is called before sizing
1766    sections.  DATA points to a mips_htab_traverse_info structure.  */
1767
1768 static bfd_boolean
1769 mips_elf_check_symbols (struct mips_elf_link_hash_entry *h, void *data)
1770 {
1771   struct mips_htab_traverse_info *hti;
1772
1773   hti = (struct mips_htab_traverse_info *) data;
1774   if (!hti->info->relocatable)
1775     mips_elf_check_mips16_stubs (hti->info, h);
1776
1777   if (mips_elf_local_pic_function_p (h))
1778     {
1779       /* PR 12845: If H is in a section that has been garbage
1780          collected it will have its output section set to *ABS*.  */
1781       if (bfd_is_abs_section (h->root.root.u.def.section->output_section))
1782         return TRUE;
1783
1784       /* H is a function that might need $25 to be valid on entry.
1785          If we're creating a non-PIC relocatable object, mark H as
1786          being PIC.  If we're creating a non-relocatable object with
1787          non-PIC branches and jumps to H, make sure that H has an la25
1788          stub.  */
1789       if (hti->info->relocatable)
1790         {
1791           if (!PIC_OBJECT_P (hti->output_bfd))
1792             h->root.other = ELF_ST_SET_MIPS_PIC (h->root.other);
1793         }
1794       else if (h->has_nonpic_branches && !mips_elf_add_la25_stub (hti->info, h))
1795         {
1796           hti->error = TRUE;
1797           return FALSE;
1798         }
1799     }
1800   return TRUE;
1801 }
1802 \f
1803 /* R_MIPS16_26 is used for the mips16 jal and jalx instructions.
1804    Most mips16 instructions are 16 bits, but these instructions
1805    are 32 bits.
1806
1807    The format of these instructions is:
1808
1809    +--------------+--------------------------------+
1810    |     JALX     | X|   Imm 20:16  |   Imm 25:21  |
1811    +--------------+--------------------------------+
1812    |                Immediate  15:0                |
1813    +-----------------------------------------------+
1814
1815    JALX is the 5-bit value 00011.  X is 0 for jal, 1 for jalx.
1816    Note that the immediate value in the first word is swapped.
1817
1818    When producing a relocatable object file, R_MIPS16_26 is
1819    handled mostly like R_MIPS_26.  In particular, the addend is
1820    stored as a straight 26-bit value in a 32-bit instruction.
1821    (gas makes life simpler for itself by never adjusting a
1822    R_MIPS16_26 reloc to be against a section, so the addend is
1823    always zero).  However, the 32 bit instruction is stored as 2
1824    16-bit values, rather than a single 32-bit value.  In a
1825    big-endian file, the result is the same; in a little-endian
1826    file, the two 16-bit halves of the 32 bit value are swapped.
1827    This is so that a disassembler can recognize the jal
1828    instruction.
1829
1830    When doing a final link, R_MIPS16_26 is treated as a 32 bit
1831    instruction stored as two 16-bit values.  The addend A is the
1832    contents of the targ26 field.  The calculation is the same as
1833    R_MIPS_26.  When storing the calculated value, reorder the
1834    immediate value as shown above, and don't forget to store the
1835    value as two 16-bit values.
1836
1837    To put it in MIPS ABI terms, the relocation field is T-targ26-16,
1838    defined as
1839
1840    big-endian:
1841    +--------+----------------------+
1842    |        |                      |
1843    |        |    targ26-16         |
1844    |31    26|25                   0|
1845    +--------+----------------------+
1846
1847    little-endian:
1848    +----------+------+-------------+
1849    |          |      |             |
1850    |  sub1    |      |     sub2    |
1851    |0        9|10  15|16         31|
1852    +----------+--------------------+
1853    where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is
1854    ((sub1 << 16) | sub2)).
1855
1856    When producing a relocatable object file, the calculation is
1857    (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1858    When producing a fully linked file, the calculation is
1859    let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1860    ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff)
1861
1862    The table below lists the other MIPS16 instruction relocations.
1863    Each one is calculated in the same way as the non-MIPS16 relocation
1864    given on the right, but using the extended MIPS16 layout of 16-bit
1865    immediate fields:
1866
1867         R_MIPS16_GPREL          R_MIPS_GPREL16
1868         R_MIPS16_GOT16          R_MIPS_GOT16
1869         R_MIPS16_CALL16         R_MIPS_CALL16
1870         R_MIPS16_HI16           R_MIPS_HI16
1871         R_MIPS16_LO16           R_MIPS_LO16
1872
1873    A typical instruction will have a format like this:
1874
1875    +--------------+--------------------------------+
1876    |    EXTEND    |     Imm 10:5    |   Imm 15:11  |
1877    +--------------+--------------------------------+
1878    |    Major     |   rx   |   ry   |   Imm  4:0   |
1879    +--------------+--------------------------------+
1880
1881    EXTEND is the five bit value 11110.  Major is the instruction
1882    opcode.
1883
1884    All we need to do here is shuffle the bits appropriately.
1885    As above, the two 16-bit halves must be swapped on a
1886    little-endian system.  */
1887
1888 static inline bfd_boolean
1889 mips16_reloc_p (int r_type)
1890 {
1891   switch (r_type)
1892     {
1893     case R_MIPS16_26:
1894     case R_MIPS16_GPREL:
1895     case R_MIPS16_GOT16:
1896     case R_MIPS16_CALL16:
1897     case R_MIPS16_HI16:
1898     case R_MIPS16_LO16:
1899     case R_MIPS16_TLS_GD:
1900     case R_MIPS16_TLS_LDM:
1901     case R_MIPS16_TLS_DTPREL_HI16:
1902     case R_MIPS16_TLS_DTPREL_LO16:
1903     case R_MIPS16_TLS_GOTTPREL:
1904     case R_MIPS16_TLS_TPREL_HI16:
1905     case R_MIPS16_TLS_TPREL_LO16:
1906       return TRUE;
1907
1908     default:
1909       return FALSE;
1910     }
1911 }
1912
1913 /* Check if a microMIPS reloc.  */
1914
1915 static inline bfd_boolean
1916 micromips_reloc_p (unsigned int r_type)
1917 {
1918   return r_type >= R_MICROMIPS_min && r_type < R_MICROMIPS_max;
1919 }
1920
1921 /* Similar to MIPS16, the two 16-bit halves in microMIPS must be swapped
1922    on a little-endian system.  This does not apply to R_MICROMIPS_PC7_S1
1923    and R_MICROMIPS_PC10_S1 relocs that apply to 16-bit instructions.  */
1924
1925 static inline bfd_boolean
1926 micromips_reloc_shuffle_p (unsigned int r_type)
1927 {
1928   return (micromips_reloc_p (r_type)
1929           && r_type != R_MICROMIPS_PC7_S1
1930           && r_type != R_MICROMIPS_PC10_S1);
1931 }
1932
1933 static inline bfd_boolean
1934 got16_reloc_p (int r_type)
1935 {
1936   return (r_type == R_MIPS_GOT16
1937           || r_type == R_MIPS16_GOT16
1938           || r_type == R_MICROMIPS_GOT16);
1939 }
1940
1941 static inline bfd_boolean
1942 call16_reloc_p (int r_type)
1943 {
1944   return (r_type == R_MIPS_CALL16
1945           || r_type == R_MIPS16_CALL16
1946           || r_type == R_MICROMIPS_CALL16);
1947 }
1948
1949 static inline bfd_boolean
1950 got_disp_reloc_p (unsigned int r_type)
1951 {
1952   return r_type == R_MIPS_GOT_DISP || r_type == R_MICROMIPS_GOT_DISP;
1953 }
1954
1955 static inline bfd_boolean
1956 got_page_reloc_p (unsigned int r_type)
1957 {
1958   return r_type == R_MIPS_GOT_PAGE || r_type == R_MICROMIPS_GOT_PAGE;
1959 }
1960
1961 static inline bfd_boolean
1962 got_ofst_reloc_p (unsigned int r_type)
1963 {
1964   return r_type == R_MIPS_GOT_OFST || r_type == R_MICROMIPS_GOT_OFST;
1965 }
1966
1967 static inline bfd_boolean
1968 got_hi16_reloc_p (unsigned int r_type)
1969 {
1970   return r_type == R_MIPS_GOT_HI16 || r_type == R_MICROMIPS_GOT_HI16;
1971 }
1972
1973 static inline bfd_boolean
1974 got_lo16_reloc_p (unsigned int r_type)
1975 {
1976   return r_type == R_MIPS_GOT_LO16 || r_type == R_MICROMIPS_GOT_LO16;
1977 }
1978
1979 static inline bfd_boolean
1980 call_hi16_reloc_p (unsigned int r_type)
1981 {
1982   return r_type == R_MIPS_CALL_HI16 || r_type == R_MICROMIPS_CALL_HI16;
1983 }
1984
1985 static inline bfd_boolean
1986 call_lo16_reloc_p (unsigned int r_type)
1987 {
1988   return r_type == R_MIPS_CALL_LO16 || r_type == R_MICROMIPS_CALL_LO16;
1989 }
1990
1991 static inline bfd_boolean
1992 hi16_reloc_p (int r_type)
1993 {
1994   return (r_type == R_MIPS_HI16
1995           || r_type == R_MIPS16_HI16
1996           || r_type == R_MICROMIPS_HI16);
1997 }
1998
1999 static inline bfd_boolean
2000 lo16_reloc_p (int r_type)
2001 {
2002   return (r_type == R_MIPS_LO16
2003           || r_type == R_MIPS16_LO16
2004           || r_type == R_MICROMIPS_LO16);
2005 }
2006
2007 static inline bfd_boolean
2008 mips16_call_reloc_p (int r_type)
2009 {
2010   return r_type == R_MIPS16_26 || r_type == R_MIPS16_CALL16;
2011 }
2012
2013 static inline bfd_boolean
2014 jal_reloc_p (int r_type)
2015 {
2016   return (r_type == R_MIPS_26
2017           || r_type == R_MIPS16_26
2018           || r_type == R_MICROMIPS_26_S1);
2019 }
2020
2021 static inline bfd_boolean
2022 micromips_branch_reloc_p (int r_type)
2023 {
2024   return (r_type == R_MICROMIPS_26_S1
2025           || r_type == R_MICROMIPS_PC16_S1
2026           || r_type == R_MICROMIPS_PC10_S1
2027           || r_type == R_MICROMIPS_PC7_S1);
2028 }
2029
2030 static inline bfd_boolean
2031 tls_gd_reloc_p (unsigned int r_type)
2032 {
2033   return (r_type == R_MIPS_TLS_GD
2034           || r_type == R_MIPS16_TLS_GD
2035           || r_type == R_MICROMIPS_TLS_GD);
2036 }
2037
2038 static inline bfd_boolean
2039 tls_ldm_reloc_p (unsigned int r_type)
2040 {
2041   return (r_type == R_MIPS_TLS_LDM
2042           || r_type == R_MIPS16_TLS_LDM
2043           || r_type == R_MICROMIPS_TLS_LDM);
2044 }
2045
2046 static inline bfd_boolean
2047 tls_gottprel_reloc_p (unsigned int r_type)
2048 {
2049   return (r_type == R_MIPS_TLS_GOTTPREL
2050           || r_type == R_MIPS16_TLS_GOTTPREL
2051           || r_type == R_MICROMIPS_TLS_GOTTPREL);
2052 }
2053
2054 void
2055 _bfd_mips_elf_reloc_unshuffle (bfd *abfd, int r_type,
2056                                bfd_boolean jal_shuffle, bfd_byte *data)
2057 {
2058   bfd_vma first, second, val;
2059
2060   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2061     return;
2062
2063   /* Pick up the first and second halfwords of the instruction.  */
2064   first = bfd_get_16 (abfd, data);
2065   second = bfd_get_16 (abfd, data + 2);
2066   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2067     val = first << 16 | second;
2068   else if (r_type != R_MIPS16_26)
2069     val = (((first & 0xf800) << 16) | ((second & 0xffe0) << 11)
2070            | ((first & 0x1f) << 11) | (first & 0x7e0) | (second & 0x1f));
2071   else
2072     val = (((first & 0xfc00) << 16) | ((first & 0x3e0) << 11)
2073            | ((first & 0x1f) << 21) | second);
2074   bfd_put_32 (abfd, val, data);
2075 }
2076
2077 void
2078 _bfd_mips_elf_reloc_shuffle (bfd *abfd, int r_type,
2079                              bfd_boolean jal_shuffle, bfd_byte *data)
2080 {
2081   bfd_vma first, second, val;
2082
2083   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2084     return;
2085
2086   val = bfd_get_32 (abfd, data);
2087   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2088     {
2089       second = val & 0xffff;
2090       first = val >> 16;
2091     }
2092   else if (r_type != R_MIPS16_26)
2093     {
2094       second = ((val >> 11) & 0xffe0) | (val & 0x1f);
2095       first = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0);
2096     }
2097   else
2098     {
2099       second = val & 0xffff;
2100       first = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0)
2101                | ((val >> 21) & 0x1f);
2102     }
2103   bfd_put_16 (abfd, second, data + 2);
2104   bfd_put_16 (abfd, first, data);
2105 }
2106
2107 bfd_reloc_status_type
2108 _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol,
2109                                arelent *reloc_entry, asection *input_section,
2110                                bfd_boolean relocatable, void *data, bfd_vma gp)
2111 {
2112   bfd_vma relocation;
2113   bfd_signed_vma val;
2114   bfd_reloc_status_type status;
2115
2116   if (bfd_is_com_section (symbol->section))
2117     relocation = 0;
2118   else
2119     relocation = symbol->value;
2120
2121   relocation += symbol->section->output_section->vma;
2122   relocation += symbol->section->output_offset;
2123
2124   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2125     return bfd_reloc_outofrange;
2126
2127   /* Set val to the offset into the section or symbol.  */
2128   val = reloc_entry->addend;
2129
2130   _bfd_mips_elf_sign_extend (val, 16);
2131
2132   /* Adjust val for the final section location and GP value.  If we
2133      are producing relocatable output, we don't want to do this for
2134      an external symbol.  */
2135   if (! relocatable
2136       || (symbol->flags & BSF_SECTION_SYM) != 0)
2137     val += relocation - gp;
2138
2139   if (reloc_entry->howto->partial_inplace)
2140     {
2141       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2142                                        (bfd_byte *) data
2143                                        + reloc_entry->address);
2144       if (status != bfd_reloc_ok)
2145         return status;
2146     }
2147   else
2148     reloc_entry->addend = val;
2149
2150   if (relocatable)
2151     reloc_entry->address += input_section->output_offset;
2152
2153   return bfd_reloc_ok;
2154 }
2155
2156 /* Used to store a REL high-part relocation such as R_MIPS_HI16 or
2157    R_MIPS_GOT16.  REL is the relocation, INPUT_SECTION is the section
2158    that contains the relocation field and DATA points to the start of
2159    INPUT_SECTION.  */
2160
2161 struct mips_hi16
2162 {
2163   struct mips_hi16 *next;
2164   bfd_byte *data;
2165   asection *input_section;
2166   arelent rel;
2167 };
2168
2169 /* FIXME: This should not be a static variable.  */
2170
2171 static struct mips_hi16 *mips_hi16_list;
2172
2173 /* A howto special_function for REL *HI16 relocations.  We can only
2174    calculate the correct value once we've seen the partnering
2175    *LO16 relocation, so just save the information for later.
2176
2177    The ABI requires that the *LO16 immediately follow the *HI16.
2178    However, as a GNU extension, we permit an arbitrary number of
2179    *HI16s to be associated with a single *LO16.  This significantly
2180    simplies the relocation handling in gcc.  */
2181
2182 bfd_reloc_status_type
2183 _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2184                           asymbol *symbol ATTRIBUTE_UNUSED, void *data,
2185                           asection *input_section, bfd *output_bfd,
2186                           char **error_message ATTRIBUTE_UNUSED)
2187 {
2188   struct mips_hi16 *n;
2189
2190   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2191     return bfd_reloc_outofrange;
2192
2193   n = bfd_malloc (sizeof *n);
2194   if (n == NULL)
2195     return bfd_reloc_outofrange;
2196
2197   n->next = mips_hi16_list;
2198   n->data = data;
2199   n->input_section = input_section;
2200   n->rel = *reloc_entry;
2201   mips_hi16_list = n;
2202
2203   if (output_bfd != NULL)
2204     reloc_entry->address += input_section->output_offset;
2205
2206   return bfd_reloc_ok;
2207 }
2208
2209 /* A howto special_function for REL R_MIPS*_GOT16 relocations.  This is just
2210    like any other 16-bit relocation when applied to global symbols, but is
2211    treated in the same as R_MIPS_HI16 when applied to local symbols.  */
2212
2213 bfd_reloc_status_type
2214 _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2215                            void *data, asection *input_section,
2216                            bfd *output_bfd, char **error_message)
2217 {
2218   if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2219       || bfd_is_und_section (bfd_get_section (symbol))
2220       || bfd_is_com_section (bfd_get_section (symbol)))
2221     /* The relocation is against a global symbol.  */
2222     return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2223                                         input_section, output_bfd,
2224                                         error_message);
2225
2226   return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
2227                                    input_section, output_bfd, error_message);
2228 }
2229
2230 /* A howto special_function for REL *LO16 relocations.  The *LO16 itself
2231    is a straightforward 16 bit inplace relocation, but we must deal with
2232    any partnering high-part relocations as well.  */
2233
2234 bfd_reloc_status_type
2235 _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2236                           void *data, asection *input_section,
2237                           bfd *output_bfd, char **error_message)
2238 {
2239   bfd_vma vallo;
2240   bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2241
2242   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2243     return bfd_reloc_outofrange;
2244
2245   _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2246                                  location);
2247   vallo = bfd_get_32 (abfd, location);
2248   _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2249                                location);
2250
2251   while (mips_hi16_list != NULL)
2252     {
2253       bfd_reloc_status_type ret;
2254       struct mips_hi16 *hi;
2255
2256       hi = mips_hi16_list;
2257
2258       /* R_MIPS*_GOT16 relocations are something of a special case.  We
2259          want to install the addend in the same way as for a R_MIPS*_HI16
2260          relocation (with a rightshift of 16).  However, since GOT16
2261          relocations can also be used with global symbols, their howto
2262          has a rightshift of 0.  */
2263       if (hi->rel.howto->type == R_MIPS_GOT16)
2264         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE);
2265       else if (hi->rel.howto->type == R_MIPS16_GOT16)
2266         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS16_HI16, FALSE);
2267       else if (hi->rel.howto->type == R_MICROMIPS_GOT16)
2268         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MICROMIPS_HI16, FALSE);
2269
2270       /* VALLO is a signed 16-bit number.  Bias it by 0x8000 so that any
2271          carry or borrow will induce a change of +1 or -1 in the high part.  */
2272       hi->rel.addend += (vallo + 0x8000) & 0xffff;
2273
2274       ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data,
2275                                          hi->input_section, output_bfd,
2276                                          error_message);
2277       if (ret != bfd_reloc_ok)
2278         return ret;
2279
2280       mips_hi16_list = hi->next;
2281       free (hi);
2282     }
2283
2284   return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2285                                       input_section, output_bfd,
2286                                       error_message);
2287 }
2288
2289 /* A generic howto special_function.  This calculates and installs the
2290    relocation itself, thus avoiding the oft-discussed problems in
2291    bfd_perform_relocation and bfd_install_relocation.  */
2292
2293 bfd_reloc_status_type
2294 _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2295                              asymbol *symbol, void *data ATTRIBUTE_UNUSED,
2296                              asection *input_section, bfd *output_bfd,
2297                              char **error_message ATTRIBUTE_UNUSED)
2298 {
2299   bfd_signed_vma val;
2300   bfd_reloc_status_type status;
2301   bfd_boolean relocatable;
2302
2303   relocatable = (output_bfd != NULL);
2304
2305   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2306     return bfd_reloc_outofrange;
2307
2308   /* Build up the field adjustment in VAL.  */
2309   val = 0;
2310   if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)
2311     {
2312       /* Either we're calculating the final field value or we have a
2313          relocation against a section symbol.  Add in the section's
2314          offset or address.  */
2315       val += symbol->section->output_section->vma;
2316       val += symbol->section->output_offset;
2317     }
2318
2319   if (!relocatable)
2320     {
2321       /* We're calculating the final field value.  Add in the symbol's value
2322          and, if pc-relative, subtract the address of the field itself.  */
2323       val += symbol->value;
2324       if (reloc_entry->howto->pc_relative)
2325         {
2326           val -= input_section->output_section->vma;
2327           val -= input_section->output_offset;
2328           val -= reloc_entry->address;
2329         }
2330     }
2331
2332   /* VAL is now the final adjustment.  If we're keeping this relocation
2333      in the output file, and if the relocation uses a separate addend,
2334      we just need to add VAL to that addend.  Otherwise we need to add
2335      VAL to the relocation field itself.  */
2336   if (relocatable && !reloc_entry->howto->partial_inplace)
2337     reloc_entry->addend += val;
2338   else
2339     {
2340       bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2341
2342       /* Add in the separate addend, if any.  */
2343       val += reloc_entry->addend;
2344
2345       /* Add VAL to the relocation field.  */
2346       _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2347                                      location);
2348       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2349                                        location);
2350       _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2351                                    location);
2352
2353       if (status != bfd_reloc_ok)
2354         return status;
2355     }
2356
2357   if (relocatable)
2358     reloc_entry->address += input_section->output_offset;
2359
2360   return bfd_reloc_ok;
2361 }
2362 \f
2363 /* Swap an entry in a .gptab section.  Note that these routines rely
2364    on the equivalence of the two elements of the union.  */
2365
2366 static void
2367 bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex,
2368                               Elf32_gptab *in)
2369 {
2370   in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value);
2371   in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes);
2372 }
2373
2374 static void
2375 bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in,
2376                                Elf32_External_gptab *ex)
2377 {
2378   H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value);
2379   H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes);
2380 }
2381
2382 static void
2383 bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in,
2384                                 Elf32_External_compact_rel *ex)
2385 {
2386   H_PUT_32 (abfd, in->id1, ex->id1);
2387   H_PUT_32 (abfd, in->num, ex->num);
2388   H_PUT_32 (abfd, in->id2, ex->id2);
2389   H_PUT_32 (abfd, in->offset, ex->offset);
2390   H_PUT_32 (abfd, in->reserved0, ex->reserved0);
2391   H_PUT_32 (abfd, in->reserved1, ex->reserved1);
2392 }
2393
2394 static void
2395 bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in,
2396                            Elf32_External_crinfo *ex)
2397 {
2398   unsigned long l;
2399
2400   l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH)
2401        | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH)
2402        | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH)
2403        | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH));
2404   H_PUT_32 (abfd, l, ex->info);
2405   H_PUT_32 (abfd, in->konst, ex->konst);
2406   H_PUT_32 (abfd, in->vaddr, ex->vaddr);
2407 }
2408 \f
2409 /* A .reginfo section holds a single Elf32_RegInfo structure.  These
2410    routines swap this structure in and out.  They are used outside of
2411    BFD, so they are globally visible.  */
2412
2413 void
2414 bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex,
2415                                 Elf32_RegInfo *in)
2416 {
2417   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2418   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2419   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2420   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2421   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2422   in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value);
2423 }
2424
2425 void
2426 bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in,
2427                                  Elf32_External_RegInfo *ex)
2428 {
2429   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2430   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2431   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2432   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2433   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2434   H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value);
2435 }
2436
2437 /* In the 64 bit ABI, the .MIPS.options section holds register
2438    information in an Elf64_Reginfo structure.  These routines swap
2439    them in and out.  They are globally visible because they are used
2440    outside of BFD.  These routines are here so that gas can call them
2441    without worrying about whether the 64 bit ABI has been included.  */
2442
2443 void
2444 bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex,
2445                                 Elf64_Internal_RegInfo *in)
2446 {
2447   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2448   in->ri_pad = H_GET_32 (abfd, ex->ri_pad);
2449   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2450   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2451   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2452   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2453   in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value);
2454 }
2455
2456 void
2457 bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in,
2458                                  Elf64_External_RegInfo *ex)
2459 {
2460   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2461   H_PUT_32 (abfd, in->ri_pad, ex->ri_pad);
2462   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2463   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2464   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2465   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2466   H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value);
2467 }
2468
2469 /* Swap in an options header.  */
2470
2471 void
2472 bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex,
2473                               Elf_Internal_Options *in)
2474 {
2475   in->kind = H_GET_8 (abfd, ex->kind);
2476   in->size = H_GET_8 (abfd, ex->size);
2477   in->section = H_GET_16 (abfd, ex->section);
2478   in->info = H_GET_32 (abfd, ex->info);
2479 }
2480
2481 /* Swap out an options header.  */
2482
2483 void
2484 bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in,
2485                                Elf_External_Options *ex)
2486 {
2487   H_PUT_8 (abfd, in->kind, ex->kind);
2488   H_PUT_8 (abfd, in->size, ex->size);
2489   H_PUT_16 (abfd, in->section, ex->section);
2490   H_PUT_32 (abfd, in->info, ex->info);
2491 }
2492 \f
2493 /* This function is called via qsort() to sort the dynamic relocation
2494    entries by increasing r_symndx value.  */
2495
2496 static int
2497 sort_dynamic_relocs (const void *arg1, const void *arg2)
2498 {
2499   Elf_Internal_Rela int_reloc1;
2500   Elf_Internal_Rela int_reloc2;
2501   int diff;
2502
2503   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
2504   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
2505
2506   diff = ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info);
2507   if (diff != 0)
2508     return diff;
2509
2510   if (int_reloc1.r_offset < int_reloc2.r_offset)
2511     return -1;
2512   if (int_reloc1.r_offset > int_reloc2.r_offset)
2513     return 1;
2514   return 0;
2515 }
2516
2517 /* Like sort_dynamic_relocs, but used for elf64 relocations.  */
2518
2519 static int
2520 sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED,
2521                         const void *arg2 ATTRIBUTE_UNUSED)
2522 {
2523 #ifdef BFD64
2524   Elf_Internal_Rela int_reloc1[3];
2525   Elf_Internal_Rela int_reloc2[3];
2526
2527   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2528     (reldyn_sorting_bfd, arg1, int_reloc1);
2529   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2530     (reldyn_sorting_bfd, arg2, int_reloc2);
2531
2532   if (ELF64_R_SYM (int_reloc1[0].r_info) < ELF64_R_SYM (int_reloc2[0].r_info))
2533     return -1;
2534   if (ELF64_R_SYM (int_reloc1[0].r_info) > ELF64_R_SYM (int_reloc2[0].r_info))
2535     return 1;
2536
2537   if (int_reloc1[0].r_offset < int_reloc2[0].r_offset)
2538     return -1;
2539   if (int_reloc1[0].r_offset > int_reloc2[0].r_offset)
2540     return 1;
2541   return 0;
2542 #else
2543   abort ();
2544 #endif
2545 }
2546
2547
2548 /* This routine is used to write out ECOFF debugging external symbol
2549    information.  It is called via mips_elf_link_hash_traverse.  The
2550    ECOFF external symbol information must match the ELF external
2551    symbol information.  Unfortunately, at this point we don't know
2552    whether a symbol is required by reloc information, so the two
2553    tables may wind up being different.  We must sort out the external
2554    symbol information before we can set the final size of the .mdebug
2555    section, and we must set the size of the .mdebug section before we
2556    can relocate any sections, and we can't know which symbols are
2557    required by relocation until we relocate the sections.
2558    Fortunately, it is relatively unlikely that any symbol will be
2559    stripped but required by a reloc.  In particular, it can not happen
2560    when generating a final executable.  */
2561
2562 static bfd_boolean
2563 mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data)
2564 {
2565   struct extsym_info *einfo = data;
2566   bfd_boolean strip;
2567   asection *sec, *output_section;
2568
2569   if (h->root.indx == -2)
2570     strip = FALSE;
2571   else if ((h->root.def_dynamic
2572             || h->root.ref_dynamic
2573             || h->root.type == bfd_link_hash_new)
2574            && !h->root.def_regular
2575            && !h->root.ref_regular)
2576     strip = TRUE;
2577   else if (einfo->info->strip == strip_all
2578            || (einfo->info->strip == strip_some
2579                && bfd_hash_lookup (einfo->info->keep_hash,
2580                                    h->root.root.root.string,
2581                                    FALSE, FALSE) == NULL))
2582     strip = TRUE;
2583   else
2584     strip = FALSE;
2585
2586   if (strip)
2587     return TRUE;
2588
2589   if (h->esym.ifd == -2)
2590     {
2591       h->esym.jmptbl = 0;
2592       h->esym.cobol_main = 0;
2593       h->esym.weakext = 0;
2594       h->esym.reserved = 0;
2595       h->esym.ifd = ifdNil;
2596       h->esym.asym.value = 0;
2597       h->esym.asym.st = stGlobal;
2598
2599       if (h->root.root.type == bfd_link_hash_undefined
2600           || h->root.root.type == bfd_link_hash_undefweak)
2601         {
2602           const char *name;
2603
2604           /* Use undefined class.  Also, set class and type for some
2605              special symbols.  */
2606           name = h->root.root.root.string;
2607           if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
2608               || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
2609             {
2610               h->esym.asym.sc = scData;
2611               h->esym.asym.st = stLabel;
2612               h->esym.asym.value = 0;
2613             }
2614           else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
2615             {
2616               h->esym.asym.sc = scAbs;
2617               h->esym.asym.st = stLabel;
2618               h->esym.asym.value =
2619                 mips_elf_hash_table (einfo->info)->procedure_count;
2620             }
2621           else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd))
2622             {
2623               h->esym.asym.sc = scAbs;
2624               h->esym.asym.st = stLabel;
2625               h->esym.asym.value = elf_gp (einfo->abfd);
2626             }
2627           else
2628             h->esym.asym.sc = scUndefined;
2629         }
2630       else if (h->root.root.type != bfd_link_hash_defined
2631           && h->root.root.type != bfd_link_hash_defweak)
2632         h->esym.asym.sc = scAbs;
2633       else
2634         {
2635           const char *name;
2636
2637           sec = h->root.root.u.def.section;
2638           output_section = sec->output_section;
2639
2640           /* When making a shared library and symbol h is the one from
2641              the another shared library, OUTPUT_SECTION may be null.  */
2642           if (output_section == NULL)
2643             h->esym.asym.sc = scUndefined;
2644           else
2645             {
2646               name = bfd_section_name (output_section->owner, output_section);
2647
2648               if (strcmp (name, ".text") == 0)
2649                 h->esym.asym.sc = scText;
2650               else if (strcmp (name, ".data") == 0)
2651                 h->esym.asym.sc = scData;
2652               else if (strcmp (name, ".sdata") == 0)
2653                 h->esym.asym.sc = scSData;
2654               else if (strcmp (name, ".rodata") == 0
2655                        || strcmp (name, ".rdata") == 0)
2656                 h->esym.asym.sc = scRData;
2657               else if (strcmp (name, ".bss") == 0)
2658                 h->esym.asym.sc = scBss;
2659               else if (strcmp (name, ".sbss") == 0)
2660                 h->esym.asym.sc = scSBss;
2661               else if (strcmp (name, ".init") == 0)
2662                 h->esym.asym.sc = scInit;
2663               else if (strcmp (name, ".fini") == 0)
2664                 h->esym.asym.sc = scFini;
2665               else
2666                 h->esym.asym.sc = scAbs;
2667             }
2668         }
2669
2670       h->esym.asym.reserved = 0;
2671       h->esym.asym.index = indexNil;
2672     }
2673
2674   if (h->root.root.type == bfd_link_hash_common)
2675     h->esym.asym.value = h->root.root.u.c.size;
2676   else if (h->root.root.type == bfd_link_hash_defined
2677            || h->root.root.type == bfd_link_hash_defweak)
2678     {
2679       if (h->esym.asym.sc == scCommon)
2680         h->esym.asym.sc = scBss;
2681       else if (h->esym.asym.sc == scSCommon)
2682         h->esym.asym.sc = scSBss;
2683
2684       sec = h->root.root.u.def.section;
2685       output_section = sec->output_section;
2686       if (output_section != NULL)
2687         h->esym.asym.value = (h->root.root.u.def.value
2688                               + sec->output_offset
2689                               + output_section->vma);
2690       else
2691         h->esym.asym.value = 0;
2692     }
2693   else
2694     {
2695       struct mips_elf_link_hash_entry *hd = h;
2696
2697       while (hd->root.root.type == bfd_link_hash_indirect)
2698         hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link;
2699
2700       if (hd->needs_lazy_stub)
2701         {
2702           /* Set type and value for a symbol with a function stub.  */
2703           h->esym.asym.st = stProc;
2704           sec = hd->root.root.u.def.section;
2705           if (sec == NULL)
2706             h->esym.asym.value = 0;
2707           else
2708             {
2709               output_section = sec->output_section;
2710               if (output_section != NULL)
2711                 h->esym.asym.value = (hd->root.plt.offset
2712                                       + sec->output_offset
2713                                       + output_section->vma);
2714               else
2715                 h->esym.asym.value = 0;
2716             }
2717         }
2718     }
2719
2720   if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap,
2721                                       h->root.root.root.string,
2722                                       &h->esym))
2723     {
2724       einfo->failed = TRUE;
2725       return FALSE;
2726     }
2727
2728   return TRUE;
2729 }
2730
2731 /* A comparison routine used to sort .gptab entries.  */
2732
2733 static int
2734 gptab_compare (const void *p1, const void *p2)
2735 {
2736   const Elf32_gptab *a1 = p1;
2737   const Elf32_gptab *a2 = p2;
2738
2739   return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value;
2740 }
2741 \f
2742 /* Functions to manage the got entry hash table.  */
2743
2744 /* Use all 64 bits of a bfd_vma for the computation of a 32-bit
2745    hash number.  */
2746
2747 static INLINE hashval_t
2748 mips_elf_hash_bfd_vma (bfd_vma addr)
2749 {
2750 #ifdef BFD64
2751   return addr + (addr >> 32);
2752 #else
2753   return addr;
2754 #endif
2755 }
2756
2757 static hashval_t
2758 mips_elf_got_entry_hash (const void *entry_)
2759 {
2760   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2761
2762   return (entry->symndx
2763           + (((entry->tls_type & GOT_TLS_TYPE) == GOT_TLS_LDM) << 18)
2764           + ((entry->tls_type & GOT_TLS_TYPE) == GOT_TLS_LDM ? 0
2765              : !entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address)
2766              : entry->symndx >= 0 ? (entry->abfd->id
2767                                      + mips_elf_hash_bfd_vma (entry->d.addend))
2768              : entry->d.h->root.root.root.hash));
2769 }
2770
2771 static int
2772 mips_elf_got_entry_eq (const void *entry1, const void *entry2)
2773 {
2774   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2775   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2776
2777   return (e1->symndx == e2->symndx
2778           && (e1->tls_type & GOT_TLS_TYPE) == (e2->tls_type & GOT_TLS_TYPE)
2779           && ((e1->tls_type & GOT_TLS_TYPE) == GOT_TLS_LDM ? TRUE
2780               : !e1->abfd ? !e2->abfd && e1->d.address == e2->d.address
2781               : e1->symndx >= 0 ? (e1->abfd == e2->abfd
2782                                    && e1->d.addend == e2->d.addend)
2783               : e2->abfd && e1->d.h == e2->d.h));
2784 }
2785
2786 static hashval_t
2787 mips_got_page_entry_hash (const void *entry_)
2788 {
2789   const struct mips_got_page_entry *entry;
2790
2791   entry = (const struct mips_got_page_entry *) entry_;
2792   return entry->abfd->id + entry->symndx;
2793 }
2794
2795 static int
2796 mips_got_page_entry_eq (const void *entry1_, const void *entry2_)
2797 {
2798   const struct mips_got_page_entry *entry1, *entry2;
2799
2800   entry1 = (const struct mips_got_page_entry *) entry1_;
2801   entry2 = (const struct mips_got_page_entry *) entry2_;
2802   return entry1->abfd == entry2->abfd && entry1->symndx == entry2->symndx;
2803 }
2804 \f
2805 /* Create and return a new mips_got_info structure.  */
2806
2807 static struct mips_got_info *
2808 mips_elf_create_got_info (bfd *abfd)
2809 {
2810   struct mips_got_info *g;
2811
2812   g = bfd_zalloc (abfd, sizeof (struct mips_got_info));
2813   if (g == NULL)
2814     return NULL;
2815
2816   g->tls_ldm_offset = MINUS_ONE;
2817   g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
2818                                     mips_elf_got_entry_eq, NULL);
2819   if (g->got_entries == NULL)
2820     return NULL;
2821
2822   g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
2823                                          mips_got_page_entry_eq, NULL);
2824   if (g->got_page_entries == NULL)
2825     return NULL;
2826
2827   return g;
2828 }
2829
2830 /* Return the GOT info for input bfd ABFD, trying to create a new one if
2831    CREATE_P and if ABFD doesn't already have a GOT.  */
2832
2833 static struct mips_got_info *
2834 mips_elf_bfd_got (bfd *abfd, bfd_boolean create_p)
2835 {
2836   struct mips_elf_obj_tdata *tdata;
2837
2838   if (!is_mips_elf (abfd))
2839     return NULL;
2840
2841   tdata = mips_elf_tdata (abfd);
2842   if (!tdata->got && create_p)
2843     tdata->got = mips_elf_create_got_info (abfd);
2844   return tdata->got;
2845 }
2846
2847 /* Record that ABFD should use output GOT G.  */
2848
2849 static void
2850 mips_elf_replace_bfd_got (bfd *abfd, struct mips_got_info *g)
2851 {
2852   struct mips_elf_obj_tdata *tdata;
2853
2854   BFD_ASSERT (is_mips_elf (abfd));
2855   tdata = mips_elf_tdata (abfd);
2856   if (tdata->got)
2857     {
2858       /* The GOT structure itself and the hash table entries are
2859          allocated to a bfd, but the hash tables aren't.  */
2860       htab_delete (tdata->got->got_entries);
2861       htab_delete (tdata->got->got_page_entries);
2862     }
2863   tdata->got = g;
2864 }
2865
2866 /* Return the dynamic relocation section.  If it doesn't exist, try to
2867    create a new it if CREATE_P, otherwise return NULL.  Also return NULL
2868    if creation fails.  */
2869
2870 static asection *
2871 mips_elf_rel_dyn_section (struct bfd_link_info *info, bfd_boolean create_p)
2872 {
2873   const char *dname;
2874   asection *sreloc;
2875   bfd *dynobj;
2876
2877   dname = MIPS_ELF_REL_DYN_NAME (info);
2878   dynobj = elf_hash_table (info)->dynobj;
2879   sreloc = bfd_get_linker_section (dynobj, dname);
2880   if (sreloc == NULL && create_p)
2881     {
2882       sreloc = bfd_make_section_anyway_with_flags (dynobj, dname,
2883                                                    (SEC_ALLOC
2884                                                     | SEC_LOAD
2885                                                     | SEC_HAS_CONTENTS
2886                                                     | SEC_IN_MEMORY
2887                                                     | SEC_LINKER_CREATED
2888                                                     | SEC_READONLY));
2889       if (sreloc == NULL
2890           || ! bfd_set_section_alignment (dynobj, sreloc,
2891                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
2892         return NULL;
2893     }
2894   return sreloc;
2895 }
2896
2897 /* Return the GOT_TLS_* type required by relocation type R_TYPE.  */
2898
2899 static int
2900 mips_elf_reloc_tls_type (unsigned int r_type)
2901 {
2902   if (tls_gd_reloc_p (r_type))
2903     return GOT_TLS_GD;
2904
2905   if (tls_ldm_reloc_p (r_type))
2906     return GOT_TLS_LDM;
2907
2908   if (tls_gottprel_reloc_p (r_type))
2909     return GOT_TLS_IE;
2910
2911   return GOT_NORMAL;
2912 }
2913
2914 /* Return the number of GOT slots needed for GOT TLS type TYPE.  */
2915
2916 static int
2917 mips_tls_got_entries (unsigned int type)
2918 {
2919   switch (type)
2920     {
2921     case GOT_TLS_GD:
2922     case GOT_TLS_LDM:
2923       return 2;
2924
2925     case GOT_TLS_IE:
2926       return 1;
2927
2928     case GOT_NORMAL:
2929       return 0;
2930     }
2931   abort ();
2932 }
2933
2934 /* Count the number of relocations needed for a TLS GOT entry, with
2935    access types from TLS_TYPE, and symbol H (or a local symbol if H
2936    is NULL).  */
2937
2938 static int
2939 mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type,
2940                      struct elf_link_hash_entry *h)
2941 {
2942   int indx = 0;
2943   bfd_boolean need_relocs = FALSE;
2944   bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
2945
2946   if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, h)
2947       && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, h)))
2948     indx = h->dynindx;
2949
2950   if ((info->shared || indx != 0)
2951       && (h == NULL
2952           || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2953           || h->root.type != bfd_link_hash_undefweak))
2954     need_relocs = TRUE;
2955
2956   if (!need_relocs)
2957     return 0;
2958
2959   switch (tls_type & GOT_TLS_TYPE)
2960     {
2961     case GOT_TLS_GD:
2962       return indx != 0 ? 2 : 1;
2963
2964     case GOT_TLS_IE:
2965       return 1;
2966
2967     case GOT_TLS_LDM:
2968       return info->shared ? 1 : 0;
2969
2970     default:
2971       return 0;
2972     }
2973 }
2974
2975 /* Add the number of GOT entries and TLS relocations required by ENTRY
2976    to G.  */
2977
2978 static void
2979 mips_elf_count_got_entry (struct bfd_link_info *info,
2980                           struct mips_got_info *g,
2981                           struct mips_got_entry *entry)
2982 {
2983   unsigned char tls_type;
2984
2985   tls_type = entry->tls_type & GOT_TLS_TYPE;
2986   if (tls_type)
2987     {
2988       g->tls_gotno += mips_tls_got_entries (tls_type);
2989       g->relocs += mips_tls_got_relocs (info, tls_type,
2990                                         entry->symndx < 0
2991                                         ? &entry->d.h->root : NULL);
2992     }
2993   else if (entry->symndx >= 0 || entry->d.h->global_got_area == GGA_NONE)
2994     g->local_gotno += 1;
2995   else
2996     g->global_gotno += 1;
2997 }
2998
2999 /* A htab_traverse callback.  Count the number of GOT entries and
3000    TLS relocations required for the GOT entry in *ENTRYP.  DATA points
3001    to a mips_elf_traverse_got_arg structure.  */
3002
3003 static int
3004 mips_elf_count_got_entries (void **entryp, void *data)
3005 {
3006   struct mips_got_entry *entry;
3007   struct mips_elf_traverse_got_arg *arg;
3008
3009   entry = (struct mips_got_entry *) *entryp;
3010   arg = (struct mips_elf_traverse_got_arg *) data;
3011   mips_elf_count_got_entry (arg->info, arg->g, entry);
3012
3013   return 1;
3014 }
3015
3016 /* A htab_traverse callback.  If *SLOT describes a GOT entry for a local
3017    symbol, count the number of GOT entries and TLS relocations that it
3018    requires.  DATA points to a mips_elf_traverse_got_arg structure.  */
3019
3020 static int
3021 mips_elf_count_local_got_entries (void **entryp, void *data)
3022 {
3023   struct mips_got_entry *entry;
3024   struct mips_elf_traverse_got_arg *arg;
3025
3026   entry = (struct mips_got_entry *) *entryp;
3027   arg = (struct mips_elf_traverse_got_arg *) data;
3028   if (entry->abfd != NULL && entry->symndx != -1)
3029     {
3030       if ((entry->tls_type & GOT_TLS_TYPE) == GOT_TLS_LDM)
3031         {
3032           if (arg->g->tls_ldm_offset == MINUS_TWO)
3033             return 1;
3034           arg->g->tls_ldm_offset = MINUS_TWO;
3035         }
3036       mips_elf_count_got_entry (arg->info, arg->g, entry);
3037     }
3038
3039   return 1;
3040 }
3041
3042 /* Count the number of TLS GOT entries and relocationss required for the
3043    global (or forced-local) symbol in ARG1.  */
3044
3045 static int
3046 mips_elf_count_global_tls_entries (void *entry, void *data)
3047 {
3048   struct mips_elf_link_hash_entry *hm;
3049   struct mips_elf_traverse_got_arg *arg;
3050
3051   hm = (struct mips_elf_link_hash_entry *) entry;
3052   if (hm->root.root.type == bfd_link_hash_indirect
3053       || hm->root.root.type == bfd_link_hash_warning)
3054     return 1;
3055
3056   arg = (struct mips_elf_traverse_got_arg *) data;
3057   if (hm->tls_gd_type)
3058     {
3059       arg->g->tls_gotno += 2;
3060       arg->g->relocs += mips_tls_got_relocs (arg->info, hm->tls_gd_type,
3061                                              &hm->root);
3062     }
3063   if (hm->tls_ie_type)
3064     {
3065       arg->g->tls_gotno += 1;
3066       arg->g->relocs += mips_tls_got_relocs (arg->info, hm->tls_ie_type,
3067                                              &hm->root);
3068     }
3069
3070   return 1;
3071 }
3072
3073 /* Output a simple dynamic relocation into SRELOC.  */
3074
3075 static void
3076 mips_elf_output_dynamic_relocation (bfd *output_bfd,
3077                                     asection *sreloc,
3078                                     unsigned long reloc_index,
3079                                     unsigned long indx,
3080                                     int r_type,
3081                                     bfd_vma offset)
3082 {
3083   Elf_Internal_Rela rel[3];
3084
3085   memset (rel, 0, sizeof (rel));
3086
3087   rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type);
3088   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
3089
3090   if (ABI_64_P (output_bfd))
3091     {
3092       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
3093         (output_bfd, &rel[0],
3094          (sreloc->contents
3095           + reloc_index * sizeof (Elf64_Mips_External_Rel)));
3096     }
3097   else
3098     bfd_elf32_swap_reloc_out
3099       (output_bfd, &rel[0],
3100        (sreloc->contents
3101         + reloc_index * sizeof (Elf32_External_Rel)));
3102 }
3103
3104 /* Initialize a set of TLS GOT entries for one symbol.  */
3105
3106 static void
3107 mips_elf_initialize_tls_slots (bfd *abfd, bfd_vma got_offset,
3108                                unsigned char *tls_type_p,
3109                                struct bfd_link_info *info,
3110                                struct mips_elf_link_hash_entry *h,
3111                                bfd_vma value)
3112 {
3113   struct mips_elf_link_hash_table *htab;
3114   int indx;
3115   asection *sreloc, *sgot;
3116   bfd_vma got_offset2;
3117   bfd_boolean need_relocs = FALSE;
3118
3119   htab = mips_elf_hash_table (info);
3120   if (htab == NULL)
3121     return;
3122
3123   sgot = htab->sgot;
3124
3125   indx = 0;
3126   if (h != NULL)
3127     {
3128       bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3129
3130       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, &h->root)
3131           && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3132         indx = h->root.dynindx;
3133     }
3134
3135   if (*tls_type_p & GOT_TLS_DONE)
3136     return;
3137
3138   if ((info->shared || indx != 0)
3139       && (h == NULL
3140           || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT
3141           || h->root.type != bfd_link_hash_undefweak))
3142     need_relocs = TRUE;
3143
3144   /* MINUS_ONE means the symbol is not defined in this object.  It may not
3145      be defined at all; assume that the value doesn't matter in that
3146      case.  Otherwise complain if we would use the value.  */
3147   BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs)
3148               || h->root.root.type == bfd_link_hash_undefweak);
3149
3150   /* Emit necessary relocations.  */
3151   sreloc = mips_elf_rel_dyn_section (info, FALSE);
3152
3153   switch (*tls_type_p & GOT_TLS_TYPE)
3154     {
3155     case GOT_TLS_GD:
3156       /* General Dynamic.  */
3157       got_offset2 = got_offset + MIPS_ELF_GOT_SIZE (abfd);
3158
3159       if (need_relocs)
3160         {
3161           mips_elf_output_dynamic_relocation
3162             (abfd, sreloc, sreloc->reloc_count++, indx,
3163              ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3164              sgot->output_offset + sgot->output_section->vma + got_offset);
3165
3166           if (indx)
3167             mips_elf_output_dynamic_relocation
3168               (abfd, sreloc, sreloc->reloc_count++, indx,
3169                ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32,
3170                sgot->output_offset + sgot->output_section->vma + got_offset2);
3171           else
3172             MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3173                                sgot->contents + got_offset2);
3174         }
3175       else
3176         {
3177           MIPS_ELF_PUT_WORD (abfd, 1,
3178                              sgot->contents + got_offset);
3179           MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3180                              sgot->contents + got_offset2);
3181         }
3182       break;
3183
3184     case GOT_TLS_IE:
3185       /* Initial Exec model.  */
3186       if (need_relocs)
3187         {
3188           if (indx == 0)
3189             MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma,
3190                                sgot->contents + got_offset);
3191           else
3192             MIPS_ELF_PUT_WORD (abfd, 0,
3193                                sgot->contents + got_offset);
3194
3195           mips_elf_output_dynamic_relocation
3196             (abfd, sreloc, sreloc->reloc_count++, indx,
3197              ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32,
3198              sgot->output_offset + sgot->output_section->vma + got_offset);
3199         }
3200       else
3201         MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info),
3202                            sgot->contents + got_offset);
3203       break;
3204
3205     case GOT_TLS_LDM:
3206       /* The initial offset is zero, and the LD offsets will include the
3207          bias by DTP_OFFSET.  */
3208       MIPS_ELF_PUT_WORD (abfd, 0,
3209                          sgot->contents + got_offset
3210                          + MIPS_ELF_GOT_SIZE (abfd));
3211
3212       if (!info->shared)
3213         MIPS_ELF_PUT_WORD (abfd, 1,
3214                            sgot->contents + got_offset);
3215       else
3216         mips_elf_output_dynamic_relocation
3217           (abfd, sreloc, sreloc->reloc_count++, indx,
3218            ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3219            sgot->output_offset + sgot->output_section->vma + got_offset);
3220       break;
3221
3222     default:
3223       abort ();
3224     }
3225
3226   *tls_type_p |= GOT_TLS_DONE;
3227 }
3228
3229 /* Return the GOT index to use for a relocation against H using the
3230    TLS model in *TLS_TYPE.  The GOT entries for this symbol/model
3231    combination start at GOT_INDEX into ABFD's GOT.  This function
3232    initializes the GOT entries and corresponding relocations.  */
3233
3234 static bfd_vma
3235 mips_tls_got_index (bfd *abfd, bfd_vma got_index, unsigned char *tls_type,
3236                     struct bfd_link_info *info,
3237                     struct mips_elf_link_hash_entry *h, bfd_vma symbol)
3238 {
3239   mips_elf_initialize_tls_slots (abfd, got_index, tls_type, info, h, symbol);
3240   return got_index;
3241 }
3242
3243 /* Return the GOT index to use for a relocation of type R_TYPE against H
3244    in ABFD.  */
3245
3246 static bfd_vma
3247 mips_tls_single_got_index (bfd *abfd, int r_type, struct bfd_link_info *info,
3248                            struct mips_elf_link_hash_entry *h, bfd_vma symbol)
3249 {
3250   if (tls_gottprel_reloc_p (r_type))
3251     return mips_tls_got_index (abfd, h->tls_ie_got_offset, &h->tls_ie_type,
3252                                info, h, symbol);
3253   if (tls_gd_reloc_p (r_type))
3254     return mips_tls_got_index (abfd, h->tls_gd_got_offset, &h->tls_gd_type,
3255                                info, h, symbol);
3256   abort ();
3257 }
3258
3259 /* Return the offset from _GLOBAL_OFFSET_TABLE_ of the .got.plt entry
3260    for global symbol H.  .got.plt comes before the GOT, so the offset
3261    will be negative.  */
3262
3263 static bfd_vma
3264 mips_elf_gotplt_index (struct bfd_link_info *info,
3265                        struct elf_link_hash_entry *h)
3266 {
3267   bfd_vma plt_index, got_address, got_value;
3268   struct mips_elf_link_hash_table *htab;
3269
3270   htab = mips_elf_hash_table (info);
3271   BFD_ASSERT (htab != NULL);
3272
3273   BFD_ASSERT (h->plt.offset != (bfd_vma) -1);
3274
3275   /* This function only works for VxWorks, because a non-VxWorks .got.plt
3276      section starts with reserved entries.  */
3277   BFD_ASSERT (htab->is_vxworks);
3278
3279   /* Calculate the index of the symbol's PLT entry.  */
3280   plt_index = (h->plt.offset - htab->plt_header_size) / htab->plt_entry_size;
3281
3282   /* Calculate the address of the associated .got.plt entry.  */
3283   got_address = (htab->sgotplt->output_section->vma
3284                  + htab->sgotplt->output_offset
3285                  + plt_index * 4);
3286
3287   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
3288   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
3289                + htab->root.hgot->root.u.def.section->output_offset
3290                + htab->root.hgot->root.u.def.value);
3291
3292   return got_address - got_value;
3293 }
3294
3295 /* Return the GOT offset for address VALUE.   If there is not yet a GOT
3296    entry for this value, create one.  If R_SYMNDX refers to a TLS symbol,
3297    create a TLS GOT entry instead.  Return -1 if no satisfactory GOT
3298    offset can be found.  */
3299
3300 static bfd_vma
3301 mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3302                           bfd_vma value, unsigned long r_symndx,
3303                           struct mips_elf_link_hash_entry *h, int r_type)
3304 {
3305   struct mips_elf_link_hash_table *htab;
3306   struct mips_got_entry *entry;
3307
3308   htab = mips_elf_hash_table (info);
3309   BFD_ASSERT (htab != NULL);
3310
3311   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value,
3312                                            r_symndx, h, r_type);
3313   if (!entry)
3314     return MINUS_ONE;
3315
3316   if (entry->tls_type)
3317     {
3318       if (entry->symndx == -1 && htab->got_info->next == NULL)
3319         /* A type (3) entry in the single-GOT case.  We use the symbol's
3320            hash table entry to track the index.  */
3321         return mips_tls_single_got_index (abfd, r_type, info, h, value);
3322       else
3323         return mips_tls_got_index (abfd, entry->gotidx, &entry->tls_type,
3324                                    info, h, value);
3325     }
3326   else
3327     return entry->gotidx;
3328 }
3329
3330 /* Return the GOT index of global symbol H in the primary GOT.  */
3331
3332 static bfd_vma
3333 mips_elf_primary_global_got_index (bfd *obfd, struct bfd_link_info *info,
3334                                    struct elf_link_hash_entry *h)
3335 {
3336   struct mips_elf_link_hash_table *htab;
3337   long global_got_dynindx;
3338   struct mips_got_info *g;
3339   bfd_vma got_index;
3340
3341   htab = mips_elf_hash_table (info);
3342   BFD_ASSERT (htab != NULL);
3343
3344   global_got_dynindx = 0;
3345   if (htab->global_gotsym != NULL)
3346     global_got_dynindx = htab->global_gotsym->dynindx;
3347
3348   /* Once we determine the global GOT entry with the lowest dynamic
3349      symbol table index, we must put all dynamic symbols with greater
3350      indices into the primary GOT.  That makes it easy to calculate the
3351      GOT offset.  */
3352   BFD_ASSERT (h->dynindx >= global_got_dynindx);
3353   g = mips_elf_bfd_got (obfd, FALSE);
3354   got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3355                * MIPS_ELF_GOT_SIZE (obfd));
3356   BFD_ASSERT (got_index < htab->sgot->size);
3357
3358   return got_index;
3359 }
3360
3361 /* Return the GOT index for the global symbol indicated by H, which is
3362    referenced by a relocation of type R_TYPE in IBFD.  */
3363
3364 static bfd_vma
3365 mips_elf_global_got_index (bfd *obfd, struct bfd_link_info *info, bfd *ibfd,
3366                            struct elf_link_hash_entry *h, int r_type)
3367 {
3368   struct mips_elf_link_hash_table *htab;
3369   bfd_vma got_index;
3370   struct mips_got_info *g, *gg;
3371
3372   htab = mips_elf_hash_table (info);
3373   BFD_ASSERT (htab != NULL);
3374
3375   gg = g = htab->got_info;
3376   if (g->next && ibfd)
3377     {
3378       struct mips_got_entry e, *p;
3379
3380       BFD_ASSERT (h->dynindx >= 0);
3381
3382       g = mips_elf_bfd_got (ibfd, FALSE);
3383       BFD_ASSERT (g);
3384       if (g->next != gg || TLS_RELOC_P (r_type))
3385         {
3386           e.abfd = ibfd;
3387           e.symndx = -1;
3388           e.d.h = (struct mips_elf_link_hash_entry *)h;
3389           e.tls_type = mips_elf_reloc_tls_type (r_type);
3390
3391           p = htab_find (g->got_entries, &e);
3392
3393           BFD_ASSERT (p && p->gotidx > 0);
3394
3395           if (p->tls_type)
3396             {
3397               bfd_vma value = MINUS_ONE;
3398               if ((h->root.type == bfd_link_hash_defined
3399                    || h->root.type == bfd_link_hash_defweak)
3400                   && h->root.u.def.section->output_section)
3401                 value = (h->root.u.def.value
3402                          + h->root.u.def.section->output_offset
3403                          + h->root.u.def.section->output_section->vma);
3404
3405               return mips_tls_got_index (obfd, p->gotidx, &p->tls_type,
3406                                          info, e.d.h, value);
3407             }
3408           else
3409             return p->gotidx;
3410         }
3411     }
3412
3413   if (TLS_RELOC_P (r_type))
3414     {
3415       struct mips_elf_link_hash_entry *hm
3416         = (struct mips_elf_link_hash_entry *) h;
3417       bfd_vma value = MINUS_ONE;
3418
3419       if ((h->root.type == bfd_link_hash_defined
3420            || h->root.type == bfd_link_hash_defweak)
3421           && h->root.u.def.section->output_section)
3422         value = (h->root.u.def.value
3423                  + h->root.u.def.section->output_offset
3424                  + h->root.u.def.section->output_section->vma);
3425
3426       got_index = mips_tls_single_got_index (obfd, r_type, info, hm, value);
3427     }
3428   else
3429     got_index = mips_elf_primary_global_got_index (obfd, info, h);
3430   BFD_ASSERT (got_index < htab->sgot->size);
3431
3432   return got_index;
3433 }
3434
3435 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3436    entries are supposed to be placed at small offsets in the GOT, i.e.,
3437    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3438    entry could be created.  If OFFSETP is nonnull, use it to return the
3439    offset of the GOT entry from VALUE.  */
3440
3441 static bfd_vma
3442 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3443                    bfd_vma value, bfd_vma *offsetp)
3444 {
3445   bfd_vma page, got_index;
3446   struct mips_got_entry *entry;
3447
3448   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3449   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3450                                            NULL, R_MIPS_GOT_PAGE);
3451
3452   if (!entry)
3453     return MINUS_ONE;
3454
3455   got_index = entry->gotidx;
3456
3457   if (offsetp)
3458     *offsetp = value - entry->d.address;
3459
3460   return got_index;
3461 }
3462
3463 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3464    EXTERNAL is true if the relocation was originally against a global
3465    symbol that binds locally.  */
3466
3467 static bfd_vma
3468 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3469                       bfd_vma value, bfd_boolean external)
3470 {
3471   struct mips_got_entry *entry;
3472
3473   /* GOT16 relocations against local symbols are followed by a LO16
3474      relocation; those against global symbols are not.  Thus if the
3475      symbol was originally local, the GOT16 relocation should load the
3476      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3477   if (! external)
3478     value = mips_elf_high (value) << 16;
3479
3480   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3481      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3482      same in all cases.  */
3483   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3484                                            NULL, R_MIPS_GOT16);
3485   if (entry)
3486     return entry->gotidx;
3487   else
3488     return MINUS_ONE;
3489 }
3490
3491 /* Returns the offset for the entry at the INDEXth position
3492    in the GOT.  */
3493
3494 static bfd_vma
3495 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3496                                 bfd *input_bfd, bfd_vma got_index)
3497 {
3498   struct mips_elf_link_hash_table *htab;
3499   asection *sgot;
3500   bfd_vma gp;
3501
3502   htab = mips_elf_hash_table (info);
3503   BFD_ASSERT (htab != NULL);
3504
3505   sgot = htab->sgot;
3506   gp = _bfd_get_gp_value (output_bfd)
3507     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3508
3509   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3510 }
3511
3512 /* Create and return a local GOT entry for VALUE, which was calculated
3513    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3514    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3515    instead.  */
3516
3517 static struct mips_got_entry *
3518 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3519                                  bfd *ibfd, bfd_vma value,
3520                                  unsigned long r_symndx,
3521                                  struct mips_elf_link_hash_entry *h,
3522                                  int r_type)
3523 {
3524   struct mips_got_entry lookup, *entry;
3525   void **loc;
3526   struct mips_got_info *g;
3527   struct mips_elf_link_hash_table *htab;
3528
3529   htab = mips_elf_hash_table (info);
3530   BFD_ASSERT (htab != NULL);
3531
3532   g = mips_elf_bfd_got (ibfd, FALSE);
3533   if (g == NULL)
3534     {
3535       g = mips_elf_bfd_got (abfd, FALSE);
3536       BFD_ASSERT (g != NULL);
3537     }
3538
3539   /* This function shouldn't be called for symbols that live in the global
3540      area of the GOT.  */
3541   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3542
3543   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3544   if (lookup.tls_type)
3545     {
3546       lookup.abfd = ibfd;
3547       if (tls_ldm_reloc_p (r_type))
3548         {
3549           lookup.symndx = 0;
3550           lookup.d.addend = 0;
3551         }
3552       else if (h == NULL)
3553         {
3554           lookup.symndx = r_symndx;
3555           lookup.d.addend = 0;
3556         }
3557       else
3558         {
3559           lookup.symndx = -1;
3560           lookup.d.h = h;
3561         }
3562
3563       entry = (struct mips_got_entry *) htab_find (g->got_entries, &lookup);
3564       BFD_ASSERT (entry);
3565
3566       return entry;
3567     }
3568
3569   lookup.abfd = NULL;
3570   lookup.symndx = -1;
3571   lookup.d.address = value;
3572   loc = htab_find_slot (g->got_entries, &lookup, INSERT);
3573   if (!loc)
3574     return NULL;
3575
3576   entry = (struct mips_got_entry *) *loc;
3577   if (entry)
3578     return entry;
3579
3580   if (g->assigned_gotno >= g->local_gotno)
3581     {
3582       /* We didn't allocate enough space in the GOT.  */
3583       (*_bfd_error_handler)
3584         (_("not enough GOT space for local GOT entries"));
3585       bfd_set_error (bfd_error_bad_value);
3586       return NULL;
3587     }
3588
3589   entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3590   if (!entry)
3591     return NULL;
3592
3593   lookup.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_gotno++;
3594   *entry = lookup;
3595   *loc = entry;
3596
3597   MIPS_ELF_PUT_WORD (abfd, value, htab->sgot->contents + entry->gotidx);
3598
3599   /* These GOT entries need a dynamic relocation on VxWorks.  */
3600   if (htab->is_vxworks)
3601     {
3602       Elf_Internal_Rela outrel;
3603       asection *s;
3604       bfd_byte *rloc;
3605       bfd_vma got_address;
3606
3607       s = mips_elf_rel_dyn_section (info, FALSE);
3608       got_address = (htab->sgot->output_section->vma
3609                      + htab->sgot->output_offset
3610                      + entry->gotidx);
3611
3612       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3613       outrel.r_offset = got_address;
3614       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3615       outrel.r_addend = value;
3616       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3617     }
3618
3619   return entry;
3620 }
3621
3622 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3623    The number might be exact or a worst-case estimate, depending on how
3624    much information is available to elf_backend_omit_section_dynsym at
3625    the current linking stage.  */
3626
3627 static bfd_size_type
3628 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3629 {
3630   bfd_size_type count;
3631
3632   count = 0;
3633   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
3634     {
3635       asection *p;
3636       const struct elf_backend_data *bed;
3637
3638       bed = get_elf_backend_data (output_bfd);
3639       for (p = output_bfd->sections; p ; p = p->next)
3640         if ((p->flags & SEC_EXCLUDE) == 0
3641             && (p->flags & SEC_ALLOC) != 0
3642             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3643           ++count;
3644     }
3645   return count;
3646 }
3647
3648 /* Sort the dynamic symbol table so that symbols that need GOT entries
3649    appear towards the end.  */
3650
3651 static bfd_boolean
3652 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3653 {
3654   struct mips_elf_link_hash_table *htab;
3655   struct mips_elf_hash_sort_data hsd;
3656   struct mips_got_info *g;
3657
3658   if (elf_hash_table (info)->dynsymcount == 0)
3659     return TRUE;
3660
3661   htab = mips_elf_hash_table (info);
3662   BFD_ASSERT (htab != NULL);
3663
3664   g = htab->got_info;
3665   if (g == NULL)
3666     return TRUE;
3667
3668   hsd.low = NULL;
3669   hsd.max_unref_got_dynindx
3670     = hsd.min_got_dynindx
3671     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3672   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3673   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3674                                 elf_hash_table (info)),
3675                                mips_elf_sort_hash_table_f,
3676                                &hsd);
3677
3678   /* There should have been enough room in the symbol table to
3679      accommodate both the GOT and non-GOT symbols.  */
3680   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3681   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3682               == elf_hash_table (info)->dynsymcount);
3683   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3684               == g->global_gotno);
3685
3686   /* Now we know which dynamic symbol has the lowest dynamic symbol
3687      table index in the GOT.  */
3688   htab->global_gotsym = hsd.low;
3689
3690   return TRUE;
3691 }
3692
3693 /* If H needs a GOT entry, assign it the highest available dynamic
3694    index.  Otherwise, assign it the lowest available dynamic
3695    index.  */
3696
3697 static bfd_boolean
3698 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3699 {
3700   struct mips_elf_hash_sort_data *hsd = data;
3701
3702   /* Symbols without dynamic symbol table entries aren't interesting
3703      at all.  */
3704   if (h->root.dynindx == -1)
3705     return TRUE;
3706
3707   switch (h->global_got_area)
3708     {
3709     case GGA_NONE:
3710       h->root.dynindx = hsd->max_non_got_dynindx++;
3711       break;
3712
3713     case GGA_NORMAL:
3714       h->root.dynindx = --hsd->min_got_dynindx;
3715       hsd->low = (struct elf_link_hash_entry *) h;
3716       break;
3717
3718     case GGA_RELOC_ONLY:
3719       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3720         hsd->low = (struct elf_link_hash_entry *) h;
3721       h->root.dynindx = hsd->max_unref_got_dynindx++;
3722       break;
3723     }
3724
3725   return TRUE;
3726 }
3727
3728 /* Record that input bfd ABFD requires a GOT entry like *LOOKUP
3729    (which is owned by the caller and shouldn't be added to the
3730    hash table directly).  */
3731
3732 static bfd_boolean
3733 mips_elf_record_got_entry (struct bfd_link_info *info, bfd *abfd,
3734                            struct mips_got_entry *lookup)
3735 {
3736   struct mips_elf_link_hash_table *htab;
3737   struct mips_got_entry *entry;
3738   struct mips_got_info *g;
3739   void **loc, **bfd_loc;
3740
3741   /* Make sure there's a slot for this entry in the master GOT.  */
3742   htab = mips_elf_hash_table (info);
3743   g = htab->got_info;
3744   loc = htab_find_slot (g->got_entries, lookup, INSERT);
3745   if (!loc)
3746     return FALSE;
3747
3748   /* Populate the entry if it isn't already.  */
3749   entry = (struct mips_got_entry *) *loc;
3750   if (!entry)
3751     {
3752       entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3753       if (!entry)
3754         return FALSE;
3755
3756       lookup->gotidx = -1;
3757       *entry = *lookup;
3758       *loc = entry;
3759     }
3760
3761   /* Reuse the same GOT entry for the BFD's GOT.  */
3762   g = mips_elf_bfd_got (abfd, TRUE);
3763   if (!g)
3764     return FALSE;
3765
3766   bfd_loc = htab_find_slot (g->got_entries, lookup, INSERT);
3767   if (!bfd_loc)
3768     return FALSE;
3769
3770   if (!*bfd_loc)
3771     *bfd_loc = entry;
3772   return TRUE;
3773 }
3774
3775 /* ABFD has a GOT relocation of type R_TYPE against H.  Reserve a GOT
3776    entry for it.  FOR_CALL is true if the caller is only interested in
3777    using the GOT entry for calls.  */
3778
3779 static bfd_boolean
3780 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3781                                    bfd *abfd, struct bfd_link_info *info,
3782                                    bfd_boolean for_call, int r_type)
3783 {
3784   struct mips_elf_link_hash_table *htab;
3785   struct mips_elf_link_hash_entry *hmips;
3786   struct mips_got_entry entry;
3787   unsigned char tls_type;
3788
3789   htab = mips_elf_hash_table (info);
3790   BFD_ASSERT (htab != NULL);
3791
3792   hmips = (struct mips_elf_link_hash_entry *) h;
3793   if (!for_call)
3794     hmips->got_only_for_calls = FALSE;
3795
3796   /* A global symbol in the GOT must also be in the dynamic symbol
3797      table.  */
3798   if (h->dynindx == -1)
3799     {
3800       switch (ELF_ST_VISIBILITY (h->other))
3801         {
3802         case STV_INTERNAL:
3803         case STV_HIDDEN:
3804           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3805           break;
3806         }
3807       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3808         return FALSE;
3809     }
3810
3811   tls_type = mips_elf_reloc_tls_type (r_type);
3812   if (tls_type == GOT_NORMAL && hmips->global_got_area > GGA_NORMAL)
3813     hmips->global_got_area = GGA_NORMAL;
3814   else if (tls_type == GOT_TLS_IE && hmips->tls_ie_type == 0)
3815     hmips->tls_ie_type = tls_type;
3816   else if (tls_type == GOT_TLS_GD && hmips->tls_gd_type == 0)
3817     hmips->tls_gd_type = tls_type;
3818
3819   entry.abfd = abfd;
3820   entry.symndx = -1;
3821   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3822   entry.tls_type = tls_type;
3823   return mips_elf_record_got_entry (info, abfd, &entry);
3824 }
3825
3826 /* ABFD has a GOT relocation of type R_TYPE against symbol SYMNDX + ADDEND,
3827    where SYMNDX is a local symbol.  Reserve a GOT entry for it.  */
3828
3829 static bfd_boolean
3830 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
3831                                   struct bfd_link_info *info, int r_type)
3832 {
3833   struct mips_elf_link_hash_table *htab;
3834   struct mips_got_info *g;
3835   struct mips_got_entry entry;
3836
3837   htab = mips_elf_hash_table (info);
3838   BFD_ASSERT (htab != NULL);
3839
3840   g = htab->got_info;
3841   BFD_ASSERT (g != NULL);
3842
3843   entry.abfd = abfd;
3844   entry.symndx = symndx;
3845   entry.d.addend = addend;
3846   entry.tls_type = mips_elf_reloc_tls_type (r_type);
3847   return mips_elf_record_got_entry (info, abfd, &entry);
3848 }
3849
3850 /* Return the maximum number of GOT page entries required for RANGE.  */
3851
3852 static bfd_vma
3853 mips_elf_pages_for_range (const struct mips_got_page_range *range)
3854 {
3855   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
3856 }
3857
3858 /* Record that ABFD has a page relocation against symbol SYMNDX and
3859    that ADDEND is the addend for that relocation.
3860
3861    This function creates an upper bound on the number of GOT slots
3862    required; no attempt is made to combine references to non-overridable
3863    global symbols across multiple input files.  */
3864
3865 static bfd_boolean
3866 mips_elf_record_got_page_entry (struct bfd_link_info *info, bfd *abfd,
3867                                 long symndx, bfd_signed_vma addend)
3868 {
3869   struct mips_elf_link_hash_table *htab;
3870   struct mips_got_info *g1, *g2;
3871   struct mips_got_page_entry lookup, *entry;
3872   struct mips_got_page_range **range_ptr, *range;
3873   bfd_vma old_pages, new_pages;
3874   void **loc, **bfd_loc;
3875
3876   htab = mips_elf_hash_table (info);
3877   BFD_ASSERT (htab != NULL);
3878
3879   g1 = htab->got_info;
3880   BFD_ASSERT (g1 != NULL);
3881
3882   /* Find the mips_got_page_entry hash table entry for this symbol.  */
3883   lookup.abfd = abfd;
3884   lookup.symndx = symndx;
3885   loc = htab_find_slot (g1->got_page_entries, &lookup, INSERT);
3886   if (loc == NULL)
3887     return FALSE;
3888
3889   /* Create a mips_got_page_entry if this is the first time we've
3890      seen the symbol.  */
3891   entry = (struct mips_got_page_entry *) *loc;
3892   if (!entry)
3893     {
3894       entry = bfd_alloc (abfd, sizeof (*entry));
3895       if (!entry)
3896         return FALSE;
3897
3898       entry->abfd = abfd;
3899       entry->symndx = symndx;
3900       entry->ranges = NULL;
3901       entry->num_pages = 0;
3902       *loc = entry;
3903     }
3904
3905   /* Add the same entry to the BFD's GOT.  */
3906   g2 = mips_elf_bfd_got (abfd, TRUE);
3907   if (!g2)
3908     return FALSE;
3909
3910   bfd_loc = htab_find_slot (g2->got_page_entries, &lookup, INSERT);
3911   if (!bfd_loc)
3912     return FALSE;
3913
3914   if (!*bfd_loc)
3915     *bfd_loc = entry;
3916
3917   /* Skip over ranges whose maximum extent cannot share a page entry
3918      with ADDEND.  */
3919   range_ptr = &entry->ranges;
3920   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
3921     range_ptr = &(*range_ptr)->next;
3922
3923   /* If we scanned to the end of the list, or found a range whose
3924      minimum extent cannot share a page entry with ADDEND, create
3925      a new singleton range.  */
3926   range = *range_ptr;
3927   if (!range || addend < range->min_addend - 0xffff)
3928     {
3929       range = bfd_alloc (abfd, sizeof (*range));
3930       if (!range)
3931         return FALSE;
3932
3933       range->next = *range_ptr;
3934       range->min_addend = addend;
3935       range->max_addend = addend;
3936
3937       *range_ptr = range;
3938       entry->num_pages++;
3939       g1->page_gotno++;
3940       g2->page_gotno++;
3941       return TRUE;
3942     }
3943
3944   /* Remember how many pages the old range contributed.  */
3945   old_pages = mips_elf_pages_for_range (range);
3946
3947   /* Update the ranges.  */
3948   if (addend < range->min_addend)
3949     range->min_addend = addend;
3950   else if (addend > range->max_addend)
3951     {
3952       if (range->next && addend >= range->next->min_addend - 0xffff)
3953         {
3954           old_pages += mips_elf_pages_for_range (range->next);
3955           range->max_addend = range->next->max_addend;
3956           range->next = range->next->next;
3957         }
3958       else
3959         range->max_addend = addend;
3960     }
3961
3962   /* Record any change in the total estimate.  */
3963   new_pages = mips_elf_pages_for_range (range);
3964   if (old_pages != new_pages)
3965     {
3966       entry->num_pages += new_pages - old_pages;
3967       g1->page_gotno += new_pages - old_pages;
3968       g2->page_gotno += new_pages - old_pages;
3969     }
3970
3971   return TRUE;
3972 }
3973
3974 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
3975
3976 static void
3977 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
3978                                        unsigned int n)
3979 {
3980   asection *s;
3981   struct mips_elf_link_hash_table *htab;
3982
3983   htab = mips_elf_hash_table (info);
3984   BFD_ASSERT (htab != NULL);
3985
3986   s = mips_elf_rel_dyn_section (info, FALSE);
3987   BFD_ASSERT (s != NULL);
3988
3989   if (htab->is_vxworks)
3990     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
3991   else
3992     {
3993       if (s->size == 0)
3994         {
3995           /* Make room for a null element.  */
3996           s->size += MIPS_ELF_REL_SIZE (abfd);
3997           ++s->reloc_count;
3998         }
3999       s->size += n * MIPS_ELF_REL_SIZE (abfd);
4000     }
4001 }
4002 \f
4003 /* A htab_traverse callback for GOT entries.  Set boolean *DATA to true
4004    if the GOT entry is for an indirect or warning symbol.  */
4005
4006 static int
4007 mips_elf_check_recreate_got (void **entryp, void *data)
4008 {
4009   struct mips_got_entry *entry;
4010   bfd_boolean *must_recreate;
4011
4012   entry = (struct mips_got_entry *) *entryp;
4013   must_recreate = (bfd_boolean *) data;
4014   if (entry->abfd != NULL && entry->symndx == -1)
4015     {
4016       struct mips_elf_link_hash_entry *h;
4017
4018       h = entry->d.h;
4019       if (h->root.root.type == bfd_link_hash_indirect
4020           || h->root.root.type == bfd_link_hash_warning)
4021         {
4022           *must_recreate = TRUE;
4023           return 0;
4024         }
4025     }
4026   return 1;
4027 }
4028
4029 /* A htab_traverse callback for GOT entries.  Add all entries to
4030    hash table *DATA, converting entries for indirect and warning
4031    symbols into entries for the target symbol.  Set *DATA to null
4032    on error.  */
4033
4034 static int
4035 mips_elf_recreate_got (void **entryp, void *data)
4036 {
4037   htab_t *new_got;
4038   struct mips_got_entry new_entry, *entry;
4039   void **slot;
4040
4041   new_got = (htab_t *) data;
4042   entry = (struct mips_got_entry *) *entryp;
4043   if (entry->abfd != NULL
4044       && entry->symndx == -1
4045       && (entry->d.h->root.root.type == bfd_link_hash_indirect
4046           || entry->d.h->root.root.type == bfd_link_hash_warning))
4047     {
4048       struct mips_elf_link_hash_entry *h;
4049
4050       new_entry = *entry;
4051       entry = &new_entry;
4052       h = entry->d.h;
4053       do
4054         {
4055           BFD_ASSERT (h->global_got_area == GGA_NONE);
4056           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
4057         }
4058       while (h->root.root.type == bfd_link_hash_indirect
4059              || h->root.root.type == bfd_link_hash_warning);
4060       entry->d.h = h;
4061     }
4062   slot = htab_find_slot (*new_got, entry, INSERT);
4063   if (slot == NULL)
4064     {
4065       *new_got = NULL;
4066       return 0;
4067     }
4068   if (*slot == NULL)
4069     {
4070       if (entry == &new_entry)
4071         {
4072           entry = bfd_alloc (entry->abfd, sizeof (*entry));
4073           if (!entry)
4074             {
4075               *new_got = NULL;
4076               return 0;
4077             }
4078           *entry = new_entry;
4079         }
4080       *slot = entry;
4081     }
4082   return 1;
4083 }
4084
4085 /* If any entries in G->got_entries are for indirect or warning symbols,
4086    replace them with entries for the target symbol.  */
4087
4088 static bfd_boolean
4089 mips_elf_resolve_final_got_entries (struct mips_got_info *g)
4090 {
4091   bfd_boolean must_recreate;
4092   htab_t new_got;
4093
4094   must_recreate = FALSE;
4095   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &must_recreate);
4096   if (must_recreate)
4097     {
4098       new_got = htab_create (htab_size (g->got_entries),
4099                              mips_elf_got_entry_hash,
4100                              mips_elf_got_entry_eq, NULL);
4101       htab_traverse (g->got_entries, mips_elf_recreate_got, &new_got);
4102       if (new_got == NULL)
4103         return FALSE;
4104
4105       htab_delete (g->got_entries);
4106       g->got_entries = new_got;
4107     }
4108   return TRUE;
4109 }
4110
4111 /* A mips_elf_link_hash_traverse callback for which DATA points
4112    to the link_info structure.  Count the number of type (3) entries
4113    in the master GOT.  */
4114
4115 static int
4116 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
4117 {
4118   struct bfd_link_info *info;
4119   struct mips_elf_link_hash_table *htab;
4120   struct mips_got_info *g;
4121
4122   info = (struct bfd_link_info *) data;
4123   htab = mips_elf_hash_table (info);
4124   g = htab->got_info;
4125   if (h->global_got_area != GGA_NONE)
4126     {
4127       /* Make a final decision about whether the symbol belongs in the
4128          local or global GOT.  Symbols that bind locally can (and in the
4129          case of forced-local symbols, must) live in the local GOT.
4130          Those that are aren't in the dynamic symbol table must also
4131          live in the local GOT.
4132
4133          Note that the former condition does not always imply the
4134          latter: symbols do not bind locally if they are completely
4135          undefined.  We'll report undefined symbols later if appropriate.  */
4136       if (h->root.dynindx == -1
4137           || (h->got_only_for_calls
4138               ? SYMBOL_CALLS_LOCAL (info, &h->root)
4139               : SYMBOL_REFERENCES_LOCAL (info, &h->root)))
4140         {
4141           /* The symbol belongs in the local GOT.  We no longer need this
4142              entry if it was only used for relocations; those relocations
4143              will be against the null or section symbol instead of H.  */
4144           if (h->global_got_area != GGA_RELOC_ONLY)
4145             g->local_gotno++;
4146           h->global_got_area = GGA_NONE;
4147         }
4148       else if (htab->is_vxworks
4149                && h->got_only_for_calls
4150                && h->root.plt.offset != MINUS_ONE)
4151         /* On VxWorks, calls can refer directly to the .got.plt entry;
4152            they don't need entries in the regular GOT.  .got.plt entries
4153            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4154         h->global_got_area = GGA_NONE;
4155       else
4156         {
4157           g->global_gotno++;
4158           if (h->global_got_area == GGA_RELOC_ONLY)
4159             g->reloc_only_gotno++;
4160         }
4161     }
4162   return 1;
4163 }
4164 \f
4165 /* A htab_traverse callback for GOT entries.  Add each one to the GOT
4166    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4167
4168 static int
4169 mips_elf_add_got_entry (void **entryp, void *data)
4170 {
4171   struct mips_got_entry *entry;
4172   struct mips_elf_traverse_got_arg *arg;
4173   void **slot;
4174
4175   entry = (struct mips_got_entry *) *entryp;
4176   arg = (struct mips_elf_traverse_got_arg *) data;
4177   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
4178   if (!slot)
4179     {
4180       arg->g = NULL;
4181       return 0;
4182     }
4183   if (!*slot)
4184     {
4185       *slot = entry;
4186       mips_elf_count_got_entry (arg->info, arg->g, entry);
4187     }
4188   return 1;
4189 }
4190
4191 /* A htab_traverse callback for GOT page entries.  Add each one to the GOT
4192    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4193
4194 static int
4195 mips_elf_add_got_page_entry (void **entryp, void *data)
4196 {
4197   struct mips_got_page_entry *entry;
4198   struct mips_elf_traverse_got_arg *arg;
4199   void **slot;
4200
4201   entry = (struct mips_got_page_entry *) *entryp;
4202   arg = (struct mips_elf_traverse_got_arg *) data;
4203   slot = htab_find_slot (arg->g->got_page_entries, entry, INSERT);
4204   if (!slot)
4205     {
4206       arg->g = NULL;
4207       return 0;
4208     }
4209   if (!*slot)
4210     {
4211       *slot = entry;
4212       arg->g->page_gotno += entry->num_pages;
4213     }
4214   return 1;
4215 }
4216
4217 /* Consider merging FROM, which is ABFD's GOT, into TO.  Return -1 if
4218    this would lead to overflow, 1 if they were merged successfully,
4219    and 0 if a merge failed due to lack of memory.  (These values are chosen
4220    so that nonnegative return values can be returned by a htab_traverse
4221    callback.)  */
4222
4223 static int
4224 mips_elf_merge_got_with (bfd *abfd, struct mips_got_info *from,
4225                          struct mips_got_info *to,
4226                          struct mips_elf_got_per_bfd_arg *arg)
4227 {
4228   struct mips_elf_traverse_got_arg tga;
4229   unsigned int estimate;
4230
4231   /* Work out how many page entries we would need for the combined GOT.  */
4232   estimate = arg->max_pages;
4233   if (estimate >= from->page_gotno + to->page_gotno)
4234     estimate = from->page_gotno + to->page_gotno;
4235
4236   /* And conservatively estimate how many local and TLS entries
4237      would be needed.  */
4238   estimate += from->local_gotno + to->local_gotno;
4239   estimate += from->tls_gotno + to->tls_gotno;
4240
4241   /* If we're merging with the primary got, any TLS relocations will
4242      come after the full set of global entries.  Otherwise estimate those
4243      conservatively as well.  */
4244   if (to == arg->primary && from->tls_gotno + to->tls_gotno)
4245     estimate += arg->global_count;
4246   else
4247     estimate += from->global_gotno + to->global_gotno;
4248
4249   /* Bail out if the combined GOT might be too big.  */
4250   if (estimate > arg->max_count)
4251     return -1;
4252
4253   /* Transfer the bfd's got information from FROM to TO.  */
4254   tga.info = arg->info;
4255   tga.g = to;
4256   htab_traverse (from->got_entries, mips_elf_add_got_entry, &tga);
4257   if (!tga.g)
4258     return 0;
4259
4260   htab_traverse (from->got_page_entries, mips_elf_add_got_page_entry, &tga);
4261   if (!tga.g)
4262     return 0;
4263
4264   mips_elf_replace_bfd_got (abfd, to);
4265   return 1;
4266 }
4267
4268 /* Attempt to merge GOT G, which belongs to ABFD.  Try to use as much
4269    as possible of the primary got, since it doesn't require explicit
4270    dynamic relocations, but don't use bfds that would reference global
4271    symbols out of the addressable range.  Failing the primary got,
4272    attempt to merge with the current got, or finish the current got
4273    and then make make the new got current.  */
4274
4275 static bfd_boolean
4276 mips_elf_merge_got (bfd *abfd, struct mips_got_info *g,
4277                     struct mips_elf_got_per_bfd_arg *arg)
4278 {
4279   struct mips_elf_traverse_got_arg tga;
4280   unsigned int estimate;
4281   int result;
4282
4283   if (!mips_elf_resolve_final_got_entries (g))
4284     return FALSE;
4285
4286   tga.info = arg->info;
4287   tga.g = g;
4288   htab_traverse (g->got_entries, mips_elf_count_got_entries, &tga);
4289
4290   /* Work out the number of page, local and TLS entries.  */
4291   estimate = arg->max_pages;
4292   if (estimate > g->page_gotno)
4293     estimate = g->page_gotno;
4294   estimate += g->local_gotno + g->tls_gotno;
4295
4296   /* We place TLS GOT entries after both locals and globals.  The globals
4297      for the primary GOT may overflow the normal GOT size limit, so be
4298      sure not to merge a GOT which requires TLS with the primary GOT in that
4299      case.  This doesn't affect non-primary GOTs.  */
4300   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4301
4302   if (estimate <= arg->max_count)
4303     {
4304       /* If we don't have a primary GOT, use it as
4305          a starting point for the primary GOT.  */
4306       if (!arg->primary)
4307         {
4308           arg->primary = g;
4309           return TRUE;
4310         }
4311
4312       /* Try merging with the primary GOT.  */
4313       result = mips_elf_merge_got_with (abfd, g, arg->primary, arg);
4314       if (result >= 0)
4315         return result;
4316     }
4317
4318   /* If we can merge with the last-created got, do it.  */
4319   if (arg->current)
4320     {
4321       result = mips_elf_merge_got_with (abfd, g, arg->current, arg);
4322       if (result >= 0)
4323         return result;
4324     }
4325
4326   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4327      fits; if it turns out that it doesn't, we'll get relocation
4328      overflows anyway.  */
4329   g->next = arg->current;
4330   arg->current = g;
4331
4332   return TRUE;
4333 }
4334
4335 /* ENTRYP is a hash table entry for a mips_got_entry.  Set its gotidx
4336    to GOTIDX, duplicating the entry if it has already been assigned
4337    an index in a different GOT.  */
4338
4339 static bfd_boolean
4340 mips_elf_set_gotidx (void **entryp, long gotidx)
4341 {
4342   struct mips_got_entry *entry;
4343
4344   entry = (struct mips_got_entry *) *entryp;
4345   if (entry->gotidx > 0)
4346     {
4347       struct mips_got_entry *new_entry;
4348
4349       new_entry = bfd_alloc (entry->abfd, sizeof (*entry));
4350       if (!new_entry)
4351         return FALSE;
4352
4353       *new_entry = *entry;
4354       *entryp = new_entry;
4355       entry = new_entry;
4356     }
4357   entry->gotidx = gotidx;
4358   return TRUE;
4359 }
4360
4361 /* Set the TLS GOT index for the GOT entry in ENTRYP.  DATA points to a
4362    mips_elf_traverse_got_arg in which DATA->value is the size of one
4363    GOT entry.  Set DATA->g to null on failure.  */
4364
4365 static int
4366 mips_elf_initialize_tls_index (void **entryp, void *data)
4367 {
4368   struct mips_got_entry *entry;
4369   struct mips_elf_traverse_got_arg *arg;
4370   struct mips_got_info *g;
4371   bfd_vma next_index;
4372   unsigned char tls_type;
4373
4374   /* We're only interested in TLS symbols.  */
4375   entry = (struct mips_got_entry *) *entryp;
4376   tls_type = (entry->tls_type & GOT_TLS_TYPE);
4377   if (tls_type == 0)
4378     return 1;
4379
4380   arg = (struct mips_elf_traverse_got_arg *) data;
4381   g = arg->g;
4382   next_index = arg->value * g->tls_assigned_gotno;
4383
4384   if (entry->symndx == -1 && g->next == NULL)
4385     {
4386       /* A type (3) got entry in the single-GOT case.  We use the symbol's
4387          hash table entry to track its index.  */
4388       if (tls_type == GOT_TLS_IE)
4389         {
4390           if (entry->d.h->tls_ie_type & GOT_TLS_OFFSET_DONE)
4391             return 1;
4392           entry->d.h->tls_ie_type |= GOT_TLS_OFFSET_DONE;
4393           entry->d.h->tls_ie_got_offset = next_index;
4394         }
4395       else
4396         {
4397           BFD_ASSERT (tls_type == GOT_TLS_GD);
4398           if (entry->d.h->tls_gd_type & GOT_TLS_OFFSET_DONE)
4399             return 1;
4400           entry->d.h->tls_gd_type |= GOT_TLS_OFFSET_DONE;
4401           entry->d.h->tls_gd_got_offset = next_index;
4402         }
4403     }
4404   else
4405     {
4406       if (tls_type == GOT_TLS_LDM)
4407         {
4408           /* There are separate mips_got_entry objects for each input bfd
4409              that requires an LDM entry.  Make sure that all LDM entries in
4410              a GOT resolve to the same index.  */
4411           if (g->tls_ldm_offset != MINUS_TWO && g->tls_ldm_offset != MINUS_ONE)
4412             {
4413               entry->gotidx = g->tls_ldm_offset;
4414               return 1;
4415             }
4416           g->tls_ldm_offset = next_index;
4417         }
4418       if (!mips_elf_set_gotidx (entryp, next_index))
4419         {
4420           arg->g = NULL;
4421           return 0;
4422         }
4423     }
4424
4425   /* Account for the entries we've just allocated.  */
4426   g->tls_assigned_gotno += mips_tls_got_entries (tls_type);
4427   return 1;
4428 }
4429
4430 /* A htab_traverse callback for GOT entries, where DATA points to a
4431    mips_elf_traverse_got_arg.  Set the global_got_area of each global
4432    symbol to DATA->value.  */
4433
4434 static int
4435 mips_elf_set_global_got_area (void **entryp, void *data)
4436 {
4437   struct mips_got_entry *entry;
4438   struct mips_elf_traverse_got_arg *arg;
4439
4440   entry = (struct mips_got_entry *) *entryp;
4441   arg = (struct mips_elf_traverse_got_arg *) data;
4442   if (entry->abfd != NULL
4443       && entry->symndx == -1
4444       && entry->d.h->global_got_area != GGA_NONE)
4445     entry->d.h->global_got_area = arg->value;
4446   return 1;
4447 }
4448
4449 /* A htab_traverse callback for secondary GOT entries, where DATA points
4450    to a mips_elf_traverse_got_arg.  Assign GOT indices to global entries
4451    and record the number of relocations they require.  DATA->value is
4452    the size of one GOT entry.  Set DATA->g to null on failure.  */
4453
4454 static int
4455 mips_elf_set_global_gotidx (void **entryp, void *data)
4456 {
4457   struct mips_got_entry *entry;
4458   struct mips_elf_traverse_got_arg *arg;
4459
4460   entry = (struct mips_got_entry *) *entryp;
4461   arg = (struct mips_elf_traverse_got_arg *) data;
4462   if (entry->abfd != NULL
4463       && entry->symndx == -1
4464       && entry->d.h->global_got_area != GGA_NONE)
4465     {
4466       if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->assigned_gotno))
4467         {
4468           arg->g = NULL;
4469           return 0;
4470         }
4471       arg->g->assigned_gotno += 1;
4472
4473       if (arg->info->shared
4474           || (elf_hash_table (arg->info)->dynamic_sections_created
4475               && entry->d.h->root.def_dynamic
4476               && !entry->d.h->root.def_regular))
4477         arg->g->relocs += 1;
4478     }
4479
4480   return 1;
4481 }
4482
4483 /* A htab_traverse callback for GOT entries for which DATA is the
4484    bfd_link_info.  Forbid any global symbols from having traditional
4485    lazy-binding stubs.  */
4486
4487 static int
4488 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4489 {
4490   struct bfd_link_info *info;
4491   struct mips_elf_link_hash_table *htab;
4492   struct mips_got_entry *entry;
4493
4494   entry = (struct mips_got_entry *) *entryp;
4495   info = (struct bfd_link_info *) data;
4496   htab = mips_elf_hash_table (info);
4497   BFD_ASSERT (htab != NULL);
4498
4499   if (entry->abfd != NULL
4500       && entry->symndx == -1
4501       && entry->d.h->needs_lazy_stub)
4502     {
4503       entry->d.h->needs_lazy_stub = FALSE;
4504       htab->lazy_stub_count--;
4505     }
4506
4507   return 1;
4508 }
4509
4510 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4511    the primary GOT.  */
4512 static bfd_vma
4513 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4514 {
4515   if (!g->next)
4516     return 0;
4517
4518   g = mips_elf_bfd_got (ibfd, FALSE);
4519   if (! g)
4520     return 0;
4521
4522   BFD_ASSERT (g->next);
4523
4524   g = g->next;
4525
4526   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4527     * MIPS_ELF_GOT_SIZE (abfd);
4528 }
4529
4530 /* Turn a single GOT that is too big for 16-bit addressing into
4531    a sequence of GOTs, each one 16-bit addressable.  */
4532
4533 static bfd_boolean
4534 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4535                     asection *got, bfd_size_type pages)
4536 {
4537   struct mips_elf_link_hash_table *htab;
4538   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4539   struct mips_elf_traverse_got_arg tga;
4540   struct mips_got_info *g, *gg;
4541   unsigned int assign, needed_relocs;
4542   bfd *dynobj, *ibfd;
4543
4544   dynobj = elf_hash_table (info)->dynobj;
4545   htab = mips_elf_hash_table (info);
4546   BFD_ASSERT (htab != NULL);
4547
4548   g = htab->got_info;
4549
4550   got_per_bfd_arg.obfd = abfd;
4551   got_per_bfd_arg.info = info;
4552   got_per_bfd_arg.current = NULL;
4553   got_per_bfd_arg.primary = NULL;
4554   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4555                                 / MIPS_ELF_GOT_SIZE (abfd))
4556                                - htab->reserved_gotno);
4557   got_per_bfd_arg.max_pages = pages;
4558   /* The number of globals that will be included in the primary GOT.
4559      See the calls to mips_elf_set_global_got_area below for more
4560      information.  */
4561   got_per_bfd_arg.global_count = g->global_gotno;
4562
4563   /* Try to merge the GOTs of input bfds together, as long as they
4564      don't seem to exceed the maximum GOT size, choosing one of them
4565      to be the primary GOT.  */
4566   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
4567     {
4568       gg = mips_elf_bfd_got (ibfd, FALSE);
4569       if (gg && !mips_elf_merge_got (ibfd, gg, &got_per_bfd_arg))
4570         return FALSE;
4571     }
4572
4573   /* If we do not find any suitable primary GOT, create an empty one.  */
4574   if (got_per_bfd_arg.primary == NULL)
4575     g->next = mips_elf_create_got_info (abfd);
4576   else
4577     g->next = got_per_bfd_arg.primary;
4578   g->next->next = got_per_bfd_arg.current;
4579
4580   /* GG is now the master GOT, and G is the primary GOT.  */
4581   gg = g;
4582   g = g->next;
4583
4584   /* Map the output bfd to the primary got.  That's what we're going
4585      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4586      didn't mark in check_relocs, and we want a quick way to find it.
4587      We can't just use gg->next because we're going to reverse the
4588      list.  */
4589   mips_elf_replace_bfd_got (abfd, g);
4590
4591   /* Every symbol that is referenced in a dynamic relocation must be
4592      present in the primary GOT, so arrange for them to appear after
4593      those that are actually referenced.  */
4594   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4595   g->global_gotno = gg->global_gotno;
4596
4597   tga.info = info;
4598   tga.value = GGA_RELOC_ONLY;
4599   htab_traverse (gg->got_entries, mips_elf_set_global_got_area, &tga);
4600   tga.value = GGA_NORMAL;
4601   htab_traverse (g->got_entries, mips_elf_set_global_got_area, &tga);
4602
4603   /* Now go through the GOTs assigning them offset ranges.
4604      [assigned_gotno, local_gotno[ will be set to the range of local
4605      entries in each GOT.  We can then compute the end of a GOT by
4606      adding local_gotno to global_gotno.  We reverse the list and make
4607      it circular since then we'll be able to quickly compute the
4608      beginning of a GOT, by computing the end of its predecessor.  To
4609      avoid special cases for the primary GOT, while still preserving
4610      assertions that are valid for both single- and multi-got links,
4611      we arrange for the main got struct to have the right number of
4612      global entries, but set its local_gotno such that the initial
4613      offset of the primary GOT is zero.  Remember that the primary GOT
4614      will become the last item in the circular linked list, so it
4615      points back to the master GOT.  */
4616   gg->local_gotno = -g->global_gotno;
4617   gg->global_gotno = g->global_gotno;
4618   gg->tls_gotno = 0;
4619   assign = 0;
4620   gg->next = gg;
4621
4622   do
4623     {
4624       struct mips_got_info *gn;
4625
4626       assign += htab->reserved_gotno;
4627       g->assigned_gotno = assign;
4628       g->local_gotno += assign;
4629       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4630       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4631
4632       /* Take g out of the direct list, and push it onto the reversed
4633          list that gg points to.  g->next is guaranteed to be nonnull after
4634          this operation, as required by mips_elf_initialize_tls_index. */
4635       gn = g->next;
4636       g->next = gg->next;
4637       gg->next = g;
4638
4639       /* Set up any TLS entries.  We always place the TLS entries after
4640          all non-TLS entries.  */
4641       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4642       tga.g = g;
4643       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4644       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
4645       if (!tga.g)
4646         return FALSE;
4647       BFD_ASSERT (g->tls_assigned_gotno == assign);
4648
4649       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4650       g = gn;
4651
4652       /* Forbid global symbols in every non-primary GOT from having
4653          lazy-binding stubs.  */
4654       if (g)
4655         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4656     }
4657   while (g);
4658
4659   got->size = assign * MIPS_ELF_GOT_SIZE (abfd);
4660
4661   needed_relocs = 0;
4662   for (g = gg->next; g && g->next != gg; g = g->next)
4663     {
4664       unsigned int save_assign;
4665
4666       /* Assign offsets to global GOT entries and count how many
4667          relocations they need.  */
4668       save_assign = g->assigned_gotno;
4669       g->assigned_gotno = g->local_gotno;
4670       tga.info = info;
4671       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4672       tga.g = g;
4673       htab_traverse (g->got_entries, mips_elf_set_global_gotidx, &tga);
4674       if (!tga.g)
4675         return FALSE;
4676       BFD_ASSERT (g->assigned_gotno == g->local_gotno + g->global_gotno);
4677       g->assigned_gotno = save_assign;
4678
4679       if (info->shared)
4680         {
4681           g->relocs += g->local_gotno - g->assigned_gotno;
4682           BFD_ASSERT (g->assigned_gotno == g->next->local_gotno
4683                       + g->next->global_gotno
4684                       + g->next->tls_gotno
4685                       + htab->reserved_gotno);
4686         }
4687       needed_relocs += g->relocs;
4688     }
4689   needed_relocs += g->relocs;
4690
4691   if (needed_relocs)
4692     mips_elf_allocate_dynamic_relocations (dynobj, info,
4693                                            needed_relocs);
4694
4695   return TRUE;
4696 }
4697
4698 \f
4699 /* Returns the first relocation of type r_type found, beginning with
4700    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4701
4702 static const Elf_Internal_Rela *
4703 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4704                           const Elf_Internal_Rela *relocation,
4705                           const Elf_Internal_Rela *relend)
4706 {
4707   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4708
4709   while (relocation < relend)
4710     {
4711       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4712           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4713         return relocation;
4714
4715       ++relocation;
4716     }
4717
4718   /* We didn't find it.  */
4719   return NULL;
4720 }
4721
4722 /* Return whether an input relocation is against a local symbol.  */
4723
4724 static bfd_boolean
4725 mips_elf_local_relocation_p (bfd *input_bfd,
4726                              const Elf_Internal_Rela *relocation,
4727                              asection **local_sections)
4728 {
4729   unsigned long r_symndx;
4730   Elf_Internal_Shdr *symtab_hdr;
4731   size_t extsymoff;
4732
4733   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4734   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4735   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
4736
4737   if (r_symndx < extsymoff)
4738     return TRUE;
4739   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
4740     return TRUE;
4741
4742   return FALSE;
4743 }
4744 \f
4745 /* Sign-extend VALUE, which has the indicated number of BITS.  */
4746
4747 bfd_vma
4748 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
4749 {
4750   if (value & ((bfd_vma) 1 << (bits - 1)))
4751     /* VALUE is negative.  */
4752     value |= ((bfd_vma) - 1) << bits;
4753
4754   return value;
4755 }
4756
4757 /* Return non-zero if the indicated VALUE has overflowed the maximum
4758    range expressible by a signed number with the indicated number of
4759    BITS.  */
4760
4761 static bfd_boolean
4762 mips_elf_overflow_p (bfd_vma value, int bits)
4763 {
4764   bfd_signed_vma svalue = (bfd_signed_vma) value;
4765
4766   if (svalue > (1 << (bits - 1)) - 1)
4767     /* The value is too big.  */
4768     return TRUE;
4769   else if (svalue < -(1 << (bits - 1)))
4770     /* The value is too small.  */
4771     return TRUE;
4772
4773   /* All is well.  */
4774   return FALSE;
4775 }
4776
4777 /* Calculate the %high function.  */
4778
4779 static bfd_vma
4780 mips_elf_high (bfd_vma value)
4781 {
4782   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
4783 }
4784
4785 /* Calculate the %higher function.  */
4786
4787 static bfd_vma
4788 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
4789 {
4790 #ifdef BFD64
4791   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
4792 #else
4793   abort ();
4794   return MINUS_ONE;
4795 #endif
4796 }
4797
4798 /* Calculate the %highest function.  */
4799
4800 static bfd_vma
4801 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
4802 {
4803 #ifdef BFD64
4804   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
4805 #else
4806   abort ();
4807   return MINUS_ONE;
4808 #endif
4809 }
4810 \f
4811 /* Create the .compact_rel section.  */
4812
4813 static bfd_boolean
4814 mips_elf_create_compact_rel_section
4815   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
4816 {
4817   flagword flags;
4818   register asection *s;
4819
4820   if (bfd_get_linker_section (abfd, ".compact_rel") == NULL)
4821     {
4822       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
4823                | SEC_READONLY);
4824
4825       s = bfd_make_section_anyway_with_flags (abfd, ".compact_rel", flags);
4826       if (s == NULL
4827           || ! bfd_set_section_alignment (abfd, s,
4828                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
4829         return FALSE;
4830
4831       s->size = sizeof (Elf32_External_compact_rel);
4832     }
4833
4834   return TRUE;
4835 }
4836
4837 /* Create the .got section to hold the global offset table.  */
4838
4839 static bfd_boolean
4840 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
4841 {
4842   flagword flags;
4843   register asection *s;
4844   struct elf_link_hash_entry *h;
4845   struct bfd_link_hash_entry *bh;
4846   struct mips_elf_link_hash_table *htab;
4847
4848   htab = mips_elf_hash_table (info);
4849   BFD_ASSERT (htab != NULL);
4850
4851   /* This function may be called more than once.  */
4852   if (htab->sgot)
4853     return TRUE;
4854
4855   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
4856            | SEC_LINKER_CREATED);
4857
4858   /* We have to use an alignment of 2**4 here because this is hardcoded
4859      in the function stub generation and in the linker script.  */
4860   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
4861   if (s == NULL
4862       || ! bfd_set_section_alignment (abfd, s, 4))
4863     return FALSE;
4864   htab->sgot = s;
4865
4866   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
4867      linker script because we don't want to define the symbol if we
4868      are not creating a global offset table.  */
4869   bh = NULL;
4870   if (! (_bfd_generic_link_add_one_symbol
4871          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
4872           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
4873     return FALSE;
4874
4875   h = (struct elf_link_hash_entry *) bh;
4876   h->non_elf = 0;
4877   h->def_regular = 1;
4878   h->type = STT_OBJECT;
4879   elf_hash_table (info)->hgot = h;
4880
4881   if (info->shared
4882       && ! bfd_elf_link_record_dynamic_symbol (info, h))
4883     return FALSE;
4884
4885   htab->got_info = mips_elf_create_got_info (abfd);
4886   mips_elf_section_data (s)->elf.this_hdr.sh_flags
4887     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
4888
4889   /* We also need a .got.plt section when generating PLTs.  */
4890   s = bfd_make_section_anyway_with_flags (abfd, ".got.plt",
4891                                           SEC_ALLOC | SEC_LOAD
4892                                           | SEC_HAS_CONTENTS
4893                                           | SEC_IN_MEMORY
4894                                           | SEC_LINKER_CREATED);
4895   if (s == NULL)
4896     return FALSE;
4897   htab->sgotplt = s;
4898
4899   return TRUE;
4900 }
4901 \f
4902 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
4903    __GOTT_INDEX__ symbols.  These symbols are only special for
4904    shared objects; they are not used in executables.  */
4905
4906 static bfd_boolean
4907 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
4908 {
4909   return (mips_elf_hash_table (info)->is_vxworks
4910           && info->shared
4911           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
4912               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
4913 }
4914
4915 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
4916    require an la25 stub.  See also mips_elf_local_pic_function_p,
4917    which determines whether the destination function ever requires a
4918    stub.  */
4919
4920 static bfd_boolean
4921 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type,
4922                                      bfd_boolean target_is_16_bit_code_p)
4923 {
4924   /* We specifically ignore branches and jumps from EF_PIC objects,
4925      where the onus is on the compiler or programmer to perform any
4926      necessary initialization of $25.  Sometimes such initialization
4927      is unnecessary; for example, -mno-shared functions do not use
4928      the incoming value of $25, and may therefore be called directly.  */
4929   if (PIC_OBJECT_P (input_bfd))
4930     return FALSE;
4931
4932   switch (r_type)
4933     {
4934     case R_MIPS_26:
4935     case R_MIPS_PC16:
4936     case R_MICROMIPS_26_S1:
4937     case R_MICROMIPS_PC7_S1:
4938     case R_MICROMIPS_PC10_S1:
4939     case R_MICROMIPS_PC16_S1:
4940     case R_MICROMIPS_PC23_S2:
4941       return TRUE;
4942
4943     case R_MIPS16_26:
4944       return !target_is_16_bit_code_p;
4945
4946     default:
4947       return FALSE;
4948     }
4949 }
4950 \f
4951 /* Calculate the value produced by the RELOCATION (which comes from
4952    the INPUT_BFD).  The ADDEND is the addend to use for this
4953    RELOCATION; RELOCATION->R_ADDEND is ignored.
4954
4955    The result of the relocation calculation is stored in VALUEP.
4956    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
4957    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
4958
4959    This function returns bfd_reloc_continue if the caller need take no
4960    further action regarding this relocation, bfd_reloc_notsupported if
4961    something goes dramatically wrong, bfd_reloc_overflow if an
4962    overflow occurs, and bfd_reloc_ok to indicate success.  */
4963
4964 static bfd_reloc_status_type
4965 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
4966                                asection *input_section,
4967                                struct bfd_link_info *info,
4968                                const Elf_Internal_Rela *relocation,
4969                                bfd_vma addend, reloc_howto_type *howto,
4970                                Elf_Internal_Sym *local_syms,
4971                                asection **local_sections, bfd_vma *valuep,
4972                                const char **namep,
4973                                bfd_boolean *cross_mode_jump_p,
4974                                bfd_boolean save_addend)
4975 {
4976   /* The eventual value we will return.  */
4977   bfd_vma value;
4978   /* The address of the symbol against which the relocation is
4979      occurring.  */
4980   bfd_vma symbol = 0;
4981   /* The final GP value to be used for the relocatable, executable, or
4982      shared object file being produced.  */
4983   bfd_vma gp;
4984   /* The place (section offset or address) of the storage unit being
4985      relocated.  */
4986   bfd_vma p;
4987   /* The value of GP used to create the relocatable object.  */
4988   bfd_vma gp0;
4989   /* The offset into the global offset table at which the address of
4990      the relocation entry symbol, adjusted by the addend, resides
4991      during execution.  */
4992   bfd_vma g = MINUS_ONE;
4993   /* The section in which the symbol referenced by the relocation is
4994      located.  */
4995   asection *sec = NULL;
4996   struct mips_elf_link_hash_entry *h = NULL;
4997   /* TRUE if the symbol referred to by this relocation is a local
4998      symbol.  */
4999   bfd_boolean local_p, was_local_p;
5000   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
5001   bfd_boolean gp_disp_p = FALSE;
5002   /* TRUE if the symbol referred to by this relocation is
5003      "__gnu_local_gp".  */
5004   bfd_boolean gnu_local_gp_p = FALSE;
5005   Elf_Internal_Shdr *symtab_hdr;
5006   size_t extsymoff;
5007   unsigned long r_symndx;
5008   int r_type;
5009   /* TRUE if overflow occurred during the calculation of the
5010      relocation value.  */
5011   bfd_boolean overflowed_p;
5012   /* TRUE if this relocation refers to a MIPS16 function.  */
5013   bfd_boolean target_is_16_bit_code_p = FALSE;
5014   bfd_boolean target_is_micromips_code_p = FALSE;
5015   struct mips_elf_link_hash_table *htab;
5016   bfd *dynobj;
5017
5018   dynobj = elf_hash_table (info)->dynobj;
5019   htab = mips_elf_hash_table (info);
5020   BFD_ASSERT (htab != NULL);
5021
5022   /* Parse the relocation.  */
5023   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
5024   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5025   p = (input_section->output_section->vma
5026        + input_section->output_offset
5027        + relocation->r_offset);
5028
5029   /* Assume that there will be no overflow.  */
5030   overflowed_p = FALSE;
5031
5032   /* Figure out whether or not the symbol is local, and get the offset
5033      used in the array of hash table entries.  */
5034   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
5035   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
5036                                          local_sections);
5037   was_local_p = local_p;
5038   if (! elf_bad_symtab (input_bfd))
5039     extsymoff = symtab_hdr->sh_info;
5040   else
5041     {
5042       /* The symbol table does not follow the rule that local symbols
5043          must come before globals.  */
5044       extsymoff = 0;
5045     }
5046
5047   /* Figure out the value of the symbol.  */
5048   if (local_p)
5049     {
5050       Elf_Internal_Sym *sym;
5051
5052       sym = local_syms + r_symndx;
5053       sec = local_sections[r_symndx];
5054
5055       symbol = sec->output_section->vma + sec->output_offset;
5056       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION
5057           || (sec->flags & SEC_MERGE))
5058         symbol += sym->st_value;
5059       if ((sec->flags & SEC_MERGE)
5060           && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
5061         {
5062           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
5063           addend -= symbol;
5064           addend += sec->output_section->vma + sec->output_offset;
5065         }
5066
5067       /* MIPS16/microMIPS text labels should be treated as odd.  */
5068       if (ELF_ST_IS_COMPRESSED (sym->st_other))
5069         ++symbol;
5070
5071       /* Record the name of this symbol, for our caller.  */
5072       *namep = bfd_elf_string_from_elf_section (input_bfd,
5073                                                 symtab_hdr->sh_link,
5074                                                 sym->st_name);
5075       if (*namep == '\0')
5076         *namep = bfd_section_name (input_bfd, sec);
5077
5078       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
5079       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
5080     }
5081   else
5082     {
5083       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
5084
5085       /* For global symbols we look up the symbol in the hash-table.  */
5086       h = ((struct mips_elf_link_hash_entry *)
5087            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
5088       /* Find the real hash-table entry for this symbol.  */
5089       while (h->root.root.type == bfd_link_hash_indirect
5090              || h->root.root.type == bfd_link_hash_warning)
5091         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
5092
5093       /* Record the name of this symbol, for our caller.  */
5094       *namep = h->root.root.root.string;
5095
5096       /* See if this is the special _gp_disp symbol.  Note that such a
5097          symbol must always be a global symbol.  */
5098       if (strcmp (*namep, "_gp_disp") == 0
5099           && ! NEWABI_P (input_bfd))
5100         {
5101           /* Relocations against _gp_disp are permitted only with
5102              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
5103           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
5104             return bfd_reloc_notsupported;
5105
5106           gp_disp_p = TRUE;
5107         }
5108       /* See if this is the special _gp symbol.  Note that such a
5109          symbol must always be a global symbol.  */
5110       else if (strcmp (*namep, "__gnu_local_gp") == 0)
5111         gnu_local_gp_p = TRUE;
5112
5113
5114       /* If this symbol is defined, calculate its address.  Note that
5115          _gp_disp is a magic symbol, always implicitly defined by the
5116          linker, so it's inappropriate to check to see whether or not
5117          its defined.  */
5118       else if ((h->root.root.type == bfd_link_hash_defined
5119                 || h->root.root.type == bfd_link_hash_defweak)
5120                && h->root.root.u.def.section)
5121         {
5122           sec = h->root.root.u.def.section;
5123           if (sec->output_section)
5124             symbol = (h->root.root.u.def.value
5125                       + sec->output_section->vma
5126                       + sec->output_offset);
5127           else
5128             symbol = h->root.root.u.def.value;
5129         }
5130       else if (h->root.root.type == bfd_link_hash_undefweak)
5131         /* We allow relocations against undefined weak symbols, giving
5132            it the value zero, so that you can undefined weak functions
5133            and check to see if they exist by looking at their
5134            addresses.  */
5135         symbol = 0;
5136       else if (info->unresolved_syms_in_objects == RM_IGNORE
5137                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5138         symbol = 0;
5139       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
5140                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
5141         {
5142           /* If this is a dynamic link, we should have created a
5143              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
5144              in in _bfd_mips_elf_create_dynamic_sections.
5145              Otherwise, we should define the symbol with a value of 0.
5146              FIXME: It should probably get into the symbol table
5147              somehow as well.  */
5148           BFD_ASSERT (! info->shared);
5149           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
5150           symbol = 0;
5151         }
5152       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
5153         {
5154           /* This is an optional symbol - an Irix specific extension to the
5155              ELF spec.  Ignore it for now.
5156              XXX - FIXME - there is more to the spec for OPTIONAL symbols
5157              than simply ignoring them, but we do not handle this for now.
5158              For information see the "64-bit ELF Object File Specification"
5159              which is available from here:
5160              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
5161           symbol = 0;
5162         }
5163       else if ((*info->callbacks->undefined_symbol)
5164                (info, h->root.root.root.string, input_bfd,
5165                 input_section, relocation->r_offset,
5166                 (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
5167                  || ELF_ST_VISIBILITY (h->root.other)))
5168         {
5169           return bfd_reloc_undefined;
5170         }
5171       else
5172         {
5173           return bfd_reloc_notsupported;
5174         }
5175
5176       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
5177       /* If the output section is the PLT section,
5178          then the target is not microMIPS.  */
5179       target_is_micromips_code_p = (htab->splt != sec
5180                                     && ELF_ST_IS_MICROMIPS (h->root.other));
5181     }
5182
5183   /* If this is a reference to a 16-bit function with a stub, we need
5184      to redirect the relocation to the stub unless:
5185
5186      (a) the relocation is for a MIPS16 JAL;
5187
5188      (b) the relocation is for a MIPS16 PIC call, and there are no
5189          non-MIPS16 uses of the GOT slot; or
5190
5191      (c) the section allows direct references to MIPS16 functions.  */
5192   if (r_type != R_MIPS16_26
5193       && !info->relocatable
5194       && ((h != NULL
5195            && h->fn_stub != NULL
5196            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5197           || (local_p
5198               && elf_tdata (input_bfd)->local_stubs != NULL
5199               && elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5200       && !section_allows_mips16_refs_p (input_section))
5201     {
5202       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5203          have already noticed that we were going to need the
5204          stub.  */
5205       if (local_p)
5206         {
5207           sec = elf_tdata (input_bfd)->local_stubs[r_symndx];
5208           value = 0;
5209         }
5210       else
5211         {
5212           BFD_ASSERT (h->need_fn_stub);
5213           if (h->la25_stub)
5214             {
5215               /* If a LA25 header for the stub itself exists, point to the
5216                  prepended LUI/ADDIU sequence.  */
5217               sec = h->la25_stub->stub_section;
5218               value = h->la25_stub->offset;
5219             }
5220           else
5221             {
5222               sec = h->fn_stub;
5223               value = 0;
5224             }
5225         }
5226
5227       symbol = sec->output_section->vma + sec->output_offset + value;
5228       /* The target is 16-bit, but the stub isn't.  */
5229       target_is_16_bit_code_p = FALSE;
5230     }
5231   /* If this is a 16-bit call to a 32- or 64-bit function with a stub, we
5232      need to redirect the call to the stub.  Note that we specifically
5233      exclude R_MIPS16_CALL16 from this behavior; indirect calls should
5234      use an indirect stub instead.  */
5235   else if (r_type == R_MIPS16_26 && !info->relocatable
5236            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5237                || (local_p
5238                    && elf_tdata (input_bfd)->local_call_stubs != NULL
5239                    && elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5240            && !target_is_16_bit_code_p)
5241     {
5242       if (local_p)
5243         sec = elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5244       else
5245         {
5246           /* If both call_stub and call_fp_stub are defined, we can figure
5247              out which one to use by checking which one appears in the input
5248              file.  */
5249           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5250             {
5251               asection *o;
5252
5253               sec = NULL;
5254               for (o = input_bfd->sections; o != NULL; o = o->next)
5255                 {
5256                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5257                     {
5258                       sec = h->call_fp_stub;
5259                       break;
5260                     }
5261                 }
5262               if (sec == NULL)
5263                 sec = h->call_stub;
5264             }
5265           else if (h->call_stub != NULL)
5266             sec = h->call_stub;
5267           else
5268             sec = h->call_fp_stub;
5269         }
5270
5271       BFD_ASSERT (sec->size > 0);
5272       symbol = sec->output_section->vma + sec->output_offset;
5273     }
5274   /* If this is a direct call to a PIC function, redirect to the
5275      non-PIC stub.  */
5276   else if (h != NULL && h->la25_stub
5277            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type,
5278                                                    target_is_16_bit_code_p))
5279     symbol = (h->la25_stub->stub_section->output_section->vma
5280               + h->la25_stub->stub_section->output_offset
5281               + h->la25_stub->offset);
5282
5283   /* Make sure MIPS16 and microMIPS are not used together.  */
5284   if ((r_type == R_MIPS16_26 && target_is_micromips_code_p)
5285       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5286    {
5287       (*_bfd_error_handler)
5288         (_("MIPS16 and microMIPS functions cannot call each other"));
5289       return bfd_reloc_notsupported;
5290    }
5291
5292   /* Calls from 16-bit code to 32-bit code and vice versa require the
5293      mode change.  However, we can ignore calls to undefined weak symbols,
5294      which should never be executed at runtime.  This exception is important
5295      because the assembly writer may have "known" that any definition of the
5296      symbol would be 16-bit code, and that direct jumps were therefore
5297      acceptable.  */
5298   *cross_mode_jump_p = (!info->relocatable
5299                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5300                         && ((r_type == R_MIPS16_26 && !target_is_16_bit_code_p)
5301                             || (r_type == R_MICROMIPS_26_S1
5302                                 && !target_is_micromips_code_p)
5303                             || ((r_type == R_MIPS_26 || r_type == R_MIPS_JALR)
5304                                 && (target_is_16_bit_code_p
5305                                     || target_is_micromips_code_p))));
5306
5307   local_p = (h == NULL
5308              || (h->got_only_for_calls
5309                  ? SYMBOL_CALLS_LOCAL (info, &h->root)
5310                  : SYMBOL_REFERENCES_LOCAL (info, &h->root)));
5311
5312   gp0 = _bfd_get_gp_value (input_bfd);
5313   gp = _bfd_get_gp_value (abfd);
5314   if (htab->got_info)
5315     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5316
5317   if (gnu_local_gp_p)
5318     symbol = gp;
5319
5320   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5321      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5322      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5323   if (got_page_reloc_p (r_type) && !local_p)
5324     {
5325       r_type = (micromips_reloc_p (r_type)
5326                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5327       addend = 0;
5328     }
5329
5330   /* If we haven't already determined the GOT offset, and we're going
5331      to need it, get it now.  */
5332   switch (r_type)
5333     {
5334     case R_MIPS16_CALL16:
5335     case R_MIPS16_GOT16:
5336     case R_MIPS_CALL16:
5337     case R_MIPS_GOT16:
5338     case R_MIPS_GOT_DISP:
5339     case R_MIPS_GOT_HI16:
5340     case R_MIPS_CALL_HI16:
5341     case R_MIPS_GOT_LO16:
5342     case R_MIPS_CALL_LO16:
5343     case R_MICROMIPS_CALL16:
5344     case R_MICROMIPS_GOT16:
5345     case R_MICROMIPS_GOT_DISP:
5346     case R_MICROMIPS_GOT_HI16:
5347     case R_MICROMIPS_CALL_HI16:
5348     case R_MICROMIPS_GOT_LO16:
5349     case R_MICROMIPS_CALL_LO16:
5350     case R_MIPS_TLS_GD:
5351     case R_MIPS_TLS_GOTTPREL:
5352     case R_MIPS_TLS_LDM:
5353     case R_MIPS16_TLS_GD:
5354     case R_MIPS16_TLS_GOTTPREL:
5355     case R_MIPS16_TLS_LDM:
5356     case R_MICROMIPS_TLS_GD:
5357     case R_MICROMIPS_TLS_GOTTPREL:
5358     case R_MICROMIPS_TLS_LDM:
5359       /* Find the index into the GOT where this value is located.  */
5360       if (tls_ldm_reloc_p (r_type))
5361         {
5362           g = mips_elf_local_got_index (abfd, input_bfd, info,
5363                                         0, 0, NULL, r_type);
5364           if (g == MINUS_ONE)
5365             return bfd_reloc_outofrange;
5366         }
5367       else if (!local_p)
5368         {
5369           /* On VxWorks, CALL relocations should refer to the .got.plt
5370              entry, which is initialized to point at the PLT stub.  */
5371           if (htab->is_vxworks
5372               && (call_hi16_reloc_p (r_type)
5373                   || call_lo16_reloc_p (r_type)
5374                   || call16_reloc_p (r_type)))
5375             {
5376               BFD_ASSERT (addend == 0);
5377               BFD_ASSERT (h->root.needs_plt);
5378               g = mips_elf_gotplt_index (info, &h->root);
5379             }
5380           else
5381             {
5382               BFD_ASSERT (addend == 0);
5383               g = mips_elf_global_got_index (abfd, info, input_bfd,
5384                                              &h->root, r_type);
5385               if (!TLS_RELOC_P (r_type)
5386                   && !elf_hash_table (info)->dynamic_sections_created)
5387                 /* This is a static link.  We must initialize the GOT entry.  */
5388                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->sgot->contents + g);
5389             }
5390         }
5391       else if (!htab->is_vxworks
5392                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5393         /* The calculation below does not involve "g".  */
5394         break;
5395       else
5396         {
5397           g = mips_elf_local_got_index (abfd, input_bfd, info,
5398                                         symbol + addend, r_symndx, h, r_type);
5399           if (g == MINUS_ONE)
5400             return bfd_reloc_outofrange;
5401         }
5402
5403       /* Convert GOT indices to actual offsets.  */
5404       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5405       break;
5406     }
5407
5408   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5409      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5410   if (h != NULL && is_gott_symbol (info, &h->root))
5411     {
5412       Elf_Internal_Rela outrel;
5413       bfd_byte *loc;
5414       asection *s;
5415
5416       s = mips_elf_rel_dyn_section (info, FALSE);
5417       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5418
5419       outrel.r_offset = (input_section->output_section->vma
5420                          + input_section->output_offset
5421                          + relocation->r_offset);
5422       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5423       outrel.r_addend = addend;
5424       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5425
5426       /* If we've written this relocation for a readonly section,
5427          we need to set DF_TEXTREL again, so that we do not delete the
5428          DT_TEXTREL tag.  */
5429       if (MIPS_ELF_READONLY_SECTION (input_section))
5430         info->flags |= DF_TEXTREL;
5431
5432       *valuep = 0;
5433       return bfd_reloc_ok;
5434     }
5435
5436   /* Figure out what kind of relocation is being performed.  */
5437   switch (r_type)
5438     {
5439     case R_MIPS_NONE:
5440       return bfd_reloc_continue;
5441
5442     case R_MIPS_16:
5443       value = symbol + _bfd_mips_elf_sign_extend (addend, 16);
5444       overflowed_p = mips_elf_overflow_p (value, 16);
5445       break;
5446
5447     case R_MIPS_32:
5448     case R_MIPS_REL32:
5449     case R_MIPS_64:
5450       if ((info->shared
5451            || (htab->root.dynamic_sections_created
5452                && h != NULL
5453                && h->root.def_dynamic
5454                && !h->root.def_regular
5455                && !h->has_static_relocs))
5456           && r_symndx != STN_UNDEF
5457           && (h == NULL
5458               || h->root.root.type != bfd_link_hash_undefweak
5459               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5460           && (input_section->flags & SEC_ALLOC) != 0)
5461         {
5462           /* If we're creating a shared library, then we can't know
5463              where the symbol will end up.  So, we create a relocation
5464              record in the output, and leave the job up to the dynamic
5465              linker.  We must do the same for executable references to
5466              shared library symbols, unless we've decided to use copy
5467              relocs or PLTs instead.  */
5468           value = addend;
5469           if (!mips_elf_create_dynamic_relocation (abfd,
5470                                                    info,
5471                                                    relocation,
5472                                                    h,
5473                                                    sec,
5474                                                    symbol,
5475                                                    &value,
5476                                                    input_section))
5477             return bfd_reloc_undefined;
5478         }
5479       else
5480         {
5481           if (r_type != R_MIPS_REL32)
5482             value = symbol + addend;
5483           else
5484             value = addend;
5485         }
5486       value &= howto->dst_mask;
5487       break;
5488
5489     case R_MIPS_PC32:
5490       value = symbol + addend - p;
5491       value &= howto->dst_mask;
5492       break;
5493
5494     case R_MIPS16_26:
5495       /* The calculation for R_MIPS16_26 is just the same as for an
5496          R_MIPS_26.  It's only the storage of the relocated field into
5497          the output file that's different.  That's handled in
5498          mips_elf_perform_relocation.  So, we just fall through to the
5499          R_MIPS_26 case here.  */
5500     case R_MIPS_26:
5501     case R_MICROMIPS_26_S1:
5502       {
5503         unsigned int shift;
5504
5505         /* Make sure the target of JALX is word-aligned.  Bit 0 must be
5506            the correct ISA mode selector and bit 1 must be 0.  */
5507         if (*cross_mode_jump_p && (symbol & 3) != (r_type == R_MIPS_26))
5508           return bfd_reloc_outofrange;
5509
5510         /* Shift is 2, unusually, for microMIPS JALX.  */
5511         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5512
5513         if (was_local_p)
5514           value = addend | ((p + 4) & (0xfc000000 << shift));
5515         else
5516           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5517         value = (value + symbol) >> shift;
5518         if (!was_local_p && h->root.root.type != bfd_link_hash_undefweak)
5519           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5520         value &= howto->dst_mask;
5521       }
5522       break;
5523
5524     case R_MIPS_TLS_DTPREL_HI16:
5525     case R_MIPS16_TLS_DTPREL_HI16:
5526     case R_MICROMIPS_TLS_DTPREL_HI16:
5527       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5528                & howto->dst_mask);
5529       break;
5530
5531     case R_MIPS_TLS_DTPREL_LO16:
5532     case R_MIPS_TLS_DTPREL32:
5533     case R_MIPS_TLS_DTPREL64:
5534     case R_MIPS16_TLS_DTPREL_LO16:
5535     case R_MICROMIPS_TLS_DTPREL_LO16:
5536       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5537       break;
5538
5539     case R_MIPS_TLS_TPREL_HI16:
5540     case R_MIPS16_TLS_TPREL_HI16:
5541     case R_MICROMIPS_TLS_TPREL_HI16:
5542       value = (mips_elf_high (addend + symbol - tprel_base (info))
5543                & howto->dst_mask);
5544       break;
5545
5546     case R_MIPS_TLS_TPREL_LO16:
5547     case R_MIPS_TLS_TPREL32:
5548     case R_MIPS_TLS_TPREL64:
5549     case R_MIPS16_TLS_TPREL_LO16:
5550     case R_MICROMIPS_TLS_TPREL_LO16:
5551       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5552       break;
5553
5554     case R_MIPS_HI16:
5555     case R_MIPS16_HI16:
5556     case R_MICROMIPS_HI16:
5557       if (!gp_disp_p)
5558         {
5559           value = mips_elf_high (addend + symbol);
5560           value &= howto->dst_mask;
5561         }
5562       else
5563         {
5564           /* For MIPS16 ABI code we generate this sequence
5565                 0: li      $v0,%hi(_gp_disp)
5566                 4: addiupc $v1,%lo(_gp_disp)
5567                 8: sll     $v0,16
5568                12: addu    $v0,$v1
5569                14: move    $gp,$v0
5570              So the offsets of hi and lo relocs are the same, but the
5571              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5572              ADDIUPC clears the low two bits of the instruction address,
5573              so the base is ($t9 + 4) & ~3.  */
5574           if (r_type == R_MIPS16_HI16)
5575             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5576           /* The microMIPS .cpload sequence uses the same assembly
5577              instructions as the traditional psABI version, but the
5578              incoming $t9 has the low bit set.  */
5579           else if (r_type == R_MICROMIPS_HI16)
5580             value = mips_elf_high (addend + gp - p - 1);
5581           else
5582             value = mips_elf_high (addend + gp - p);
5583           overflowed_p = mips_elf_overflow_p (value, 16);
5584         }
5585       break;
5586
5587     case R_MIPS_LO16:
5588     case R_MIPS16_LO16:
5589     case R_MICROMIPS_LO16:
5590     case R_MICROMIPS_HI0_LO16:
5591       if (!gp_disp_p)
5592         value = (symbol + addend) & howto->dst_mask;
5593       else
5594         {
5595           /* See the comment for R_MIPS16_HI16 above for the reason
5596              for this conditional.  */
5597           if (r_type == R_MIPS16_LO16)
5598             value = addend + gp - (p & ~(bfd_vma) 0x3);
5599           else if (r_type == R_MICROMIPS_LO16
5600                    || r_type == R_MICROMIPS_HI0_LO16)
5601             value = addend + gp - p + 3;
5602           else
5603             value = addend + gp - p + 4;
5604           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5605              for overflow.  But, on, say, IRIX5, relocations against
5606              _gp_disp are normally generated from the .cpload
5607              pseudo-op.  It generates code that normally looks like
5608              this:
5609
5610                lui    $gp,%hi(_gp_disp)
5611                addiu  $gp,$gp,%lo(_gp_disp)
5612                addu   $gp,$gp,$t9
5613
5614              Here $t9 holds the address of the function being called,
5615              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5616              relocation can easily overflow in this situation, but the
5617              R_MIPS_HI16 relocation will handle the overflow.
5618              Therefore, we consider this a bug in the MIPS ABI, and do
5619              not check for overflow here.  */
5620         }
5621       break;
5622
5623     case R_MIPS_LITERAL:
5624     case R_MICROMIPS_LITERAL:
5625       /* Because we don't merge literal sections, we can handle this
5626          just like R_MIPS_GPREL16.  In the long run, we should merge
5627          shared literals, and then we will need to additional work
5628          here.  */
5629
5630       /* Fall through.  */
5631
5632     case R_MIPS16_GPREL:
5633       /* The R_MIPS16_GPREL performs the same calculation as
5634          R_MIPS_GPREL16, but stores the relocated bits in a different
5635          order.  We don't need to do anything special here; the
5636          differences are handled in mips_elf_perform_relocation.  */
5637     case R_MIPS_GPREL16:
5638     case R_MICROMIPS_GPREL7_S2:
5639     case R_MICROMIPS_GPREL16:
5640       /* Only sign-extend the addend if it was extracted from the
5641          instruction.  If the addend was separate, leave it alone,
5642          otherwise we may lose significant bits.  */
5643       if (howto->partial_inplace)
5644         addend = _bfd_mips_elf_sign_extend (addend, 16);
5645       value = symbol + addend - gp;
5646       /* If the symbol was local, any earlier relocatable links will
5647          have adjusted its addend with the gp offset, so compensate
5648          for that now.  Don't do it for symbols forced local in this
5649          link, though, since they won't have had the gp offset applied
5650          to them before.  */
5651       if (was_local_p)
5652         value += gp0;
5653       overflowed_p = mips_elf_overflow_p (value, 16);
5654       break;
5655
5656     case R_MIPS16_GOT16:
5657     case R_MIPS16_CALL16:
5658     case R_MIPS_GOT16:
5659     case R_MIPS_CALL16:
5660     case R_MICROMIPS_GOT16:
5661     case R_MICROMIPS_CALL16:
5662       /* VxWorks does not have separate local and global semantics for
5663          R_MIPS*_GOT16; every relocation evaluates to "G".  */
5664       if (!htab->is_vxworks && local_p)
5665         {
5666           value = mips_elf_got16_entry (abfd, input_bfd, info,
5667                                         symbol + addend, !was_local_p);
5668           if (value == MINUS_ONE)
5669             return bfd_reloc_outofrange;
5670           value
5671             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5672           overflowed_p = mips_elf_overflow_p (value, 16);
5673           break;
5674         }
5675
5676       /* Fall through.  */
5677
5678     case R_MIPS_TLS_GD:
5679     case R_MIPS_TLS_GOTTPREL:
5680     case R_MIPS_TLS_LDM:
5681     case R_MIPS_GOT_DISP:
5682     case R_MIPS16_TLS_GD:
5683     case R_MIPS16_TLS_GOTTPREL:
5684     case R_MIPS16_TLS_LDM:
5685     case R_MICROMIPS_TLS_GD:
5686     case R_MICROMIPS_TLS_GOTTPREL:
5687     case R_MICROMIPS_TLS_LDM:
5688     case R_MICROMIPS_GOT_DISP:
5689       value = g;
5690       overflowed_p = mips_elf_overflow_p (value, 16);
5691       break;
5692
5693     case R_MIPS_GPREL32:
5694       value = (addend + symbol + gp0 - gp);
5695       if (!save_addend)
5696         value &= howto->dst_mask;
5697       break;
5698
5699     case R_MIPS_PC16:
5700     case R_MIPS_GNU_REL16_S2:
5701       value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p;
5702       overflowed_p = mips_elf_overflow_p (value, 18);
5703       value >>= howto->rightshift;
5704       value &= howto->dst_mask;
5705       break;
5706
5707     case R_MICROMIPS_PC7_S1:
5708       value = symbol + _bfd_mips_elf_sign_extend (addend, 8) - p;
5709       overflowed_p = mips_elf_overflow_p (value, 8);
5710       value >>= howto->rightshift;
5711       value &= howto->dst_mask;
5712       break;
5713
5714     case R_MICROMIPS_PC10_S1:
5715       value = symbol + _bfd_mips_elf_sign_extend (addend, 11) - p;
5716       overflowed_p = mips_elf_overflow_p (value, 11);
5717       value >>= howto->rightshift;
5718       value &= howto->dst_mask;
5719       break;
5720
5721     case R_MICROMIPS_PC16_S1:
5722       value = symbol + _bfd_mips_elf_sign_extend (addend, 17) - p;
5723       overflowed_p = mips_elf_overflow_p (value, 17);
5724       value >>= howto->rightshift;
5725       value &= howto->dst_mask;
5726       break;
5727
5728     case R_MICROMIPS_PC23_S2:
5729       value = symbol + _bfd_mips_elf_sign_extend (addend, 25) - ((p | 3) ^ 3);
5730       overflowed_p = mips_elf_overflow_p (value, 25);
5731       value >>= howto->rightshift;
5732       value &= howto->dst_mask;
5733       break;
5734
5735     case R_MIPS_GOT_HI16:
5736     case R_MIPS_CALL_HI16:
5737     case R_MICROMIPS_GOT_HI16:
5738     case R_MICROMIPS_CALL_HI16:
5739       /* We're allowed to handle these two relocations identically.
5740          The dynamic linker is allowed to handle the CALL relocations
5741          differently by creating a lazy evaluation stub.  */
5742       value = g;
5743       value = mips_elf_high (value);
5744       value &= howto->dst_mask;
5745       break;
5746
5747     case R_MIPS_GOT_LO16:
5748     case R_MIPS_CALL_LO16:
5749     case R_MICROMIPS_GOT_LO16:
5750     case R_MICROMIPS_CALL_LO16:
5751       value = g & howto->dst_mask;
5752       break;
5753
5754     case R_MIPS_GOT_PAGE:
5755     case R_MICROMIPS_GOT_PAGE:
5756       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
5757       if (value == MINUS_ONE)
5758         return bfd_reloc_outofrange;
5759       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5760       overflowed_p = mips_elf_overflow_p (value, 16);
5761       break;
5762
5763     case R_MIPS_GOT_OFST:
5764     case R_MICROMIPS_GOT_OFST:
5765       if (local_p)
5766         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
5767       else
5768         value = addend;
5769       overflowed_p = mips_elf_overflow_p (value, 16);
5770       break;
5771
5772     case R_MIPS_SUB:
5773     case R_MICROMIPS_SUB:
5774       value = symbol - addend;
5775       value &= howto->dst_mask;
5776       break;
5777
5778     case R_MIPS_HIGHER:
5779     case R_MICROMIPS_HIGHER:
5780       value = mips_elf_higher (addend + symbol);
5781       value &= howto->dst_mask;
5782       break;
5783
5784     case R_MIPS_HIGHEST:
5785     case R_MICROMIPS_HIGHEST:
5786       value = mips_elf_highest (addend + symbol);
5787       value &= howto->dst_mask;
5788       break;
5789
5790     case R_MIPS_SCN_DISP:
5791     case R_MICROMIPS_SCN_DISP:
5792       value = symbol + addend - sec->output_offset;
5793       value &= howto->dst_mask;
5794       break;
5795
5796     case R_MIPS_JALR:
5797     case R_MICROMIPS_JALR:
5798       /* This relocation is only a hint.  In some cases, we optimize
5799          it into a bal instruction.  But we don't try to optimize
5800          when the symbol does not resolve locally.  */
5801       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
5802         return bfd_reloc_continue;
5803       value = symbol + addend;
5804       break;
5805
5806     case R_MIPS_PJUMP:
5807     case R_MIPS_GNU_VTINHERIT:
5808     case R_MIPS_GNU_VTENTRY:
5809       /* We don't do anything with these at present.  */
5810       return bfd_reloc_continue;
5811
5812     default:
5813       /* An unrecognized relocation type.  */
5814       return bfd_reloc_notsupported;
5815     }
5816
5817   /* Store the VALUE for our caller.  */
5818   *valuep = value;
5819   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
5820 }
5821
5822 /* Obtain the field relocated by RELOCATION.  */
5823
5824 static bfd_vma
5825 mips_elf_obtain_contents (reloc_howto_type *howto,
5826                           const Elf_Internal_Rela *relocation,
5827                           bfd *input_bfd, bfd_byte *contents)
5828 {
5829   bfd_vma x;
5830   bfd_byte *location = contents + relocation->r_offset;
5831
5832   /* Obtain the bytes.  */
5833   x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location);
5834
5835   return x;
5836 }
5837
5838 /* It has been determined that the result of the RELOCATION is the
5839    VALUE.  Use HOWTO to place VALUE into the output file at the
5840    appropriate position.  The SECTION is the section to which the
5841    relocation applies.
5842    CROSS_MODE_JUMP_P is true if the relocation field
5843    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5844
5845    Returns FALSE if anything goes wrong.  */
5846
5847 static bfd_boolean
5848 mips_elf_perform_relocation (struct bfd_link_info *info,
5849                              reloc_howto_type *howto,
5850                              const Elf_Internal_Rela *relocation,
5851                              bfd_vma value, bfd *input_bfd,
5852                              asection *input_section, bfd_byte *contents,
5853                              bfd_boolean cross_mode_jump_p)
5854 {
5855   bfd_vma x;
5856   bfd_byte *location;
5857   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5858
5859   /* Figure out where the relocation is occurring.  */
5860   location = contents + relocation->r_offset;
5861
5862   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
5863
5864   /* Obtain the current value.  */
5865   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
5866
5867   /* Clear the field we are setting.  */
5868   x &= ~howto->dst_mask;
5869
5870   /* Set the field.  */
5871   x |= (value & howto->dst_mask);
5872
5873   /* If required, turn JAL into JALX.  */
5874   if (cross_mode_jump_p && jal_reloc_p (r_type))
5875     {
5876       bfd_boolean ok;
5877       bfd_vma opcode = x >> 26;
5878       bfd_vma jalx_opcode;
5879
5880       /* Check to see if the opcode is already JAL or JALX.  */
5881       if (r_type == R_MIPS16_26)
5882         {
5883           ok = ((opcode == 0x6) || (opcode == 0x7));
5884           jalx_opcode = 0x7;
5885         }
5886       else if (r_type == R_MICROMIPS_26_S1)
5887         {
5888           ok = ((opcode == 0x3d) || (opcode == 0x3c));
5889           jalx_opcode = 0x3c;
5890         }
5891       else
5892         {
5893           ok = ((opcode == 0x3) || (opcode == 0x1d));
5894           jalx_opcode = 0x1d;
5895         }
5896
5897       /* If the opcode is not JAL or JALX, there's a problem.  We cannot
5898          convert J or JALS to JALX.  */
5899       if (!ok)
5900         {
5901           (*_bfd_error_handler)
5902             (_("%B: %A+0x%lx: Unsupported jump between ISA modes; consider recompiling with interlinking enabled."),
5903              input_bfd,
5904              input_section,
5905              (unsigned long) relocation->r_offset);
5906           bfd_set_error (bfd_error_bad_value);
5907           return FALSE;
5908         }
5909
5910       /* Make this the JALX opcode.  */
5911       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
5912     }
5913
5914   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
5915      range.  */
5916   if (!info->relocatable
5917       && !cross_mode_jump_p
5918       && ((JAL_TO_BAL_P (input_bfd)
5919            && r_type == R_MIPS_26
5920            && (x >> 26) == 0x3)         /* jal addr */
5921           || (JALR_TO_BAL_P (input_bfd)
5922               && r_type == R_MIPS_JALR
5923               && x == 0x0320f809)       /* jalr t9 */
5924           || (JR_TO_B_P (input_bfd)
5925               && r_type == R_MIPS_JALR
5926               && x == 0x03200008)))     /* jr t9 */
5927     {
5928       bfd_vma addr;
5929       bfd_vma dest;
5930       bfd_signed_vma off;
5931
5932       addr = (input_section->output_section->vma
5933               + input_section->output_offset
5934               + relocation->r_offset
5935               + 4);
5936       if (r_type == R_MIPS_26)
5937         dest = (value << 2) | ((addr >> 28) << 28);
5938       else
5939         dest = value;
5940       off = dest - addr;
5941       if (off <= 0x1ffff && off >= -0x20000)
5942         {
5943           if (x == 0x03200008)  /* jr t9 */
5944             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
5945           else
5946             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
5947         }
5948     }
5949
5950   /* Put the value into the output.  */
5951   bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location);
5952
5953   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !info->relocatable,
5954                                location);
5955
5956   return TRUE;
5957 }
5958 \f
5959 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
5960    is the original relocation, which is now being transformed into a
5961    dynamic relocation.  The ADDENDP is adjusted if necessary; the
5962    caller should store the result in place of the original addend.  */
5963
5964 static bfd_boolean
5965 mips_elf_create_dynamic_relocation (bfd *output_bfd,
5966                                     struct bfd_link_info *info,
5967                                     const Elf_Internal_Rela *rel,
5968                                     struct mips_elf_link_hash_entry *h,
5969                                     asection *sec, bfd_vma symbol,
5970                                     bfd_vma *addendp, asection *input_section)
5971 {
5972   Elf_Internal_Rela outrel[3];
5973   asection *sreloc;
5974   bfd *dynobj;
5975   int r_type;
5976   long indx;
5977   bfd_boolean defined_p;
5978   struct mips_elf_link_hash_table *htab;
5979
5980   htab = mips_elf_hash_table (info);
5981   BFD_ASSERT (htab != NULL);
5982
5983   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
5984   dynobj = elf_hash_table (info)->dynobj;
5985   sreloc = mips_elf_rel_dyn_section (info, FALSE);
5986   BFD_ASSERT (sreloc != NULL);
5987   BFD_ASSERT (sreloc->contents != NULL);
5988   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
5989               < sreloc->size);
5990
5991   outrel[0].r_offset =
5992     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
5993   if (ABI_64_P (output_bfd))
5994     {
5995       outrel[1].r_offset =
5996         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
5997       outrel[2].r_offset =
5998         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
5999     }
6000
6001   if (outrel[0].r_offset == MINUS_ONE)
6002     /* The relocation field has been deleted.  */
6003     return TRUE;
6004
6005   if (outrel[0].r_offset == MINUS_TWO)
6006     {
6007       /* The relocation field has been converted into a relative value of
6008          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
6009          the field to be fully relocated, so add in the symbol's value.  */
6010       *addendp += symbol;
6011       return TRUE;
6012     }
6013
6014   /* We must now calculate the dynamic symbol table index to use
6015      in the relocation.  */
6016   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
6017     {
6018       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
6019       indx = h->root.dynindx;
6020       if (SGI_COMPAT (output_bfd))
6021         defined_p = h->root.def_regular;
6022       else
6023         /* ??? glibc's ld.so just adds the final GOT entry to the
6024            relocation field.  It therefore treats relocs against
6025            defined symbols in the same way as relocs against
6026            undefined symbols.  */
6027         defined_p = FALSE;
6028     }
6029   else
6030     {
6031       if (sec != NULL && bfd_is_abs_section (sec))
6032         indx = 0;
6033       else if (sec == NULL || sec->owner == NULL)
6034         {
6035           bfd_set_error (bfd_error_bad_value);
6036           return FALSE;
6037         }
6038       else
6039         {
6040           indx = elf_section_data (sec->output_section)->dynindx;
6041           if (indx == 0)
6042             {
6043               asection *osec = htab->root.text_index_section;
6044               indx = elf_section_data (osec)->dynindx;
6045             }
6046           if (indx == 0)
6047             abort ();
6048         }
6049
6050       /* Instead of generating a relocation using the section
6051          symbol, we may as well make it a fully relative
6052          relocation.  We want to avoid generating relocations to
6053          local symbols because we used to generate them
6054          incorrectly, without adding the original symbol value,
6055          which is mandated by the ABI for section symbols.  In
6056          order to give dynamic loaders and applications time to
6057          phase out the incorrect use, we refrain from emitting
6058          section-relative relocations.  It's not like they're
6059          useful, after all.  This should be a bit more efficient
6060          as well.  */
6061       /* ??? Although this behavior is compatible with glibc's ld.so,
6062          the ABI says that relocations against STN_UNDEF should have
6063          a symbol value of 0.  Irix rld honors this, so relocations
6064          against STN_UNDEF have no effect.  */
6065       if (!SGI_COMPAT (output_bfd))
6066         indx = 0;
6067       defined_p = TRUE;
6068     }
6069
6070   /* If the relocation was previously an absolute relocation and
6071      this symbol will not be referred to by the relocation, we must
6072      adjust it by the value we give it in the dynamic symbol table.
6073      Otherwise leave the job up to the dynamic linker.  */
6074   if (defined_p && r_type != R_MIPS_REL32)
6075     *addendp += symbol;
6076
6077   if (htab->is_vxworks)
6078     /* VxWorks uses non-relative relocations for this.  */
6079     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
6080   else
6081     /* The relocation is always an REL32 relocation because we don't
6082        know where the shared library will wind up at load-time.  */
6083     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
6084                                    R_MIPS_REL32);
6085
6086   /* For strict adherence to the ABI specification, we should
6087      generate a R_MIPS_64 relocation record by itself before the
6088      _REL32/_64 record as well, such that the addend is read in as
6089      a 64-bit value (REL32 is a 32-bit relocation, after all).
6090      However, since none of the existing ELF64 MIPS dynamic
6091      loaders seems to care, we don't waste space with these
6092      artificial relocations.  If this turns out to not be true,
6093      mips_elf_allocate_dynamic_relocation() should be tweaked so
6094      as to make room for a pair of dynamic relocations per
6095      invocation if ABI_64_P, and here we should generate an
6096      additional relocation record with R_MIPS_64 by itself for a
6097      NULL symbol before this relocation record.  */
6098   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
6099                                  ABI_64_P (output_bfd)
6100                                  ? R_MIPS_64
6101                                  : R_MIPS_NONE);
6102   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
6103
6104   /* Adjust the output offset of the relocation to reference the
6105      correct location in the output file.  */
6106   outrel[0].r_offset += (input_section->output_section->vma
6107                          + input_section->output_offset);
6108   outrel[1].r_offset += (input_section->output_section->vma
6109                          + input_section->output_offset);
6110   outrel[2].r_offset += (input_section->output_section->vma
6111                          + input_section->output_offset);
6112
6113   /* Put the relocation back out.  We have to use the special
6114      relocation outputter in the 64-bit case since the 64-bit
6115      relocation format is non-standard.  */
6116   if (ABI_64_P (output_bfd))
6117     {
6118       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
6119         (output_bfd, &outrel[0],
6120          (sreloc->contents
6121           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
6122     }
6123   else if (htab->is_vxworks)
6124     {
6125       /* VxWorks uses RELA rather than REL dynamic relocations.  */
6126       outrel[0].r_addend = *addendp;
6127       bfd_elf32_swap_reloca_out
6128         (output_bfd, &outrel[0],
6129          (sreloc->contents
6130           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
6131     }
6132   else
6133     bfd_elf32_swap_reloc_out
6134       (output_bfd, &outrel[0],
6135        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
6136
6137   /* We've now added another relocation.  */
6138   ++sreloc->reloc_count;
6139
6140   /* Make sure the output section is writable.  The dynamic linker
6141      will be writing to it.  */
6142   elf_section_data (input_section->output_section)->this_hdr.sh_flags
6143     |= SHF_WRITE;
6144
6145   /* On IRIX5, make an entry of compact relocation info.  */
6146   if (IRIX_COMPAT (output_bfd) == ict_irix5)
6147     {
6148       asection *scpt = bfd_get_linker_section (dynobj, ".compact_rel");
6149       bfd_byte *cr;
6150
6151       if (scpt)
6152         {
6153           Elf32_crinfo cptrel;
6154
6155           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
6156           cptrel.vaddr = (rel->r_offset
6157                           + input_section->output_section->vma
6158                           + input_section->output_offset);
6159           if (r_type == R_MIPS_REL32)
6160             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
6161           else
6162             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
6163           mips_elf_set_cr_dist2to (cptrel, 0);
6164           cptrel.konst = *addendp;
6165
6166           cr = (scpt->contents
6167                 + sizeof (Elf32_External_compact_rel));
6168           mips_elf_set_cr_relvaddr (cptrel, 0);
6169           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
6170                                      ((Elf32_External_crinfo *) cr
6171                                       + scpt->reloc_count));
6172           ++scpt->reloc_count;
6173         }
6174     }
6175
6176   /* If we've written this relocation for a readonly section,
6177      we need to set DF_TEXTREL again, so that we do not delete the
6178      DT_TEXTREL tag.  */
6179   if (MIPS_ELF_READONLY_SECTION (input_section))
6180     info->flags |= DF_TEXTREL;
6181
6182   return TRUE;
6183 }
6184 \f
6185 /* Return the MACH for a MIPS e_flags value.  */
6186
6187 unsigned long
6188 _bfd_elf_mips_mach (flagword flags)
6189 {
6190   switch (flags & EF_MIPS_MACH)
6191     {
6192     case E_MIPS_MACH_3900:
6193       return bfd_mach_mips3900;
6194
6195     case E_MIPS_MACH_4010:
6196       return bfd_mach_mips4010;
6197
6198     case E_MIPS_MACH_4100:
6199       return bfd_mach_mips4100;
6200
6201     case E_MIPS_MACH_4111:
6202       return bfd_mach_mips4111;
6203
6204     case E_MIPS_MACH_4120:
6205       return bfd_mach_mips4120;
6206
6207     case E_MIPS_MACH_4650:
6208       return bfd_mach_mips4650;
6209
6210     case E_MIPS_MACH_5400:
6211       return bfd_mach_mips5400;
6212
6213     case E_MIPS_MACH_5500:
6214       return bfd_mach_mips5500;
6215
6216     case E_MIPS_MACH_5900:
6217       return bfd_mach_mips5900;
6218
6219     case E_MIPS_MACH_9000:
6220       return bfd_mach_mips9000;
6221
6222     case E_MIPS_MACH_SB1:
6223       return bfd_mach_mips_sb1;
6224
6225     case E_MIPS_MACH_LS2E:
6226       return bfd_mach_mips_loongson_2e;
6227
6228     case E_MIPS_MACH_LS2F:
6229       return bfd_mach_mips_loongson_2f;
6230
6231     case E_MIPS_MACH_LS3A:
6232       return bfd_mach_mips_loongson_3a;
6233
6234     case E_MIPS_MACH_OCTEON2:
6235       return bfd_mach_mips_octeon2;
6236
6237     case E_MIPS_MACH_OCTEON:
6238       return bfd_mach_mips_octeon;
6239
6240     case E_MIPS_MACH_XLR:
6241       return bfd_mach_mips_xlr;
6242
6243     default:
6244       switch (flags & EF_MIPS_ARCH)
6245         {
6246         default:
6247         case E_MIPS_ARCH_1:
6248           return bfd_mach_mips3000;
6249
6250         case E_MIPS_ARCH_2:
6251           return bfd_mach_mips6000;
6252
6253         case E_MIPS_ARCH_3:
6254           return bfd_mach_mips4000;
6255
6256         case E_MIPS_ARCH_4:
6257           return bfd_mach_mips8000;
6258
6259         case E_MIPS_ARCH_5:
6260           return bfd_mach_mips5;
6261
6262         case E_MIPS_ARCH_32:
6263           return bfd_mach_mipsisa32;
6264
6265         case E_MIPS_ARCH_64:
6266           return bfd_mach_mipsisa64;
6267
6268         case E_MIPS_ARCH_32R2:
6269           return bfd_mach_mipsisa32r2;
6270
6271         case E_MIPS_ARCH_64R2:
6272           return bfd_mach_mipsisa64r2;
6273         }
6274     }
6275
6276   return 0;
6277 }
6278
6279 /* Return printable name for ABI.  */
6280
6281 static INLINE char *
6282 elf_mips_abi_name (bfd *abfd)
6283 {
6284   flagword flags;
6285
6286   flags = elf_elfheader (abfd)->e_flags;
6287   switch (flags & EF_MIPS_ABI)
6288     {
6289     case 0:
6290       if (ABI_N32_P (abfd))
6291         return "N32";
6292       else if (ABI_64_P (abfd))
6293         return "64";
6294       else
6295         return "none";
6296     case E_MIPS_ABI_O32:
6297       return "O32";
6298     case E_MIPS_ABI_O64:
6299       return "O64";
6300     case E_MIPS_ABI_EABI32:
6301       return "EABI32";
6302     case E_MIPS_ABI_EABI64:
6303       return "EABI64";
6304     default:
6305       return "unknown abi";
6306     }
6307 }
6308 \f
6309 /* MIPS ELF uses two common sections.  One is the usual one, and the
6310    other is for small objects.  All the small objects are kept
6311    together, and then referenced via the gp pointer, which yields
6312    faster assembler code.  This is what we use for the small common
6313    section.  This approach is copied from ecoff.c.  */
6314 static asection mips_elf_scom_section;
6315 static asymbol mips_elf_scom_symbol;
6316 static asymbol *mips_elf_scom_symbol_ptr;
6317
6318 /* MIPS ELF also uses an acommon section, which represents an
6319    allocated common symbol which may be overridden by a
6320    definition in a shared library.  */
6321 static asection mips_elf_acom_section;
6322 static asymbol mips_elf_acom_symbol;
6323 static asymbol *mips_elf_acom_symbol_ptr;
6324
6325 /* This is used for both the 32-bit and the 64-bit ABI.  */
6326
6327 void
6328 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6329 {
6330   elf_symbol_type *elfsym;
6331
6332   /* Handle the special MIPS section numbers that a symbol may use.  */
6333   elfsym = (elf_symbol_type *) asym;
6334   switch (elfsym->internal_elf_sym.st_shndx)
6335     {
6336     case SHN_MIPS_ACOMMON:
6337       /* This section is used in a dynamically linked executable file.
6338          It is an allocated common section.  The dynamic linker can
6339          either resolve these symbols to something in a shared
6340          library, or it can just leave them here.  For our purposes,
6341          we can consider these symbols to be in a new section.  */
6342       if (mips_elf_acom_section.name == NULL)
6343         {
6344           /* Initialize the acommon section.  */
6345           mips_elf_acom_section.name = ".acommon";
6346           mips_elf_acom_section.flags = SEC_ALLOC;
6347           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6348           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6349           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6350           mips_elf_acom_symbol.name = ".acommon";
6351           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6352           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6353           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6354         }
6355       asym->section = &mips_elf_acom_section;
6356       break;
6357
6358     case SHN_COMMON:
6359       /* Common symbols less than the GP size are automatically
6360          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6361       if (asym->value > elf_gp_size (abfd)
6362           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6363           || IRIX_COMPAT (abfd) == ict_irix6)
6364         break;
6365       /* Fall through.  */
6366     case SHN_MIPS_SCOMMON:
6367       if (mips_elf_scom_section.name == NULL)
6368         {
6369           /* Initialize the small common section.  */
6370           mips_elf_scom_section.name = ".scommon";
6371           mips_elf_scom_section.flags = SEC_IS_COMMON;
6372           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6373           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6374           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6375           mips_elf_scom_symbol.name = ".scommon";
6376           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6377           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6378           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6379         }
6380       asym->section = &mips_elf_scom_section;
6381       asym->value = elfsym->internal_elf_sym.st_size;
6382       break;
6383
6384     case SHN_MIPS_SUNDEFINED:
6385       asym->section = bfd_und_section_ptr;
6386       break;
6387
6388     case SHN_MIPS_TEXT:
6389       {
6390         asection *section = bfd_get_section_by_name (abfd, ".text");
6391
6392         if (section != NULL)
6393           {
6394             asym->section = section;
6395             /* MIPS_TEXT is a bit special, the address is not an offset
6396                to the base of the .text section.  So substract the section
6397                base address to make it an offset.  */
6398             asym->value -= section->vma;
6399           }
6400       }
6401       break;
6402
6403     case SHN_MIPS_DATA:
6404       {
6405         asection *section = bfd_get_section_by_name (abfd, ".data");
6406
6407         if (section != NULL)
6408           {
6409             asym->section = section;
6410             /* MIPS_DATA is a bit special, the address is not an offset
6411                to the base of the .data section.  So substract the section
6412                base address to make it an offset.  */
6413             asym->value -= section->vma;
6414           }
6415       }
6416       break;
6417     }
6418
6419   /* If this is an odd-valued function symbol, assume it's a MIPS16
6420      or microMIPS one.  */
6421   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6422       && (asym->value & 1) != 0)
6423     {
6424       asym->value--;
6425       if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
6426         elfsym->internal_elf_sym.st_other
6427           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6428       else
6429         elfsym->internal_elf_sym.st_other
6430           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6431     }
6432 }
6433 \f
6434 /* Implement elf_backend_eh_frame_address_size.  This differs from
6435    the default in the way it handles EABI64.
6436
6437    EABI64 was originally specified as an LP64 ABI, and that is what
6438    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6439    historically accepted the combination of -mabi=eabi and -mlong32,
6440    and this ILP32 variation has become semi-official over time.
6441    Both forms use elf32 and have pointer-sized FDE addresses.
6442
6443    If an EABI object was generated by GCC 4.0 or above, it will have
6444    an empty .gcc_compiled_longXX section, where XX is the size of longs
6445    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6446    have no special marking to distinguish them from LP64 objects.
6447
6448    We don't want users of the official LP64 ABI to be punished for the
6449    existence of the ILP32 variant, but at the same time, we don't want
6450    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6451    We therefore take the following approach:
6452
6453       - If ABFD contains a .gcc_compiled_longXX section, use it to
6454         determine the pointer size.
6455
6456       - Otherwise check the type of the first relocation.  Assume that
6457         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
6458
6459       - Otherwise punt.
6460
6461    The second check is enough to detect LP64 objects generated by pre-4.0
6462    compilers because, in the kind of output generated by those compilers,
6463    the first relocation will be associated with either a CIE personality
6464    routine or an FDE start address.  Furthermore, the compilers never
6465    used a special (non-pointer) encoding for this ABI.
6466
6467    Checking the relocation type should also be safe because there is no
6468    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
6469    did so.  */
6470
6471 unsigned int
6472 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
6473 {
6474   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
6475     return 8;
6476   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
6477     {
6478       bfd_boolean long32_p, long64_p;
6479
6480       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
6481       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
6482       if (long32_p && long64_p)
6483         return 0;
6484       if (long32_p)
6485         return 4;
6486       if (long64_p)
6487         return 8;
6488
6489       if (sec->reloc_count > 0
6490           && elf_section_data (sec)->relocs != NULL
6491           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
6492               == R_MIPS_64))
6493         return 8;
6494
6495       return 0;
6496     }
6497   return 4;
6498 }
6499 \f
6500 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
6501    relocations against two unnamed section symbols to resolve to the
6502    same address.  For example, if we have code like:
6503
6504         lw      $4,%got_disp(.data)($gp)
6505         lw      $25,%got_disp(.text)($gp)
6506         jalr    $25
6507
6508    then the linker will resolve both relocations to .data and the program
6509    will jump there rather than to .text.
6510
6511    We can work around this problem by giving names to local section symbols.
6512    This is also what the MIPSpro tools do.  */
6513
6514 bfd_boolean
6515 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
6516 {
6517   return SGI_COMPAT (abfd);
6518 }
6519 \f
6520 /* Work over a section just before writing it out.  This routine is
6521    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
6522    sections that need the SHF_MIPS_GPREL flag by name; there has to be
6523    a better way.  */
6524
6525 bfd_boolean
6526 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
6527 {
6528   if (hdr->sh_type == SHT_MIPS_REGINFO
6529       && hdr->sh_size > 0)
6530     {
6531       bfd_byte buf[4];
6532
6533       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
6534       BFD_ASSERT (hdr->contents == NULL);
6535
6536       if (bfd_seek (abfd,
6537                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
6538                     SEEK_SET) != 0)
6539         return FALSE;
6540       H_PUT_32 (abfd, elf_gp (abfd), buf);
6541       if (bfd_bwrite (buf, 4, abfd) != 4)
6542         return FALSE;
6543     }
6544
6545   if (hdr->sh_type == SHT_MIPS_OPTIONS
6546       && hdr->bfd_section != NULL
6547       && mips_elf_section_data (hdr->bfd_section) != NULL
6548       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
6549     {
6550       bfd_byte *contents, *l, *lend;
6551
6552       /* We stored the section contents in the tdata field in the
6553          set_section_contents routine.  We save the section contents
6554          so that we don't have to read them again.
6555          At this point we know that elf_gp is set, so we can look
6556          through the section contents to see if there is an
6557          ODK_REGINFO structure.  */
6558
6559       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
6560       l = contents;
6561       lend = contents + hdr->sh_size;
6562       while (l + sizeof (Elf_External_Options) <= lend)
6563         {
6564           Elf_Internal_Options intopt;
6565
6566           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6567                                         &intopt);
6568           if (intopt.size < sizeof (Elf_External_Options))
6569             {
6570               (*_bfd_error_handler)
6571                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6572                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6573               break;
6574             }
6575           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6576             {
6577               bfd_byte buf[8];
6578
6579               if (bfd_seek (abfd,
6580                             (hdr->sh_offset
6581                              + (l - contents)
6582                              + sizeof (Elf_External_Options)
6583                              + (sizeof (Elf64_External_RegInfo) - 8)),
6584                              SEEK_SET) != 0)
6585                 return FALSE;
6586               H_PUT_64 (abfd, elf_gp (abfd), buf);
6587               if (bfd_bwrite (buf, 8, abfd) != 8)
6588                 return FALSE;
6589             }
6590           else if (intopt.kind == ODK_REGINFO)
6591             {
6592               bfd_byte buf[4];
6593
6594               if (bfd_seek (abfd,
6595                             (hdr->sh_offset
6596                              + (l - contents)
6597                              + sizeof (Elf_External_Options)
6598                              + (sizeof (Elf32_External_RegInfo) - 4)),
6599                             SEEK_SET) != 0)
6600                 return FALSE;
6601               H_PUT_32 (abfd, elf_gp (abfd), buf);
6602               if (bfd_bwrite (buf, 4, abfd) != 4)
6603                 return FALSE;
6604             }
6605           l += intopt.size;
6606         }
6607     }
6608
6609   if (hdr->bfd_section != NULL)
6610     {
6611       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
6612
6613       /* .sbss is not handled specially here because the GNU/Linux
6614          prelinker can convert .sbss from NOBITS to PROGBITS and
6615          changing it back to NOBITS breaks the binary.  The entry in
6616          _bfd_mips_elf_special_sections will ensure the correct flags
6617          are set on .sbss if BFD creates it without reading it from an
6618          input file, and without special handling here the flags set
6619          on it in an input file will be followed.  */
6620       if (strcmp (name, ".sdata") == 0
6621           || strcmp (name, ".lit8") == 0
6622           || strcmp (name, ".lit4") == 0)
6623         {
6624           hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
6625           hdr->sh_type = SHT_PROGBITS;
6626         }
6627       else if (strcmp (name, ".srdata") == 0)
6628         {
6629           hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
6630           hdr->sh_type = SHT_PROGBITS;
6631         }
6632       else if (strcmp (name, ".compact_rel") == 0)
6633         {
6634           hdr->sh_flags = 0;
6635           hdr->sh_type = SHT_PROGBITS;
6636         }
6637       else if (strcmp (name, ".rtproc") == 0)
6638         {
6639           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
6640             {
6641               unsigned int adjust;
6642
6643               adjust = hdr->sh_size % hdr->sh_addralign;
6644               if (adjust != 0)
6645                 hdr->sh_size += hdr->sh_addralign - adjust;
6646             }
6647         }
6648     }
6649
6650   return TRUE;
6651 }
6652
6653 /* Handle a MIPS specific section when reading an object file.  This
6654    is called when elfcode.h finds a section with an unknown type.
6655    This routine supports both the 32-bit and 64-bit ELF ABI.
6656
6657    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
6658    how to.  */
6659
6660 bfd_boolean
6661 _bfd_mips_elf_section_from_shdr (bfd *abfd,
6662                                  Elf_Internal_Shdr *hdr,
6663                                  const char *name,
6664                                  int shindex)
6665 {
6666   flagword flags = 0;
6667
6668   /* There ought to be a place to keep ELF backend specific flags, but
6669      at the moment there isn't one.  We just keep track of the
6670      sections by their name, instead.  Fortunately, the ABI gives
6671      suggested names for all the MIPS specific sections, so we will
6672      probably get away with this.  */
6673   switch (hdr->sh_type)
6674     {
6675     case SHT_MIPS_LIBLIST:
6676       if (strcmp (name, ".liblist") != 0)
6677         return FALSE;
6678       break;
6679     case SHT_MIPS_MSYM:
6680       if (strcmp (name, ".msym") != 0)
6681         return FALSE;
6682       break;
6683     case SHT_MIPS_CONFLICT:
6684       if (strcmp (name, ".conflict") != 0)
6685         return FALSE;
6686       break;
6687     case SHT_MIPS_GPTAB:
6688       if (! CONST_STRNEQ (name, ".gptab."))
6689         return FALSE;
6690       break;
6691     case SHT_MIPS_UCODE:
6692       if (strcmp (name, ".ucode") != 0)
6693         return FALSE;
6694       break;
6695     case SHT_MIPS_DEBUG:
6696       if (strcmp (name, ".mdebug") != 0)
6697         return FALSE;
6698       flags = SEC_DEBUGGING;
6699       break;
6700     case SHT_MIPS_REGINFO:
6701       if (strcmp (name, ".reginfo") != 0
6702           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
6703         return FALSE;
6704       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6705       break;
6706     case SHT_MIPS_IFACE:
6707       if (strcmp (name, ".MIPS.interfaces") != 0)
6708         return FALSE;
6709       break;
6710     case SHT_MIPS_CONTENT:
6711       if (! CONST_STRNEQ (name, ".MIPS.content"))
6712         return FALSE;
6713       break;
6714     case SHT_MIPS_OPTIONS:
6715       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6716         return FALSE;
6717       break;
6718     case SHT_MIPS_DWARF:
6719       if (! CONST_STRNEQ (name, ".debug_")
6720           && ! CONST_STRNEQ (name, ".zdebug_"))
6721         return FALSE;
6722       break;
6723     case SHT_MIPS_SYMBOL_LIB:
6724       if (strcmp (name, ".MIPS.symlib") != 0)
6725         return FALSE;
6726       break;
6727     case SHT_MIPS_EVENTS:
6728       if (! CONST_STRNEQ (name, ".MIPS.events")
6729           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
6730         return FALSE;
6731       break;
6732     default:
6733       break;
6734     }
6735
6736   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
6737     return FALSE;
6738
6739   if (flags)
6740     {
6741       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
6742                                    (bfd_get_section_flags (abfd,
6743                                                            hdr->bfd_section)
6744                                     | flags)))
6745         return FALSE;
6746     }
6747
6748   /* FIXME: We should record sh_info for a .gptab section.  */
6749
6750   /* For a .reginfo section, set the gp value in the tdata information
6751      from the contents of this section.  We need the gp value while
6752      processing relocs, so we just get it now.  The .reginfo section
6753      is not used in the 64-bit MIPS ELF ABI.  */
6754   if (hdr->sh_type == SHT_MIPS_REGINFO)
6755     {
6756       Elf32_External_RegInfo ext;
6757       Elf32_RegInfo s;
6758
6759       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
6760                                       &ext, 0, sizeof ext))
6761         return FALSE;
6762       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
6763       elf_gp (abfd) = s.ri_gp_value;
6764     }
6765
6766   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
6767      set the gp value based on what we find.  We may see both
6768      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
6769      they should agree.  */
6770   if (hdr->sh_type == SHT_MIPS_OPTIONS)
6771     {
6772       bfd_byte *contents, *l, *lend;
6773
6774       contents = bfd_malloc (hdr->sh_size);
6775       if (contents == NULL)
6776         return FALSE;
6777       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
6778                                       0, hdr->sh_size))
6779         {
6780           free (contents);
6781           return FALSE;
6782         }
6783       l = contents;
6784       lend = contents + hdr->sh_size;
6785       while (l + sizeof (Elf_External_Options) <= lend)
6786         {
6787           Elf_Internal_Options intopt;
6788
6789           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6790                                         &intopt);
6791           if (intopt.size < sizeof (Elf_External_Options))
6792             {
6793               (*_bfd_error_handler)
6794                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6795                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6796               break;
6797             }
6798           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6799             {
6800               Elf64_Internal_RegInfo intreg;
6801
6802               bfd_mips_elf64_swap_reginfo_in
6803                 (abfd,
6804                  ((Elf64_External_RegInfo *)
6805                   (l + sizeof (Elf_External_Options))),
6806                  &intreg);
6807               elf_gp (abfd) = intreg.ri_gp_value;
6808             }
6809           else if (intopt.kind == ODK_REGINFO)
6810             {
6811               Elf32_RegInfo intreg;
6812
6813               bfd_mips_elf32_swap_reginfo_in
6814                 (abfd,
6815                  ((Elf32_External_RegInfo *)
6816                   (l + sizeof (Elf_External_Options))),
6817                  &intreg);
6818               elf_gp (abfd) = intreg.ri_gp_value;
6819             }
6820           l += intopt.size;
6821         }
6822       free (contents);
6823     }
6824
6825   return TRUE;
6826 }
6827
6828 /* Set the correct type for a MIPS ELF section.  We do this by the
6829    section name, which is a hack, but ought to work.  This routine is
6830    used by both the 32-bit and the 64-bit ABI.  */
6831
6832 bfd_boolean
6833 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
6834 {
6835   const char *name = bfd_get_section_name (abfd, sec);
6836
6837   if (strcmp (name, ".liblist") == 0)
6838     {
6839       hdr->sh_type = SHT_MIPS_LIBLIST;
6840       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
6841       /* The sh_link field is set in final_write_processing.  */
6842     }
6843   else if (strcmp (name, ".conflict") == 0)
6844     hdr->sh_type = SHT_MIPS_CONFLICT;
6845   else if (CONST_STRNEQ (name, ".gptab."))
6846     {
6847       hdr->sh_type = SHT_MIPS_GPTAB;
6848       hdr->sh_entsize = sizeof (Elf32_External_gptab);
6849       /* The sh_info field is set in final_write_processing.  */
6850     }
6851   else if (strcmp (name, ".ucode") == 0)
6852     hdr->sh_type = SHT_MIPS_UCODE;
6853   else if (strcmp (name, ".mdebug") == 0)
6854     {
6855       hdr->sh_type = SHT_MIPS_DEBUG;
6856       /* In a shared object on IRIX 5.3, the .mdebug section has an
6857          entsize of 0.  FIXME: Does this matter?  */
6858       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
6859         hdr->sh_entsize = 0;
6860       else
6861         hdr->sh_entsize = 1;
6862     }
6863   else if (strcmp (name, ".reginfo") == 0)
6864     {
6865       hdr->sh_type = SHT_MIPS_REGINFO;
6866       /* In a shared object on IRIX 5.3, the .reginfo section has an
6867          entsize of 0x18.  FIXME: Does this matter?  */
6868       if (SGI_COMPAT (abfd))
6869         {
6870           if ((abfd->flags & DYNAMIC) != 0)
6871             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6872           else
6873             hdr->sh_entsize = 1;
6874         }
6875       else
6876         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6877     }
6878   else if (SGI_COMPAT (abfd)
6879            && (strcmp (name, ".hash") == 0
6880                || strcmp (name, ".dynamic") == 0
6881                || strcmp (name, ".dynstr") == 0))
6882     {
6883       if (SGI_COMPAT (abfd))
6884         hdr->sh_entsize = 0;
6885 #if 0
6886       /* This isn't how the IRIX6 linker behaves.  */
6887       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
6888 #endif
6889     }
6890   else if (strcmp (name, ".got") == 0
6891            || strcmp (name, ".srdata") == 0
6892            || strcmp (name, ".sdata") == 0
6893            || strcmp (name, ".sbss") == 0
6894            || strcmp (name, ".lit4") == 0
6895            || strcmp (name, ".lit8") == 0)
6896     hdr->sh_flags |= SHF_MIPS_GPREL;
6897   else if (strcmp (name, ".MIPS.interfaces") == 0)
6898     {
6899       hdr->sh_type = SHT_MIPS_IFACE;
6900       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6901     }
6902   else if (CONST_STRNEQ (name, ".MIPS.content"))
6903     {
6904       hdr->sh_type = SHT_MIPS_CONTENT;
6905       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6906       /* The sh_info field is set in final_write_processing.  */
6907     }
6908   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6909     {
6910       hdr->sh_type = SHT_MIPS_OPTIONS;
6911       hdr->sh_entsize = 1;
6912       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6913     }
6914   else if (CONST_STRNEQ (name, ".debug_")
6915            || CONST_STRNEQ (name, ".zdebug_"))
6916     {
6917       hdr->sh_type = SHT_MIPS_DWARF;
6918
6919       /* Irix facilities such as libexc expect a single .debug_frame
6920          per executable, the system ones have NOSTRIP set and the linker
6921          doesn't merge sections with different flags so ...  */
6922       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
6923         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6924     }
6925   else if (strcmp (name, ".MIPS.symlib") == 0)
6926     {
6927       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
6928       /* The sh_link and sh_info fields are set in
6929          final_write_processing.  */
6930     }
6931   else if (CONST_STRNEQ (name, ".MIPS.events")
6932            || CONST_STRNEQ (name, ".MIPS.post_rel"))
6933     {
6934       hdr->sh_type = SHT_MIPS_EVENTS;
6935       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6936       /* The sh_link field is set in final_write_processing.  */
6937     }
6938   else if (strcmp (name, ".msym") == 0)
6939     {
6940       hdr->sh_type = SHT_MIPS_MSYM;
6941       hdr->sh_flags |= SHF_ALLOC;
6942       hdr->sh_entsize = 8;
6943     }
6944
6945   /* The generic elf_fake_sections will set up REL_HDR using the default
6946    kind of relocations.  We used to set up a second header for the
6947    non-default kind of relocations here, but only NewABI would use
6948    these, and the IRIX ld doesn't like resulting empty RELA sections.
6949    Thus we create those header only on demand now.  */
6950
6951   return TRUE;
6952 }
6953
6954 /* Given a BFD section, try to locate the corresponding ELF section
6955    index.  This is used by both the 32-bit and the 64-bit ABI.
6956    Actually, it's not clear to me that the 64-bit ABI supports these,
6957    but for non-PIC objects we will certainly want support for at least
6958    the .scommon section.  */
6959
6960 bfd_boolean
6961 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
6962                                         asection *sec, int *retval)
6963 {
6964   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
6965     {
6966       *retval = SHN_MIPS_SCOMMON;
6967       return TRUE;
6968     }
6969   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
6970     {
6971       *retval = SHN_MIPS_ACOMMON;
6972       return TRUE;
6973     }
6974   return FALSE;
6975 }
6976 \f
6977 /* Hook called by the linker routine which adds symbols from an object
6978    file.  We must handle the special MIPS section numbers here.  */
6979
6980 bfd_boolean
6981 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
6982                                Elf_Internal_Sym *sym, const char **namep,
6983                                flagword *flagsp ATTRIBUTE_UNUSED,
6984                                asection **secp, bfd_vma *valp)
6985 {
6986   if (SGI_COMPAT (abfd)
6987       && (abfd->flags & DYNAMIC) != 0
6988       && strcmp (*namep, "_rld_new_interface") == 0)
6989     {
6990       /* Skip IRIX5 rld entry name.  */
6991       *namep = NULL;
6992       return TRUE;
6993     }
6994
6995   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
6996      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
6997      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
6998      a magic symbol resolved by the linker, we ignore this bogus definition
6999      of _gp_disp.  New ABI objects do not suffer from this problem so this
7000      is not done for them. */
7001   if (!NEWABI_P(abfd)
7002       && (sym->st_shndx == SHN_ABS)
7003       && (strcmp (*namep, "_gp_disp") == 0))
7004     {
7005       *namep = NULL;
7006       return TRUE;
7007     }
7008
7009   switch (sym->st_shndx)
7010     {
7011     case SHN_COMMON:
7012       /* Common symbols less than the GP size are automatically
7013          treated as SHN_MIPS_SCOMMON symbols.  */
7014       if (sym->st_size > elf_gp_size (abfd)
7015           || ELF_ST_TYPE (sym->st_info) == STT_TLS
7016           || IRIX_COMPAT (abfd) == ict_irix6)
7017         break;
7018       /* Fall through.  */
7019     case SHN_MIPS_SCOMMON:
7020       *secp = bfd_make_section_old_way (abfd, ".scommon");
7021       (*secp)->flags |= SEC_IS_COMMON;
7022       *valp = sym->st_size;
7023       break;
7024
7025     case SHN_MIPS_TEXT:
7026       /* This section is used in a shared object.  */
7027       if (elf_tdata (abfd)->elf_text_section == NULL)
7028         {
7029           asymbol *elf_text_symbol;
7030           asection *elf_text_section;
7031           bfd_size_type amt = sizeof (asection);
7032
7033           elf_text_section = bfd_zalloc (abfd, amt);
7034           if (elf_text_section == NULL)
7035             return FALSE;
7036
7037           amt = sizeof (asymbol);
7038           elf_text_symbol = bfd_zalloc (abfd, amt);
7039           if (elf_text_symbol == NULL)
7040             return FALSE;
7041
7042           /* Initialize the section.  */
7043
7044           elf_tdata (abfd)->elf_text_section = elf_text_section;
7045           elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
7046
7047           elf_text_section->symbol = elf_text_symbol;
7048           elf_text_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_text_symbol;
7049
7050           elf_text_section->name = ".text";
7051           elf_text_section->flags = SEC_NO_FLAGS;
7052           elf_text_section->output_section = NULL;
7053           elf_text_section->owner = abfd;
7054           elf_text_symbol->name = ".text";
7055           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7056           elf_text_symbol->section = elf_text_section;
7057         }
7058       /* This code used to do *secp = bfd_und_section_ptr if
7059          info->shared.  I don't know why, and that doesn't make sense,
7060          so I took it out.  */
7061       *secp = elf_tdata (abfd)->elf_text_section;
7062       break;
7063
7064     case SHN_MIPS_ACOMMON:
7065       /* Fall through. XXX Can we treat this as allocated data?  */
7066     case SHN_MIPS_DATA:
7067       /* This section is used in a shared object.  */
7068       if (elf_tdata (abfd)->elf_data_section == NULL)
7069         {
7070           asymbol *elf_data_symbol;
7071           asection *elf_data_section;
7072           bfd_size_type amt = sizeof (asection);
7073
7074           elf_data_section = bfd_zalloc (abfd, amt);
7075           if (elf_data_section == NULL)
7076             return FALSE;
7077
7078           amt = sizeof (asymbol);
7079           elf_data_symbol = bfd_zalloc (abfd, amt);
7080           if (elf_data_symbol == NULL)
7081             return FALSE;
7082
7083           /* Initialize the section.  */
7084
7085           elf_tdata (abfd)->elf_data_section = elf_data_section;
7086           elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
7087
7088           elf_data_section->symbol = elf_data_symbol;
7089           elf_data_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_data_symbol;
7090
7091           elf_data_section->name = ".data";
7092           elf_data_section->flags = SEC_NO_FLAGS;
7093           elf_data_section->output_section = NULL;
7094           elf_data_section->owner = abfd;
7095           elf_data_symbol->name = ".data";
7096           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7097           elf_data_symbol->section = elf_data_section;
7098         }
7099       /* This code used to do *secp = bfd_und_section_ptr if
7100          info->shared.  I don't know why, and that doesn't make sense,
7101          so I took it out.  */
7102       *secp = elf_tdata (abfd)->elf_data_section;
7103       break;
7104
7105     case SHN_MIPS_SUNDEFINED:
7106       *secp = bfd_und_section_ptr;
7107       break;
7108     }
7109
7110   if (SGI_COMPAT (abfd)
7111       && ! info->shared
7112       && info->output_bfd->xvec == abfd->xvec
7113       && strcmp (*namep, "__rld_obj_head") == 0)
7114     {
7115       struct elf_link_hash_entry *h;
7116       struct bfd_link_hash_entry *bh;
7117
7118       /* Mark __rld_obj_head as dynamic.  */
7119       bh = NULL;
7120       if (! (_bfd_generic_link_add_one_symbol
7121              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
7122               get_elf_backend_data (abfd)->collect, &bh)))
7123         return FALSE;
7124
7125       h = (struct elf_link_hash_entry *) bh;
7126       h->non_elf = 0;
7127       h->def_regular = 1;
7128       h->type = STT_OBJECT;
7129
7130       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7131         return FALSE;
7132
7133       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
7134       mips_elf_hash_table (info)->rld_symbol = h;
7135     }
7136
7137   /* If this is a mips16 text symbol, add 1 to the value to make it
7138      odd.  This will cause something like .word SYM to come up with
7139      the right value when it is loaded into the PC.  */
7140   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7141     ++*valp;
7142
7143   return TRUE;
7144 }
7145
7146 /* This hook function is called before the linker writes out a global
7147    symbol.  We mark symbols as small common if appropriate.  This is
7148    also where we undo the increment of the value for a mips16 symbol.  */
7149
7150 int
7151 _bfd_mips_elf_link_output_symbol_hook
7152   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
7153    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
7154    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
7155 {
7156   /* If we see a common symbol, which implies a relocatable link, then
7157      if a symbol was small common in an input file, mark it as small
7158      common in the output file.  */
7159   if (sym->st_shndx == SHN_COMMON
7160       && strcmp (input_sec->name, ".scommon") == 0)
7161     sym->st_shndx = SHN_MIPS_SCOMMON;
7162
7163   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7164     sym->st_value &= ~1;
7165
7166   return 1;
7167 }
7168 \f
7169 /* Functions for the dynamic linker.  */
7170
7171 /* Create dynamic sections when linking against a dynamic object.  */
7172
7173 bfd_boolean
7174 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
7175 {
7176   struct elf_link_hash_entry *h;
7177   struct bfd_link_hash_entry *bh;
7178   flagword flags;
7179   register asection *s;
7180   const char * const *namep;
7181   struct mips_elf_link_hash_table *htab;
7182
7183   htab = mips_elf_hash_table (info);
7184   BFD_ASSERT (htab != NULL);
7185
7186   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
7187            | SEC_LINKER_CREATED | SEC_READONLY);
7188
7189   /* The psABI requires a read-only .dynamic section, but the VxWorks
7190      EABI doesn't.  */
7191   if (!htab->is_vxworks)
7192     {
7193       s = bfd_get_linker_section (abfd, ".dynamic");
7194       if (s != NULL)
7195         {
7196           if (! bfd_set_section_flags (abfd, s, flags))
7197             return FALSE;
7198         }
7199     }
7200
7201   /* We need to create .got section.  */
7202   if (!mips_elf_create_got_section (abfd, info))
7203     return FALSE;
7204
7205   if (! mips_elf_rel_dyn_section (info, TRUE))
7206     return FALSE;
7207
7208   /* Create .stub section.  */
7209   s = bfd_make_section_anyway_with_flags (abfd,
7210                                           MIPS_ELF_STUB_SECTION_NAME (abfd),
7211                                           flags | SEC_CODE);
7212   if (s == NULL
7213       || ! bfd_set_section_alignment (abfd, s,
7214                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7215     return FALSE;
7216   htab->sstubs = s;
7217
7218   if (!mips_elf_hash_table (info)->use_rld_obj_head
7219       && !info->shared
7220       && bfd_get_linker_section (abfd, ".rld_map") == NULL)
7221     {
7222       s = bfd_make_section_anyway_with_flags (abfd, ".rld_map",
7223                                               flags &~ (flagword) SEC_READONLY);
7224       if (s == NULL
7225           || ! bfd_set_section_alignment (abfd, s,
7226                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7227         return FALSE;
7228     }
7229
7230   /* On IRIX5, we adjust add some additional symbols and change the
7231      alignments of several sections.  There is no ABI documentation
7232      indicating that this is necessary on IRIX6, nor any evidence that
7233      the linker takes such action.  */
7234   if (IRIX_COMPAT (abfd) == ict_irix5)
7235     {
7236       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7237         {
7238           bh = NULL;
7239           if (! (_bfd_generic_link_add_one_symbol
7240                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7241                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7242             return FALSE;
7243
7244           h = (struct elf_link_hash_entry *) bh;
7245           h->non_elf = 0;
7246           h->def_regular = 1;
7247           h->type = STT_SECTION;
7248
7249           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7250             return FALSE;
7251         }
7252
7253       /* We need to create a .compact_rel section.  */
7254       if (SGI_COMPAT (abfd))
7255         {
7256           if (!mips_elf_create_compact_rel_section (abfd, info))
7257             return FALSE;
7258         }
7259
7260       /* Change alignments of some sections.  */
7261       s = bfd_get_linker_section (abfd, ".hash");
7262       if (s != NULL)
7263         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7264       s = bfd_get_linker_section (abfd, ".dynsym");
7265       if (s != NULL)
7266         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7267       s = bfd_get_linker_section (abfd, ".dynstr");
7268       if (s != NULL)
7269         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7270       /* ??? */
7271       s = bfd_get_section_by_name (abfd, ".reginfo");
7272       if (s != NULL)
7273         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7274       s = bfd_get_linker_section (abfd, ".dynamic");
7275       if (s != NULL)
7276         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7277     }
7278
7279   if (!info->shared)
7280     {
7281       const char *name;
7282
7283       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7284       bh = NULL;
7285       if (!(_bfd_generic_link_add_one_symbol
7286             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7287              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7288         return FALSE;
7289
7290       h = (struct elf_link_hash_entry *) bh;
7291       h->non_elf = 0;
7292       h->def_regular = 1;
7293       h->type = STT_SECTION;
7294
7295       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7296         return FALSE;
7297
7298       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7299         {
7300           /* __rld_map is a four byte word located in the .data section
7301              and is filled in by the rtld to contain a pointer to
7302              the _r_debug structure. Its symbol value will be set in
7303              _bfd_mips_elf_finish_dynamic_symbol.  */
7304           s = bfd_get_linker_section (abfd, ".rld_map");
7305           BFD_ASSERT (s != NULL);
7306
7307           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7308           bh = NULL;
7309           if (!(_bfd_generic_link_add_one_symbol
7310                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7311                  get_elf_backend_data (abfd)->collect, &bh)))
7312             return FALSE;
7313
7314           h = (struct elf_link_hash_entry *) bh;
7315           h->non_elf = 0;
7316           h->def_regular = 1;
7317           h->type = STT_OBJECT;
7318
7319           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7320             return FALSE;
7321           mips_elf_hash_table (info)->rld_symbol = h;
7322         }
7323     }
7324
7325   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7326      Also create the _PROCEDURE_LINKAGE_TABLE symbol.  */
7327   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7328     return FALSE;
7329
7330   /* Cache the sections created above.  */
7331   htab->splt = bfd_get_linker_section (abfd, ".plt");
7332   htab->sdynbss = bfd_get_linker_section (abfd, ".dynbss");
7333   if (htab->is_vxworks)
7334     {
7335       htab->srelbss = bfd_get_linker_section (abfd, ".rela.bss");
7336       htab->srelplt = bfd_get_linker_section (abfd, ".rela.plt");
7337     }
7338   else
7339     htab->srelplt = bfd_get_linker_section (abfd, ".rel.plt");
7340   if (!htab->sdynbss
7341       || (htab->is_vxworks && !htab->srelbss && !info->shared)
7342       || !htab->srelplt
7343       || !htab->splt)
7344     abort ();
7345
7346   if (htab->is_vxworks)
7347     {
7348       /* Do the usual VxWorks handling.  */
7349       if (!elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7350         return FALSE;
7351
7352       /* Work out the PLT sizes.  */
7353       if (info->shared)
7354         {
7355           htab->plt_header_size
7356             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
7357           htab->plt_entry_size
7358             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
7359         }
7360       else
7361         {
7362           htab->plt_header_size
7363             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
7364           htab->plt_entry_size
7365             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
7366         }
7367     }
7368   else if (!info->shared)
7369     {
7370       /* All variants of the plt0 entry are the same size.  */
7371       htab->plt_header_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
7372       htab->plt_entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
7373     }
7374
7375   return TRUE;
7376 }
7377 \f
7378 /* Return true if relocation REL against section SEC is a REL rather than
7379    RELA relocation.  RELOCS is the first relocation in the section and
7380    ABFD is the bfd that contains SEC.  */
7381
7382 static bfd_boolean
7383 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7384                            const Elf_Internal_Rela *relocs,
7385                            const Elf_Internal_Rela *rel)
7386 {
7387   Elf_Internal_Shdr *rel_hdr;
7388   const struct elf_backend_data *bed;
7389
7390   /* To determine which flavor of relocation this is, we depend on the
7391      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7392   rel_hdr = elf_section_data (sec)->rel.hdr;
7393   if (rel_hdr == NULL)
7394     return FALSE;
7395   bed = get_elf_backend_data (abfd);
7396   return ((size_t) (rel - relocs)
7397           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7398 }
7399
7400 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7401    HOWTO is the relocation's howto and CONTENTS points to the contents
7402    of the section that REL is against.  */
7403
7404 static bfd_vma
7405 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7406                           reloc_howto_type *howto, bfd_byte *contents)
7407 {
7408   bfd_byte *location;
7409   unsigned int r_type;
7410   bfd_vma addend;
7411
7412   r_type = ELF_R_TYPE (abfd, rel->r_info);
7413   location = contents + rel->r_offset;
7414
7415   /* Get the addend, which is stored in the input file.  */
7416   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7417   addend = mips_elf_obtain_contents (howto, rel, abfd, contents);
7418   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7419
7420   return addend & howto->src_mask;
7421 }
7422
7423 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7424    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7425    and update *ADDEND with the final addend.  Return true on success
7426    or false if the LO16 could not be found.  RELEND is the exclusive
7427    upper bound on the relocations for REL's section.  */
7428
7429 static bfd_boolean
7430 mips_elf_add_lo16_rel_addend (bfd *abfd,
7431                               const Elf_Internal_Rela *rel,
7432                               const Elf_Internal_Rela *relend,
7433                               bfd_byte *contents, bfd_vma *addend)
7434 {
7435   unsigned int r_type, lo16_type;
7436   const Elf_Internal_Rela *lo16_relocation;
7437   reloc_howto_type *lo16_howto;
7438   bfd_vma l;
7439
7440   r_type = ELF_R_TYPE (abfd, rel->r_info);
7441   if (mips16_reloc_p (r_type))
7442     lo16_type = R_MIPS16_LO16;
7443   else if (micromips_reloc_p (r_type))
7444     lo16_type = R_MICROMIPS_LO16;
7445   else
7446     lo16_type = R_MIPS_LO16;
7447
7448   /* The combined value is the sum of the HI16 addend, left-shifted by
7449      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7450      code does a `lui' of the HI16 value, and then an `addiu' of the
7451      LO16 value.)
7452
7453      Scan ahead to find a matching LO16 relocation.
7454
7455      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7456      be immediately following.  However, for the IRIX6 ABI, the next
7457      relocation may be a composed relocation consisting of several
7458      relocations for the same address.  In that case, the R_MIPS_LO16
7459      relocation may occur as one of these.  We permit a similar
7460      extension in general, as that is useful for GCC.
7461
7462      In some cases GCC dead code elimination removes the LO16 but keeps
7463      the corresponding HI16.  This is strictly speaking a violation of
7464      the ABI but not immediately harmful.  */
7465   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
7466   if (lo16_relocation == NULL)
7467     return FALSE;
7468
7469   /* Obtain the addend kept there.  */
7470   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
7471   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
7472
7473   l <<= lo16_howto->rightshift;
7474   l = _bfd_mips_elf_sign_extend (l, 16);
7475
7476   *addend <<= 16;
7477   *addend += l;
7478   return TRUE;
7479 }
7480
7481 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
7482    store the contents in *CONTENTS on success.  Assume that *CONTENTS
7483    already holds the contents if it is nonull on entry.  */
7484
7485 static bfd_boolean
7486 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
7487 {
7488   if (*contents)
7489     return TRUE;
7490
7491   /* Get cached copy if it exists.  */
7492   if (elf_section_data (sec)->this_hdr.contents != NULL)
7493     {
7494       *contents = elf_section_data (sec)->this_hdr.contents;
7495       return TRUE;
7496     }
7497
7498   return bfd_malloc_and_get_section (abfd, sec, contents);
7499 }
7500
7501 /* Look through the relocs for a section during the first phase, and
7502    allocate space in the global offset table.  */
7503
7504 bfd_boolean
7505 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
7506                             asection *sec, const Elf_Internal_Rela *relocs)
7507 {
7508   const char *name;
7509   bfd *dynobj;
7510   Elf_Internal_Shdr *symtab_hdr;
7511   struct elf_link_hash_entry **sym_hashes;
7512   size_t extsymoff;
7513   const Elf_Internal_Rela *rel;
7514   const Elf_Internal_Rela *rel_end;
7515   asection *sreloc;
7516   const struct elf_backend_data *bed;
7517   struct mips_elf_link_hash_table *htab;
7518   bfd_byte *contents;
7519   bfd_vma addend;
7520   reloc_howto_type *howto;
7521
7522   if (info->relocatable)
7523     return TRUE;
7524
7525   htab = mips_elf_hash_table (info);
7526   BFD_ASSERT (htab != NULL);
7527
7528   dynobj = elf_hash_table (info)->dynobj;
7529   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7530   sym_hashes = elf_sym_hashes (abfd);
7531   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
7532
7533   bed = get_elf_backend_data (abfd);
7534   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
7535
7536   /* Check for the mips16 stub sections.  */
7537
7538   name = bfd_get_section_name (abfd, sec);
7539   if (FN_STUB_P (name))
7540     {
7541       unsigned long r_symndx;
7542
7543       /* Look at the relocation information to figure out which symbol
7544          this is for.  */
7545
7546       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7547       if (r_symndx == 0)
7548         {
7549           (*_bfd_error_handler)
7550             (_("%B: Warning: cannot determine the target function for"
7551                " stub section `%s'"),
7552              abfd, name);
7553           bfd_set_error (bfd_error_bad_value);
7554           return FALSE;
7555         }
7556
7557       if (r_symndx < extsymoff
7558           || sym_hashes[r_symndx - extsymoff] == NULL)
7559         {
7560           asection *o;
7561
7562           /* This stub is for a local symbol.  This stub will only be
7563              needed if there is some relocation in this BFD, other
7564              than a 16 bit function call, which refers to this symbol.  */
7565           for (o = abfd->sections; o != NULL; o = o->next)
7566             {
7567               Elf_Internal_Rela *sec_relocs;
7568               const Elf_Internal_Rela *r, *rend;
7569
7570               /* We can ignore stub sections when looking for relocs.  */
7571               if ((o->flags & SEC_RELOC) == 0
7572                   || o->reloc_count == 0
7573                   || section_allows_mips16_refs_p (o))
7574                 continue;
7575
7576               sec_relocs
7577                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7578                                              info->keep_memory);
7579               if (sec_relocs == NULL)
7580                 return FALSE;
7581
7582               rend = sec_relocs + o->reloc_count;
7583               for (r = sec_relocs; r < rend; r++)
7584                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7585                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
7586                   break;
7587
7588               if (elf_section_data (o)->relocs != sec_relocs)
7589                 free (sec_relocs);
7590
7591               if (r < rend)
7592                 break;
7593             }
7594
7595           if (o == NULL)
7596             {
7597               /* There is no non-call reloc for this stub, so we do
7598                  not need it.  Since this function is called before
7599                  the linker maps input sections to output sections, we
7600                  can easily discard it by setting the SEC_EXCLUDE
7601                  flag.  */
7602               sec->flags |= SEC_EXCLUDE;
7603               return TRUE;
7604             }
7605
7606           /* Record this stub in an array of local symbol stubs for
7607              this BFD.  */
7608           if (elf_tdata (abfd)->local_stubs == NULL)
7609             {
7610               unsigned long symcount;
7611               asection **n;
7612               bfd_size_type amt;
7613
7614               if (elf_bad_symtab (abfd))
7615                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7616               else
7617                 symcount = symtab_hdr->sh_info;
7618               amt = symcount * sizeof (asection *);
7619               n = bfd_zalloc (abfd, amt);
7620               if (n == NULL)
7621                 return FALSE;
7622               elf_tdata (abfd)->local_stubs = n;
7623             }
7624
7625           sec->flags |= SEC_KEEP;
7626           elf_tdata (abfd)->local_stubs[r_symndx] = sec;
7627
7628           /* We don't need to set mips16_stubs_seen in this case.
7629              That flag is used to see whether we need to look through
7630              the global symbol table for stubs.  We don't need to set
7631              it here, because we just have a local stub.  */
7632         }
7633       else
7634         {
7635           struct mips_elf_link_hash_entry *h;
7636
7637           h = ((struct mips_elf_link_hash_entry *)
7638                sym_hashes[r_symndx - extsymoff]);
7639
7640           while (h->root.root.type == bfd_link_hash_indirect
7641                  || h->root.root.type == bfd_link_hash_warning)
7642             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
7643
7644           /* H is the symbol this stub is for.  */
7645
7646           /* If we already have an appropriate stub for this function, we
7647              don't need another one, so we can discard this one.  Since
7648              this function is called before the linker maps input sections
7649              to output sections, we can easily discard it by setting the
7650              SEC_EXCLUDE flag.  */
7651           if (h->fn_stub != NULL)
7652             {
7653               sec->flags |= SEC_EXCLUDE;
7654               return TRUE;
7655             }
7656
7657           sec->flags |= SEC_KEEP;
7658           h->fn_stub = sec;
7659           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7660         }
7661     }
7662   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
7663     {
7664       unsigned long r_symndx;
7665       struct mips_elf_link_hash_entry *h;
7666       asection **loc;
7667
7668       /* Look at the relocation information to figure out which symbol
7669          this is for.  */
7670
7671       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7672       if (r_symndx == 0)
7673         {
7674           (*_bfd_error_handler)
7675             (_("%B: Warning: cannot determine the target function for"
7676                " stub section `%s'"),
7677              abfd, name);
7678           bfd_set_error (bfd_error_bad_value);
7679           return FALSE;
7680         }
7681
7682       if (r_symndx < extsymoff
7683           || sym_hashes[r_symndx - extsymoff] == NULL)
7684         {
7685           asection *o;
7686
7687           /* This stub is for a local symbol.  This stub will only be
7688              needed if there is some relocation (R_MIPS16_26) in this BFD
7689              that refers to this symbol.  */
7690           for (o = abfd->sections; o != NULL; o = o->next)
7691             {
7692               Elf_Internal_Rela *sec_relocs;
7693               const Elf_Internal_Rela *r, *rend;
7694
7695               /* We can ignore stub sections when looking for relocs.  */
7696               if ((o->flags & SEC_RELOC) == 0
7697                   || o->reloc_count == 0
7698                   || section_allows_mips16_refs_p (o))
7699                 continue;
7700
7701               sec_relocs
7702                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7703                                              info->keep_memory);
7704               if (sec_relocs == NULL)
7705                 return FALSE;
7706
7707               rend = sec_relocs + o->reloc_count;
7708               for (r = sec_relocs; r < rend; r++)
7709                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7710                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
7711                     break;
7712
7713               if (elf_section_data (o)->relocs != sec_relocs)
7714                 free (sec_relocs);
7715
7716               if (r < rend)
7717                 break;
7718             }
7719
7720           if (o == NULL)
7721             {
7722               /* There is no non-call reloc for this stub, so we do
7723                  not need it.  Since this function is called before
7724                  the linker maps input sections to output sections, we
7725                  can easily discard it by setting the SEC_EXCLUDE
7726                  flag.  */
7727               sec->flags |= SEC_EXCLUDE;
7728               return TRUE;
7729             }
7730
7731           /* Record this stub in an array of local symbol call_stubs for
7732              this BFD.  */
7733           if (elf_tdata (abfd)->local_call_stubs == NULL)
7734             {
7735               unsigned long symcount;
7736               asection **n;
7737               bfd_size_type amt;
7738
7739               if (elf_bad_symtab (abfd))
7740                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7741               else
7742                 symcount = symtab_hdr->sh_info;
7743               amt = symcount * sizeof (asection *);
7744               n = bfd_zalloc (abfd, amt);
7745               if (n == NULL)
7746                 return FALSE;
7747               elf_tdata (abfd)->local_call_stubs = n;
7748             }
7749
7750           sec->flags |= SEC_KEEP;
7751           elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
7752
7753           /* We don't need to set mips16_stubs_seen in this case.
7754              That flag is used to see whether we need to look through
7755              the global symbol table for stubs.  We don't need to set
7756              it here, because we just have a local stub.  */
7757         }
7758       else
7759         {
7760           h = ((struct mips_elf_link_hash_entry *)
7761                sym_hashes[r_symndx - extsymoff]);
7762
7763           /* H is the symbol this stub is for.  */
7764
7765           if (CALL_FP_STUB_P (name))
7766             loc = &h->call_fp_stub;
7767           else
7768             loc = &h->call_stub;
7769
7770           /* If we already have an appropriate stub for this function, we
7771              don't need another one, so we can discard this one.  Since
7772              this function is called before the linker maps input sections
7773              to output sections, we can easily discard it by setting the
7774              SEC_EXCLUDE flag.  */
7775           if (*loc != NULL)
7776             {
7777               sec->flags |= SEC_EXCLUDE;
7778               return TRUE;
7779             }
7780
7781           sec->flags |= SEC_KEEP;
7782           *loc = sec;
7783           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7784         }
7785     }
7786
7787   sreloc = NULL;
7788   contents = NULL;
7789   for (rel = relocs; rel < rel_end; ++rel)
7790     {
7791       unsigned long r_symndx;
7792       unsigned int r_type;
7793       struct elf_link_hash_entry *h;
7794       bfd_boolean can_make_dynamic_p;
7795
7796       r_symndx = ELF_R_SYM (abfd, rel->r_info);
7797       r_type = ELF_R_TYPE (abfd, rel->r_info);
7798
7799       if (r_symndx < extsymoff)
7800         h = NULL;
7801       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
7802         {
7803           (*_bfd_error_handler)
7804             (_("%B: Malformed reloc detected for section %s"),
7805              abfd, name);
7806           bfd_set_error (bfd_error_bad_value);
7807           return FALSE;
7808         }
7809       else
7810         {
7811           h = sym_hashes[r_symndx - extsymoff];
7812           while (h != NULL
7813                  && (h->root.type == bfd_link_hash_indirect
7814                      || h->root.type == bfd_link_hash_warning))
7815             h = (struct elf_link_hash_entry *) h->root.u.i.link;
7816         }
7817
7818       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
7819          relocation into a dynamic one.  */
7820       can_make_dynamic_p = FALSE;
7821       switch (r_type)
7822         {
7823         case R_MIPS_GOT16:
7824         case R_MIPS_CALL16:
7825         case R_MIPS_CALL_HI16:
7826         case R_MIPS_CALL_LO16:
7827         case R_MIPS_GOT_HI16:
7828         case R_MIPS_GOT_LO16:
7829         case R_MIPS_GOT_PAGE:
7830         case R_MIPS_GOT_OFST:
7831         case R_MIPS_GOT_DISP:
7832         case R_MIPS_TLS_GOTTPREL:
7833         case R_MIPS_TLS_GD:
7834         case R_MIPS_TLS_LDM:
7835         case R_MIPS16_GOT16:
7836         case R_MIPS16_CALL16:
7837         case R_MIPS16_TLS_GOTTPREL:
7838         case R_MIPS16_TLS_GD:
7839         case R_MIPS16_TLS_LDM:
7840         case R_MICROMIPS_GOT16:
7841         case R_MICROMIPS_CALL16:
7842         case R_MICROMIPS_CALL_HI16:
7843         case R_MICROMIPS_CALL_LO16:
7844         case R_MICROMIPS_GOT_HI16:
7845         case R_MICROMIPS_GOT_LO16:
7846         case R_MICROMIPS_GOT_PAGE:
7847         case R_MICROMIPS_GOT_OFST:
7848         case R_MICROMIPS_GOT_DISP:
7849         case R_MICROMIPS_TLS_GOTTPREL:
7850         case R_MICROMIPS_TLS_GD:
7851         case R_MICROMIPS_TLS_LDM:
7852           if (dynobj == NULL)
7853             elf_hash_table (info)->dynobj = dynobj = abfd;
7854           if (!mips_elf_create_got_section (dynobj, info))
7855             return FALSE;
7856           if (htab->is_vxworks && !info->shared)
7857             {
7858               (*_bfd_error_handler)
7859                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
7860                  abfd, (unsigned long) rel->r_offset);
7861               bfd_set_error (bfd_error_bad_value);
7862               return FALSE;
7863             }
7864           break;
7865
7866           /* This is just a hint; it can safely be ignored.  Don't set
7867              has_static_relocs for the corresponding symbol.  */
7868         case R_MIPS_JALR:
7869         case R_MICROMIPS_JALR:
7870           break;
7871
7872         case R_MIPS_32:
7873         case R_MIPS_REL32:
7874         case R_MIPS_64:
7875           /* In VxWorks executables, references to external symbols
7876              must be handled using copy relocs or PLT entries; it is not
7877              possible to convert this relocation into a dynamic one.
7878
7879              For executables that use PLTs and copy-relocs, we have a
7880              choice between converting the relocation into a dynamic
7881              one or using copy relocations or PLT entries.  It is
7882              usually better to do the former, unless the relocation is
7883              against a read-only section.  */
7884           if ((info->shared
7885                || (h != NULL
7886                    && !htab->is_vxworks
7887                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
7888                    && !(!info->nocopyreloc
7889                         && !PIC_OBJECT_P (abfd)
7890                         && MIPS_ELF_READONLY_SECTION (sec))))
7891               && (sec->flags & SEC_ALLOC) != 0)
7892             {
7893               can_make_dynamic_p = TRUE;
7894               if (dynobj == NULL)
7895                 elf_hash_table (info)->dynobj = dynobj = abfd;
7896               break;
7897             }
7898           /* For sections that are not SEC_ALLOC a copy reloc would be
7899              output if possible (implying questionable semantics for
7900              read-only data objects) or otherwise the final link would
7901              fail as ld.so will not process them and could not therefore
7902              handle any outstanding dynamic relocations.
7903
7904              For such sections that are also SEC_DEBUGGING, we can avoid
7905              these problems by simply ignoring any relocs as these
7906              sections have a predefined use and we know it is safe to do
7907              so.
7908
7909              This is needed in cases such as a global symbol definition
7910              in a shared library causing a common symbol from an object
7911              file to be converted to an undefined reference.  If that
7912              happens, then all the relocations against this symbol from
7913              SEC_DEBUGGING sections in the object file will resolve to
7914              nil.  */
7915           if ((sec->flags & SEC_DEBUGGING) != 0)
7916             break;
7917           /* Fall through.  */
7918
7919         default:
7920           /* Most static relocations require pointer equality, except
7921              for branches.  */
7922           if (h)
7923             h->pointer_equality_needed = TRUE;
7924           /* Fall through.  */
7925
7926         case R_MIPS_26:
7927         case R_MIPS_PC16:
7928         case R_MIPS16_26:
7929         case R_MICROMIPS_26_S1:
7930         case R_MICROMIPS_PC7_S1:
7931         case R_MICROMIPS_PC10_S1:
7932         case R_MICROMIPS_PC16_S1:
7933         case R_MICROMIPS_PC23_S2:
7934           if (h)
7935             ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = TRUE;
7936           break;
7937         }
7938
7939       if (h)
7940         {
7941           /* Relocations against the special VxWorks __GOTT_BASE__ and
7942              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
7943              room for them in .rela.dyn.  */
7944           if (is_gott_symbol (info, h))
7945             {
7946               if (sreloc == NULL)
7947                 {
7948                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
7949                   if (sreloc == NULL)
7950                     return FALSE;
7951                 }
7952               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
7953               if (MIPS_ELF_READONLY_SECTION (sec))
7954                 /* We tell the dynamic linker that there are
7955                    relocations against the text segment.  */
7956                 info->flags |= DF_TEXTREL;
7957             }
7958         }
7959       else if (call_lo16_reloc_p (r_type)
7960                || got_lo16_reloc_p (r_type)
7961                || got_disp_reloc_p (r_type)
7962                || (got16_reloc_p (r_type) && htab->is_vxworks))
7963         {
7964           /* We may need a local GOT entry for this relocation.  We
7965              don't count R_MIPS_GOT_PAGE because we can estimate the
7966              maximum number of pages needed by looking at the size of
7967              the segment.  Similar comments apply to R_MIPS*_GOT16 and
7968              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
7969              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
7970              R_MIPS_CALL_HI16 because these are always followed by an
7971              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
7972           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
7973                                                  rel->r_addend, info, r_type))
7974             return FALSE;
7975         }
7976
7977       if (h != NULL
7978           && mips_elf_relocation_needs_la25_stub (abfd, r_type,
7979                                                   ELF_ST_IS_MIPS16 (h->other)))
7980         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
7981
7982       switch (r_type)
7983         {
7984         case R_MIPS_CALL16:
7985         case R_MIPS16_CALL16:
7986         case R_MICROMIPS_CALL16:
7987           if (h == NULL)
7988             {
7989               (*_bfd_error_handler)
7990                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
7991                  abfd, (unsigned long) rel->r_offset);
7992               bfd_set_error (bfd_error_bad_value);
7993               return FALSE;
7994             }
7995           /* Fall through.  */
7996
7997         case R_MIPS_CALL_HI16:
7998         case R_MIPS_CALL_LO16:
7999         case R_MICROMIPS_CALL_HI16:
8000         case R_MICROMIPS_CALL_LO16:
8001           if (h != NULL)
8002             {
8003               /* Make sure there is room in the regular GOT to hold the
8004                  function's address.  We may eliminate it in favour of
8005                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
8006               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE,
8007                                                       r_type))
8008                 return FALSE;
8009
8010               /* We need a stub, not a plt entry for the undefined
8011                  function.  But we record it as if it needs plt.  See
8012                  _bfd_elf_adjust_dynamic_symbol.  */
8013               h->needs_plt = 1;
8014               h->type = STT_FUNC;
8015             }
8016           break;
8017
8018         case R_MIPS_GOT_PAGE:
8019         case R_MICROMIPS_GOT_PAGE:
8020           /* If this is a global, overridable symbol, GOT_PAGE will
8021              decay to GOT_DISP, so we'll need a GOT entry for it.  */
8022           if (h)
8023             {
8024               struct mips_elf_link_hash_entry *hmips =
8025                 (struct mips_elf_link_hash_entry *) h;
8026
8027               /* This symbol is definitely not overridable.  */
8028               if (hmips->root.def_regular
8029                   && ! (info->shared && ! info->symbolic
8030                         && ! hmips->root.forced_local))
8031                 h = NULL;
8032             }
8033           /* Fall through.  */
8034
8035         case R_MIPS16_GOT16:
8036         case R_MIPS_GOT16:
8037         case R_MIPS_GOT_HI16:
8038         case R_MIPS_GOT_LO16:
8039         case R_MICROMIPS_GOT16:
8040         case R_MICROMIPS_GOT_HI16:
8041         case R_MICROMIPS_GOT_LO16:
8042           if (!h || got_page_reloc_p (r_type))
8043             {
8044               /* This relocation needs (or may need, if h != NULL) a
8045                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
8046                  know for sure until we know whether the symbol is
8047                  preemptible.  */
8048               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
8049                 {
8050                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
8051                     return FALSE;
8052                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8053                   addend = mips_elf_read_rel_addend (abfd, rel,
8054                                                      howto, contents);
8055                   if (got16_reloc_p (r_type))
8056                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
8057                                                   contents, &addend);
8058                   else
8059                     addend <<= howto->rightshift;
8060                 }
8061               else
8062                 addend = rel->r_addend;
8063               if (!mips_elf_record_got_page_entry (info, abfd, r_symndx,
8064                                                    addend))
8065                 return FALSE;
8066             }
8067           /* Fall through.  */
8068
8069         case R_MIPS_GOT_DISP:
8070         case R_MICROMIPS_GOT_DISP:
8071           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8072                                                        FALSE, r_type))
8073             return FALSE;
8074           break;
8075
8076         case R_MIPS_TLS_GOTTPREL:
8077         case R_MIPS16_TLS_GOTTPREL:
8078         case R_MICROMIPS_TLS_GOTTPREL:
8079           if (info->shared)
8080             info->flags |= DF_STATIC_TLS;
8081           /* Fall through */
8082
8083         case R_MIPS_TLS_LDM:
8084         case R_MIPS16_TLS_LDM:
8085         case R_MICROMIPS_TLS_LDM:
8086           if (tls_ldm_reloc_p (r_type))
8087             {
8088               r_symndx = STN_UNDEF;
8089               h = NULL;
8090             }
8091           /* Fall through */
8092
8093         case R_MIPS_TLS_GD:
8094         case R_MIPS16_TLS_GD:
8095         case R_MICROMIPS_TLS_GD:
8096           /* This symbol requires a global offset table entry, or two
8097              for TLS GD relocations.  */
8098           if (h != NULL)
8099             {
8100               if (!mips_elf_record_global_got_symbol (h, abfd, info,
8101                                                       FALSE, r_type))
8102                 return FALSE;
8103             }
8104           else
8105             {
8106               if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8107                                                      rel->r_addend,
8108                                                      info, r_type))
8109                 return FALSE;
8110             }
8111           break;
8112
8113         case R_MIPS_32:
8114         case R_MIPS_REL32:
8115         case R_MIPS_64:
8116           /* In VxWorks executables, references to external symbols
8117              are handled using copy relocs or PLT stubs, so there's
8118              no need to add a .rela.dyn entry for this relocation.  */
8119           if (can_make_dynamic_p)
8120             {
8121               if (sreloc == NULL)
8122                 {
8123                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8124                   if (sreloc == NULL)
8125                     return FALSE;
8126                 }
8127               if (info->shared && h == NULL)
8128                 {
8129                   /* When creating a shared object, we must copy these
8130                      reloc types into the output file as R_MIPS_REL32
8131                      relocs.  Make room for this reloc in .rel(a).dyn.  */
8132                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8133                   if (MIPS_ELF_READONLY_SECTION (sec))
8134                     /* We tell the dynamic linker that there are
8135                        relocations against the text segment.  */
8136                     info->flags |= DF_TEXTREL;
8137                 }
8138               else
8139                 {
8140                   struct mips_elf_link_hash_entry *hmips;
8141
8142                   /* For a shared object, we must copy this relocation
8143                      unless the symbol turns out to be undefined and
8144                      weak with non-default visibility, in which case
8145                      it will be left as zero.
8146
8147                      We could elide R_MIPS_REL32 for locally binding symbols
8148                      in shared libraries, but do not yet do so.
8149
8150                      For an executable, we only need to copy this
8151                      reloc if the symbol is defined in a dynamic
8152                      object.  */
8153                   hmips = (struct mips_elf_link_hash_entry *) h;
8154                   ++hmips->possibly_dynamic_relocs;
8155                   if (MIPS_ELF_READONLY_SECTION (sec))
8156                     /* We need it to tell the dynamic linker if there
8157                        are relocations against the text segment.  */
8158                     hmips->readonly_reloc = TRUE;
8159                 }
8160             }
8161
8162           if (SGI_COMPAT (abfd))
8163             mips_elf_hash_table (info)->compact_rel_size +=
8164               sizeof (Elf32_External_crinfo);
8165           break;
8166
8167         case R_MIPS_26:
8168         case R_MIPS_GPREL16:
8169         case R_MIPS_LITERAL:
8170         case R_MIPS_GPREL32:
8171         case R_MICROMIPS_26_S1:
8172         case R_MICROMIPS_GPREL16:
8173         case R_MICROMIPS_LITERAL:
8174         case R_MICROMIPS_GPREL7_S2:
8175           if (SGI_COMPAT (abfd))
8176             mips_elf_hash_table (info)->compact_rel_size +=
8177               sizeof (Elf32_External_crinfo);
8178           break;
8179
8180           /* This relocation describes the C++ object vtable hierarchy.
8181              Reconstruct it for later use during GC.  */
8182         case R_MIPS_GNU_VTINHERIT:
8183           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
8184             return FALSE;
8185           break;
8186
8187           /* This relocation describes which C++ vtable entries are actually
8188              used.  Record for later use during GC.  */
8189         case R_MIPS_GNU_VTENTRY:
8190           BFD_ASSERT (h != NULL);
8191           if (h != NULL
8192               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
8193             return FALSE;
8194           break;
8195
8196         default:
8197           break;
8198         }
8199
8200       /* We must not create a stub for a symbol that has relocations
8201          related to taking the function's address.  This doesn't apply to
8202          VxWorks, where CALL relocs refer to a .got.plt entry instead of
8203          a normal .got entry.  */
8204       if (!htab->is_vxworks && h != NULL)
8205         switch (r_type)
8206           {
8207           default:
8208             ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8209             break;
8210           case R_MIPS16_CALL16:
8211           case R_MIPS_CALL16:
8212           case R_MIPS_CALL_HI16:
8213           case R_MIPS_CALL_LO16:
8214           case R_MIPS_JALR:
8215           case R_MICROMIPS_CALL16:
8216           case R_MICROMIPS_CALL_HI16:
8217           case R_MICROMIPS_CALL_LO16:
8218           case R_MICROMIPS_JALR:
8219             break;
8220           }
8221
8222       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8223          if there is one.  We only need to handle global symbols here;
8224          we decide whether to keep or delete stubs for local symbols
8225          when processing the stub's relocations.  */
8226       if (h != NULL
8227           && !mips16_call_reloc_p (r_type)
8228           && !section_allows_mips16_refs_p (sec))
8229         {
8230           struct mips_elf_link_hash_entry *mh;
8231
8232           mh = (struct mips_elf_link_hash_entry *) h;
8233           mh->need_fn_stub = TRUE;
8234         }
8235
8236       /* Refuse some position-dependent relocations when creating a
8237          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8238          not PIC, but we can create dynamic relocations and the result
8239          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8240          combined with R_MIPS_GOT16.  */
8241       if (info->shared)
8242         {
8243           switch (r_type)
8244             {
8245             case R_MIPS16_HI16:
8246             case R_MIPS_HI16:
8247             case R_MIPS_HIGHER:
8248             case R_MIPS_HIGHEST:
8249             case R_MICROMIPS_HI16:
8250             case R_MICROMIPS_HIGHER:
8251             case R_MICROMIPS_HIGHEST:
8252               /* Don't refuse a high part relocation if it's against
8253                  no symbol (e.g. part of a compound relocation).  */
8254               if (r_symndx == STN_UNDEF)
8255                 break;
8256
8257               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8258                  and has a special meaning.  */
8259               if (!NEWABI_P (abfd) && h != NULL
8260                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8261                 break;
8262
8263               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8264               if (is_gott_symbol (info, h))
8265                 break;
8266
8267               /* FALLTHROUGH */
8268
8269             case R_MIPS16_26:
8270             case R_MIPS_26:
8271             case R_MICROMIPS_26_S1:
8272               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8273               (*_bfd_error_handler)
8274                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8275                  abfd, howto->name,
8276                  (h) ? h->root.root.string : "a local symbol");
8277               bfd_set_error (bfd_error_bad_value);
8278               return FALSE;
8279             default:
8280               break;
8281             }
8282         }
8283     }
8284
8285   return TRUE;
8286 }
8287 \f
8288 bfd_boolean
8289 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8290                          struct bfd_link_info *link_info,
8291                          bfd_boolean *again)
8292 {
8293   Elf_Internal_Rela *internal_relocs;
8294   Elf_Internal_Rela *irel, *irelend;
8295   Elf_Internal_Shdr *symtab_hdr;
8296   bfd_byte *contents = NULL;
8297   size_t extsymoff;
8298   bfd_boolean changed_contents = FALSE;
8299   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8300   Elf_Internal_Sym *isymbuf = NULL;
8301
8302   /* We are not currently changing any sizes, so only one pass.  */
8303   *again = FALSE;
8304
8305   if (link_info->relocatable)
8306     return TRUE;
8307
8308   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8309                                                link_info->keep_memory);
8310   if (internal_relocs == NULL)
8311     return TRUE;
8312
8313   irelend = internal_relocs + sec->reloc_count
8314     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8315   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8316   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8317
8318   for (irel = internal_relocs; irel < irelend; irel++)
8319     {
8320       bfd_vma symval;
8321       bfd_signed_vma sym_offset;
8322       unsigned int r_type;
8323       unsigned long r_symndx;
8324       asection *sym_sec;
8325       unsigned long instruction;
8326
8327       /* Turn jalr into bgezal, and jr into beq, if they're marked
8328          with a JALR relocation, that indicate where they jump to.
8329          This saves some pipeline bubbles.  */
8330       r_type = ELF_R_TYPE (abfd, irel->r_info);
8331       if (r_type != R_MIPS_JALR)
8332         continue;
8333
8334       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8335       /* Compute the address of the jump target.  */
8336       if (r_symndx >= extsymoff)
8337         {
8338           struct mips_elf_link_hash_entry *h
8339             = ((struct mips_elf_link_hash_entry *)
8340                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8341
8342           while (h->root.root.type == bfd_link_hash_indirect
8343                  || h->root.root.type == bfd_link_hash_warning)
8344             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8345
8346           /* If a symbol is undefined, or if it may be overridden,
8347              skip it.  */
8348           if (! ((h->root.root.type == bfd_link_hash_defined
8349                   || h->root.root.type == bfd_link_hash_defweak)
8350                  && h->root.root.u.def.section)
8351               || (link_info->shared && ! link_info->symbolic
8352                   && !h->root.forced_local))
8353             continue;
8354
8355           sym_sec = h->root.root.u.def.section;
8356           if (sym_sec->output_section)
8357             symval = (h->root.root.u.def.value
8358                       + sym_sec->output_section->vma
8359                       + sym_sec->output_offset);
8360           else
8361             symval = h->root.root.u.def.value;
8362         }
8363       else
8364         {
8365           Elf_Internal_Sym *isym;
8366
8367           /* Read this BFD's symbols if we haven't done so already.  */
8368           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8369             {
8370               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8371               if (isymbuf == NULL)
8372                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8373                                                 symtab_hdr->sh_info, 0,
8374                                                 NULL, NULL, NULL);
8375               if (isymbuf == NULL)
8376                 goto relax_return;
8377             }
8378
8379           isym = isymbuf + r_symndx;
8380           if (isym->st_shndx == SHN_UNDEF)
8381             continue;
8382           else if (isym->st_shndx == SHN_ABS)
8383             sym_sec = bfd_abs_section_ptr;
8384           else if (isym->st_shndx == SHN_COMMON)
8385             sym_sec = bfd_com_section_ptr;
8386           else
8387             sym_sec
8388               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8389           symval = isym->st_value
8390             + sym_sec->output_section->vma
8391             + sym_sec->output_offset;
8392         }
8393
8394       /* Compute branch offset, from delay slot of the jump to the
8395          branch target.  */
8396       sym_offset = (symval + irel->r_addend)
8397         - (sec_start + irel->r_offset + 4);
8398
8399       /* Branch offset must be properly aligned.  */
8400       if ((sym_offset & 3) != 0)
8401         continue;
8402
8403       sym_offset >>= 2;
8404
8405       /* Check that it's in range.  */
8406       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
8407         continue;
8408
8409       /* Get the section contents if we haven't done so already.  */
8410       if (!mips_elf_get_section_contents (abfd, sec, &contents))
8411         goto relax_return;
8412
8413       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
8414
8415       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
8416       if ((instruction & 0xfc1fffff) == 0x0000f809)
8417         instruction = 0x04110000;
8418       /* If it was jr <reg>, turn it into b <target>.  */
8419       else if ((instruction & 0xfc1fffff) == 0x00000008)
8420         instruction = 0x10000000;
8421       else
8422         continue;
8423
8424       instruction |= (sym_offset & 0xffff);
8425       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
8426       changed_contents = TRUE;
8427     }
8428
8429   if (contents != NULL
8430       && elf_section_data (sec)->this_hdr.contents != contents)
8431     {
8432       if (!changed_contents && !link_info->keep_memory)
8433         free (contents);
8434       else
8435         {
8436           /* Cache the section contents for elf_link_input_bfd.  */
8437           elf_section_data (sec)->this_hdr.contents = contents;
8438         }
8439     }
8440   return TRUE;
8441
8442  relax_return:
8443   if (contents != NULL
8444       && elf_section_data (sec)->this_hdr.contents != contents)
8445     free (contents);
8446   return FALSE;
8447 }
8448 \f
8449 /* Allocate space for global sym dynamic relocs.  */
8450
8451 static bfd_boolean
8452 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
8453 {
8454   struct bfd_link_info *info = inf;
8455   bfd *dynobj;
8456   struct mips_elf_link_hash_entry *hmips;
8457   struct mips_elf_link_hash_table *htab;
8458
8459   htab = mips_elf_hash_table (info);
8460   BFD_ASSERT (htab != NULL);
8461
8462   dynobj = elf_hash_table (info)->dynobj;
8463   hmips = (struct mips_elf_link_hash_entry *) h;
8464
8465   /* VxWorks executables are handled elsewhere; we only need to
8466      allocate relocations in shared objects.  */
8467   if (htab->is_vxworks && !info->shared)
8468     return TRUE;
8469
8470   /* Ignore indirect symbols.  All relocations against such symbols
8471      will be redirected to the target symbol.  */
8472   if (h->root.type == bfd_link_hash_indirect)
8473     return TRUE;
8474
8475   /* If this symbol is defined in a dynamic object, or we are creating
8476      a shared library, we will need to copy any R_MIPS_32 or
8477      R_MIPS_REL32 relocs against it into the output file.  */
8478   if (! info->relocatable
8479       && hmips->possibly_dynamic_relocs != 0
8480       && (h->root.type == bfd_link_hash_defweak
8481           || (!h->def_regular && !ELF_COMMON_DEF_P (h))
8482           || info->shared))
8483     {
8484       bfd_boolean do_copy = TRUE;
8485
8486       if (h->root.type == bfd_link_hash_undefweak)
8487         {
8488           /* Do not copy relocations for undefined weak symbols with
8489              non-default visibility.  */
8490           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
8491             do_copy = FALSE;
8492
8493           /* Make sure undefined weak symbols are output as a dynamic
8494              symbol in PIEs.  */
8495           else if (h->dynindx == -1 && !h->forced_local)
8496             {
8497               if (! bfd_elf_link_record_dynamic_symbol (info, h))
8498                 return FALSE;
8499             }
8500         }
8501
8502       if (do_copy)
8503         {
8504           /* Even though we don't directly need a GOT entry for this symbol,
8505              the SVR4 psABI requires it to have a dynamic symbol table
8506              index greater that DT_MIPS_GOTSYM if there are dynamic
8507              relocations against it.
8508
8509              VxWorks does not enforce the same mapping between the GOT
8510              and the symbol table, so the same requirement does not
8511              apply there.  */
8512           if (!htab->is_vxworks)
8513             {
8514               if (hmips->global_got_area > GGA_RELOC_ONLY)
8515                 hmips->global_got_area = GGA_RELOC_ONLY;
8516               hmips->got_only_for_calls = FALSE;
8517             }
8518
8519           mips_elf_allocate_dynamic_relocations
8520             (dynobj, info, hmips->possibly_dynamic_relocs);
8521           if (hmips->readonly_reloc)
8522             /* We tell the dynamic linker that there are relocations
8523                against the text segment.  */
8524             info->flags |= DF_TEXTREL;
8525         }
8526     }
8527
8528   return TRUE;
8529 }
8530
8531 /* Adjust a symbol defined by a dynamic object and referenced by a
8532    regular object.  The current definition is in some section of the
8533    dynamic object, but we're not including those sections.  We have to
8534    change the definition to something the rest of the link can
8535    understand.  */
8536
8537 bfd_boolean
8538 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
8539                                      struct elf_link_hash_entry *h)
8540 {
8541   bfd *dynobj;
8542   struct mips_elf_link_hash_entry *hmips;
8543   struct mips_elf_link_hash_table *htab;
8544
8545   htab = mips_elf_hash_table (info);
8546   BFD_ASSERT (htab != NULL);
8547
8548   dynobj = elf_hash_table (info)->dynobj;
8549   hmips = (struct mips_elf_link_hash_entry *) h;
8550
8551   /* Make sure we know what is going on here.  */
8552   BFD_ASSERT (dynobj != NULL
8553               && (h->needs_plt
8554                   || h->u.weakdef != NULL
8555                   || (h->def_dynamic
8556                       && h->ref_regular
8557                       && !h->def_regular)));
8558
8559   hmips = (struct mips_elf_link_hash_entry *) h;
8560
8561   /* If there are call relocations against an externally-defined symbol,
8562      see whether we can create a MIPS lazy-binding stub for it.  We can
8563      only do this if all references to the function are through call
8564      relocations, and in that case, the traditional lazy-binding stubs
8565      are much more efficient than PLT entries.
8566
8567      Traditional stubs are only available on SVR4 psABI-based systems;
8568      VxWorks always uses PLTs instead.  */
8569   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
8570     {
8571       if (! elf_hash_table (info)->dynamic_sections_created)
8572         return TRUE;
8573
8574       /* If this symbol is not defined in a regular file, then set
8575          the symbol to the stub location.  This is required to make
8576          function pointers compare as equal between the normal
8577          executable and the shared library.  */
8578       if (!h->def_regular)
8579         {
8580           hmips->needs_lazy_stub = TRUE;
8581           htab->lazy_stub_count++;
8582           return TRUE;
8583         }
8584     }
8585   /* As above, VxWorks requires PLT entries for externally-defined
8586      functions that are only accessed through call relocations.
8587
8588      Both VxWorks and non-VxWorks targets also need PLT entries if there
8589      are static-only relocations against an externally-defined function.
8590      This can technically occur for shared libraries if there are
8591      branches to the symbol, although it is unlikely that this will be
8592      used in practice due to the short ranges involved.  It can occur
8593      for any relative or absolute relocation in executables; in that
8594      case, the PLT entry becomes the function's canonical address.  */
8595   else if (((h->needs_plt && !hmips->no_fn_stub)
8596             || (h->type == STT_FUNC && hmips->has_static_relocs))
8597            && htab->use_plts_and_copy_relocs
8598            && !SYMBOL_CALLS_LOCAL (info, h)
8599            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
8600                 && h->root.type == bfd_link_hash_undefweak))
8601     {
8602       /* If this is the first symbol to need a PLT entry, allocate room
8603          for the header.  */
8604       if (htab->splt->size == 0)
8605         {
8606           BFD_ASSERT (htab->sgotplt->size == 0);
8607
8608           /* If we're using the PLT additions to the psABI, each PLT
8609              entry is 16 bytes and the PLT0 entry is 32 bytes.
8610              Encourage better cache usage by aligning.  We do this
8611              lazily to avoid pessimizing traditional objects.  */
8612           if (!htab->is_vxworks
8613               && !bfd_set_section_alignment (dynobj, htab->splt, 5))
8614             return FALSE;
8615
8616           /* Make sure that .got.plt is word-aligned.  We do this lazily
8617              for the same reason as above.  */
8618           if (!bfd_set_section_alignment (dynobj, htab->sgotplt,
8619                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
8620             return FALSE;
8621
8622           htab->splt->size += htab->plt_header_size;
8623
8624           /* On non-VxWorks targets, the first two entries in .got.plt
8625              are reserved.  */
8626           if (!htab->is_vxworks)
8627             htab->sgotplt->size
8628               += get_elf_backend_data (dynobj)->got_header_size;
8629
8630           /* On VxWorks, also allocate room for the header's
8631              .rela.plt.unloaded entries.  */
8632           if (htab->is_vxworks && !info->shared)
8633             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
8634         }
8635
8636       /* Assign the next .plt entry to this symbol.  */
8637       h->plt.offset = htab->splt->size;
8638       htab->splt->size += htab->plt_entry_size;
8639
8640       /* If the output file has no definition of the symbol, set the
8641          symbol's value to the address of the stub.  */
8642       if (!info->shared && !h->def_regular)
8643         {
8644           h->root.u.def.section = htab->splt;
8645           h->root.u.def.value = h->plt.offset;
8646           /* For VxWorks, point at the PLT load stub rather than the
8647              lazy resolution stub; this stub will become the canonical
8648              function address.  */
8649           if (htab->is_vxworks)
8650             h->root.u.def.value += 8;
8651         }
8652
8653       /* Make room for the .got.plt entry and the R_MIPS_JUMP_SLOT
8654          relocation.  */
8655       htab->sgotplt->size += MIPS_ELF_GOT_SIZE (dynobj);
8656       htab->srelplt->size += (htab->is_vxworks
8657                               ? MIPS_ELF_RELA_SIZE (dynobj)
8658                               : MIPS_ELF_REL_SIZE (dynobj));
8659
8660       /* Make room for the .rela.plt.unloaded relocations.  */
8661       if (htab->is_vxworks && !info->shared)
8662         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
8663
8664       /* All relocations against this symbol that could have been made
8665          dynamic will now refer to the PLT entry instead.  */
8666       hmips->possibly_dynamic_relocs = 0;
8667
8668       return TRUE;
8669     }
8670
8671   /* If this is a weak symbol, and there is a real definition, the
8672      processor independent code will have arranged for us to see the
8673      real definition first, and we can just use the same value.  */
8674   if (h->u.weakdef != NULL)
8675     {
8676       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
8677                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
8678       h->root.u.def.section = h->u.weakdef->root.u.def.section;
8679       h->root.u.def.value = h->u.weakdef->root.u.def.value;
8680       return TRUE;
8681     }
8682
8683   /* Otherwise, there is nothing further to do for symbols defined
8684      in regular objects.  */
8685   if (h->def_regular)
8686     return TRUE;
8687
8688   /* There's also nothing more to do if we'll convert all relocations
8689      against this symbol into dynamic relocations.  */
8690   if (!hmips->has_static_relocs)
8691     return TRUE;
8692
8693   /* We're now relying on copy relocations.  Complain if we have
8694      some that we can't convert.  */
8695   if (!htab->use_plts_and_copy_relocs || info->shared)
8696     {
8697       (*_bfd_error_handler) (_("non-dynamic relocations refer to "
8698                                "dynamic symbol %s"),
8699                              h->root.root.string);
8700       bfd_set_error (bfd_error_bad_value);
8701       return FALSE;
8702     }
8703
8704   /* We must allocate the symbol in our .dynbss section, which will
8705      become part of the .bss section of the executable.  There will be
8706      an entry for this symbol in the .dynsym section.  The dynamic
8707      object will contain position independent code, so all references
8708      from the dynamic object to this symbol will go through the global
8709      offset table.  The dynamic linker will use the .dynsym entry to
8710      determine the address it must put in the global offset table, so
8711      both the dynamic object and the regular object will refer to the
8712      same memory location for the variable.  */
8713
8714   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
8715     {
8716       if (htab->is_vxworks)
8717         htab->srelbss->size += sizeof (Elf32_External_Rela);
8718       else
8719         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8720       h->needs_copy = 1;
8721     }
8722
8723   /* All relocations against this symbol that could have been made
8724      dynamic will now refer to the local copy instead.  */
8725   hmips->possibly_dynamic_relocs = 0;
8726
8727   return _bfd_elf_adjust_dynamic_copy (h, htab->sdynbss);
8728 }
8729 \f
8730 /* This function is called after all the input files have been read,
8731    and the input sections have been assigned to output sections.  We
8732    check for any mips16 stub sections that we can discard.  */
8733
8734 bfd_boolean
8735 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
8736                                     struct bfd_link_info *info)
8737 {
8738   asection *ri;
8739   struct mips_elf_link_hash_table *htab;
8740   struct mips_htab_traverse_info hti;
8741
8742   htab = mips_elf_hash_table (info);
8743   BFD_ASSERT (htab != NULL);
8744
8745   /* The .reginfo section has a fixed size.  */
8746   ri = bfd_get_section_by_name (output_bfd, ".reginfo");
8747   if (ri != NULL)
8748     bfd_set_section_size (output_bfd, ri, sizeof (Elf32_External_RegInfo));
8749
8750   hti.info = info;
8751   hti.output_bfd = output_bfd;
8752   hti.error = FALSE;
8753   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
8754                                mips_elf_check_symbols, &hti);
8755   if (hti.error)
8756     return FALSE;
8757
8758   return TRUE;
8759 }
8760
8761 /* If the link uses a GOT, lay it out and work out its size.  */
8762
8763 static bfd_boolean
8764 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
8765 {
8766   bfd *dynobj;
8767   asection *s;
8768   struct mips_got_info *g;
8769   bfd_size_type loadable_size = 0;
8770   bfd_size_type page_gotno;
8771   bfd *ibfd;
8772   struct mips_elf_traverse_got_arg tga;
8773   struct mips_elf_link_hash_table *htab;
8774
8775   htab = mips_elf_hash_table (info);
8776   BFD_ASSERT (htab != NULL);
8777
8778   s = htab->sgot;
8779   if (s == NULL)
8780     return TRUE;
8781
8782   dynobj = elf_hash_table (info)->dynobj;
8783   g = htab->got_info;
8784
8785   /* Allocate room for the reserved entries.  VxWorks always reserves
8786      3 entries; other objects only reserve 2 entries.  */
8787   BFD_ASSERT (g->assigned_gotno == 0);
8788   if (htab->is_vxworks)
8789     htab->reserved_gotno = 3;
8790   else
8791     htab->reserved_gotno = 2;
8792   g->local_gotno += htab->reserved_gotno;
8793   g->assigned_gotno = htab->reserved_gotno;
8794
8795   /* Replace entries for indirect and warning symbols with entries for
8796      the target symbol.  */
8797   if (!mips_elf_resolve_final_got_entries (g))
8798     return FALSE;
8799
8800   /* Count the number of GOT symbols.  */
8801   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
8802
8803   /* Calculate the total loadable size of the output.  That
8804      will give us the maximum number of GOT_PAGE entries
8805      required.  */
8806   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
8807     {
8808       asection *subsection;
8809
8810       for (subsection = ibfd->sections;
8811            subsection;
8812            subsection = subsection->next)
8813         {
8814           if ((subsection->flags & SEC_ALLOC) == 0)
8815             continue;
8816           loadable_size += ((subsection->size + 0xf)
8817                             &~ (bfd_size_type) 0xf);
8818         }
8819     }
8820
8821   if (htab->is_vxworks)
8822     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
8823        relocations against local symbols evaluate to "G", and the EABI does
8824        not include R_MIPS_GOT_PAGE.  */
8825     page_gotno = 0;
8826   else
8827     /* Assume there are two loadable segments consisting of contiguous
8828        sections.  Is 5 enough?  */
8829     page_gotno = (loadable_size >> 16) + 5;
8830
8831   /* Choose the smaller of the two estimates; both are intended to be
8832      conservative.  */
8833   if (page_gotno > g->page_gotno)
8834     page_gotno = g->page_gotno;
8835
8836   g->local_gotno += page_gotno;
8837
8838   /* Count the number of local GOT entries and TLS relocs.  */
8839   tga.info = info;
8840   tga.g = g;
8841   htab_traverse (g->got_entries, mips_elf_count_local_got_entries, &tga);
8842
8843   /* We need to calculate tls_gotno for global symbols at this point
8844      instead of building it up earlier, to avoid doublecounting
8845      entries for one global symbol from multiple input files.  */
8846   elf_link_hash_traverse (elf_hash_table (info),
8847                           mips_elf_count_global_tls_entries,
8848                           &tga);
8849
8850   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8851   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8852   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8853
8854   /* VxWorks does not support multiple GOTs.  It initializes $gp to
8855      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
8856      dynamic loader.  */
8857   if (htab->is_vxworks)
8858     {
8859       /* VxWorks executables do not need a GOT.  */
8860       if (info->shared)
8861         {
8862           /* Each VxWorks GOT entry needs an explicit relocation.  */
8863           unsigned int count;
8864
8865           count = g->global_gotno + g->local_gotno - htab->reserved_gotno;
8866           if (count)
8867             mips_elf_allocate_dynamic_relocations (dynobj, info, count);
8868         }
8869     }
8870   else if (s->size > MIPS_ELF_GOT_MAX_SIZE (info))
8871     {
8872       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
8873         return FALSE;
8874     }
8875   else
8876     {
8877       /* Record that all bfds use G.  This also has the effect of freeing
8878          the per-bfd GOTs, which we no longer need.  */
8879       for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
8880         if (mips_elf_bfd_got (ibfd, FALSE))
8881           mips_elf_replace_bfd_got (ibfd, g);
8882       mips_elf_replace_bfd_got (output_bfd, g);
8883
8884       /* Set up TLS entries.  */
8885       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
8886       tga.info = info;
8887       tga.g = g;
8888       tga.value = MIPS_ELF_GOT_SIZE (output_bfd);
8889       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
8890       if (!tga.g)
8891         return FALSE;
8892       BFD_ASSERT (g->tls_assigned_gotno
8893                   == g->global_gotno + g->local_gotno + g->tls_gotno);
8894
8895       /* Allocate room for the TLS relocations.  */
8896       if (g->relocs)
8897         mips_elf_allocate_dynamic_relocations (dynobj, info, g->relocs);
8898     }
8899
8900   return TRUE;
8901 }
8902
8903 /* Estimate the size of the .MIPS.stubs section.  */
8904
8905 static void
8906 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
8907 {
8908   struct mips_elf_link_hash_table *htab;
8909   bfd_size_type dynsymcount;
8910
8911   htab = mips_elf_hash_table (info);
8912   BFD_ASSERT (htab != NULL);
8913
8914   if (htab->lazy_stub_count == 0)
8915     return;
8916
8917   /* IRIX rld assumes that a function stub isn't at the end of the .text
8918      section, so add a dummy entry to the end.  */
8919   htab->lazy_stub_count++;
8920
8921   /* Get a worst-case estimate of the number of dynamic symbols needed.
8922      At this point, dynsymcount does not account for section symbols
8923      and count_section_dynsyms may overestimate the number that will
8924      be needed.  */
8925   dynsymcount = (elf_hash_table (info)->dynsymcount
8926                  + count_section_dynsyms (output_bfd, info));
8927
8928   /* Determine the size of one stub entry.  */
8929   htab->function_stub_size = (dynsymcount > 0x10000
8930                               ? MIPS_FUNCTION_STUB_BIG_SIZE
8931                               : MIPS_FUNCTION_STUB_NORMAL_SIZE);
8932
8933   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
8934 }
8935
8936 /* A mips_elf_link_hash_traverse callback for which DATA points to the
8937    MIPS hash table.  If H needs a traditional MIPS lazy-binding stub,
8938    allocate an entry in the stubs section.  */
8939
8940 static bfd_boolean
8941 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void **data)
8942 {
8943   struct mips_elf_link_hash_table *htab;
8944
8945   htab = (struct mips_elf_link_hash_table *) data;
8946   if (h->needs_lazy_stub)
8947     {
8948       h->root.root.u.def.section = htab->sstubs;
8949       h->root.root.u.def.value = htab->sstubs->size;
8950       h->root.plt.offset = htab->sstubs->size;
8951       htab->sstubs->size += htab->function_stub_size;
8952     }
8953   return TRUE;
8954 }
8955
8956 /* Allocate offsets in the stubs section to each symbol that needs one.
8957    Set the final size of the .MIPS.stub section.  */
8958
8959 static void
8960 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
8961 {
8962   struct mips_elf_link_hash_table *htab;
8963
8964   htab = mips_elf_hash_table (info);
8965   BFD_ASSERT (htab != NULL);
8966
8967   if (htab->lazy_stub_count == 0)
8968     return;
8969
8970   htab->sstubs->size = 0;
8971   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, htab);
8972   htab->sstubs->size += htab->function_stub_size;
8973   BFD_ASSERT (htab->sstubs->size
8974               == htab->lazy_stub_count * htab->function_stub_size);
8975 }
8976
8977 /* Set the sizes of the dynamic sections.  */
8978
8979 bfd_boolean
8980 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
8981                                      struct bfd_link_info *info)
8982 {
8983   bfd *dynobj;
8984   asection *s, *sreldyn;
8985   bfd_boolean reltext;
8986   struct mips_elf_link_hash_table *htab;
8987
8988   htab = mips_elf_hash_table (info);
8989   BFD_ASSERT (htab != NULL);
8990   dynobj = elf_hash_table (info)->dynobj;
8991   BFD_ASSERT (dynobj != NULL);
8992
8993   if (elf_hash_table (info)->dynamic_sections_created)
8994     {
8995       /* Set the contents of the .interp section to the interpreter.  */
8996       if (info->executable)
8997         {
8998           s = bfd_get_linker_section (dynobj, ".interp");
8999           BFD_ASSERT (s != NULL);
9000           s->size
9001             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
9002           s->contents
9003             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
9004         }
9005
9006       /* Create a symbol for the PLT, if we know that we are using it.  */
9007       if (htab->splt && htab->splt->size > 0 && htab->root.hplt == NULL)
9008         {
9009           struct elf_link_hash_entry *h;
9010
9011           BFD_ASSERT (htab->use_plts_and_copy_relocs);
9012
9013           h = _bfd_elf_define_linkage_sym (dynobj, info, htab->splt,
9014                                            "_PROCEDURE_LINKAGE_TABLE_");
9015           htab->root.hplt = h;
9016           if (h == NULL)
9017             return FALSE;
9018           h->type = STT_FUNC;
9019         }
9020     }
9021
9022   /* Allocate space for global sym dynamic relocs.  */
9023   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, info);
9024
9025   mips_elf_estimate_stub_size (output_bfd, info);
9026
9027   if (!mips_elf_lay_out_got (output_bfd, info))
9028     return FALSE;
9029
9030   mips_elf_lay_out_lazy_stubs (info);
9031
9032   /* The check_relocs and adjust_dynamic_symbol entry points have
9033      determined the sizes of the various dynamic sections.  Allocate
9034      memory for them.  */
9035   reltext = FALSE;
9036   for (s = dynobj->sections; s != NULL; s = s->next)
9037     {
9038       const char *name;
9039
9040       /* It's OK to base decisions on the section name, because none
9041          of the dynobj section names depend upon the input files.  */
9042       name = bfd_get_section_name (dynobj, s);
9043
9044       if ((s->flags & SEC_LINKER_CREATED) == 0)
9045         continue;
9046
9047       if (CONST_STRNEQ (name, ".rel"))
9048         {
9049           if (s->size != 0)
9050             {
9051               const char *outname;
9052               asection *target;
9053
9054               /* If this relocation section applies to a read only
9055                  section, then we probably need a DT_TEXTREL entry.
9056                  If the relocation section is .rel(a).dyn, we always
9057                  assert a DT_TEXTREL entry rather than testing whether
9058                  there exists a relocation to a read only section or
9059                  not.  */
9060               outname = bfd_get_section_name (output_bfd,
9061                                               s->output_section);
9062               target = bfd_get_section_by_name (output_bfd, outname + 4);
9063               if ((target != NULL
9064                    && (target->flags & SEC_READONLY) != 0
9065                    && (target->flags & SEC_ALLOC) != 0)
9066                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
9067                 reltext = TRUE;
9068
9069               /* We use the reloc_count field as a counter if we need
9070                  to copy relocs into the output file.  */
9071               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
9072                 s->reloc_count = 0;
9073
9074               /* If combreloc is enabled, elf_link_sort_relocs() will
9075                  sort relocations, but in a different way than we do,
9076                  and before we're done creating relocations.  Also, it
9077                  will move them around between input sections'
9078                  relocation's contents, so our sorting would be
9079                  broken, so don't let it run.  */
9080               info->combreloc = 0;
9081             }
9082         }
9083       else if (! info->shared
9084                && ! mips_elf_hash_table (info)->use_rld_obj_head
9085                && CONST_STRNEQ (name, ".rld_map"))
9086         {
9087           /* We add a room for __rld_map.  It will be filled in by the
9088              rtld to contain a pointer to the _r_debug structure.  */
9089           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
9090         }
9091       else if (SGI_COMPAT (output_bfd)
9092                && CONST_STRNEQ (name, ".compact_rel"))
9093         s->size += mips_elf_hash_table (info)->compact_rel_size;
9094       else if (s == htab->splt)
9095         {
9096           /* If the last PLT entry has a branch delay slot, allocate
9097              room for an extra nop to fill the delay slot.  This is
9098              for CPUs without load interlocking.  */
9099           if (! LOAD_INTERLOCKS_P (output_bfd)
9100               && ! htab->is_vxworks && s->size > 0)
9101             s->size += 4;
9102         }
9103       else if (! CONST_STRNEQ (name, ".init")
9104                && s != htab->sgot
9105                && s != htab->sgotplt
9106                && s != htab->sstubs
9107                && s != htab->sdynbss)
9108         {
9109           /* It's not one of our sections, so don't allocate space.  */
9110           continue;
9111         }
9112
9113       if (s->size == 0)
9114         {
9115           s->flags |= SEC_EXCLUDE;
9116           continue;
9117         }
9118
9119       if ((s->flags & SEC_HAS_CONTENTS) == 0)
9120         continue;
9121
9122       /* Allocate memory for the section contents.  */
9123       s->contents = bfd_zalloc (dynobj, s->size);
9124       if (s->contents == NULL)
9125         {
9126           bfd_set_error (bfd_error_no_memory);
9127           return FALSE;
9128         }
9129     }
9130
9131   if (elf_hash_table (info)->dynamic_sections_created)
9132     {
9133       /* Add some entries to the .dynamic section.  We fill in the
9134          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
9135          must add the entries now so that we get the correct size for
9136          the .dynamic section.  */
9137
9138       /* SGI object has the equivalence of DT_DEBUG in the
9139          DT_MIPS_RLD_MAP entry.  This must come first because glibc
9140          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and some tools
9141          may only look at the first one they see.  */
9142       if (!info->shared
9143           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
9144         return FALSE;
9145
9146       /* The DT_DEBUG entry may be filled in by the dynamic linker and
9147          used by the debugger.  */
9148       if (info->executable
9149           && !SGI_COMPAT (output_bfd)
9150           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
9151         return FALSE;
9152
9153       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
9154         info->flags |= DF_TEXTREL;
9155
9156       if ((info->flags & DF_TEXTREL) != 0)
9157         {
9158           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
9159             return FALSE;
9160
9161           /* Clear the DF_TEXTREL flag.  It will be set again if we
9162              write out an actual text relocation; we may not, because
9163              at this point we do not know whether e.g. any .eh_frame
9164              absolute relocations have been converted to PC-relative.  */
9165           info->flags &= ~DF_TEXTREL;
9166         }
9167
9168       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
9169         return FALSE;
9170
9171       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
9172       if (htab->is_vxworks)
9173         {
9174           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
9175              use any of the DT_MIPS_* tags.  */
9176           if (sreldyn && sreldyn->size > 0)
9177             {
9178               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
9179                 return FALSE;
9180
9181               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
9182                 return FALSE;
9183
9184               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
9185                 return FALSE;
9186             }
9187         }
9188       else
9189         {
9190           if (sreldyn && sreldyn->size > 0)
9191             {
9192               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
9193                 return FALSE;
9194
9195               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
9196                 return FALSE;
9197
9198               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
9199                 return FALSE;
9200             }
9201
9202           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
9203             return FALSE;
9204
9205           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
9206             return FALSE;
9207
9208           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
9209             return FALSE;
9210
9211           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
9212             return FALSE;
9213
9214           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
9215             return FALSE;
9216
9217           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
9218             return FALSE;
9219
9220           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
9221             return FALSE;
9222
9223           if (IRIX_COMPAT (dynobj) == ict_irix5
9224               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
9225             return FALSE;
9226
9227           if (IRIX_COMPAT (dynobj) == ict_irix6
9228               && (bfd_get_section_by_name
9229                   (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
9230               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
9231             return FALSE;
9232         }
9233       if (htab->splt->size > 0)
9234         {
9235           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
9236             return FALSE;
9237
9238           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
9239             return FALSE;
9240
9241           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
9242             return FALSE;
9243
9244           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
9245             return FALSE;
9246         }
9247       if (htab->is_vxworks
9248           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
9249         return FALSE;
9250     }
9251
9252   return TRUE;
9253 }
9254 \f
9255 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
9256    Adjust its R_ADDEND field so that it is correct for the output file.
9257    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
9258    and sections respectively; both use symbol indexes.  */
9259
9260 static void
9261 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
9262                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
9263                         asection **local_sections, Elf_Internal_Rela *rel)
9264 {
9265   unsigned int r_type, r_symndx;
9266   Elf_Internal_Sym *sym;
9267   asection *sec;
9268
9269   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9270     {
9271       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9272       if (gprel16_reloc_p (r_type)
9273           || r_type == R_MIPS_GPREL32
9274           || literal_reloc_p (r_type))
9275         {
9276           rel->r_addend += _bfd_get_gp_value (input_bfd);
9277           rel->r_addend -= _bfd_get_gp_value (output_bfd);
9278         }
9279
9280       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
9281       sym = local_syms + r_symndx;
9282
9283       /* Adjust REL's addend to account for section merging.  */
9284       if (!info->relocatable)
9285         {
9286           sec = local_sections[r_symndx];
9287           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
9288         }
9289
9290       /* This would normally be done by the rela_normal code in elflink.c.  */
9291       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
9292         rel->r_addend += local_sections[r_symndx]->output_offset;
9293     }
9294 }
9295
9296 /* Handle relocations against symbols from removed linkonce sections,
9297    or sections discarded by a linker script.  We use this wrapper around
9298    RELOC_AGAINST_DISCARDED_SECTION to handle triplets of compound relocs
9299    on 64-bit ELF targets.  In this case for any relocation handled, which
9300    always be the first in a triplet, the remaining two have to be processed
9301    together with the first, even if they are R_MIPS_NONE.  It is the symbol
9302    index referred by the first reloc that applies to all the three and the
9303    remaining two never refer to an object symbol.  And it is the final
9304    relocation (the last non-null one) that determines the output field of
9305    the whole relocation so retrieve the corresponding howto structure for
9306    the relocatable field to be cleared by RELOC_AGAINST_DISCARDED_SECTION.
9307
9308    Note that RELOC_AGAINST_DISCARDED_SECTION is a macro that uses "continue"
9309    and therefore requires to be pasted in a loop.  It also defines a block
9310    and does not protect any of its arguments, hence the extra brackets.  */
9311
9312 static void
9313 mips_reloc_against_discarded_section (bfd *output_bfd,
9314                                       struct bfd_link_info *info,
9315                                       bfd *input_bfd, asection *input_section,
9316                                       Elf_Internal_Rela **rel,
9317                                       const Elf_Internal_Rela **relend,
9318                                       bfd_boolean rel_reloc,
9319                                       reloc_howto_type *howto,
9320                                       bfd_byte *contents)
9321 {
9322   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
9323   int count = bed->s->int_rels_per_ext_rel;
9324   unsigned int r_type;
9325   int i;
9326
9327   for (i = count - 1; i > 0; i--)
9328     {
9329       r_type = ELF_R_TYPE (output_bfd, (*rel)[i].r_info);
9330       if (r_type != R_MIPS_NONE)
9331         {
9332           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9333           break;
9334         }
9335     }
9336   do
9337     {
9338        RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
9339                                         (*rel), count, (*relend),
9340                                         howto, i, contents);
9341     }
9342   while (0);
9343 }
9344
9345 /* Relocate a MIPS ELF section.  */
9346
9347 bfd_boolean
9348 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
9349                                 bfd *input_bfd, asection *input_section,
9350                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
9351                                 Elf_Internal_Sym *local_syms,
9352                                 asection **local_sections)
9353 {
9354   Elf_Internal_Rela *rel;
9355   const Elf_Internal_Rela *relend;
9356   bfd_vma addend = 0;
9357   bfd_boolean use_saved_addend_p = FALSE;
9358   const struct elf_backend_data *bed;
9359
9360   bed = get_elf_backend_data (output_bfd);
9361   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
9362   for (rel = relocs; rel < relend; ++rel)
9363     {
9364       const char *name;
9365       bfd_vma value = 0;
9366       reloc_howto_type *howto;
9367       bfd_boolean cross_mode_jump_p;
9368       /* TRUE if the relocation is a RELA relocation, rather than a
9369          REL relocation.  */
9370       bfd_boolean rela_relocation_p = TRUE;
9371       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9372       const char *msg;
9373       unsigned long r_symndx;
9374       asection *sec;
9375       Elf_Internal_Shdr *symtab_hdr;
9376       struct elf_link_hash_entry *h;
9377       bfd_boolean rel_reloc;
9378
9379       rel_reloc = (NEWABI_P (input_bfd)
9380                    && mips_elf_rel_relocation_p (input_bfd, input_section,
9381                                                  relocs, rel));
9382       /* Find the relocation howto for this relocation.  */
9383       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9384
9385       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
9386       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9387       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9388         {
9389           sec = local_sections[r_symndx];
9390           h = NULL;
9391         }
9392       else
9393         {
9394           unsigned long extsymoff;
9395
9396           extsymoff = 0;
9397           if (!elf_bad_symtab (input_bfd))
9398             extsymoff = symtab_hdr->sh_info;
9399           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
9400           while (h->root.type == bfd_link_hash_indirect
9401                  || h->root.type == bfd_link_hash_warning)
9402             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9403
9404           sec = NULL;
9405           if (h->root.type == bfd_link_hash_defined
9406               || h->root.type == bfd_link_hash_defweak)
9407             sec = h->root.u.def.section;
9408         }
9409
9410       if (sec != NULL && discarded_section (sec))
9411         {
9412           mips_reloc_against_discarded_section (output_bfd, info, input_bfd,
9413                                                 input_section, &rel, &relend,
9414                                                 rel_reloc, howto, contents);
9415           continue;
9416         }
9417
9418       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
9419         {
9420           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
9421              64-bit code, but make sure all their addresses are in the
9422              lowermost or uppermost 32-bit section of the 64-bit address
9423              space.  Thus, when they use an R_MIPS_64 they mean what is
9424              usually meant by R_MIPS_32, with the exception that the
9425              stored value is sign-extended to 64 bits.  */
9426           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
9427
9428           /* On big-endian systems, we need to lie about the position
9429              of the reloc.  */
9430           if (bfd_big_endian (input_bfd))
9431             rel->r_offset += 4;
9432         }
9433
9434       if (!use_saved_addend_p)
9435         {
9436           /* If these relocations were originally of the REL variety,
9437              we must pull the addend out of the field that will be
9438              relocated.  Otherwise, we simply use the contents of the
9439              RELA relocation.  */
9440           if (mips_elf_rel_relocation_p (input_bfd, input_section,
9441                                          relocs, rel))
9442             {
9443               rela_relocation_p = FALSE;
9444               addend = mips_elf_read_rel_addend (input_bfd, rel,
9445                                                  howto, contents);
9446               if (hi16_reloc_p (r_type)
9447                   || (got16_reloc_p (r_type)
9448                       && mips_elf_local_relocation_p (input_bfd, rel,
9449                                                       local_sections)))
9450                 {
9451                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
9452                                                      contents, &addend))
9453                     {
9454                       if (h)
9455                         name = h->root.root.string;
9456                       else
9457                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9458                                                  local_syms + r_symndx,
9459                                                  sec);
9460                       (*_bfd_error_handler)
9461                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
9462                          input_bfd, input_section, name, howto->name,
9463                          rel->r_offset);
9464                     }
9465                 }
9466               else
9467                 addend <<= howto->rightshift;
9468             }
9469           else
9470             addend = rel->r_addend;
9471           mips_elf_adjust_addend (output_bfd, info, input_bfd,
9472                                   local_syms, local_sections, rel);
9473         }
9474
9475       if (info->relocatable)
9476         {
9477           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
9478               && bfd_big_endian (input_bfd))
9479             rel->r_offset -= 4;
9480
9481           if (!rela_relocation_p && rel->r_addend)
9482             {
9483               addend += rel->r_addend;
9484               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
9485                 addend = mips_elf_high (addend);
9486               else if (r_type == R_MIPS_HIGHER)
9487                 addend = mips_elf_higher (addend);
9488               else if (r_type == R_MIPS_HIGHEST)
9489                 addend = mips_elf_highest (addend);
9490               else
9491                 addend >>= howto->rightshift;
9492
9493               /* We use the source mask, rather than the destination
9494                  mask because the place to which we are writing will be
9495                  source of the addend in the final link.  */
9496               addend &= howto->src_mask;
9497
9498               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9499                 /* See the comment above about using R_MIPS_64 in the 32-bit
9500                    ABI.  Here, we need to update the addend.  It would be
9501                    possible to get away with just using the R_MIPS_32 reloc
9502                    but for endianness.  */
9503                 {
9504                   bfd_vma sign_bits;
9505                   bfd_vma low_bits;
9506                   bfd_vma high_bits;
9507
9508                   if (addend & ((bfd_vma) 1 << 31))
9509 #ifdef BFD64
9510                     sign_bits = ((bfd_vma) 1 << 32) - 1;
9511 #else
9512                     sign_bits = -1;
9513 #endif
9514                   else
9515                     sign_bits = 0;
9516
9517                   /* If we don't know that we have a 64-bit type,
9518                      do two separate stores.  */
9519                   if (bfd_big_endian (input_bfd))
9520                     {
9521                       /* Store the sign-bits (which are most significant)
9522                          first.  */
9523                       low_bits = sign_bits;
9524                       high_bits = addend;
9525                     }
9526                   else
9527                     {
9528                       low_bits = addend;
9529                       high_bits = sign_bits;
9530                     }
9531                   bfd_put_32 (input_bfd, low_bits,
9532                               contents + rel->r_offset);
9533                   bfd_put_32 (input_bfd, high_bits,
9534                               contents + rel->r_offset + 4);
9535                   continue;
9536                 }
9537
9538               if (! mips_elf_perform_relocation (info, howto, rel, addend,
9539                                                  input_bfd, input_section,
9540                                                  contents, FALSE))
9541                 return FALSE;
9542             }
9543
9544           /* Go on to the next relocation.  */
9545           continue;
9546         }
9547
9548       /* In the N32 and 64-bit ABIs there may be multiple consecutive
9549          relocations for the same offset.  In that case we are
9550          supposed to treat the output of each relocation as the addend
9551          for the next.  */
9552       if (rel + 1 < relend
9553           && rel->r_offset == rel[1].r_offset
9554           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
9555         use_saved_addend_p = TRUE;
9556       else
9557         use_saved_addend_p = FALSE;
9558
9559       /* Figure out what value we are supposed to relocate.  */
9560       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
9561                                              input_section, info, rel,
9562                                              addend, howto, local_syms,
9563                                              local_sections, &value,
9564                                              &name, &cross_mode_jump_p,
9565                                              use_saved_addend_p))
9566         {
9567         case bfd_reloc_continue:
9568           /* There's nothing to do.  */
9569           continue;
9570
9571         case bfd_reloc_undefined:
9572           /* mips_elf_calculate_relocation already called the
9573              undefined_symbol callback.  There's no real point in
9574              trying to perform the relocation at this point, so we
9575              just skip ahead to the next relocation.  */
9576           continue;
9577
9578         case bfd_reloc_notsupported:
9579           msg = _("internal error: unsupported relocation error");
9580           info->callbacks->warning
9581             (info, msg, name, input_bfd, input_section, rel->r_offset);
9582           return FALSE;
9583
9584         case bfd_reloc_overflow:
9585           if (use_saved_addend_p)
9586             /* Ignore overflow until we reach the last relocation for
9587                a given location.  */
9588             ;
9589           else
9590             {
9591               struct mips_elf_link_hash_table *htab;
9592
9593               htab = mips_elf_hash_table (info);
9594               BFD_ASSERT (htab != NULL);
9595               BFD_ASSERT (name != NULL);
9596               if (!htab->small_data_overflow_reported
9597                   && (gprel16_reloc_p (howto->type)
9598                       || literal_reloc_p (howto->type)))
9599                 {
9600                   msg = _("small-data section exceeds 64KB;"
9601                           " lower small-data size limit (see option -G)");
9602
9603                   htab->small_data_overflow_reported = TRUE;
9604                   (*info->callbacks->einfo) ("%P: %s\n", msg);
9605                 }
9606               if (! ((*info->callbacks->reloc_overflow)
9607                      (info, NULL, name, howto->name, (bfd_vma) 0,
9608                       input_bfd, input_section, rel->r_offset)))
9609                 return FALSE;
9610             }
9611           break;
9612
9613         case bfd_reloc_ok:
9614           break;
9615
9616         case bfd_reloc_outofrange:
9617           if (jal_reloc_p (howto->type))
9618             {
9619               msg = _("JALX to a non-word-aligned address");
9620               info->callbacks->warning
9621                 (info, msg, name, input_bfd, input_section, rel->r_offset);
9622               return FALSE;
9623             }
9624           /* Fall through.  */
9625
9626         default:
9627           abort ();
9628           break;
9629         }
9630
9631       /* If we've got another relocation for the address, keep going
9632          until we reach the last one.  */
9633       if (use_saved_addend_p)
9634         {
9635           addend = value;
9636           continue;
9637         }
9638
9639       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9640         /* See the comment above about using R_MIPS_64 in the 32-bit
9641            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
9642            that calculated the right value.  Now, however, we
9643            sign-extend the 32-bit result to 64-bits, and store it as a
9644            64-bit value.  We are especially generous here in that we
9645            go to extreme lengths to support this usage on systems with
9646            only a 32-bit VMA.  */
9647         {
9648           bfd_vma sign_bits;
9649           bfd_vma low_bits;
9650           bfd_vma high_bits;
9651
9652           if (value & ((bfd_vma) 1 << 31))
9653 #ifdef BFD64
9654             sign_bits = ((bfd_vma) 1 << 32) - 1;
9655 #else
9656             sign_bits = -1;
9657 #endif
9658           else
9659             sign_bits = 0;
9660
9661           /* If we don't know that we have a 64-bit type,
9662              do two separate stores.  */
9663           if (bfd_big_endian (input_bfd))
9664             {
9665               /* Undo what we did above.  */
9666               rel->r_offset -= 4;
9667               /* Store the sign-bits (which are most significant)
9668                  first.  */
9669               low_bits = sign_bits;
9670               high_bits = value;
9671             }
9672           else
9673             {
9674               low_bits = value;
9675               high_bits = sign_bits;
9676             }
9677           bfd_put_32 (input_bfd, low_bits,
9678                       contents + rel->r_offset);
9679           bfd_put_32 (input_bfd, high_bits,
9680                       contents + rel->r_offset + 4);
9681           continue;
9682         }
9683
9684       /* Actually perform the relocation.  */
9685       if (! mips_elf_perform_relocation (info, howto, rel, value,
9686                                          input_bfd, input_section,
9687                                          contents, cross_mode_jump_p))
9688         return FALSE;
9689     }
9690
9691   return TRUE;
9692 }
9693 \f
9694 /* A function that iterates over each entry in la25_stubs and fills
9695    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
9696
9697 static int
9698 mips_elf_create_la25_stub (void **slot, void *data)
9699 {
9700   struct mips_htab_traverse_info *hti;
9701   struct mips_elf_link_hash_table *htab;
9702   struct mips_elf_la25_stub *stub;
9703   asection *s;
9704   bfd_byte *loc;
9705   bfd_vma offset, target, target_high, target_low;
9706
9707   stub = (struct mips_elf_la25_stub *) *slot;
9708   hti = (struct mips_htab_traverse_info *) data;
9709   htab = mips_elf_hash_table (hti->info);
9710   BFD_ASSERT (htab != NULL);
9711
9712   /* Create the section contents, if we haven't already.  */
9713   s = stub->stub_section;
9714   loc = s->contents;
9715   if (loc == NULL)
9716     {
9717       loc = bfd_malloc (s->size);
9718       if (loc == NULL)
9719         {
9720           hti->error = TRUE;
9721           return FALSE;
9722         }
9723       s->contents = loc;
9724     }
9725
9726   /* Work out where in the section this stub should go.  */
9727   offset = stub->offset;
9728
9729   /* Work out the target address.  */
9730   target = mips_elf_get_la25_target (stub, &s);
9731   target += s->output_section->vma + s->output_offset;
9732
9733   target_high = ((target + 0x8000) >> 16) & 0xffff;
9734   target_low = (target & 0xffff);
9735
9736   if (stub->stub_section != htab->strampoline)
9737     {
9738       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
9739          of the section and write the two instructions at the end.  */
9740       memset (loc, 0, offset);
9741       loc += offset;
9742       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9743         {
9744           bfd_put_micromips_32 (hti->output_bfd,
9745                                 LA25_LUI_MICROMIPS (target_high),
9746                                 loc);
9747           bfd_put_micromips_32 (hti->output_bfd,
9748                                 LA25_ADDIU_MICROMIPS (target_low),
9749                                 loc + 4);
9750         }
9751       else
9752         {
9753           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9754           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
9755         }
9756     }
9757   else
9758     {
9759       /* This is trampoline.  */
9760       loc += offset;
9761       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9762         {
9763           bfd_put_micromips_32 (hti->output_bfd,
9764                                 LA25_LUI_MICROMIPS (target_high), loc);
9765           bfd_put_micromips_32 (hti->output_bfd,
9766                                 LA25_J_MICROMIPS (target), loc + 4);
9767           bfd_put_micromips_32 (hti->output_bfd,
9768                                 LA25_ADDIU_MICROMIPS (target_low), loc + 8);
9769           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9770         }
9771       else
9772         {
9773           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9774           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
9775           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
9776           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9777         }
9778     }
9779   return TRUE;
9780 }
9781
9782 /* If NAME is one of the special IRIX6 symbols defined by the linker,
9783    adjust it appropriately now.  */
9784
9785 static void
9786 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
9787                                       const char *name, Elf_Internal_Sym *sym)
9788 {
9789   /* The linker script takes care of providing names and values for
9790      these, but we must place them into the right sections.  */
9791   static const char* const text_section_symbols[] = {
9792     "_ftext",
9793     "_etext",
9794     "__dso_displacement",
9795     "__elf_header",
9796     "__program_header_table",
9797     NULL
9798   };
9799
9800   static const char* const data_section_symbols[] = {
9801     "_fdata",
9802     "_edata",
9803     "_end",
9804     "_fbss",
9805     NULL
9806   };
9807
9808   const char* const *p;
9809   int i;
9810
9811   for (i = 0; i < 2; ++i)
9812     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
9813          *p;
9814          ++p)
9815       if (strcmp (*p, name) == 0)
9816         {
9817           /* All of these symbols are given type STT_SECTION by the
9818              IRIX6 linker.  */
9819           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9820           sym->st_other = STO_PROTECTED;
9821
9822           /* The IRIX linker puts these symbols in special sections.  */
9823           if (i == 0)
9824             sym->st_shndx = SHN_MIPS_TEXT;
9825           else
9826             sym->st_shndx = SHN_MIPS_DATA;
9827
9828           break;
9829         }
9830 }
9831
9832 /* Finish up dynamic symbol handling.  We set the contents of various
9833    dynamic sections here.  */
9834
9835 bfd_boolean
9836 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
9837                                      struct bfd_link_info *info,
9838                                      struct elf_link_hash_entry *h,
9839                                      Elf_Internal_Sym *sym)
9840 {
9841   bfd *dynobj;
9842   asection *sgot;
9843   struct mips_got_info *g, *gg;
9844   const char *name;
9845   int idx;
9846   struct mips_elf_link_hash_table *htab;
9847   struct mips_elf_link_hash_entry *hmips;
9848
9849   htab = mips_elf_hash_table (info);
9850   BFD_ASSERT (htab != NULL);
9851   dynobj = elf_hash_table (info)->dynobj;
9852   hmips = (struct mips_elf_link_hash_entry *) h;
9853
9854   BFD_ASSERT (!htab->is_vxworks);
9855
9856   if (h->plt.offset != MINUS_ONE && hmips->no_fn_stub)
9857     {
9858       /* We've decided to create a PLT entry for this symbol.  */
9859       bfd_byte *loc;
9860       bfd_vma header_address, plt_index, got_address;
9861       bfd_vma got_address_high, got_address_low, load;
9862       const bfd_vma *plt_entry;
9863
9864       BFD_ASSERT (htab->use_plts_and_copy_relocs);
9865       BFD_ASSERT (h->dynindx != -1);
9866       BFD_ASSERT (htab->splt != NULL);
9867       BFD_ASSERT (h->plt.offset <= htab->splt->size);
9868       BFD_ASSERT (!h->def_regular);
9869
9870       /* Calculate the address of the PLT header.  */
9871       header_address = (htab->splt->output_section->vma
9872                         + htab->splt->output_offset);
9873
9874       /* Calculate the index of the entry.  */
9875       plt_index = ((h->plt.offset - htab->plt_header_size)
9876                    / htab->plt_entry_size);
9877
9878       /* Calculate the address of the .got.plt entry.  */
9879       got_address = (htab->sgotplt->output_section->vma
9880                      + htab->sgotplt->output_offset
9881                      + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9882       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
9883       got_address_low = got_address & 0xffff;
9884
9885       /* Initially point the .got.plt entry at the PLT header.  */
9886       loc = (htab->sgotplt->contents
9887              + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9888       if (ABI_64_P (output_bfd))
9889         bfd_put_64 (output_bfd, header_address, loc);
9890       else
9891         bfd_put_32 (output_bfd, header_address, loc);
9892
9893       /* Find out where the .plt entry should go.  */
9894       loc = htab->splt->contents + h->plt.offset;
9895
9896       /* Pick the load opcode.  */
9897       load = MIPS_ELF_LOAD_WORD (output_bfd);
9898
9899       /* Fill in the PLT entry itself.  */
9900       plt_entry = mips_exec_plt_entry;
9901       bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
9902       bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load, loc + 4);
9903
9904       if (! LOAD_INTERLOCKS_P (output_bfd))
9905         {
9906           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
9907           bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
9908         }
9909       else
9910         {
9911           bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
9912           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 12);
9913         }
9914
9915       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
9916       mips_elf_output_dynamic_relocation (output_bfd, htab->srelplt,
9917                                           plt_index, h->dynindx,
9918                                           R_MIPS_JUMP_SLOT, got_address);
9919
9920       /* We distinguish between PLT entries and lazy-binding stubs by
9921          giving the former an st_other value of STO_MIPS_PLT.  Set the
9922          flag and leave the value if there are any relocations in the
9923          binary where pointer equality matters.  */
9924       sym->st_shndx = SHN_UNDEF;
9925       if (h->pointer_equality_needed)
9926         sym->st_other = STO_MIPS_PLT;
9927       else
9928         sym->st_value = 0;
9929     }
9930   else if (h->plt.offset != MINUS_ONE)
9931     {
9932       /* We've decided to create a lazy-binding stub.  */
9933       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
9934
9935       /* This symbol has a stub.  Set it up.  */
9936
9937       BFD_ASSERT (h->dynindx != -1);
9938
9939       BFD_ASSERT ((htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9940                   || (h->dynindx <= 0xffff));
9941
9942       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
9943          sign extension at runtime in the stub, resulting in a negative
9944          index value.  */
9945       if (h->dynindx & ~0x7fffffff)
9946         return FALSE;
9947
9948       /* Fill the stub.  */
9949       idx = 0;
9950       bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
9951       idx += 4;
9952       bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + idx);
9953       idx += 4;
9954       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9955         {
9956           bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
9957                       stub + idx);
9958           idx += 4;
9959         }
9960       bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
9961       idx += 4;
9962
9963       /* If a large stub is not required and sign extension is not a
9964          problem, then use legacy code in the stub.  */
9965       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9966         bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff), stub + idx);
9967       else if (h->dynindx & ~0x7fff)
9968         bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff), stub + idx);
9969       else
9970         bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
9971                     stub + idx);
9972
9973       BFD_ASSERT (h->plt.offset <= htab->sstubs->size);
9974       memcpy (htab->sstubs->contents + h->plt.offset,
9975               stub, htab->function_stub_size);
9976
9977       /* Mark the symbol as undefined.  plt.offset != -1 occurs
9978          only for the referenced symbol.  */
9979       sym->st_shndx = SHN_UNDEF;
9980
9981       /* The run-time linker uses the st_value field of the symbol
9982          to reset the global offset table entry for this external
9983          to its stub address when unlinking a shared object.  */
9984       sym->st_value = (htab->sstubs->output_section->vma
9985                        + htab->sstubs->output_offset
9986                        + h->plt.offset);
9987     }
9988
9989   /* If we have a MIPS16 function with a stub, the dynamic symbol must
9990      refer to the stub, since only the stub uses the standard calling
9991      conventions.  */
9992   if (h->dynindx != -1 && hmips->fn_stub != NULL)
9993     {
9994       BFD_ASSERT (hmips->need_fn_stub);
9995       sym->st_value = (hmips->fn_stub->output_section->vma
9996                        + hmips->fn_stub->output_offset);
9997       sym->st_size = hmips->fn_stub->size;
9998       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
9999     }
10000
10001   BFD_ASSERT (h->dynindx != -1
10002               || h->forced_local);
10003
10004   sgot = htab->sgot;
10005   g = htab->got_info;
10006   BFD_ASSERT (g != NULL);
10007
10008   /* Run through the global symbol table, creating GOT entries for all
10009      the symbols that need them.  */
10010   if (hmips->global_got_area != GGA_NONE)
10011     {
10012       bfd_vma offset;
10013       bfd_vma value;
10014
10015       value = sym->st_value;
10016       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
10017       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
10018     }
10019
10020   if (hmips->global_got_area != GGA_NONE && g->next)
10021     {
10022       struct mips_got_entry e, *p;
10023       bfd_vma entry;
10024       bfd_vma offset;
10025
10026       gg = g;
10027
10028       e.abfd = output_bfd;
10029       e.symndx = -1;
10030       e.d.h = hmips;
10031       e.tls_type = 0;
10032
10033       for (g = g->next; g->next != gg; g = g->next)
10034         {
10035           if (g->got_entries
10036               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
10037                                                            &e)))
10038             {
10039               offset = p->gotidx;
10040               if (info->shared
10041                   || (elf_hash_table (info)->dynamic_sections_created
10042                       && p->d.h != NULL
10043                       && p->d.h->root.def_dynamic
10044                       && !p->d.h->root.def_regular))
10045                 {
10046                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
10047                      the various compatibility problems, it's easier to mock
10048                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
10049                      mips_elf_create_dynamic_relocation to calculate the
10050                      appropriate addend.  */
10051                   Elf_Internal_Rela rel[3];
10052
10053                   memset (rel, 0, sizeof (rel));
10054                   if (ABI_64_P (output_bfd))
10055                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
10056                   else
10057                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
10058                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
10059
10060                   entry = 0;
10061                   if (! (mips_elf_create_dynamic_relocation
10062                          (output_bfd, info, rel,
10063                           e.d.h, NULL, sym->st_value, &entry, sgot)))
10064                     return FALSE;
10065                 }
10066               else
10067                 entry = sym->st_value;
10068               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
10069             }
10070         }
10071     }
10072
10073   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
10074   name = h->root.root.string;
10075   if (h == elf_hash_table (info)->hdynamic
10076       || h == elf_hash_table (info)->hgot)
10077     sym->st_shndx = SHN_ABS;
10078   else if (strcmp (name, "_DYNAMIC_LINK") == 0
10079            || strcmp (name, "_DYNAMIC_LINKING") == 0)
10080     {
10081       sym->st_shndx = SHN_ABS;
10082       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10083       sym->st_value = 1;
10084     }
10085   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
10086     {
10087       sym->st_shndx = SHN_ABS;
10088       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10089       sym->st_value = elf_gp (output_bfd);
10090     }
10091   else if (SGI_COMPAT (output_bfd))
10092     {
10093       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
10094           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
10095         {
10096           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10097           sym->st_other = STO_PROTECTED;
10098           sym->st_value = 0;
10099           sym->st_shndx = SHN_MIPS_DATA;
10100         }
10101       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
10102         {
10103           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10104           sym->st_other = STO_PROTECTED;
10105           sym->st_value = mips_elf_hash_table (info)->procedure_count;
10106           sym->st_shndx = SHN_ABS;
10107         }
10108       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
10109         {
10110           if (h->type == STT_FUNC)
10111             sym->st_shndx = SHN_MIPS_TEXT;
10112           else if (h->type == STT_OBJECT)
10113             sym->st_shndx = SHN_MIPS_DATA;
10114         }
10115     }
10116
10117   /* Emit a copy reloc, if needed.  */
10118   if (h->needs_copy)
10119     {
10120       asection *s;
10121       bfd_vma symval;
10122
10123       BFD_ASSERT (h->dynindx != -1);
10124       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10125
10126       s = mips_elf_rel_dyn_section (info, FALSE);
10127       symval = (h->root.u.def.section->output_section->vma
10128                 + h->root.u.def.section->output_offset
10129                 + h->root.u.def.value);
10130       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
10131                                           h->dynindx, R_MIPS_COPY, symval);
10132     }
10133
10134   /* Handle the IRIX6-specific symbols.  */
10135   if (IRIX_COMPAT (output_bfd) == ict_irix6)
10136     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
10137
10138   /* Keep dynamic MIPS16 symbols odd.  This allows the dynamic linker to
10139      treat MIPS16 symbols like any other.  */
10140   if (ELF_ST_IS_MIPS16 (sym->st_other))
10141     {
10142       BFD_ASSERT (sym->st_value & 1);
10143       sym->st_other -= STO_MIPS16;
10144     }
10145
10146   return TRUE;
10147 }
10148
10149 /* Likewise, for VxWorks.  */
10150
10151 bfd_boolean
10152 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
10153                                          struct bfd_link_info *info,
10154                                          struct elf_link_hash_entry *h,
10155                                          Elf_Internal_Sym *sym)
10156 {
10157   bfd *dynobj;
10158   asection *sgot;
10159   struct mips_got_info *g;
10160   struct mips_elf_link_hash_table *htab;
10161   struct mips_elf_link_hash_entry *hmips;
10162
10163   htab = mips_elf_hash_table (info);
10164   BFD_ASSERT (htab != NULL);
10165   dynobj = elf_hash_table (info)->dynobj;
10166   hmips = (struct mips_elf_link_hash_entry *) h;
10167
10168   if (h->plt.offset != (bfd_vma) -1)
10169     {
10170       bfd_byte *loc;
10171       bfd_vma plt_address, plt_index, got_address, got_offset, branch_offset;
10172       Elf_Internal_Rela rel;
10173       static const bfd_vma *plt_entry;
10174
10175       BFD_ASSERT (h->dynindx != -1);
10176       BFD_ASSERT (htab->splt != NULL);
10177       BFD_ASSERT (h->plt.offset <= htab->splt->size);
10178
10179       /* Calculate the address of the .plt entry.  */
10180       plt_address = (htab->splt->output_section->vma
10181                      + htab->splt->output_offset
10182                      + h->plt.offset);
10183
10184       /* Calculate the index of the entry.  */
10185       plt_index = ((h->plt.offset - htab->plt_header_size)
10186                    / htab->plt_entry_size);
10187
10188       /* Calculate the address of the .got.plt entry.  */
10189       got_address = (htab->sgotplt->output_section->vma
10190                      + htab->sgotplt->output_offset
10191                      + plt_index * 4);
10192
10193       /* Calculate the offset of the .got.plt entry from
10194          _GLOBAL_OFFSET_TABLE_.  */
10195       got_offset = mips_elf_gotplt_index (info, h);
10196
10197       /* Calculate the offset for the branch at the start of the PLT
10198          entry.  The branch jumps to the beginning of .plt.  */
10199       branch_offset = -(h->plt.offset / 4 + 1) & 0xffff;
10200
10201       /* Fill in the initial value of the .got.plt entry.  */
10202       bfd_put_32 (output_bfd, plt_address,
10203                   htab->sgotplt->contents + plt_index * 4);
10204
10205       /* Find out where the .plt entry should go.  */
10206       loc = htab->splt->contents + h->plt.offset;
10207
10208       if (info->shared)
10209         {
10210           plt_entry = mips_vxworks_shared_plt_entry;
10211           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10212           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10213         }
10214       else
10215         {
10216           bfd_vma got_address_high, got_address_low;
10217
10218           plt_entry = mips_vxworks_exec_plt_entry;
10219           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10220           got_address_low = got_address & 0xffff;
10221
10222           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10223           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10224           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
10225           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
10226           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10227           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10228           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10229           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10230
10231           loc = (htab->srelplt2->contents
10232                  + (plt_index * 3 + 2) * sizeof (Elf32_External_Rela));
10233
10234           /* Emit a relocation for the .got.plt entry.  */
10235           rel.r_offset = got_address;
10236           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10237           rel.r_addend = h->plt.offset;
10238           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10239
10240           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
10241           loc += sizeof (Elf32_External_Rela);
10242           rel.r_offset = plt_address + 8;
10243           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10244           rel.r_addend = got_offset;
10245           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10246
10247           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
10248           loc += sizeof (Elf32_External_Rela);
10249           rel.r_offset += 4;
10250           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10251           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10252         }
10253
10254       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10255       loc = htab->srelplt->contents + plt_index * sizeof (Elf32_External_Rela);
10256       rel.r_offset = got_address;
10257       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
10258       rel.r_addend = 0;
10259       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10260
10261       if (!h->def_regular)
10262         sym->st_shndx = SHN_UNDEF;
10263     }
10264
10265   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
10266
10267   sgot = htab->sgot;
10268   g = htab->got_info;
10269   BFD_ASSERT (g != NULL);
10270
10271   /* See if this symbol has an entry in the GOT.  */
10272   if (hmips->global_got_area != GGA_NONE)
10273     {
10274       bfd_vma offset;
10275       Elf_Internal_Rela outrel;
10276       bfd_byte *loc;
10277       asection *s;
10278
10279       /* Install the symbol value in the GOT.   */
10280       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
10281       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
10282
10283       /* Add a dynamic relocation for it.  */
10284       s = mips_elf_rel_dyn_section (info, FALSE);
10285       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
10286       outrel.r_offset = (sgot->output_section->vma
10287                          + sgot->output_offset
10288                          + offset);
10289       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
10290       outrel.r_addend = 0;
10291       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
10292     }
10293
10294   /* Emit a copy reloc, if needed.  */
10295   if (h->needs_copy)
10296     {
10297       Elf_Internal_Rela rel;
10298
10299       BFD_ASSERT (h->dynindx != -1);
10300
10301       rel.r_offset = (h->root.u.def.section->output_section->vma
10302                       + h->root.u.def.section->output_offset
10303                       + h->root.u.def.value);
10304       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
10305       rel.r_addend = 0;
10306       bfd_elf32_swap_reloca_out (output_bfd, &rel,
10307                                  htab->srelbss->contents
10308                                  + (htab->srelbss->reloc_count
10309                                     * sizeof (Elf32_External_Rela)));
10310       ++htab->srelbss->reloc_count;
10311     }
10312
10313   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
10314   if (ELF_ST_IS_COMPRESSED (sym->st_other))
10315     sym->st_value &= ~1;
10316
10317   return TRUE;
10318 }
10319
10320 /* Write out a plt0 entry to the beginning of .plt.  */
10321
10322 static void
10323 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10324 {
10325   bfd_byte *loc;
10326   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
10327   static const bfd_vma *plt_entry;
10328   struct mips_elf_link_hash_table *htab;
10329
10330   htab = mips_elf_hash_table (info);
10331   BFD_ASSERT (htab != NULL);
10332
10333   if (ABI_64_P (output_bfd))
10334     plt_entry = mips_n64_exec_plt0_entry;
10335   else if (ABI_N32_P (output_bfd))
10336     plt_entry = mips_n32_exec_plt0_entry;
10337   else
10338     plt_entry = mips_o32_exec_plt0_entry;
10339
10340   /* Calculate the value of .got.plt.  */
10341   gotplt_value = (htab->sgotplt->output_section->vma
10342                   + htab->sgotplt->output_offset);
10343   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
10344   gotplt_value_low = gotplt_value & 0xffff;
10345
10346   /* The PLT sequence is not safe for N64 if .got.plt's address can
10347      not be loaded in two instructions.  */
10348   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
10349               || ~(gotplt_value | 0x7fffffff) == 0);
10350
10351   /* Install the PLT header.  */
10352   loc = htab->splt->contents;
10353   bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
10354   bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
10355   bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
10356   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10357   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10358   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10359   bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10360   bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10361 }
10362
10363 /* Install the PLT header for a VxWorks executable and finalize the
10364    contents of .rela.plt.unloaded.  */
10365
10366 static void
10367 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10368 {
10369   Elf_Internal_Rela rela;
10370   bfd_byte *loc;
10371   bfd_vma got_value, got_value_high, got_value_low, plt_address;
10372   static const bfd_vma *plt_entry;
10373   struct mips_elf_link_hash_table *htab;
10374
10375   htab = mips_elf_hash_table (info);
10376   BFD_ASSERT (htab != NULL);
10377
10378   plt_entry = mips_vxworks_exec_plt0_entry;
10379
10380   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
10381   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
10382                + htab->root.hgot->root.u.def.section->output_offset
10383                + htab->root.hgot->root.u.def.value);
10384
10385   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
10386   got_value_low = got_value & 0xffff;
10387
10388   /* Calculate the address of the PLT header.  */
10389   plt_address = htab->splt->output_section->vma + htab->splt->output_offset;
10390
10391   /* Install the PLT header.  */
10392   loc = htab->splt->contents;
10393   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
10394   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
10395   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
10396   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10397   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10398   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10399
10400   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
10401   loc = htab->srelplt2->contents;
10402   rela.r_offset = plt_address;
10403   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10404   rela.r_addend = 0;
10405   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10406   loc += sizeof (Elf32_External_Rela);
10407
10408   /* Output the relocation for the following addiu of
10409      %lo(_GLOBAL_OFFSET_TABLE_).  */
10410   rela.r_offset += 4;
10411   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10412   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10413   loc += sizeof (Elf32_External_Rela);
10414
10415   /* Fix up the remaining relocations.  They may have the wrong
10416      symbol index for _G_O_T_ or _P_L_T_ depending on the order
10417      in which symbols were output.  */
10418   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
10419     {
10420       Elf_Internal_Rela rel;
10421
10422       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10423       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10424       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10425       loc += sizeof (Elf32_External_Rela);
10426
10427       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10428       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10429       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10430       loc += sizeof (Elf32_External_Rela);
10431
10432       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10433       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10434       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10435       loc += sizeof (Elf32_External_Rela);
10436     }
10437 }
10438
10439 /* Install the PLT header for a VxWorks shared library.  */
10440
10441 static void
10442 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
10443 {
10444   unsigned int i;
10445   struct mips_elf_link_hash_table *htab;
10446
10447   htab = mips_elf_hash_table (info);
10448   BFD_ASSERT (htab != NULL);
10449
10450   /* We just need to copy the entry byte-by-byte.  */
10451   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
10452     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
10453                 htab->splt->contents + i * 4);
10454 }
10455
10456 /* Finish up the dynamic sections.  */
10457
10458 bfd_boolean
10459 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
10460                                        struct bfd_link_info *info)
10461 {
10462   bfd *dynobj;
10463   asection *sdyn;
10464   asection *sgot;
10465   struct mips_got_info *gg, *g;
10466   struct mips_elf_link_hash_table *htab;
10467
10468   htab = mips_elf_hash_table (info);
10469   BFD_ASSERT (htab != NULL);
10470
10471   dynobj = elf_hash_table (info)->dynobj;
10472
10473   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
10474
10475   sgot = htab->sgot;
10476   gg = htab->got_info;
10477
10478   if (elf_hash_table (info)->dynamic_sections_created)
10479     {
10480       bfd_byte *b;
10481       int dyn_to_skip = 0, dyn_skipped = 0;
10482
10483       BFD_ASSERT (sdyn != NULL);
10484       BFD_ASSERT (gg != NULL);
10485
10486       g = mips_elf_bfd_got (output_bfd, FALSE);
10487       BFD_ASSERT (g != NULL);
10488
10489       for (b = sdyn->contents;
10490            b < sdyn->contents + sdyn->size;
10491            b += MIPS_ELF_DYN_SIZE (dynobj))
10492         {
10493           Elf_Internal_Dyn dyn;
10494           const char *name;
10495           size_t elemsize;
10496           asection *s;
10497           bfd_boolean swap_out_p;
10498
10499           /* Read in the current dynamic entry.  */
10500           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10501
10502           /* Assume that we're going to modify it and write it out.  */
10503           swap_out_p = TRUE;
10504
10505           switch (dyn.d_tag)
10506             {
10507             case DT_RELENT:
10508               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
10509               break;
10510
10511             case DT_RELAENT:
10512               BFD_ASSERT (htab->is_vxworks);
10513               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
10514               break;
10515
10516             case DT_STRSZ:
10517               /* Rewrite DT_STRSZ.  */
10518               dyn.d_un.d_val =
10519                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
10520               break;
10521
10522             case DT_PLTGOT:
10523               s = htab->sgot;
10524               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10525               break;
10526
10527             case DT_MIPS_PLTGOT:
10528               s = htab->sgotplt;
10529               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10530               break;
10531
10532             case DT_MIPS_RLD_VERSION:
10533               dyn.d_un.d_val = 1; /* XXX */
10534               break;
10535
10536             case DT_MIPS_FLAGS:
10537               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
10538               break;
10539
10540             case DT_MIPS_TIME_STAMP:
10541               {
10542                 time_t t;
10543                 time (&t);
10544                 dyn.d_un.d_val = t;
10545               }
10546               break;
10547
10548             case DT_MIPS_ICHECKSUM:
10549               /* XXX FIXME: */
10550               swap_out_p = FALSE;
10551               break;
10552
10553             case DT_MIPS_IVERSION:
10554               /* XXX FIXME: */
10555               swap_out_p = FALSE;
10556               break;
10557
10558             case DT_MIPS_BASE_ADDRESS:
10559               s = output_bfd->sections;
10560               BFD_ASSERT (s != NULL);
10561               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
10562               break;
10563
10564             case DT_MIPS_LOCAL_GOTNO:
10565               dyn.d_un.d_val = g->local_gotno;
10566               break;
10567
10568             case DT_MIPS_UNREFEXTNO:
10569               /* The index into the dynamic symbol table which is the
10570                  entry of the first external symbol that is not
10571                  referenced within the same object.  */
10572               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
10573               break;
10574
10575             case DT_MIPS_GOTSYM:
10576               if (htab->global_gotsym)
10577                 {
10578                   dyn.d_un.d_val = htab->global_gotsym->dynindx;
10579                   break;
10580                 }
10581               /* In case if we don't have global got symbols we default
10582                  to setting DT_MIPS_GOTSYM to the same value as
10583                  DT_MIPS_SYMTABNO, so we just fall through.  */
10584
10585             case DT_MIPS_SYMTABNO:
10586               name = ".dynsym";
10587               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
10588               s = bfd_get_section_by_name (output_bfd, name);
10589               BFD_ASSERT (s != NULL);
10590
10591               dyn.d_un.d_val = s->size / elemsize;
10592               break;
10593
10594             case DT_MIPS_HIPAGENO:
10595               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
10596               break;
10597
10598             case DT_MIPS_RLD_MAP:
10599               {
10600                 struct elf_link_hash_entry *h;
10601                 h = mips_elf_hash_table (info)->rld_symbol;
10602                 if (!h)
10603                   {
10604                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10605                     swap_out_p = FALSE;
10606                     break;
10607                   }
10608                 s = h->root.u.def.section;
10609                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
10610                                   + h->root.u.def.value);
10611               }
10612               break;
10613
10614             case DT_MIPS_OPTIONS:
10615               s = (bfd_get_section_by_name
10616                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
10617               dyn.d_un.d_ptr = s->vma;
10618               break;
10619
10620             case DT_RELASZ:
10621               BFD_ASSERT (htab->is_vxworks);
10622               /* The count does not include the JUMP_SLOT relocations.  */
10623               if (htab->srelplt)
10624                 dyn.d_un.d_val -= htab->srelplt->size;
10625               break;
10626
10627             case DT_PLTREL:
10628               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10629               if (htab->is_vxworks)
10630                 dyn.d_un.d_val = DT_RELA;
10631               else
10632                 dyn.d_un.d_val = DT_REL;
10633               break;
10634
10635             case DT_PLTRELSZ:
10636               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10637               dyn.d_un.d_val = htab->srelplt->size;
10638               break;
10639
10640             case DT_JMPREL:
10641               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10642               dyn.d_un.d_ptr = (htab->srelplt->output_section->vma
10643                                 + htab->srelplt->output_offset);
10644               break;
10645
10646             case DT_TEXTREL:
10647               /* If we didn't need any text relocations after all, delete
10648                  the dynamic tag.  */
10649               if (!(info->flags & DF_TEXTREL))
10650                 {
10651                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10652                   swap_out_p = FALSE;
10653                 }
10654               break;
10655
10656             case DT_FLAGS:
10657               /* If we didn't need any text relocations after all, clear
10658                  DF_TEXTREL from DT_FLAGS.  */
10659               if (!(info->flags & DF_TEXTREL))
10660                 dyn.d_un.d_val &= ~DF_TEXTREL;
10661               else
10662                 swap_out_p = FALSE;
10663               break;
10664
10665             default:
10666               swap_out_p = FALSE;
10667               if (htab->is_vxworks
10668                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
10669                 swap_out_p = TRUE;
10670               break;
10671             }
10672
10673           if (swap_out_p || dyn_skipped)
10674             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10675               (dynobj, &dyn, b - dyn_skipped);
10676
10677           if (dyn_to_skip)
10678             {
10679               dyn_skipped += dyn_to_skip;
10680               dyn_to_skip = 0;
10681             }
10682         }
10683
10684       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
10685       if (dyn_skipped > 0)
10686         memset (b - dyn_skipped, 0, dyn_skipped);
10687     }
10688
10689   if (sgot != NULL && sgot->size > 0
10690       && !bfd_is_abs_section (sgot->output_section))
10691     {
10692       if (htab->is_vxworks)
10693         {
10694           /* The first entry of the global offset table points to the
10695              ".dynamic" section.  The second is initialized by the
10696              loader and contains the shared library identifier.
10697              The third is also initialized by the loader and points
10698              to the lazy resolution stub.  */
10699           MIPS_ELF_PUT_WORD (output_bfd,
10700                              sdyn->output_offset + sdyn->output_section->vma,
10701                              sgot->contents);
10702           MIPS_ELF_PUT_WORD (output_bfd, 0,
10703                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10704           MIPS_ELF_PUT_WORD (output_bfd, 0,
10705                              sgot->contents
10706                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
10707         }
10708       else
10709         {
10710           /* The first entry of the global offset table will be filled at
10711              runtime. The second entry will be used by some runtime loaders.
10712              This isn't the case of IRIX rld.  */
10713           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
10714           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10715                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10716         }
10717
10718       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
10719          = MIPS_ELF_GOT_SIZE (output_bfd);
10720     }
10721
10722   /* Generate dynamic relocations for the non-primary gots.  */
10723   if (gg != NULL && gg->next)
10724     {
10725       Elf_Internal_Rela rel[3];
10726       bfd_vma addend = 0;
10727
10728       memset (rel, 0, sizeof (rel));
10729       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
10730
10731       for (g = gg->next; g->next != gg; g = g->next)
10732         {
10733           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
10734             + g->next->tls_gotno;
10735
10736           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
10737                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10738           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10739                              sgot->contents
10740                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10741
10742           if (! info->shared)
10743             continue;
10744
10745           while (got_index < g->assigned_gotno)
10746             {
10747               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
10748                 = got_index++ * MIPS_ELF_GOT_SIZE (output_bfd);
10749               if (!(mips_elf_create_dynamic_relocation
10750                     (output_bfd, info, rel, NULL,
10751                      bfd_abs_section_ptr,
10752                      0, &addend, sgot)))
10753                 return FALSE;
10754               BFD_ASSERT (addend == 0);
10755             }
10756         }
10757     }
10758
10759   /* The generation of dynamic relocations for the non-primary gots
10760      adds more dynamic relocations.  We cannot count them until
10761      here.  */
10762
10763   if (elf_hash_table (info)->dynamic_sections_created)
10764     {
10765       bfd_byte *b;
10766       bfd_boolean swap_out_p;
10767
10768       BFD_ASSERT (sdyn != NULL);
10769
10770       for (b = sdyn->contents;
10771            b < sdyn->contents + sdyn->size;
10772            b += MIPS_ELF_DYN_SIZE (dynobj))
10773         {
10774           Elf_Internal_Dyn dyn;
10775           asection *s;
10776
10777           /* Read in the current dynamic entry.  */
10778           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10779
10780           /* Assume that we're going to modify it and write it out.  */
10781           swap_out_p = TRUE;
10782
10783           switch (dyn.d_tag)
10784             {
10785             case DT_RELSZ:
10786               /* Reduce DT_RELSZ to account for any relocations we
10787                  decided not to make.  This is for the n64 irix rld,
10788                  which doesn't seem to apply any relocations if there
10789                  are trailing null entries.  */
10790               s = mips_elf_rel_dyn_section (info, FALSE);
10791               dyn.d_un.d_val = (s->reloc_count
10792                                 * (ABI_64_P (output_bfd)
10793                                    ? sizeof (Elf64_Mips_External_Rel)
10794                                    : sizeof (Elf32_External_Rel)));
10795               /* Adjust the section size too.  Tools like the prelinker
10796                  can reasonably expect the values to the same.  */
10797               elf_section_data (s->output_section)->this_hdr.sh_size
10798                 = dyn.d_un.d_val;
10799               break;
10800
10801             default:
10802               swap_out_p = FALSE;
10803               break;
10804             }
10805
10806           if (swap_out_p)
10807             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10808               (dynobj, &dyn, b);
10809         }
10810     }
10811
10812   {
10813     asection *s;
10814     Elf32_compact_rel cpt;
10815
10816     if (SGI_COMPAT (output_bfd))
10817       {
10818         /* Write .compact_rel section out.  */
10819         s = bfd_get_linker_section (dynobj, ".compact_rel");
10820         if (s != NULL)
10821           {
10822             cpt.id1 = 1;
10823             cpt.num = s->reloc_count;
10824             cpt.id2 = 2;
10825             cpt.offset = (s->output_section->filepos
10826                           + sizeof (Elf32_External_compact_rel));
10827             cpt.reserved0 = 0;
10828             cpt.reserved1 = 0;
10829             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
10830                                             ((Elf32_External_compact_rel *)
10831                                              s->contents));
10832
10833             /* Clean up a dummy stub function entry in .text.  */
10834             if (htab->sstubs != NULL)
10835               {
10836                 file_ptr dummy_offset;
10837
10838                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
10839                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
10840                 memset (htab->sstubs->contents + dummy_offset, 0,
10841                         htab->function_stub_size);
10842               }
10843           }
10844       }
10845
10846     /* The psABI says that the dynamic relocations must be sorted in
10847        increasing order of r_symndx.  The VxWorks EABI doesn't require
10848        this, and because the code below handles REL rather than RELA
10849        relocations, using it for VxWorks would be outright harmful.  */
10850     if (!htab->is_vxworks)
10851       {
10852         s = mips_elf_rel_dyn_section (info, FALSE);
10853         if (s != NULL
10854             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
10855           {
10856             reldyn_sorting_bfd = output_bfd;
10857
10858             if (ABI_64_P (output_bfd))
10859               qsort ((Elf64_External_Rel *) s->contents + 1,
10860                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
10861                      sort_dynamic_relocs_64);
10862             else
10863               qsort ((Elf32_External_Rel *) s->contents + 1,
10864                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
10865                      sort_dynamic_relocs);
10866           }
10867       }
10868   }
10869
10870   if (htab->splt && htab->splt->size > 0)
10871     {
10872       if (htab->is_vxworks)
10873         {
10874           if (info->shared)
10875             mips_vxworks_finish_shared_plt (output_bfd, info);
10876           else
10877             mips_vxworks_finish_exec_plt (output_bfd, info);
10878         }
10879       else
10880         {
10881           BFD_ASSERT (!info->shared);
10882           mips_finish_exec_plt (output_bfd, info);
10883         }
10884     }
10885   return TRUE;
10886 }
10887
10888
10889 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
10890
10891 static void
10892 mips_set_isa_flags (bfd *abfd)
10893 {
10894   flagword val;
10895
10896   switch (bfd_get_mach (abfd))
10897     {
10898     default:
10899     case bfd_mach_mips3000:
10900       val = E_MIPS_ARCH_1;
10901       break;
10902
10903     case bfd_mach_mips3900:
10904       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
10905       break;
10906
10907     case bfd_mach_mips6000:
10908       val = E_MIPS_ARCH_2;
10909       break;
10910
10911     case bfd_mach_mips4000:
10912     case bfd_mach_mips4300:
10913     case bfd_mach_mips4400:
10914     case bfd_mach_mips4600:
10915       val = E_MIPS_ARCH_3;
10916       break;
10917
10918     case bfd_mach_mips4010:
10919       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
10920       break;
10921
10922     case bfd_mach_mips4100:
10923       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
10924       break;
10925
10926     case bfd_mach_mips4111:
10927       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
10928       break;
10929
10930     case bfd_mach_mips4120:
10931       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
10932       break;
10933
10934     case bfd_mach_mips4650:
10935       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
10936       break;
10937
10938     case bfd_mach_mips5400:
10939       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
10940       break;
10941
10942     case bfd_mach_mips5500:
10943       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
10944       break;
10945
10946     case bfd_mach_mips5900:
10947       val = E_MIPS_ARCH_3 | E_MIPS_MACH_5900;
10948       break;
10949
10950     case bfd_mach_mips9000:
10951       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
10952       break;
10953
10954     case bfd_mach_mips5000:
10955     case bfd_mach_mips7000:
10956     case bfd_mach_mips8000:
10957     case bfd_mach_mips10000:
10958     case bfd_mach_mips12000:
10959     case bfd_mach_mips14000:
10960     case bfd_mach_mips16000:
10961       val = E_MIPS_ARCH_4;
10962       break;
10963
10964     case bfd_mach_mips5:
10965       val = E_MIPS_ARCH_5;
10966       break;
10967
10968     case bfd_mach_mips_loongson_2e:
10969       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
10970       break;
10971
10972     case bfd_mach_mips_loongson_2f:
10973       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
10974       break;
10975
10976     case bfd_mach_mips_sb1:
10977       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
10978       break;
10979
10980     case bfd_mach_mips_loongson_3a:
10981       val = E_MIPS_ARCH_64 | E_MIPS_MACH_LS3A;
10982       break;
10983
10984     case bfd_mach_mips_octeon:
10985     case bfd_mach_mips_octeonp:
10986       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
10987       break;
10988
10989     case bfd_mach_mips_xlr:
10990       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
10991       break;
10992
10993     case bfd_mach_mips_octeon2:
10994       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
10995       break;
10996
10997     case bfd_mach_mipsisa32:
10998       val = E_MIPS_ARCH_32;
10999       break;
11000
11001     case bfd_mach_mipsisa64:
11002       val = E_MIPS_ARCH_64;
11003       break;
11004
11005     case bfd_mach_mipsisa32r2:
11006       val = E_MIPS_ARCH_32R2;
11007       break;
11008
11009     case bfd_mach_mipsisa64r2:
11010       val = E_MIPS_ARCH_64R2;
11011       break;
11012     }
11013   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
11014   elf_elfheader (abfd)->e_flags |= val;
11015
11016 }
11017
11018
11019 /* The final processing done just before writing out a MIPS ELF object
11020    file.  This gets the MIPS architecture right based on the machine
11021    number.  This is used by both the 32-bit and the 64-bit ABI.  */
11022
11023 void
11024 _bfd_mips_elf_final_write_processing (bfd *abfd,
11025                                       bfd_boolean linker ATTRIBUTE_UNUSED)
11026 {
11027   unsigned int i;
11028   Elf_Internal_Shdr **hdrpp;
11029   const char *name;
11030   asection *sec;
11031
11032   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
11033      is nonzero.  This is for compatibility with old objects, which used
11034      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
11035   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
11036     mips_set_isa_flags (abfd);
11037
11038   /* Set the sh_info field for .gptab sections and other appropriate
11039      info for each special section.  */
11040   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
11041        i < elf_numsections (abfd);
11042        i++, hdrpp++)
11043     {
11044       switch ((*hdrpp)->sh_type)
11045         {
11046         case SHT_MIPS_MSYM:
11047         case SHT_MIPS_LIBLIST:
11048           sec = bfd_get_section_by_name (abfd, ".dynstr");
11049           if (sec != NULL)
11050             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11051           break;
11052
11053         case SHT_MIPS_GPTAB:
11054           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11055           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11056           BFD_ASSERT (name != NULL
11057                       && CONST_STRNEQ (name, ".gptab."));
11058           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
11059           BFD_ASSERT (sec != NULL);
11060           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11061           break;
11062
11063         case SHT_MIPS_CONTENT:
11064           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11065           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11066           BFD_ASSERT (name != NULL
11067                       && CONST_STRNEQ (name, ".MIPS.content"));
11068           sec = bfd_get_section_by_name (abfd,
11069                                          name + sizeof ".MIPS.content" - 1);
11070           BFD_ASSERT (sec != NULL);
11071           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11072           break;
11073
11074         case SHT_MIPS_SYMBOL_LIB:
11075           sec = bfd_get_section_by_name (abfd, ".dynsym");
11076           if (sec != NULL)
11077             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11078           sec = bfd_get_section_by_name (abfd, ".liblist");
11079           if (sec != NULL)
11080             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11081           break;
11082
11083         case SHT_MIPS_EVENTS:
11084           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11085           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11086           BFD_ASSERT (name != NULL);
11087           if (CONST_STRNEQ (name, ".MIPS.events"))
11088             sec = bfd_get_section_by_name (abfd,
11089                                            name + sizeof ".MIPS.events" - 1);
11090           else
11091             {
11092               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
11093               sec = bfd_get_section_by_name (abfd,
11094                                              (name
11095                                               + sizeof ".MIPS.post_rel" - 1));
11096             }
11097           BFD_ASSERT (sec != NULL);
11098           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11099           break;
11100
11101         }
11102     }
11103 }
11104 \f
11105 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
11106    segments.  */
11107
11108 int
11109 _bfd_mips_elf_additional_program_headers (bfd *abfd,
11110                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
11111 {
11112   asection *s;
11113   int ret = 0;
11114
11115   /* See if we need a PT_MIPS_REGINFO segment.  */
11116   s = bfd_get_section_by_name (abfd, ".reginfo");
11117   if (s && (s->flags & SEC_LOAD))
11118     ++ret;
11119
11120   /* See if we need a PT_MIPS_OPTIONS segment.  */
11121   if (IRIX_COMPAT (abfd) == ict_irix6
11122       && bfd_get_section_by_name (abfd,
11123                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
11124     ++ret;
11125
11126   /* See if we need a PT_MIPS_RTPROC segment.  */
11127   if (IRIX_COMPAT (abfd) == ict_irix5
11128       && bfd_get_section_by_name (abfd, ".dynamic")
11129       && bfd_get_section_by_name (abfd, ".mdebug"))
11130     ++ret;
11131
11132   /* Allocate a PT_NULL header in dynamic objects.  See
11133      _bfd_mips_elf_modify_segment_map for details.  */
11134   if (!SGI_COMPAT (abfd)
11135       && bfd_get_section_by_name (abfd, ".dynamic"))
11136     ++ret;
11137
11138   return ret;
11139 }
11140
11141 /* Modify the segment map for an IRIX5 executable.  */
11142
11143 bfd_boolean
11144 _bfd_mips_elf_modify_segment_map (bfd *abfd,
11145                                   struct bfd_link_info *info)
11146 {
11147   asection *s;
11148   struct elf_segment_map *m, **pm;
11149   bfd_size_type amt;
11150
11151   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
11152      segment.  */
11153   s = bfd_get_section_by_name (abfd, ".reginfo");
11154   if (s != NULL && (s->flags & SEC_LOAD) != 0)
11155     {
11156       for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11157         if (m->p_type == PT_MIPS_REGINFO)
11158           break;
11159       if (m == NULL)
11160         {
11161           amt = sizeof *m;
11162           m = bfd_zalloc (abfd, amt);
11163           if (m == NULL)
11164             return FALSE;
11165
11166           m->p_type = PT_MIPS_REGINFO;
11167           m->count = 1;
11168           m->sections[0] = s;
11169
11170           /* We want to put it after the PHDR and INTERP segments.  */
11171           pm = &elf_tdata (abfd)->segment_map;
11172           while (*pm != NULL
11173                  && ((*pm)->p_type == PT_PHDR
11174                      || (*pm)->p_type == PT_INTERP))
11175             pm = &(*pm)->next;
11176
11177           m->next = *pm;
11178           *pm = m;
11179         }
11180     }
11181
11182   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
11183      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
11184      PT_MIPS_OPTIONS segment immediately following the program header
11185      table.  */
11186   if (NEWABI_P (abfd)
11187       /* On non-IRIX6 new abi, we'll have already created a segment
11188          for this section, so don't create another.  I'm not sure this
11189          is not also the case for IRIX 6, but I can't test it right
11190          now.  */
11191       && IRIX_COMPAT (abfd) == ict_irix6)
11192     {
11193       for (s = abfd->sections; s; s = s->next)
11194         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
11195           break;
11196
11197       if (s)
11198         {
11199           struct elf_segment_map *options_segment;
11200
11201           pm = &elf_tdata (abfd)->segment_map;
11202           while (*pm != NULL
11203                  && ((*pm)->p_type == PT_PHDR
11204                      || (*pm)->p_type == PT_INTERP))
11205             pm = &(*pm)->next;
11206
11207           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
11208             {
11209               amt = sizeof (struct elf_segment_map);
11210               options_segment = bfd_zalloc (abfd, amt);
11211               options_segment->next = *pm;
11212               options_segment->p_type = PT_MIPS_OPTIONS;
11213               options_segment->p_flags = PF_R;
11214               options_segment->p_flags_valid = TRUE;
11215               options_segment->count = 1;
11216               options_segment->sections[0] = s;
11217               *pm = options_segment;
11218             }
11219         }
11220     }
11221   else
11222     {
11223       if (IRIX_COMPAT (abfd) == ict_irix5)
11224         {
11225           /* If there are .dynamic and .mdebug sections, we make a room
11226              for the RTPROC header.  FIXME: Rewrite without section names.  */
11227           if (bfd_get_section_by_name (abfd, ".interp") == NULL
11228               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
11229               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
11230             {
11231               for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11232                 if (m->p_type == PT_MIPS_RTPROC)
11233                   break;
11234               if (m == NULL)
11235                 {
11236                   amt = sizeof *m;
11237                   m = bfd_zalloc (abfd, amt);
11238                   if (m == NULL)
11239                     return FALSE;
11240
11241                   m->p_type = PT_MIPS_RTPROC;
11242
11243                   s = bfd_get_section_by_name (abfd, ".rtproc");
11244                   if (s == NULL)
11245                     {
11246                       m->count = 0;
11247                       m->p_flags = 0;
11248                       m->p_flags_valid = 1;
11249                     }
11250                   else
11251                     {
11252                       m->count = 1;
11253                       m->sections[0] = s;
11254                     }
11255
11256                   /* We want to put it after the DYNAMIC segment.  */
11257                   pm = &elf_tdata (abfd)->segment_map;
11258                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
11259                     pm = &(*pm)->next;
11260                   if (*pm != NULL)
11261                     pm = &(*pm)->next;
11262
11263                   m->next = *pm;
11264                   *pm = m;
11265                 }
11266             }
11267         }
11268       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
11269          .dynstr, .dynsym, and .hash sections, and everything in
11270          between.  */
11271       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL;
11272            pm = &(*pm)->next)
11273         if ((*pm)->p_type == PT_DYNAMIC)
11274           break;
11275       m = *pm;
11276       if (m != NULL && IRIX_COMPAT (abfd) == ict_none)
11277         {
11278           /* For a normal mips executable the permissions for the PT_DYNAMIC
11279              segment are read, write and execute. We do that here since
11280              the code in elf.c sets only the read permission. This matters
11281              sometimes for the dynamic linker.  */
11282           if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
11283             {
11284               m->p_flags = PF_R | PF_W | PF_X;
11285               m->p_flags_valid = 1;
11286             }
11287         }
11288       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
11289          glibc's dynamic linker has traditionally derived the number of
11290          tags from the p_filesz field, and sometimes allocates stack
11291          arrays of that size.  An overly-big PT_DYNAMIC segment can
11292          be actively harmful in such cases.  Making PT_DYNAMIC contain
11293          other sections can also make life hard for the prelinker,
11294          which might move one of the other sections to a different
11295          PT_LOAD segment.  */
11296       if (SGI_COMPAT (abfd)
11297           && m != NULL
11298           && m->count == 1
11299           && strcmp (m->sections[0]->name, ".dynamic") == 0)
11300         {
11301           static const char *sec_names[] =
11302           {
11303             ".dynamic", ".dynstr", ".dynsym", ".hash"
11304           };
11305           bfd_vma low, high;
11306           unsigned int i, c;
11307           struct elf_segment_map *n;
11308
11309           low = ~(bfd_vma) 0;
11310           high = 0;
11311           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
11312             {
11313               s = bfd_get_section_by_name (abfd, sec_names[i]);
11314               if (s != NULL && (s->flags & SEC_LOAD) != 0)
11315                 {
11316                   bfd_size_type sz;
11317
11318                   if (low > s->vma)
11319                     low = s->vma;
11320                   sz = s->size;
11321                   if (high < s->vma + sz)
11322                     high = s->vma + sz;
11323                 }
11324             }
11325
11326           c = 0;
11327           for (s = abfd->sections; s != NULL; s = s->next)
11328             if ((s->flags & SEC_LOAD) != 0
11329                 && s->vma >= low
11330                 && s->vma + s->size <= high)
11331               ++c;
11332
11333           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
11334           n = bfd_zalloc (abfd, amt);
11335           if (n == NULL)
11336             return FALSE;
11337           *n = *m;
11338           n->count = c;
11339
11340           i = 0;
11341           for (s = abfd->sections; s != NULL; s = s->next)
11342             {
11343               if ((s->flags & SEC_LOAD) != 0
11344                   && s->vma >= low
11345                   && s->vma + s->size <= high)
11346                 {
11347                   n->sections[i] = s;
11348                   ++i;
11349                 }
11350             }
11351
11352           *pm = n;
11353         }
11354     }
11355
11356   /* Allocate a spare program header in dynamic objects so that tools
11357      like the prelinker can add an extra PT_LOAD entry.
11358
11359      If the prelinker needs to make room for a new PT_LOAD entry, its
11360      standard procedure is to move the first (read-only) sections into
11361      the new (writable) segment.  However, the MIPS ABI requires
11362      .dynamic to be in a read-only segment, and the section will often
11363      start within sizeof (ElfNN_Phdr) bytes of the last program header.
11364
11365      Although the prelinker could in principle move .dynamic to a
11366      writable segment, it seems better to allocate a spare program
11367      header instead, and avoid the need to move any sections.
11368      There is a long tradition of allocating spare dynamic tags,
11369      so allocating a spare program header seems like a natural
11370      extension.
11371
11372      If INFO is NULL, we may be copying an already prelinked binary
11373      with objcopy or strip, so do not add this header.  */
11374   if (info != NULL
11375       && !SGI_COMPAT (abfd)
11376       && bfd_get_section_by_name (abfd, ".dynamic"))
11377     {
11378       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL; pm = &(*pm)->next)
11379         if ((*pm)->p_type == PT_NULL)
11380           break;
11381       if (*pm == NULL)
11382         {
11383           m = bfd_zalloc (abfd, sizeof (*m));
11384           if (m == NULL)
11385             return FALSE;
11386
11387           m->p_type = PT_NULL;
11388           *pm = m;
11389         }
11390     }
11391
11392   return TRUE;
11393 }
11394 \f
11395 /* Return the section that should be marked against GC for a given
11396    relocation.  */
11397
11398 asection *
11399 _bfd_mips_elf_gc_mark_hook (asection *sec,
11400                             struct bfd_link_info *info,
11401                             Elf_Internal_Rela *rel,
11402                             struct elf_link_hash_entry *h,
11403                             Elf_Internal_Sym *sym)
11404 {
11405   /* ??? Do mips16 stub sections need to be handled special?  */
11406
11407   if (h != NULL)
11408     switch (ELF_R_TYPE (sec->owner, rel->r_info))
11409       {
11410       case R_MIPS_GNU_VTINHERIT:
11411       case R_MIPS_GNU_VTENTRY:
11412         return NULL;
11413       }
11414
11415   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
11416 }
11417
11418 /* Update the got entry reference counts for the section being removed.  */
11419
11420 bfd_boolean
11421 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
11422                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
11423                              asection *sec ATTRIBUTE_UNUSED,
11424                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
11425 {
11426 #if 0
11427   Elf_Internal_Shdr *symtab_hdr;
11428   struct elf_link_hash_entry **sym_hashes;
11429   bfd_signed_vma *local_got_refcounts;
11430   const Elf_Internal_Rela *rel, *relend;
11431   unsigned long r_symndx;
11432   struct elf_link_hash_entry *h;
11433
11434   if (info->relocatable)
11435     return TRUE;
11436
11437   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11438   sym_hashes = elf_sym_hashes (abfd);
11439   local_got_refcounts = elf_local_got_refcounts (abfd);
11440
11441   relend = relocs + sec->reloc_count;
11442   for (rel = relocs; rel < relend; rel++)
11443     switch (ELF_R_TYPE (abfd, rel->r_info))
11444       {
11445       case R_MIPS16_GOT16:
11446       case R_MIPS16_CALL16:
11447       case R_MIPS_GOT16:
11448       case R_MIPS_CALL16:
11449       case R_MIPS_CALL_HI16:
11450       case R_MIPS_CALL_LO16:
11451       case R_MIPS_GOT_HI16:
11452       case R_MIPS_GOT_LO16:
11453       case R_MIPS_GOT_DISP:
11454       case R_MIPS_GOT_PAGE:
11455       case R_MIPS_GOT_OFST:
11456       case R_MICROMIPS_GOT16:
11457       case R_MICROMIPS_CALL16:
11458       case R_MICROMIPS_CALL_HI16:
11459       case R_MICROMIPS_CALL_LO16:
11460       case R_MICROMIPS_GOT_HI16:
11461       case R_MICROMIPS_GOT_LO16:
11462       case R_MICROMIPS_GOT_DISP:
11463       case R_MICROMIPS_GOT_PAGE:
11464       case R_MICROMIPS_GOT_OFST:
11465         /* ??? It would seem that the existing MIPS code does no sort
11466            of reference counting or whatnot on its GOT and PLT entries,
11467            so it is not possible to garbage collect them at this time.  */
11468         break;
11469
11470       default:
11471         break;
11472       }
11473 #endif
11474
11475   return TRUE;
11476 }
11477 \f
11478 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
11479    hiding the old indirect symbol.  Process additional relocation
11480    information.  Also called for weakdefs, in which case we just let
11481    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
11482
11483 void
11484 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
11485                                     struct elf_link_hash_entry *dir,
11486                                     struct elf_link_hash_entry *ind)
11487 {
11488   struct mips_elf_link_hash_entry *dirmips, *indmips;
11489
11490   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
11491
11492   dirmips = (struct mips_elf_link_hash_entry *) dir;
11493   indmips = (struct mips_elf_link_hash_entry *) ind;
11494   /* Any absolute non-dynamic relocations against an indirect or weak
11495      definition will be against the target symbol.  */
11496   if (indmips->has_static_relocs)
11497     dirmips->has_static_relocs = TRUE;
11498
11499   if (ind->root.type != bfd_link_hash_indirect)
11500     return;
11501
11502   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
11503   if (indmips->readonly_reloc)
11504     dirmips->readonly_reloc = TRUE;
11505   if (indmips->no_fn_stub)
11506     dirmips->no_fn_stub = TRUE;
11507   if (indmips->fn_stub)
11508     {
11509       dirmips->fn_stub = indmips->fn_stub;
11510       indmips->fn_stub = NULL;
11511     }
11512   if (indmips->need_fn_stub)
11513     {
11514       dirmips->need_fn_stub = TRUE;
11515       indmips->need_fn_stub = FALSE;
11516     }
11517   if (indmips->call_stub)
11518     {
11519       dirmips->call_stub = indmips->call_stub;
11520       indmips->call_stub = NULL;
11521     }
11522   if (indmips->call_fp_stub)
11523     {
11524       dirmips->call_fp_stub = indmips->call_fp_stub;
11525       indmips->call_fp_stub = NULL;
11526     }
11527   if (indmips->global_got_area < dirmips->global_got_area)
11528     dirmips->global_got_area = indmips->global_got_area;
11529   if (indmips->global_got_area < GGA_NONE)
11530     indmips->global_got_area = GGA_NONE;
11531   if (indmips->has_nonpic_branches)
11532     dirmips->has_nonpic_branches = TRUE;
11533
11534   if (dirmips->tls_ie_type == 0)
11535     dirmips->tls_ie_type = indmips->tls_ie_type;
11536   if (dirmips->tls_gd_type == 0)
11537     dirmips->tls_gd_type = indmips->tls_gd_type;
11538 }
11539 \f
11540 #define PDR_SIZE 32
11541
11542 bfd_boolean
11543 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
11544                             struct bfd_link_info *info)
11545 {
11546   asection *o;
11547   bfd_boolean ret = FALSE;
11548   unsigned char *tdata;
11549   size_t i, skip;
11550
11551   o = bfd_get_section_by_name (abfd, ".pdr");
11552   if (! o)
11553     return FALSE;
11554   if (o->size == 0)
11555     return FALSE;
11556   if (o->size % PDR_SIZE != 0)
11557     return FALSE;
11558   if (o->output_section != NULL
11559       && bfd_is_abs_section (o->output_section))
11560     return FALSE;
11561
11562   tdata = bfd_zmalloc (o->size / PDR_SIZE);
11563   if (! tdata)
11564     return FALSE;
11565
11566   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
11567                                             info->keep_memory);
11568   if (!cookie->rels)
11569     {
11570       free (tdata);
11571       return FALSE;
11572     }
11573
11574   cookie->rel = cookie->rels;
11575   cookie->relend = cookie->rels + o->reloc_count;
11576
11577   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
11578     {
11579       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
11580         {
11581           tdata[i] = 1;
11582           skip ++;
11583         }
11584     }
11585
11586   if (skip != 0)
11587     {
11588       mips_elf_section_data (o)->u.tdata = tdata;
11589       o->size -= skip * PDR_SIZE;
11590       ret = TRUE;
11591     }
11592   else
11593     free (tdata);
11594
11595   if (! info->keep_memory)
11596     free (cookie->rels);
11597
11598   return ret;
11599 }
11600
11601 bfd_boolean
11602 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
11603 {
11604   if (strcmp (sec->name, ".pdr") == 0)
11605     return TRUE;
11606   return FALSE;
11607 }
11608
11609 bfd_boolean
11610 _bfd_mips_elf_write_section (bfd *output_bfd,
11611                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
11612                              asection *sec, bfd_byte *contents)
11613 {
11614   bfd_byte *to, *from, *end;
11615   int i;
11616
11617   if (strcmp (sec->name, ".pdr") != 0)
11618     return FALSE;
11619
11620   if (mips_elf_section_data (sec)->u.tdata == NULL)
11621     return FALSE;
11622
11623   to = contents;
11624   end = contents + sec->size;
11625   for (from = contents, i = 0;
11626        from < end;
11627        from += PDR_SIZE, i++)
11628     {
11629       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
11630         continue;
11631       if (to != from)
11632         memcpy (to, from, PDR_SIZE);
11633       to += PDR_SIZE;
11634     }
11635   bfd_set_section_contents (output_bfd, sec->output_section, contents,
11636                             sec->output_offset, sec->size);
11637   return TRUE;
11638 }
11639 \f
11640 /* microMIPS code retains local labels for linker relaxation.  Omit them
11641    from output by default for clarity.  */
11642
11643 bfd_boolean
11644 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
11645 {
11646   return _bfd_elf_is_local_label_name (abfd, sym->name);
11647 }
11648
11649 /* MIPS ELF uses a special find_nearest_line routine in order the
11650    handle the ECOFF debugging information.  */
11651
11652 struct mips_elf_find_line
11653 {
11654   struct ecoff_debug_info d;
11655   struct ecoff_find_line i;
11656 };
11657
11658 bfd_boolean
11659 _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section,
11660                                  asymbol **symbols, bfd_vma offset,
11661                                  const char **filename_ptr,
11662                                  const char **functionname_ptr,
11663                                  unsigned int *line_ptr)
11664 {
11665   asection *msec;
11666
11667   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
11668                                      filename_ptr, functionname_ptr,
11669                                      line_ptr))
11670     return TRUE;
11671
11672   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
11673                                      section, symbols, offset,
11674                                      filename_ptr, functionname_ptr,
11675                                      line_ptr, NULL, ABI_64_P (abfd) ? 8 : 0,
11676                                      &elf_tdata (abfd)->dwarf2_find_line_info))
11677     return TRUE;
11678
11679   msec = bfd_get_section_by_name (abfd, ".mdebug");
11680   if (msec != NULL)
11681     {
11682       flagword origflags;
11683       struct mips_elf_find_line *fi;
11684       const struct ecoff_debug_swap * const swap =
11685         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
11686
11687       /* If we are called during a link, mips_elf_final_link may have
11688          cleared the SEC_HAS_CONTENTS field.  We force it back on here
11689          if appropriate (which it normally will be).  */
11690       origflags = msec->flags;
11691       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
11692         msec->flags |= SEC_HAS_CONTENTS;
11693
11694       fi = elf_tdata (abfd)->find_line_info;
11695       if (fi == NULL)
11696         {
11697           bfd_size_type external_fdr_size;
11698           char *fraw_src;
11699           char *fraw_end;
11700           struct fdr *fdr_ptr;
11701           bfd_size_type amt = sizeof (struct mips_elf_find_line);
11702
11703           fi = bfd_zalloc (abfd, amt);
11704           if (fi == NULL)
11705             {
11706               msec->flags = origflags;
11707               return FALSE;
11708             }
11709
11710           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
11711             {
11712               msec->flags = origflags;
11713               return FALSE;
11714             }
11715
11716           /* Swap in the FDR information.  */
11717           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
11718           fi->d.fdr = bfd_alloc (abfd, amt);
11719           if (fi->d.fdr == NULL)
11720             {
11721               msec->flags = origflags;
11722               return FALSE;
11723             }
11724           external_fdr_size = swap->external_fdr_size;
11725           fdr_ptr = fi->d.fdr;
11726           fraw_src = (char *) fi->d.external_fdr;
11727           fraw_end = (fraw_src
11728                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
11729           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
11730             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
11731
11732           elf_tdata (abfd)->find_line_info = fi;
11733
11734           /* Note that we don't bother to ever free this information.
11735              find_nearest_line is either called all the time, as in
11736              objdump -l, so the information should be saved, or it is
11737              rarely called, as in ld error messages, so the memory
11738              wasted is unimportant.  Still, it would probably be a
11739              good idea for free_cached_info to throw it away.  */
11740         }
11741
11742       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
11743                                   &fi->i, filename_ptr, functionname_ptr,
11744                                   line_ptr))
11745         {
11746           msec->flags = origflags;
11747           return TRUE;
11748         }
11749
11750       msec->flags = origflags;
11751     }
11752
11753   /* Fall back on the generic ELF find_nearest_line routine.  */
11754
11755   return _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
11756                                      filename_ptr, functionname_ptr,
11757                                      line_ptr);
11758 }
11759
11760 bfd_boolean
11761 _bfd_mips_elf_find_inliner_info (bfd *abfd,
11762                                  const char **filename_ptr,
11763                                  const char **functionname_ptr,
11764                                  unsigned int *line_ptr)
11765 {
11766   bfd_boolean found;
11767   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
11768                                          functionname_ptr, line_ptr,
11769                                          & elf_tdata (abfd)->dwarf2_find_line_info);
11770   return found;
11771 }
11772
11773 \f
11774 /* When are writing out the .options or .MIPS.options section,
11775    remember the bytes we are writing out, so that we can install the
11776    GP value in the section_processing routine.  */
11777
11778 bfd_boolean
11779 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
11780                                     const void *location,
11781                                     file_ptr offset, bfd_size_type count)
11782 {
11783   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
11784     {
11785       bfd_byte *c;
11786
11787       if (elf_section_data (section) == NULL)
11788         {
11789           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
11790           section->used_by_bfd = bfd_zalloc (abfd, amt);
11791           if (elf_section_data (section) == NULL)
11792             return FALSE;
11793         }
11794       c = mips_elf_section_data (section)->u.tdata;
11795       if (c == NULL)
11796         {
11797           c = bfd_zalloc (abfd, section->size);
11798           if (c == NULL)
11799             return FALSE;
11800           mips_elf_section_data (section)->u.tdata = c;
11801         }
11802
11803       memcpy (c + offset, location, count);
11804     }
11805
11806   return _bfd_elf_set_section_contents (abfd, section, location, offset,
11807                                         count);
11808 }
11809
11810 /* This is almost identical to bfd_generic_get_... except that some
11811    MIPS relocations need to be handled specially.  Sigh.  */
11812
11813 bfd_byte *
11814 _bfd_elf_mips_get_relocated_section_contents
11815   (bfd *abfd,
11816    struct bfd_link_info *link_info,
11817    struct bfd_link_order *link_order,
11818    bfd_byte *data,
11819    bfd_boolean relocatable,
11820    asymbol **symbols)
11821 {
11822   /* Get enough memory to hold the stuff */
11823   bfd *input_bfd = link_order->u.indirect.section->owner;
11824   asection *input_section = link_order->u.indirect.section;
11825   bfd_size_type sz;
11826
11827   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
11828   arelent **reloc_vector = NULL;
11829   long reloc_count;
11830
11831   if (reloc_size < 0)
11832     goto error_return;
11833
11834   reloc_vector = bfd_malloc (reloc_size);
11835   if (reloc_vector == NULL && reloc_size != 0)
11836     goto error_return;
11837
11838   /* read in the section */
11839   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
11840   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
11841     goto error_return;
11842
11843   reloc_count = bfd_canonicalize_reloc (input_bfd,
11844                                         input_section,
11845                                         reloc_vector,
11846                                         symbols);
11847   if (reloc_count < 0)
11848     goto error_return;
11849
11850   if (reloc_count > 0)
11851     {
11852       arelent **parent;
11853       /* for mips */
11854       int gp_found;
11855       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
11856
11857       {
11858         struct bfd_hash_entry *h;
11859         struct bfd_link_hash_entry *lh;
11860         /* Skip all this stuff if we aren't mixing formats.  */
11861         if (abfd && input_bfd
11862             && abfd->xvec == input_bfd->xvec)
11863           lh = 0;
11864         else
11865           {
11866             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
11867             lh = (struct bfd_link_hash_entry *) h;
11868           }
11869       lookup:
11870         if (lh)
11871           {
11872             switch (lh->type)
11873               {
11874               case bfd_link_hash_undefined:
11875               case bfd_link_hash_undefweak:
11876               case bfd_link_hash_common:
11877                 gp_found = 0;
11878                 break;
11879               case bfd_link_hash_defined:
11880               case bfd_link_hash_defweak:
11881                 gp_found = 1;
11882                 gp = lh->u.def.value;
11883                 break;
11884               case bfd_link_hash_indirect:
11885               case bfd_link_hash_warning:
11886                 lh = lh->u.i.link;
11887                 /* @@FIXME  ignoring warning for now */
11888                 goto lookup;
11889               case bfd_link_hash_new:
11890               default:
11891                 abort ();
11892               }
11893           }
11894         else
11895           gp_found = 0;
11896       }
11897       /* end mips */
11898       for (parent = reloc_vector; *parent != NULL; parent++)
11899         {
11900           char *error_message = NULL;
11901           bfd_reloc_status_type r;
11902
11903           /* Specific to MIPS: Deal with relocation types that require
11904              knowing the gp of the output bfd.  */
11905           asymbol *sym = *(*parent)->sym_ptr_ptr;
11906
11907           /* If we've managed to find the gp and have a special
11908              function for the relocation then go ahead, else default
11909              to the generic handling.  */
11910           if (gp_found
11911               && (*parent)->howto->special_function
11912               == _bfd_mips_elf32_gprel16_reloc)
11913             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
11914                                                input_section, relocatable,
11915                                                data, gp);
11916           else
11917             r = bfd_perform_relocation (input_bfd, *parent, data,
11918                                         input_section,
11919                                         relocatable ? abfd : NULL,
11920                                         &error_message);
11921
11922           if (relocatable)
11923             {
11924               asection *os = input_section->output_section;
11925
11926               /* A partial link, so keep the relocs */
11927               os->orelocation[os->reloc_count] = *parent;
11928               os->reloc_count++;
11929             }
11930
11931           if (r != bfd_reloc_ok)
11932             {
11933               switch (r)
11934                 {
11935                 case bfd_reloc_undefined:
11936                   if (!((*link_info->callbacks->undefined_symbol)
11937                         (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11938                          input_bfd, input_section, (*parent)->address, TRUE)))
11939                     goto error_return;
11940                   break;
11941                 case bfd_reloc_dangerous:
11942                   BFD_ASSERT (error_message != NULL);
11943                   if (!((*link_info->callbacks->reloc_dangerous)
11944                         (link_info, error_message, input_bfd, input_section,
11945                          (*parent)->address)))
11946                     goto error_return;
11947                   break;
11948                 case bfd_reloc_overflow:
11949                   if (!((*link_info->callbacks->reloc_overflow)
11950                         (link_info, NULL,
11951                          bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11952                          (*parent)->howto->name, (*parent)->addend,
11953                          input_bfd, input_section, (*parent)->address)))
11954                     goto error_return;
11955                   break;
11956                 case bfd_reloc_outofrange:
11957                 default:
11958                   abort ();
11959                   break;
11960                 }
11961
11962             }
11963         }
11964     }
11965   if (reloc_vector != NULL)
11966     free (reloc_vector);
11967   return data;
11968
11969 error_return:
11970   if (reloc_vector != NULL)
11971     free (reloc_vector);
11972   return NULL;
11973 }
11974 \f
11975 static bfd_boolean
11976 mips_elf_relax_delete_bytes (bfd *abfd,
11977                              asection *sec, bfd_vma addr, int count)
11978 {
11979   Elf_Internal_Shdr *symtab_hdr;
11980   unsigned int sec_shndx;
11981   bfd_byte *contents;
11982   Elf_Internal_Rela *irel, *irelend;
11983   Elf_Internal_Sym *isym;
11984   Elf_Internal_Sym *isymend;
11985   struct elf_link_hash_entry **sym_hashes;
11986   struct elf_link_hash_entry **end_hashes;
11987   struct elf_link_hash_entry **start_hashes;
11988   unsigned int symcount;
11989
11990   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
11991   contents = elf_section_data (sec)->this_hdr.contents;
11992
11993   irel = elf_section_data (sec)->relocs;
11994   irelend = irel + sec->reloc_count;
11995
11996   /* Actually delete the bytes.  */
11997   memmove (contents + addr, contents + addr + count,
11998            (size_t) (sec->size - addr - count));
11999   sec->size -= count;
12000
12001   /* Adjust all the relocs.  */
12002   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
12003     {
12004       /* Get the new reloc address.  */
12005       if (irel->r_offset > addr)
12006         irel->r_offset -= count;
12007     }
12008
12009   BFD_ASSERT (addr % 2 == 0);
12010   BFD_ASSERT (count % 2 == 0);
12011
12012   /* Adjust the local symbols defined in this section.  */
12013   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12014   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
12015   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
12016     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
12017       isym->st_value -= count;
12018
12019   /* Now adjust the global symbols defined in this section.  */
12020   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
12021               - symtab_hdr->sh_info);
12022   sym_hashes = start_hashes = elf_sym_hashes (abfd);
12023   end_hashes = sym_hashes + symcount;
12024
12025   for (; sym_hashes < end_hashes; sym_hashes++)
12026     {
12027       struct elf_link_hash_entry *sym_hash = *sym_hashes;
12028
12029       if ((sym_hash->root.type == bfd_link_hash_defined
12030            || sym_hash->root.type == bfd_link_hash_defweak)
12031           && sym_hash->root.u.def.section == sec)
12032         {
12033           bfd_vma value = sym_hash->root.u.def.value;
12034
12035           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
12036             value &= MINUS_TWO;
12037           if (value > addr)
12038             sym_hash->root.u.def.value -= count;
12039         }
12040     }
12041
12042   return TRUE;
12043 }
12044
12045
12046 /* Opcodes needed for microMIPS relaxation as found in
12047    opcodes/micromips-opc.c.  */
12048
12049 struct opcode_descriptor {
12050   unsigned long match;
12051   unsigned long mask;
12052 };
12053
12054 /* The $ra register aka $31.  */
12055
12056 #define RA 31
12057
12058 /* 32-bit instruction format register fields.  */
12059
12060 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
12061 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
12062
12063 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
12064
12065 #define OP16_VALID_REG(r) \
12066   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
12067
12068
12069 /* 32-bit and 16-bit branches.  */
12070
12071 static const struct opcode_descriptor b_insns_32[] = {
12072   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
12073   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
12074   { 0, 0 }  /* End marker for find_match().  */
12075 };
12076
12077 static const struct opcode_descriptor bc_insn_32 =
12078   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
12079
12080 static const struct opcode_descriptor bz_insn_32 =
12081   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
12082
12083 static const struct opcode_descriptor bzal_insn_32 =
12084   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
12085
12086 static const struct opcode_descriptor beq_insn_32 =
12087   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
12088
12089 static const struct opcode_descriptor b_insn_16 =
12090   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
12091
12092 static const struct opcode_descriptor bz_insn_16 =
12093   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
12094
12095
12096 /* 32-bit and 16-bit branch EQ and NE zero.  */
12097
12098 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
12099    eq and second the ne.  This convention is used when replacing a
12100    32-bit BEQ/BNE with the 16-bit version.  */
12101
12102 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
12103
12104 static const struct opcode_descriptor bz_rs_insns_32[] = {
12105   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
12106   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
12107   { 0, 0 }  /* End marker for find_match().  */
12108 };
12109
12110 static const struct opcode_descriptor bz_rt_insns_32[] = {
12111   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
12112   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
12113   { 0, 0 }  /* End marker for find_match().  */
12114 };
12115
12116 static const struct opcode_descriptor bzc_insns_32[] = {
12117   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
12118   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
12119   { 0, 0 }  /* End marker for find_match().  */
12120 };
12121
12122 static const struct opcode_descriptor bz_insns_16[] = {
12123   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
12124   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
12125   { 0, 0 }  /* End marker for find_match().  */
12126 };
12127
12128 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
12129
12130 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0x17) + 2)
12131 #define BZ16_REG_FIELD(r) \
12132   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 7)
12133
12134
12135 /* 32-bit instructions with a delay slot.  */
12136
12137 static const struct opcode_descriptor jal_insn_32_bd16 =
12138   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
12139
12140 static const struct opcode_descriptor jal_insn_32_bd32 =
12141   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
12142
12143 static const struct opcode_descriptor jal_x_insn_32_bd32 =
12144   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
12145
12146 static const struct opcode_descriptor j_insn_32 =
12147   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
12148
12149 static const struct opcode_descriptor jalr_insn_32 =
12150   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
12151
12152 /* This table can be compacted, because no opcode replacement is made.  */
12153
12154 static const struct opcode_descriptor ds_insns_32_bd16[] = {
12155   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
12156
12157   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
12158   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
12159
12160   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
12161   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
12162   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
12163   { 0, 0 }  /* End marker for find_match().  */
12164 };
12165
12166 /* This table can be compacted, because no opcode replacement is made.  */
12167
12168 static const struct opcode_descriptor ds_insns_32_bd32[] = {
12169   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
12170
12171   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
12172   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
12173   { 0, 0 }  /* End marker for find_match().  */
12174 };
12175
12176
12177 /* 16-bit instructions with a delay slot.  */
12178
12179 static const struct opcode_descriptor jalr_insn_16_bd16 =
12180   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
12181
12182 static const struct opcode_descriptor jalr_insn_16_bd32 =
12183   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
12184
12185 static const struct opcode_descriptor jr_insn_16 =
12186   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
12187
12188 #define JR16_REG(opcode) ((opcode) & 0x1f)
12189
12190 /* This table can be compacted, because no opcode replacement is made.  */
12191
12192 static const struct opcode_descriptor ds_insns_16_bd16[] = {
12193   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
12194
12195   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
12196   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
12197   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
12198   { 0, 0 }  /* End marker for find_match().  */
12199 };
12200
12201
12202 /* LUI instruction.  */
12203
12204 static const struct opcode_descriptor lui_insn =
12205  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
12206
12207
12208 /* ADDIU instruction.  */
12209
12210 static const struct opcode_descriptor addiu_insn =
12211   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
12212
12213 static const struct opcode_descriptor addiupc_insn =
12214   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
12215
12216 #define ADDIUPC_REG_FIELD(r) \
12217   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
12218
12219
12220 /* Relaxable instructions in a JAL delay slot: MOVE.  */
12221
12222 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
12223    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
12224 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
12225 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
12226
12227 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
12228 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
12229
12230 static const struct opcode_descriptor move_insns_32[] = {
12231   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
12232   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
12233   { 0, 0 }  /* End marker for find_match().  */
12234 };
12235
12236 static const struct opcode_descriptor move_insn_16 =
12237   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
12238
12239
12240 /* NOP instructions.  */
12241
12242 static const struct opcode_descriptor nop_insn_32 =
12243   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
12244
12245 static const struct opcode_descriptor nop_insn_16 =
12246   { /* "nop",   "",             */ 0x0c00,     0xffff };
12247
12248
12249 /* Instruction match support.  */
12250
12251 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
12252
12253 static int
12254 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
12255 {
12256   unsigned long indx;
12257
12258   for (indx = 0; insn[indx].mask != 0; indx++)
12259     if (MATCH (opcode, insn[indx]))
12260       return indx;
12261
12262   return -1;
12263 }
12264
12265
12266 /* Branch and delay slot decoding support.  */
12267
12268 /* If PTR points to what *might* be a 16-bit branch or jump, then
12269    return the minimum length of its delay slot, otherwise return 0.
12270    Non-zero results are not definitive as we might be checking against
12271    the second half of another instruction.  */
12272
12273 static int
12274 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
12275 {
12276   unsigned long opcode;
12277   int bdsize;
12278
12279   opcode = bfd_get_16 (abfd, ptr);
12280   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
12281     /* 16-bit branch/jump with a 32-bit delay slot.  */
12282     bdsize = 4;
12283   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
12284            || find_match (opcode, ds_insns_16_bd16) >= 0)
12285     /* 16-bit branch/jump with a 16-bit delay slot.  */
12286     bdsize = 2;
12287   else
12288     /* No delay slot.  */
12289     bdsize = 0;
12290
12291   return bdsize;
12292 }
12293
12294 /* If PTR points to what *might* be a 32-bit branch or jump, then
12295    return the minimum length of its delay slot, otherwise return 0.
12296    Non-zero results are not definitive as we might be checking against
12297    the second half of another instruction.  */
12298
12299 static int
12300 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
12301 {
12302   unsigned long opcode;
12303   int bdsize;
12304
12305   opcode = bfd_get_micromips_32 (abfd, ptr);
12306   if (find_match (opcode, ds_insns_32_bd32) >= 0)
12307     /* 32-bit branch/jump with a 32-bit delay slot.  */
12308     bdsize = 4;
12309   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
12310     /* 32-bit branch/jump with a 16-bit delay slot.  */
12311     bdsize = 2;
12312   else
12313     /* No delay slot.  */
12314     bdsize = 0;
12315
12316   return bdsize;
12317 }
12318
12319 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
12320    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
12321
12322 static bfd_boolean
12323 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12324 {
12325   unsigned long opcode;
12326
12327   opcode = bfd_get_16 (abfd, ptr);
12328   if (MATCH (opcode, b_insn_16)
12329                                                 /* B16  */
12330       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
12331                                                 /* JR16  */
12332       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
12333                                                 /* BEQZ16, BNEZ16  */
12334       || (MATCH (opcode, jalr_insn_16_bd32)
12335                                                 /* JALR16  */
12336           && reg != JR16_REG (opcode) && reg != RA))
12337     return TRUE;
12338
12339   return FALSE;
12340 }
12341
12342 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
12343    then return TRUE, otherwise FALSE.  */
12344
12345 static bfd_boolean
12346 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12347 {
12348   unsigned long opcode;
12349
12350   opcode = bfd_get_micromips_32 (abfd, ptr);
12351   if (MATCH (opcode, j_insn_32)
12352                                                 /* J  */
12353       || MATCH (opcode, bc_insn_32)
12354                                                 /* BC1F, BC1T, BC2F, BC2T  */
12355       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
12356                                                 /* JAL, JALX  */
12357       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
12358                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
12359       || (MATCH (opcode, bzal_insn_32)
12360                                                 /* BGEZAL, BLTZAL  */
12361           && reg != OP32_SREG (opcode) && reg != RA)
12362       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
12363                                                 /* JALR, JALR.HB, BEQ, BNE  */
12364           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
12365     return TRUE;
12366
12367   return FALSE;
12368 }
12369
12370 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
12371    IRELEND) at OFFSET indicate that there must be a compact branch there,
12372    then return TRUE, otherwise FALSE.  */
12373
12374 static bfd_boolean
12375 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
12376                      const Elf_Internal_Rela *internal_relocs,
12377                      const Elf_Internal_Rela *irelend)
12378 {
12379   const Elf_Internal_Rela *irel;
12380   unsigned long opcode;
12381
12382   opcode = bfd_get_micromips_32 (abfd, ptr);
12383   if (find_match (opcode, bzc_insns_32) < 0)
12384     return FALSE;
12385
12386   for (irel = internal_relocs; irel < irelend; irel++)
12387     if (irel->r_offset == offset
12388         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
12389       return TRUE;
12390
12391   return FALSE;
12392 }
12393
12394 /* Bitsize checking.  */
12395 #define IS_BITSIZE(val, N)                                              \
12396   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
12397     - (1ULL << ((N) - 1))) == (val))
12398
12399 \f
12400 bfd_boolean
12401 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
12402                              struct bfd_link_info *link_info,
12403                              bfd_boolean *again)
12404 {
12405   Elf_Internal_Shdr *symtab_hdr;
12406   Elf_Internal_Rela *internal_relocs;
12407   Elf_Internal_Rela *irel, *irelend;
12408   bfd_byte *contents = NULL;
12409   Elf_Internal_Sym *isymbuf = NULL;
12410
12411   /* Assume nothing changes.  */
12412   *again = FALSE;
12413
12414   /* We don't have to do anything for a relocatable link, if
12415      this section does not have relocs, or if this is not a
12416      code section.  */
12417
12418   if (link_info->relocatable
12419       || (sec->flags & SEC_RELOC) == 0
12420       || sec->reloc_count == 0
12421       || (sec->flags & SEC_CODE) == 0)
12422     return TRUE;
12423
12424   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12425
12426   /* Get a copy of the native relocations.  */
12427   internal_relocs = (_bfd_elf_link_read_relocs
12428                      (abfd, sec, NULL, (Elf_Internal_Rela *) NULL,
12429                       link_info->keep_memory));
12430   if (internal_relocs == NULL)
12431     goto error_return;
12432
12433   /* Walk through them looking for relaxing opportunities.  */
12434   irelend = internal_relocs + sec->reloc_count;
12435   for (irel = internal_relocs; irel < irelend; irel++)
12436     {
12437       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
12438       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
12439       bfd_boolean target_is_micromips_code_p;
12440       unsigned long opcode;
12441       bfd_vma symval;
12442       bfd_vma pcrval;
12443       bfd_byte *ptr;
12444       int fndopc;
12445
12446       /* The number of bytes to delete for relaxation and from where
12447          to delete these bytes starting at irel->r_offset.  */
12448       int delcnt = 0;
12449       int deloff = 0;
12450
12451       /* If this isn't something that can be relaxed, then ignore
12452          this reloc.  */
12453       if (r_type != R_MICROMIPS_HI16
12454           && r_type != R_MICROMIPS_PC16_S1
12455           && r_type != R_MICROMIPS_26_S1)
12456         continue;
12457
12458       /* Get the section contents if we haven't done so already.  */
12459       if (contents == NULL)
12460         {
12461           /* Get cached copy if it exists.  */
12462           if (elf_section_data (sec)->this_hdr.contents != NULL)
12463             contents = elf_section_data (sec)->this_hdr.contents;
12464           /* Go get them off disk.  */
12465           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
12466             goto error_return;
12467         }
12468       ptr = contents + irel->r_offset;
12469
12470       /* Read this BFD's local symbols if we haven't done so already.  */
12471       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
12472         {
12473           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
12474           if (isymbuf == NULL)
12475             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12476                                             symtab_hdr->sh_info, 0,
12477                                             NULL, NULL, NULL);
12478           if (isymbuf == NULL)
12479             goto error_return;
12480         }
12481
12482       /* Get the value of the symbol referred to by the reloc.  */
12483       if (r_symndx < symtab_hdr->sh_info)
12484         {
12485           /* A local symbol.  */
12486           Elf_Internal_Sym *isym;
12487           asection *sym_sec;
12488
12489           isym = isymbuf + r_symndx;
12490           if (isym->st_shndx == SHN_UNDEF)
12491             sym_sec = bfd_und_section_ptr;
12492           else if (isym->st_shndx == SHN_ABS)
12493             sym_sec = bfd_abs_section_ptr;
12494           else if (isym->st_shndx == SHN_COMMON)
12495             sym_sec = bfd_com_section_ptr;
12496           else
12497             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
12498           symval = (isym->st_value
12499                     + sym_sec->output_section->vma
12500                     + sym_sec->output_offset);
12501           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
12502         }
12503       else
12504         {
12505           unsigned long indx;
12506           struct elf_link_hash_entry *h;
12507
12508           /* An external symbol.  */
12509           indx = r_symndx - symtab_hdr->sh_info;
12510           h = elf_sym_hashes (abfd)[indx];
12511           BFD_ASSERT (h != NULL);
12512
12513           if (h->root.type != bfd_link_hash_defined
12514               && h->root.type != bfd_link_hash_defweak)
12515             /* This appears to be a reference to an undefined
12516                symbol.  Just ignore it -- it will be caught by the
12517                regular reloc processing.  */
12518             continue;
12519
12520           symval = (h->root.u.def.value
12521                     + h->root.u.def.section->output_section->vma
12522                     + h->root.u.def.section->output_offset);
12523           target_is_micromips_code_p = (!h->needs_plt
12524                                         && ELF_ST_IS_MICROMIPS (h->other));
12525         }
12526
12527
12528       /* For simplicity of coding, we are going to modify the
12529          section contents, the section relocs, and the BFD symbol
12530          table.  We must tell the rest of the code not to free up this
12531          information.  It would be possible to instead create a table
12532          of changes which have to be made, as is done in coff-mips.c;
12533          that would be more work, but would require less memory when
12534          the linker is run.  */
12535
12536       /* Only 32-bit instructions relaxed.  */
12537       if (irel->r_offset + 4 > sec->size)
12538         continue;
12539
12540       opcode = bfd_get_micromips_32 (abfd, ptr);
12541
12542       /* This is the pc-relative distance from the instruction the
12543          relocation is applied to, to the symbol referred.  */
12544       pcrval = (symval
12545                 - (sec->output_section->vma + sec->output_offset)
12546                 - irel->r_offset);
12547
12548       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
12549          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
12550          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
12551
12552            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
12553
12554          where pcrval has first to be adjusted to apply against the LO16
12555          location (we make the adjustment later on, when we have figured
12556          out the offset).  */
12557       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
12558         {
12559           bfd_boolean bzc = FALSE;
12560           unsigned long nextopc;
12561           unsigned long reg;
12562           bfd_vma offset;
12563
12564           /* Give up if the previous reloc was a HI16 against this symbol
12565              too.  */
12566           if (irel > internal_relocs
12567               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
12568               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
12569             continue;
12570
12571           /* Or if the next reloc is not a LO16 against this symbol.  */
12572           if (irel + 1 >= irelend
12573               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
12574               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
12575             continue;
12576
12577           /* Or if the second next reloc is a LO16 against this symbol too.  */
12578           if (irel + 2 >= irelend
12579               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
12580               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
12581             continue;
12582
12583           /* See if the LUI instruction *might* be in a branch delay slot.
12584              We check whether what looks like a 16-bit branch or jump is
12585              actually an immediate argument to a compact branch, and let
12586              it through if so.  */
12587           if (irel->r_offset >= 2
12588               && check_br16_dslot (abfd, ptr - 2)
12589               && !(irel->r_offset >= 4
12590                    && (bzc = check_relocated_bzc (abfd,
12591                                                   ptr - 4, irel->r_offset - 4,
12592                                                   internal_relocs, irelend))))
12593             continue;
12594           if (irel->r_offset >= 4
12595               && !bzc
12596               && check_br32_dslot (abfd, ptr - 4))
12597             continue;
12598
12599           reg = OP32_SREG (opcode);
12600
12601           /* We only relax adjacent instructions or ones separated with
12602              a branch or jump that has a delay slot.  The branch or jump
12603              must not fiddle with the register used to hold the address.
12604              Subtract 4 for the LUI itself.  */
12605           offset = irel[1].r_offset - irel[0].r_offset;
12606           switch (offset - 4)
12607             {
12608             case 0:
12609               break;
12610             case 2:
12611               if (check_br16 (abfd, ptr + 4, reg))
12612                 break;
12613               continue;
12614             case 4:
12615               if (check_br32 (abfd, ptr + 4, reg))
12616                 break;
12617               continue;
12618             default:
12619               continue;
12620             }
12621
12622           nextopc = bfd_get_micromips_32 (abfd, contents + irel[1].r_offset);
12623
12624           /* Give up unless the same register is used with both
12625              relocations.  */
12626           if (OP32_SREG (nextopc) != reg)
12627             continue;
12628
12629           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
12630              and rounding up to take masking of the two LSBs into account.  */
12631           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
12632
12633           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
12634           if (IS_BITSIZE (symval, 16))
12635             {
12636               /* Fix the relocation's type.  */
12637               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
12638
12639               /* Instructions using R_MICROMIPS_LO16 have the base or
12640                  source register in bits 20:16.  This register becomes $0
12641                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
12642               nextopc &= ~0x001f0000;
12643               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
12644                           contents + irel[1].r_offset);
12645             }
12646
12647           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
12648              We add 4 to take LUI deletion into account while checking
12649              the PC-relative distance.  */
12650           else if (symval % 4 == 0
12651                    && IS_BITSIZE (pcrval + 4, 25)
12652                    && MATCH (nextopc, addiu_insn)
12653                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
12654                    && OP16_VALID_REG (OP32_TREG (nextopc)))
12655             {
12656               /* Fix the relocation's type.  */
12657               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
12658
12659               /* Replace ADDIU with the ADDIUPC version.  */
12660               nextopc = (addiupc_insn.match
12661                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
12662
12663               bfd_put_micromips_32 (abfd, nextopc,
12664                                     contents + irel[1].r_offset);
12665             }
12666
12667           /* Can't do anything, give up, sigh...  */
12668           else
12669             continue;
12670
12671           /* Fix the relocation's type.  */
12672           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
12673
12674           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
12675           delcnt = 4;
12676           deloff = 0;
12677         }
12678
12679       /* Compact branch relaxation -- due to the multitude of macros
12680          employed by the compiler/assembler, compact branches are not
12681          always generated.  Obviously, this can/will be fixed elsewhere,
12682          but there is no drawback in double checking it here.  */
12683       else if (r_type == R_MICROMIPS_PC16_S1
12684                && irel->r_offset + 5 < sec->size
12685                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12686                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
12687                && MATCH (bfd_get_16 (abfd, ptr + 4), nop_insn_16))
12688         {
12689           unsigned long reg;
12690
12691           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12692
12693           /* Replace BEQZ/BNEZ with the compact version.  */
12694           opcode = (bzc_insns_32[fndopc].match
12695                     | BZC32_REG_FIELD (reg)
12696                     | (opcode & 0xffff));               /* Addend value.  */
12697
12698           bfd_put_micromips_32 (abfd, opcode, ptr);
12699
12700           /* Delete the 16-bit delay slot NOP: two bytes from
12701              irel->offset + 4.  */
12702           delcnt = 2;
12703           deloff = 4;
12704         }
12705
12706       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
12707          to check the distance from the next instruction, so subtract 2.  */
12708       else if (r_type == R_MICROMIPS_PC16_S1
12709                && IS_BITSIZE (pcrval - 2, 11)
12710                && find_match (opcode, b_insns_32) >= 0)
12711         {
12712           /* Fix the relocation's type.  */
12713           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
12714
12715           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12716           bfd_put_16 (abfd,
12717                       (b_insn_16.match
12718                        | (opcode & 0x3ff)),             /* Addend value.  */
12719                       ptr);
12720
12721           /* Delete 2 bytes from irel->r_offset + 2.  */
12722           delcnt = 2;
12723           deloff = 2;
12724         }
12725
12726       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
12727          to check the distance from the next instruction, so subtract 2.  */
12728       else if (r_type == R_MICROMIPS_PC16_S1
12729                && IS_BITSIZE (pcrval - 2, 8)
12730                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12731                     && OP16_VALID_REG (OP32_SREG (opcode)))
12732                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
12733                        && OP16_VALID_REG (OP32_TREG (opcode)))))
12734         {
12735           unsigned long reg;
12736
12737           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12738
12739           /* Fix the relocation's type.  */
12740           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
12741
12742           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12743           bfd_put_16 (abfd,
12744                       (bz_insns_16[fndopc].match
12745                        | BZ16_REG_FIELD (reg)
12746                        | (opcode & 0x7f)),              /* Addend value.  */
12747                       ptr);
12748
12749           /* Delete 2 bytes from irel->r_offset + 2.  */
12750           delcnt = 2;
12751           deloff = 2;
12752         }
12753
12754       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
12755       else if (r_type == R_MICROMIPS_26_S1
12756                && target_is_micromips_code_p
12757                && irel->r_offset + 7 < sec->size
12758                && MATCH (opcode, jal_insn_32_bd32))
12759         {
12760           unsigned long n32opc;
12761           bfd_boolean relaxed = FALSE;
12762
12763           n32opc = bfd_get_micromips_32 (abfd, ptr + 4);
12764
12765           if (MATCH (n32opc, nop_insn_32))
12766             {
12767               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
12768               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
12769
12770               relaxed = TRUE;
12771             }
12772           else if (find_match (n32opc, move_insns_32) >= 0)
12773             {
12774               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
12775               bfd_put_16 (abfd,
12776                           (move_insn_16.match
12777                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
12778                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
12779                           ptr + 4);
12780
12781               relaxed = TRUE;
12782             }
12783           /* Other 32-bit instructions relaxable to 16-bit
12784              instructions will be handled here later.  */
12785
12786           if (relaxed)
12787             {
12788               /* JAL with 32-bit delay slot that is changed to a JALS
12789                  with 16-bit delay slot.  */
12790               bfd_put_micromips_32 (abfd, jal_insn_32_bd16.match, ptr);
12791
12792               /* Delete 2 bytes from irel->r_offset + 6.  */
12793               delcnt = 2;
12794               deloff = 6;
12795             }
12796         }
12797
12798       if (delcnt != 0)
12799         {
12800           /* Note that we've changed the relocs, section contents, etc.  */
12801           elf_section_data (sec)->relocs = internal_relocs;
12802           elf_section_data (sec)->this_hdr.contents = contents;
12803           symtab_hdr->contents = (unsigned char *) isymbuf;
12804
12805           /* Delete bytes depending on the delcnt and deloff.  */
12806           if (!mips_elf_relax_delete_bytes (abfd, sec,
12807                                             irel->r_offset + deloff, delcnt))
12808             goto error_return;
12809
12810           /* That will change things, so we should relax again.
12811              Note that this is not required, and it may be slow.  */
12812           *again = TRUE;
12813         }
12814     }
12815
12816   if (isymbuf != NULL
12817       && symtab_hdr->contents != (unsigned char *) isymbuf)
12818     {
12819       if (! link_info->keep_memory)
12820         free (isymbuf);
12821       else
12822         {
12823           /* Cache the symbols for elf_link_input_bfd.  */
12824           symtab_hdr->contents = (unsigned char *) isymbuf;
12825         }
12826     }
12827
12828   if (contents != NULL
12829       && elf_section_data (sec)->this_hdr.contents != contents)
12830     {
12831       if (! link_info->keep_memory)
12832         free (contents);
12833       else
12834         {
12835           /* Cache the section contents for elf_link_input_bfd.  */
12836           elf_section_data (sec)->this_hdr.contents = contents;
12837         }
12838     }
12839
12840   if (internal_relocs != NULL
12841       && elf_section_data (sec)->relocs != internal_relocs)
12842     free (internal_relocs);
12843
12844   return TRUE;
12845
12846  error_return:
12847   if (isymbuf != NULL
12848       && symtab_hdr->contents != (unsigned char *) isymbuf)
12849     free (isymbuf);
12850   if (contents != NULL
12851       && elf_section_data (sec)->this_hdr.contents != contents)
12852     free (contents);
12853   if (internal_relocs != NULL
12854       && elf_section_data (sec)->relocs != internal_relocs)
12855     free (internal_relocs);
12856
12857   return FALSE;
12858 }
12859 \f
12860 /* Create a MIPS ELF linker hash table.  */
12861
12862 struct bfd_link_hash_table *
12863 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
12864 {
12865   struct mips_elf_link_hash_table *ret;
12866   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
12867
12868   ret = bfd_zmalloc (amt);
12869   if (ret == NULL)
12870     return NULL;
12871
12872   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
12873                                       mips_elf_link_hash_newfunc,
12874                                       sizeof (struct mips_elf_link_hash_entry),
12875                                       MIPS_ELF_DATA))
12876     {
12877       free (ret);
12878       return NULL;
12879     }
12880
12881   return &ret->root.root;
12882 }
12883
12884 /* Likewise, but indicate that the target is VxWorks.  */
12885
12886 struct bfd_link_hash_table *
12887 _bfd_mips_vxworks_link_hash_table_create (bfd *abfd)
12888 {
12889   struct bfd_link_hash_table *ret;
12890
12891   ret = _bfd_mips_elf_link_hash_table_create (abfd);
12892   if (ret)
12893     {
12894       struct mips_elf_link_hash_table *htab;
12895
12896       htab = (struct mips_elf_link_hash_table *) ret;
12897       htab->use_plts_and_copy_relocs = TRUE;
12898       htab->is_vxworks = TRUE;
12899     }
12900   return ret;
12901 }
12902
12903 /* A function that the linker calls if we are allowed to use PLTs
12904    and copy relocs.  */
12905
12906 void
12907 _bfd_mips_elf_use_plts_and_copy_relocs (struct bfd_link_info *info)
12908 {
12909   mips_elf_hash_table (info)->use_plts_and_copy_relocs = TRUE;
12910 }
12911 \f
12912 /* We need to use a special link routine to handle the .reginfo and
12913    the .mdebug sections.  We need to merge all instances of these
12914    sections together, not write them all out sequentially.  */
12915
12916 bfd_boolean
12917 _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info)
12918 {
12919   asection *o;
12920   struct bfd_link_order *p;
12921   asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec;
12922   asection *rtproc_sec;
12923   Elf32_RegInfo reginfo;
12924   struct ecoff_debug_info debug;
12925   struct mips_htab_traverse_info hti;
12926   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12927   const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap;
12928   HDRR *symhdr = &debug.symbolic_header;
12929   void *mdebug_handle = NULL;
12930   asection *s;
12931   EXTR esym;
12932   unsigned int i;
12933   bfd_size_type amt;
12934   struct mips_elf_link_hash_table *htab;
12935
12936   static const char * const secname[] =
12937   {
12938     ".text", ".init", ".fini", ".data",
12939     ".rodata", ".sdata", ".sbss", ".bss"
12940   };
12941   static const int sc[] =
12942   {
12943     scText, scInit, scFini, scData,
12944     scRData, scSData, scSBss, scBss
12945   };
12946
12947   /* Sort the dynamic symbols so that those with GOT entries come after
12948      those without.  */
12949   htab = mips_elf_hash_table (info);
12950   BFD_ASSERT (htab != NULL);
12951
12952   if (!mips_elf_sort_hash_table (abfd, info))
12953     return FALSE;
12954
12955   /* Create any scheduled LA25 stubs.  */
12956   hti.info = info;
12957   hti.output_bfd = abfd;
12958   hti.error = FALSE;
12959   htab_traverse (htab->la25_stubs, mips_elf_create_la25_stub, &hti);
12960   if (hti.error)
12961     return FALSE;
12962
12963   /* Get a value for the GP register.  */
12964   if (elf_gp (abfd) == 0)
12965     {
12966       struct bfd_link_hash_entry *h;
12967
12968       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
12969       if (h != NULL && h->type == bfd_link_hash_defined)
12970         elf_gp (abfd) = (h->u.def.value
12971                          + h->u.def.section->output_section->vma
12972                          + h->u.def.section->output_offset);
12973       else if (htab->is_vxworks
12974                && (h = bfd_link_hash_lookup (info->hash,
12975                                              "_GLOBAL_OFFSET_TABLE_",
12976                                              FALSE, FALSE, TRUE))
12977                && h->type == bfd_link_hash_defined)
12978         elf_gp (abfd) = (h->u.def.section->output_section->vma
12979                          + h->u.def.section->output_offset
12980                          + h->u.def.value);
12981       else if (info->relocatable)
12982         {
12983           bfd_vma lo = MINUS_ONE;
12984
12985           /* Find the GP-relative section with the lowest offset.  */
12986           for (o = abfd->sections; o != NULL; o = o->next)
12987             if (o->vma < lo
12988                 && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL))
12989               lo = o->vma;
12990
12991           /* And calculate GP relative to that.  */
12992           elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (info);
12993         }
12994       else
12995         {
12996           /* If the relocate_section function needs to do a reloc
12997              involving the GP value, it should make a reloc_dangerous
12998              callback to warn that GP is not defined.  */
12999         }
13000     }
13001
13002   /* Go through the sections and collect the .reginfo and .mdebug
13003      information.  */
13004   reginfo_sec = NULL;
13005   mdebug_sec = NULL;
13006   gptab_data_sec = NULL;
13007   gptab_bss_sec = NULL;
13008   for (o = abfd->sections; o != NULL; o = o->next)
13009     {
13010       if (strcmp (o->name, ".reginfo") == 0)
13011         {
13012           memset (&reginfo, 0, sizeof reginfo);
13013
13014           /* We have found the .reginfo section in the output file.
13015              Look through all the link_orders comprising it and merge
13016              the information together.  */
13017           for (p = o->map_head.link_order; p != NULL; p = p->next)
13018             {
13019               asection *input_section;
13020               bfd *input_bfd;
13021               Elf32_External_RegInfo ext;
13022               Elf32_RegInfo sub;
13023
13024               if (p->type != bfd_indirect_link_order)
13025                 {
13026                   if (p->type == bfd_data_link_order)
13027                     continue;
13028                   abort ();
13029                 }
13030
13031               input_section = p->u.indirect.section;
13032               input_bfd = input_section->owner;
13033
13034               if (! bfd_get_section_contents (input_bfd, input_section,
13035                                               &ext, 0, sizeof ext))
13036                 return FALSE;
13037
13038               bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub);
13039
13040               reginfo.ri_gprmask |= sub.ri_gprmask;
13041               reginfo.ri_cprmask[0] |= sub.ri_cprmask[0];
13042               reginfo.ri_cprmask[1] |= sub.ri_cprmask[1];
13043               reginfo.ri_cprmask[2] |= sub.ri_cprmask[2];
13044               reginfo.ri_cprmask[3] |= sub.ri_cprmask[3];
13045
13046               /* ri_gp_value is set by the function
13047                  mips_elf32_section_processing when the section is
13048                  finally written out.  */
13049
13050               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13051                  elf_link_input_bfd ignores this section.  */
13052               input_section->flags &= ~SEC_HAS_CONTENTS;
13053             }
13054
13055           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
13056           BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo));
13057
13058           /* Skip this section later on (I don't think this currently
13059              matters, but someday it might).  */
13060           o->map_head.link_order = NULL;
13061
13062           reginfo_sec = o;
13063         }
13064
13065       if (strcmp (o->name, ".mdebug") == 0)
13066         {
13067           struct extsym_info einfo;
13068           bfd_vma last;
13069
13070           /* We have found the .mdebug section in the output file.
13071              Look through all the link_orders comprising it and merge
13072              the information together.  */
13073           symhdr->magic = swap->sym_magic;
13074           /* FIXME: What should the version stamp be?  */
13075           symhdr->vstamp = 0;
13076           symhdr->ilineMax = 0;
13077           symhdr->cbLine = 0;
13078           symhdr->idnMax = 0;
13079           symhdr->ipdMax = 0;
13080           symhdr->isymMax = 0;
13081           symhdr->ioptMax = 0;
13082           symhdr->iauxMax = 0;
13083           symhdr->issMax = 0;
13084           symhdr->issExtMax = 0;
13085           symhdr->ifdMax = 0;
13086           symhdr->crfd = 0;
13087           symhdr->iextMax = 0;
13088
13089           /* We accumulate the debugging information itself in the
13090              debug_info structure.  */
13091           debug.line = NULL;
13092           debug.external_dnr = NULL;
13093           debug.external_pdr = NULL;
13094           debug.external_sym = NULL;
13095           debug.external_opt = NULL;
13096           debug.external_aux = NULL;
13097           debug.ss = NULL;
13098           debug.ssext = debug.ssext_end = NULL;
13099           debug.external_fdr = NULL;
13100           debug.external_rfd = NULL;
13101           debug.external_ext = debug.external_ext_end = NULL;
13102
13103           mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info);
13104           if (mdebug_handle == NULL)
13105             return FALSE;
13106
13107           esym.jmptbl = 0;
13108           esym.cobol_main = 0;
13109           esym.weakext = 0;
13110           esym.reserved = 0;
13111           esym.ifd = ifdNil;
13112           esym.asym.iss = issNil;
13113           esym.asym.st = stLocal;
13114           esym.asym.reserved = 0;
13115           esym.asym.index = indexNil;
13116           last = 0;
13117           for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++)
13118             {
13119               esym.asym.sc = sc[i];
13120               s = bfd_get_section_by_name (abfd, secname[i]);
13121               if (s != NULL)
13122                 {
13123                   esym.asym.value = s->vma;
13124                   last = s->vma + s->size;
13125                 }
13126               else
13127                 esym.asym.value = last;
13128               if (!bfd_ecoff_debug_one_external (abfd, &debug, swap,
13129                                                  secname[i], &esym))
13130                 return FALSE;
13131             }
13132
13133           for (p = o->map_head.link_order; p != NULL; p = p->next)
13134             {
13135               asection *input_section;
13136               bfd *input_bfd;
13137               const struct ecoff_debug_swap *input_swap;
13138               struct ecoff_debug_info input_debug;
13139               char *eraw_src;
13140               char *eraw_end;
13141
13142               if (p->type != bfd_indirect_link_order)
13143                 {
13144                   if (p->type == bfd_data_link_order)
13145                     continue;
13146                   abort ();
13147                 }
13148
13149               input_section = p->u.indirect.section;
13150               input_bfd = input_section->owner;
13151
13152               if (!is_mips_elf (input_bfd))
13153                 {
13154                   /* I don't know what a non MIPS ELF bfd would be
13155                      doing with a .mdebug section, but I don't really
13156                      want to deal with it.  */
13157                   continue;
13158                 }
13159
13160               input_swap = (get_elf_backend_data (input_bfd)
13161                             ->elf_backend_ecoff_debug_swap);
13162
13163               BFD_ASSERT (p->size == input_section->size);
13164
13165               /* The ECOFF linking code expects that we have already
13166                  read in the debugging information and set up an
13167                  ecoff_debug_info structure, so we do that now.  */
13168               if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section,
13169                                                    &input_debug))
13170                 return FALSE;
13171
13172               if (! (bfd_ecoff_debug_accumulate
13173                      (mdebug_handle, abfd, &debug, swap, input_bfd,
13174                       &input_debug, input_swap, info)))
13175                 return FALSE;
13176
13177               /* Loop through the external symbols.  For each one with
13178                  interesting information, try to find the symbol in
13179                  the linker global hash table and save the information
13180                  for the output external symbols.  */
13181               eraw_src = input_debug.external_ext;
13182               eraw_end = (eraw_src
13183                           + (input_debug.symbolic_header.iextMax
13184                              * input_swap->external_ext_size));
13185               for (;
13186                    eraw_src < eraw_end;
13187                    eraw_src += input_swap->external_ext_size)
13188                 {
13189                   EXTR ext;
13190                   const char *name;
13191                   struct mips_elf_link_hash_entry *h;
13192
13193                   (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext);
13194                   if (ext.asym.sc == scNil
13195                       || ext.asym.sc == scUndefined
13196                       || ext.asym.sc == scSUndefined)
13197                     continue;
13198
13199                   name = input_debug.ssext + ext.asym.iss;
13200                   h = mips_elf_link_hash_lookup (mips_elf_hash_table (info),
13201                                                  name, FALSE, FALSE, TRUE);
13202                   if (h == NULL || h->esym.ifd != -2)
13203                     continue;
13204
13205                   if (ext.ifd != -1)
13206                     {
13207                       BFD_ASSERT (ext.ifd
13208                                   < input_debug.symbolic_header.ifdMax);
13209                       ext.ifd = input_debug.ifdmap[ext.ifd];
13210                     }
13211
13212                   h->esym = ext;
13213                 }
13214
13215               /* Free up the information we just read.  */
13216               free (input_debug.line);
13217               free (input_debug.external_dnr);
13218               free (input_debug.external_pdr);
13219               free (input_debug.external_sym);
13220               free (input_debug.external_opt);
13221               free (input_debug.external_aux);
13222               free (input_debug.ss);
13223               free (input_debug.ssext);
13224               free (input_debug.external_fdr);
13225               free (input_debug.external_rfd);
13226               free (input_debug.external_ext);
13227
13228               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13229                  elf_link_input_bfd ignores this section.  */
13230               input_section->flags &= ~SEC_HAS_CONTENTS;
13231             }
13232
13233           if (SGI_COMPAT (abfd) && info->shared)
13234             {
13235               /* Create .rtproc section.  */
13236               rtproc_sec = bfd_get_linker_section (abfd, ".rtproc");
13237               if (rtproc_sec == NULL)
13238                 {
13239                   flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
13240                                     | SEC_LINKER_CREATED | SEC_READONLY);
13241
13242                   rtproc_sec = bfd_make_section_anyway_with_flags (abfd,
13243                                                                    ".rtproc",
13244                                                                    flags);
13245                   if (rtproc_sec == NULL
13246                       || ! bfd_set_section_alignment (abfd, rtproc_sec, 4))
13247                     return FALSE;
13248                 }
13249
13250               if (! mips_elf_create_procedure_table (mdebug_handle, abfd,
13251                                                      info, rtproc_sec,
13252                                                      &debug))
13253                 return FALSE;
13254             }
13255
13256           /* Build the external symbol information.  */
13257           einfo.abfd = abfd;
13258           einfo.info = info;
13259           einfo.debug = &debug;
13260           einfo.swap = swap;
13261           einfo.failed = FALSE;
13262           mips_elf_link_hash_traverse (mips_elf_hash_table (info),
13263                                        mips_elf_output_extsym, &einfo);
13264           if (einfo.failed)
13265             return FALSE;
13266
13267           /* Set the size of the .mdebug section.  */
13268           o->size = bfd_ecoff_debug_size (abfd, &debug, swap);
13269
13270           /* Skip this section later on (I don't think this currently
13271              matters, but someday it might).  */
13272           o->map_head.link_order = NULL;
13273
13274           mdebug_sec = o;
13275         }
13276
13277       if (CONST_STRNEQ (o->name, ".gptab."))
13278         {
13279           const char *subname;
13280           unsigned int c;
13281           Elf32_gptab *tab;
13282           Elf32_External_gptab *ext_tab;
13283           unsigned int j;
13284
13285           /* The .gptab.sdata and .gptab.sbss sections hold
13286              information describing how the small data area would
13287              change depending upon the -G switch.  These sections
13288              not used in executables files.  */
13289           if (! info->relocatable)
13290             {
13291               for (p = o->map_head.link_order; p != NULL; p = p->next)
13292                 {
13293                   asection *input_section;
13294
13295                   if (p->type != bfd_indirect_link_order)
13296                     {
13297                       if (p->type == bfd_data_link_order)
13298                         continue;
13299                       abort ();
13300                     }
13301
13302                   input_section = p->u.indirect.section;
13303
13304                   /* Hack: reset the SEC_HAS_CONTENTS flag so that
13305                      elf_link_input_bfd ignores this section.  */
13306                   input_section->flags &= ~SEC_HAS_CONTENTS;
13307                 }
13308
13309               /* Skip this section later on (I don't think this
13310                  currently matters, but someday it might).  */
13311               o->map_head.link_order = NULL;
13312
13313               /* Really remove the section.  */
13314               bfd_section_list_remove (abfd, o);
13315               --abfd->section_count;
13316
13317               continue;
13318             }
13319
13320           /* There is one gptab for initialized data, and one for
13321              uninitialized data.  */
13322           if (strcmp (o->name, ".gptab.sdata") == 0)
13323             gptab_data_sec = o;
13324           else if (strcmp (o->name, ".gptab.sbss") == 0)
13325             gptab_bss_sec = o;
13326           else
13327             {
13328               (*_bfd_error_handler)
13329                 (_("%s: illegal section name `%s'"),
13330                  bfd_get_filename (abfd), o->name);
13331               bfd_set_error (bfd_error_nonrepresentable_section);
13332               return FALSE;
13333             }
13334
13335           /* The linker script always combines .gptab.data and
13336              .gptab.sdata into .gptab.sdata, and likewise for
13337              .gptab.bss and .gptab.sbss.  It is possible that there is
13338              no .sdata or .sbss section in the output file, in which
13339              case we must change the name of the output section.  */
13340           subname = o->name + sizeof ".gptab" - 1;
13341           if (bfd_get_section_by_name (abfd, subname) == NULL)
13342             {
13343               if (o == gptab_data_sec)
13344                 o->name = ".gptab.data";
13345               else
13346                 o->name = ".gptab.bss";
13347               subname = o->name + sizeof ".gptab" - 1;
13348               BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL);
13349             }
13350
13351           /* Set up the first entry.  */
13352           c = 1;
13353           amt = c * sizeof (Elf32_gptab);
13354           tab = bfd_malloc (amt);
13355           if (tab == NULL)
13356             return FALSE;
13357           tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd);
13358           tab[0].gt_header.gt_unused = 0;
13359
13360           /* Combine the input sections.  */
13361           for (p = o->map_head.link_order; p != NULL; p = p->next)
13362             {
13363               asection *input_section;
13364               bfd *input_bfd;
13365               bfd_size_type size;
13366               unsigned long last;
13367               bfd_size_type gpentry;
13368
13369               if (p->type != bfd_indirect_link_order)
13370                 {
13371                   if (p->type == bfd_data_link_order)
13372                     continue;
13373                   abort ();
13374                 }
13375
13376               input_section = p->u.indirect.section;
13377               input_bfd = input_section->owner;
13378
13379               /* Combine the gptab entries for this input section one
13380                  by one.  We know that the input gptab entries are
13381                  sorted by ascending -G value.  */
13382               size = input_section->size;
13383               last = 0;
13384               for (gpentry = sizeof (Elf32_External_gptab);
13385                    gpentry < size;
13386                    gpentry += sizeof (Elf32_External_gptab))
13387                 {
13388                   Elf32_External_gptab ext_gptab;
13389                   Elf32_gptab int_gptab;
13390                   unsigned long val;
13391                   unsigned long add;
13392                   bfd_boolean exact;
13393                   unsigned int look;
13394
13395                   if (! (bfd_get_section_contents
13396                          (input_bfd, input_section, &ext_gptab, gpentry,
13397                           sizeof (Elf32_External_gptab))))
13398                     {
13399                       free (tab);
13400                       return FALSE;
13401                     }
13402
13403                   bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab,
13404                                                 &int_gptab);
13405                   val = int_gptab.gt_entry.gt_g_value;
13406                   add = int_gptab.gt_entry.gt_bytes - last;
13407
13408                   exact = FALSE;
13409                   for (look = 1; look < c; look++)
13410                     {
13411                       if (tab[look].gt_entry.gt_g_value >= val)
13412                         tab[look].gt_entry.gt_bytes += add;
13413
13414                       if (tab[look].gt_entry.gt_g_value == val)
13415                         exact = TRUE;
13416                     }
13417
13418                   if (! exact)
13419                     {
13420                       Elf32_gptab *new_tab;
13421                       unsigned int max;
13422
13423                       /* We need a new table entry.  */
13424                       amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab);
13425                       new_tab = bfd_realloc (tab, amt);
13426                       if (new_tab == NULL)
13427                         {
13428                           free (tab);
13429                           return FALSE;
13430                         }
13431                       tab = new_tab;
13432                       tab[c].gt_entry.gt_g_value = val;
13433                       tab[c].gt_entry.gt_bytes = add;
13434
13435                       /* Merge in the size for the next smallest -G
13436                          value, since that will be implied by this new
13437                          value.  */
13438                       max = 0;
13439                       for (look = 1; look < c; look++)
13440                         {
13441                           if (tab[look].gt_entry.gt_g_value < val
13442                               && (max == 0
13443                                   || (tab[look].gt_entry.gt_g_value
13444                                       > tab[max].gt_entry.gt_g_value)))
13445                             max = look;
13446                         }
13447                       if (max != 0)
13448                         tab[c].gt_entry.gt_bytes +=
13449                           tab[max].gt_entry.gt_bytes;
13450
13451                       ++c;
13452                     }
13453
13454                   last = int_gptab.gt_entry.gt_bytes;
13455                 }
13456
13457               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13458                  elf_link_input_bfd ignores this section.  */
13459               input_section->flags &= ~SEC_HAS_CONTENTS;
13460             }
13461
13462           /* The table must be sorted by -G value.  */
13463           if (c > 2)
13464             qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare);
13465
13466           /* Swap out the table.  */
13467           amt = (bfd_size_type) c * sizeof (Elf32_External_gptab);
13468           ext_tab = bfd_alloc (abfd, amt);
13469           if (ext_tab == NULL)
13470             {
13471               free (tab);
13472               return FALSE;
13473             }
13474
13475           for (j = 0; j < c; j++)
13476             bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j);
13477           free (tab);
13478
13479           o->size = c * sizeof (Elf32_External_gptab);
13480           o->contents = (bfd_byte *) ext_tab;
13481
13482           /* Skip this section later on (I don't think this currently
13483              matters, but someday it might).  */
13484           o->map_head.link_order = NULL;
13485         }
13486     }
13487
13488   /* Invoke the regular ELF backend linker to do all the work.  */
13489   if (!bfd_elf_final_link (abfd, info))
13490     return FALSE;
13491
13492   /* Now write out the computed sections.  */
13493
13494   if (reginfo_sec != NULL)
13495     {
13496       Elf32_External_RegInfo ext;
13497
13498       bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext);
13499       if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext))
13500         return FALSE;
13501     }
13502
13503   if (mdebug_sec != NULL)
13504     {
13505       BFD_ASSERT (abfd->output_has_begun);
13506       if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug,
13507                                                swap, info,
13508                                                mdebug_sec->filepos))
13509         return FALSE;
13510
13511       bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info);
13512     }
13513
13514   if (gptab_data_sec != NULL)
13515     {
13516       if (! bfd_set_section_contents (abfd, gptab_data_sec,
13517                                       gptab_data_sec->contents,
13518                                       0, gptab_data_sec->size))
13519         return FALSE;
13520     }
13521
13522   if (gptab_bss_sec != NULL)
13523     {
13524       if (! bfd_set_section_contents (abfd, gptab_bss_sec,
13525                                       gptab_bss_sec->contents,
13526                                       0, gptab_bss_sec->size))
13527         return FALSE;
13528     }
13529
13530   if (SGI_COMPAT (abfd))
13531     {
13532       rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
13533       if (rtproc_sec != NULL)
13534         {
13535           if (! bfd_set_section_contents (abfd, rtproc_sec,
13536                                           rtproc_sec->contents,
13537                                           0, rtproc_sec->size))
13538             return FALSE;
13539         }
13540     }
13541
13542   return TRUE;
13543 }
13544 \f
13545 /* Structure for saying that BFD machine EXTENSION extends BASE.  */
13546
13547 struct mips_mach_extension {
13548   unsigned long extension, base;
13549 };
13550
13551
13552 /* An array describing how BFD machines relate to one another.  The entries
13553    are ordered topologically with MIPS I extensions listed last.  */
13554
13555 static const struct mips_mach_extension mips_mach_extensions[] = {
13556   /* MIPS64r2 extensions.  */
13557   { bfd_mach_mips_octeon2, bfd_mach_mips_octeonp },
13558   { bfd_mach_mips_octeonp, bfd_mach_mips_octeon },
13559   { bfd_mach_mips_octeon, bfd_mach_mipsisa64r2 },
13560
13561   /* MIPS64 extensions.  */
13562   { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 },
13563   { bfd_mach_mips_sb1, bfd_mach_mipsisa64 },
13564   { bfd_mach_mips_xlr, bfd_mach_mipsisa64 },
13565   { bfd_mach_mips_loongson_3a, bfd_mach_mipsisa64 },
13566
13567   /* MIPS V extensions.  */
13568   { bfd_mach_mipsisa64, bfd_mach_mips5 },
13569
13570   /* R10000 extensions.  */
13571   { bfd_mach_mips12000, bfd_mach_mips10000 },
13572   { bfd_mach_mips14000, bfd_mach_mips10000 },
13573   { bfd_mach_mips16000, bfd_mach_mips10000 },
13574
13575   /* R5000 extensions.  Note: the vr5500 ISA is an extension of the core
13576      vr5400 ISA, but doesn't include the multimedia stuff.  It seems
13577      better to allow vr5400 and vr5500 code to be merged anyway, since
13578      many libraries will just use the core ISA.  Perhaps we could add
13579      some sort of ASE flag if this ever proves a problem.  */
13580   { bfd_mach_mips5500, bfd_mach_mips5400 },
13581   { bfd_mach_mips5400, bfd_mach_mips5000 },
13582
13583   /* MIPS IV extensions.  */
13584   { bfd_mach_mips5, bfd_mach_mips8000 },
13585   { bfd_mach_mips10000, bfd_mach_mips8000 },
13586   { bfd_mach_mips5000, bfd_mach_mips8000 },
13587   { bfd_mach_mips7000, bfd_mach_mips8000 },
13588   { bfd_mach_mips9000, bfd_mach_mips8000 },
13589
13590   /* VR4100 extensions.  */
13591   { bfd_mach_mips4120, bfd_mach_mips4100 },
13592   { bfd_mach_mips4111, bfd_mach_mips4100 },
13593
13594   /* MIPS III extensions.  */
13595   { bfd_mach_mips_loongson_2e, bfd_mach_mips4000 },
13596   { bfd_mach_mips_loongson_2f, bfd_mach_mips4000 },
13597   { bfd_mach_mips8000, bfd_mach_mips4000 },
13598   { bfd_mach_mips4650, bfd_mach_mips4000 },
13599   { bfd_mach_mips4600, bfd_mach_mips4000 },
13600   { bfd_mach_mips4400, bfd_mach_mips4000 },
13601   { bfd_mach_mips4300, bfd_mach_mips4000 },
13602   { bfd_mach_mips4100, bfd_mach_mips4000 },
13603   { bfd_mach_mips4010, bfd_mach_mips4000 },
13604   { bfd_mach_mips5900, bfd_mach_mips4000 },
13605
13606   /* MIPS32 extensions.  */
13607   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
13608
13609   /* MIPS II extensions.  */
13610   { bfd_mach_mips4000, bfd_mach_mips6000 },
13611   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
13612
13613   /* MIPS I extensions.  */
13614   { bfd_mach_mips6000, bfd_mach_mips3000 },
13615   { bfd_mach_mips3900, bfd_mach_mips3000 }
13616 };
13617
13618
13619 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
13620
13621 static bfd_boolean
13622 mips_mach_extends_p (unsigned long base, unsigned long extension)
13623 {
13624   size_t i;
13625
13626   if (extension == base)
13627     return TRUE;
13628
13629   if (base == bfd_mach_mipsisa32
13630       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
13631     return TRUE;
13632
13633   if (base == bfd_mach_mipsisa32r2
13634       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
13635     return TRUE;
13636
13637   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
13638     if (extension == mips_mach_extensions[i].extension)
13639       {
13640         extension = mips_mach_extensions[i].base;
13641         if (extension == base)
13642           return TRUE;
13643       }
13644
13645   return FALSE;
13646 }
13647
13648
13649 /* Return true if the given ELF header flags describe a 32-bit binary.  */
13650
13651 static bfd_boolean
13652 mips_32bit_flags_p (flagword flags)
13653 {
13654   return ((flags & EF_MIPS_32BITMODE) != 0
13655           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
13656           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
13657           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
13658           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
13659           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
13660           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2);
13661 }
13662
13663
13664 /* Merge object attributes from IBFD into OBFD.  Raise an error if
13665    there are conflicting attributes.  */
13666 static bfd_boolean
13667 mips_elf_merge_obj_attributes (bfd *ibfd, bfd *obfd)
13668 {
13669   obj_attribute *in_attr;
13670   obj_attribute *out_attr;
13671   bfd *abi_fp_bfd;
13672
13673   abi_fp_bfd = mips_elf_tdata (obfd)->abi_fp_bfd;
13674   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
13675   if (!abi_fp_bfd && in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13676     mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
13677
13678   if (!elf_known_obj_attributes_proc (obfd)[0].i)
13679     {
13680       /* This is the first object.  Copy the attributes.  */
13681       _bfd_elf_copy_obj_attributes (ibfd, obfd);
13682
13683       /* Use the Tag_null value to indicate the attributes have been
13684          initialized.  */
13685       elf_known_obj_attributes_proc (obfd)[0].i = 1;
13686
13687       return TRUE;
13688     }
13689
13690   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
13691      non-conflicting ones.  */
13692   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
13693   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
13694     {
13695       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
13696       if (out_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
13697         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
13698       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13699         switch (out_attr[Tag_GNU_MIPS_ABI_FP].i)
13700           {
13701           case 1:
13702             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13703               {
13704               case 2:
13705                 _bfd_error_handler
13706                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13707                    obfd, abi_fp_bfd, ibfd, "-mdouble-float", "-msingle-float");
13708                 break;
13709
13710               case 3:
13711                 _bfd_error_handler
13712                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13713                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13714                 break;
13715
13716               case 4:
13717                 _bfd_error_handler
13718                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13719                    obfd, abi_fp_bfd, ibfd,
13720                    "-mdouble-float", "-mips32r2 -mfp64");
13721                 break;
13722
13723               default:
13724                 _bfd_error_handler
13725                   (_("Warning: %B uses %s (set by %B), "
13726                      "%B uses unknown floating point ABI %d"),
13727                    obfd, abi_fp_bfd, ibfd,
13728                    "-mdouble-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13729                 break;
13730               }
13731             break;
13732
13733           case 2:
13734             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13735               {
13736               case 1:
13737                 _bfd_error_handler
13738                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13739                    obfd, abi_fp_bfd, ibfd, "-msingle-float", "-mdouble-float");
13740                 break;
13741
13742               case 3:
13743                 _bfd_error_handler
13744                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13745                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13746                 break;
13747
13748               case 4:
13749                 _bfd_error_handler
13750                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13751                    obfd, abi_fp_bfd, ibfd,
13752                    "-msingle-float", "-mips32r2 -mfp64");
13753                 break;
13754
13755               default:
13756                 _bfd_error_handler
13757                   (_("Warning: %B uses %s (set by %B), "
13758                      "%B uses unknown floating point ABI %d"),
13759                    obfd, abi_fp_bfd, ibfd,
13760                    "-msingle-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13761                 break;
13762               }
13763             break;
13764
13765           case 3:
13766             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13767               {
13768               case 1:
13769               case 2:
13770               case 4:
13771                 _bfd_error_handler
13772                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13773                    obfd, abi_fp_bfd, ibfd, "-msoft-float", "-mhard-float");
13774                 break;
13775
13776               default:
13777                 _bfd_error_handler
13778                   (_("Warning: %B uses %s (set by %B), "
13779                      "%B uses unknown floating point ABI %d"),
13780                    obfd, abi_fp_bfd, ibfd,
13781                    "-msoft-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13782                 break;
13783               }
13784             break;
13785
13786           case 4:
13787             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13788               {
13789               case 1:
13790                 _bfd_error_handler
13791                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13792                    obfd, abi_fp_bfd, ibfd,
13793                    "-mips32r2 -mfp64", "-mdouble-float");
13794                 break;
13795
13796               case 2:
13797                 _bfd_error_handler
13798                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13799                    obfd, abi_fp_bfd, ibfd,
13800                    "-mips32r2 -mfp64", "-msingle-float");
13801                 break;
13802
13803               case 3:
13804                 _bfd_error_handler
13805                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13806                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13807                 break;
13808
13809               default:
13810                 _bfd_error_handler
13811                   (_("Warning: %B uses %s (set by %B), "
13812                      "%B uses unknown floating point ABI %d"),
13813                    obfd, abi_fp_bfd, ibfd,
13814                    "-mips32r2 -mfp64", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13815                 break;
13816               }
13817             break;
13818
13819           default:
13820             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13821               {
13822               case 1:
13823                 _bfd_error_handler
13824                   (_("Warning: %B uses unknown floating point ABI %d "
13825                      "(set by %B), %B uses %s"),
13826                    obfd, abi_fp_bfd, ibfd,
13827                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mdouble-float");
13828                 break;
13829
13830               case 2:
13831                 _bfd_error_handler
13832                   (_("Warning: %B uses unknown floating point ABI %d "
13833                      "(set by %B), %B uses %s"),
13834                    obfd, abi_fp_bfd, ibfd,
13835                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msingle-float");
13836                 break;
13837
13838               case 3:
13839                 _bfd_error_handler
13840                   (_("Warning: %B uses unknown floating point ABI %d "
13841                      "(set by %B), %B uses %s"),
13842                    obfd, abi_fp_bfd, ibfd,
13843                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msoft-float");
13844                 break;
13845
13846               case 4:
13847                 _bfd_error_handler
13848                   (_("Warning: %B uses unknown floating point ABI %d "
13849                      "(set by %B), %B uses %s"),
13850                    obfd, abi_fp_bfd, ibfd,
13851                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mips32r2 -mfp64");
13852                 break;
13853
13854               default:
13855                 _bfd_error_handler
13856                   (_("Warning: %B uses unknown floating point ABI %d "
13857                      "(set by %B), %B uses unknown floating point ABI %d"),
13858                    obfd, abi_fp_bfd, ibfd,
13859                    out_attr[Tag_GNU_MIPS_ABI_FP].i,
13860                    in_attr[Tag_GNU_MIPS_ABI_FP].i);
13861                 break;
13862               }
13863             break;
13864           }
13865     }
13866
13867   /* Merge Tag_compatibility attributes and any common GNU ones.  */
13868   _bfd_elf_merge_object_attributes (ibfd, obfd);
13869
13870   return TRUE;
13871 }
13872
13873 /* Merge backend specific data from an object file to the output
13874    object file when linking.  */
13875
13876 bfd_boolean
13877 _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
13878 {
13879   flagword old_flags;
13880   flagword new_flags;
13881   bfd_boolean ok;
13882   bfd_boolean null_input_bfd = TRUE;
13883   asection *sec;
13884
13885   /* Check if we have the same endianness.  */
13886   if (! _bfd_generic_verify_endian_match (ibfd, obfd))
13887     {
13888       (*_bfd_error_handler)
13889         (_("%B: endianness incompatible with that of the selected emulation"),
13890          ibfd);
13891       return FALSE;
13892     }
13893
13894   if (!is_mips_elf (ibfd) || !is_mips_elf (obfd))
13895     return TRUE;
13896
13897   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
13898     {
13899       (*_bfd_error_handler)
13900         (_("%B: ABI is incompatible with that of the selected emulation"),
13901          ibfd);
13902       return FALSE;
13903     }
13904
13905   if (!mips_elf_merge_obj_attributes (ibfd, obfd))
13906     return FALSE;
13907
13908   new_flags = elf_elfheader (ibfd)->e_flags;
13909   elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER;
13910   old_flags = elf_elfheader (obfd)->e_flags;
13911
13912   if (! elf_flags_init (obfd))
13913     {
13914       elf_flags_init (obfd) = TRUE;
13915       elf_elfheader (obfd)->e_flags = new_flags;
13916       elf_elfheader (obfd)->e_ident[EI_CLASS]
13917         = elf_elfheader (ibfd)->e_ident[EI_CLASS];
13918
13919       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
13920           && (bfd_get_arch_info (obfd)->the_default
13921               || mips_mach_extends_p (bfd_get_mach (obfd),
13922                                       bfd_get_mach (ibfd))))
13923         {
13924           if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
13925                                    bfd_get_mach (ibfd)))
13926             return FALSE;
13927         }
13928
13929       return TRUE;
13930     }
13931
13932   /* Check flag compatibility.  */
13933
13934   new_flags &= ~EF_MIPS_NOREORDER;
13935   old_flags &= ~EF_MIPS_NOREORDER;
13936
13937   /* Some IRIX 6 BSD-compatibility objects have this bit set.  It
13938      doesn't seem to matter.  */
13939   new_flags &= ~EF_MIPS_XGOT;
13940   old_flags &= ~EF_MIPS_XGOT;
13941
13942   /* MIPSpro generates ucode info in n64 objects.  Again, we should
13943      just be able to ignore this.  */
13944   new_flags &= ~EF_MIPS_UCODE;
13945   old_flags &= ~EF_MIPS_UCODE;
13946
13947   /* DSOs should only be linked with CPIC code.  */
13948   if ((ibfd->flags & DYNAMIC) != 0)
13949     new_flags |= EF_MIPS_PIC | EF_MIPS_CPIC;
13950
13951   if (new_flags == old_flags)
13952     return TRUE;
13953
13954   /* Check to see if the input BFD actually contains any sections.
13955      If not, its flags may not have been initialised either, but it cannot
13956      actually cause any incompatibility.  */
13957   for (sec = ibfd->sections; sec != NULL; sec = sec->next)
13958     {
13959       /* Ignore synthetic sections and empty .text, .data and .bss sections
13960          which are automatically generated by gas.  Also ignore fake
13961          (s)common sections, since merely defining a common symbol does
13962          not affect compatibility.  */
13963       if ((sec->flags & SEC_IS_COMMON) == 0
13964           && strcmp (sec->name, ".reginfo")
13965           && strcmp (sec->name, ".mdebug")
13966           && (sec->size != 0
13967               || (strcmp (sec->name, ".text")
13968                   && strcmp (sec->name, ".data")
13969                   && strcmp (sec->name, ".bss"))))
13970         {
13971           null_input_bfd = FALSE;
13972           break;
13973         }
13974     }
13975   if (null_input_bfd)
13976     return TRUE;
13977
13978   ok = TRUE;
13979
13980   if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)
13981       != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0))
13982     {
13983       (*_bfd_error_handler)
13984         (_("%B: warning: linking abicalls files with non-abicalls files"),
13985          ibfd);
13986       ok = TRUE;
13987     }
13988
13989   if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC))
13990     elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC;
13991   if (! (new_flags & EF_MIPS_PIC))
13992     elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC;
13993
13994   new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13995   old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13996
13997   /* Compare the ISAs.  */
13998   if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags))
13999     {
14000       (*_bfd_error_handler)
14001         (_("%B: linking 32-bit code with 64-bit code"),
14002          ibfd);
14003       ok = FALSE;
14004     }
14005   else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd)))
14006     {
14007       /* OBFD's ISA isn't the same as, or an extension of, IBFD's.  */
14008       if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd)))
14009         {
14010           /* Copy the architecture info from IBFD to OBFD.  Also copy
14011              the 32-bit flag (if set) so that we continue to recognise
14012              OBFD as a 32-bit binary.  */
14013           bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd));
14014           elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
14015           elf_elfheader (obfd)->e_flags
14016             |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14017
14018           /* Copy across the ABI flags if OBFD doesn't use them
14019              and if that was what caused us to treat IBFD as 32-bit.  */
14020           if ((old_flags & EF_MIPS_ABI) == 0
14021               && mips_32bit_flags_p (new_flags)
14022               && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI))
14023             elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI;
14024         }
14025       else
14026         {
14027           /* The ISAs aren't compatible.  */
14028           (*_bfd_error_handler)
14029             (_("%B: linking %s module with previous %s modules"),
14030              ibfd,
14031              bfd_printable_name (ibfd),
14032              bfd_printable_name (obfd));
14033           ok = FALSE;
14034         }
14035     }
14036
14037   new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14038   old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14039
14040   /* Compare ABIs.  The 64-bit ABI does not use EF_MIPS_ABI.  But, it
14041      does set EI_CLASS differently from any 32-bit ABI.  */
14042   if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI)
14043       || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14044           != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14045     {
14046       /* Only error if both are set (to different values).  */
14047       if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI))
14048           || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14049               != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14050         {
14051           (*_bfd_error_handler)
14052             (_("%B: ABI mismatch: linking %s module with previous %s modules"),
14053              ibfd,
14054              elf_mips_abi_name (ibfd),
14055              elf_mips_abi_name (obfd));
14056           ok = FALSE;
14057         }
14058       new_flags &= ~EF_MIPS_ABI;
14059       old_flags &= ~EF_MIPS_ABI;
14060     }
14061
14062   /* Compare ASEs.  Forbid linking MIPS16 and microMIPS ASE modules together
14063      and allow arbitrary mixing of the remaining ASEs (retain the union).  */
14064   if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE))
14065     {
14066       int old_micro = old_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14067       int new_micro = new_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14068       int old_m16 = old_flags & EF_MIPS_ARCH_ASE_M16;
14069       int new_m16 = new_flags & EF_MIPS_ARCH_ASE_M16;
14070       int micro_mis = old_m16 && new_micro;
14071       int m16_mis = old_micro && new_m16;
14072
14073       if (m16_mis || micro_mis)
14074         {
14075           (*_bfd_error_handler)
14076             (_("%B: ASE mismatch: linking %s module with previous %s modules"),
14077              ibfd,
14078              m16_mis ? "MIPS16" : "microMIPS",
14079              m16_mis ? "microMIPS" : "MIPS16");
14080           ok = FALSE;
14081         }
14082
14083       elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE;
14084
14085       new_flags &= ~ EF_MIPS_ARCH_ASE;
14086       old_flags &= ~ EF_MIPS_ARCH_ASE;
14087     }
14088
14089   /* Warn about any other mismatches */
14090   if (new_flags != old_flags)
14091     {
14092       (*_bfd_error_handler)
14093         (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"),
14094          ibfd, (unsigned long) new_flags,
14095          (unsigned long) old_flags);
14096       ok = FALSE;
14097     }
14098
14099   if (! ok)
14100     {
14101       bfd_set_error (bfd_error_bad_value);
14102       return FALSE;
14103     }
14104
14105   return TRUE;
14106 }
14107
14108 /* Function to keep MIPS specific file flags like as EF_MIPS_PIC.  */
14109
14110 bfd_boolean
14111 _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags)
14112 {
14113   BFD_ASSERT (!elf_flags_init (abfd)
14114               || elf_elfheader (abfd)->e_flags == flags);
14115
14116   elf_elfheader (abfd)->e_flags = flags;
14117   elf_flags_init (abfd) = TRUE;
14118   return TRUE;
14119 }
14120
14121 char *
14122 _bfd_mips_elf_get_target_dtag (bfd_vma dtag)
14123 {
14124   switch (dtag)
14125     {
14126     default: return "";
14127     case DT_MIPS_RLD_VERSION:
14128       return "MIPS_RLD_VERSION";
14129     case DT_MIPS_TIME_STAMP:
14130       return "MIPS_TIME_STAMP";
14131     case DT_MIPS_ICHECKSUM:
14132       return "MIPS_ICHECKSUM";
14133     case DT_MIPS_IVERSION:
14134       return "MIPS_IVERSION";
14135     case DT_MIPS_FLAGS:
14136       return "MIPS_FLAGS";
14137     case DT_MIPS_BASE_ADDRESS:
14138       return "MIPS_BASE_ADDRESS";
14139     case DT_MIPS_MSYM:
14140       return "MIPS_MSYM";
14141     case DT_MIPS_CONFLICT:
14142       return "MIPS_CONFLICT";
14143     case DT_MIPS_LIBLIST:
14144       return "MIPS_LIBLIST";
14145     case DT_MIPS_LOCAL_GOTNO:
14146       return "MIPS_LOCAL_GOTNO";
14147     case DT_MIPS_CONFLICTNO:
14148       return "MIPS_CONFLICTNO";
14149     case DT_MIPS_LIBLISTNO:
14150       return "MIPS_LIBLISTNO";
14151     case DT_MIPS_SYMTABNO:
14152       return "MIPS_SYMTABNO";
14153     case DT_MIPS_UNREFEXTNO:
14154       return "MIPS_UNREFEXTNO";
14155     case DT_MIPS_GOTSYM:
14156       return "MIPS_GOTSYM";
14157     case DT_MIPS_HIPAGENO:
14158       return "MIPS_HIPAGENO";
14159     case DT_MIPS_RLD_MAP:
14160       return "MIPS_RLD_MAP";
14161     case DT_MIPS_DELTA_CLASS:
14162       return "MIPS_DELTA_CLASS";
14163     case DT_MIPS_DELTA_CLASS_NO:
14164       return "MIPS_DELTA_CLASS_NO";
14165     case DT_MIPS_DELTA_INSTANCE:
14166       return "MIPS_DELTA_INSTANCE";
14167     case DT_MIPS_DELTA_INSTANCE_NO:
14168       return "MIPS_DELTA_INSTANCE_NO";
14169     case DT_MIPS_DELTA_RELOC:
14170       return "MIPS_DELTA_RELOC";
14171     case DT_MIPS_DELTA_RELOC_NO:
14172       return "MIPS_DELTA_RELOC_NO";
14173     case DT_MIPS_DELTA_SYM:
14174       return "MIPS_DELTA_SYM";
14175     case DT_MIPS_DELTA_SYM_NO:
14176       return "MIPS_DELTA_SYM_NO";
14177     case DT_MIPS_DELTA_CLASSSYM:
14178       return "MIPS_DELTA_CLASSSYM";
14179     case DT_MIPS_DELTA_CLASSSYM_NO:
14180       return "MIPS_DELTA_CLASSSYM_NO";
14181     case DT_MIPS_CXX_FLAGS:
14182       return "MIPS_CXX_FLAGS";
14183     case DT_MIPS_PIXIE_INIT:
14184       return "MIPS_PIXIE_INIT";
14185     case DT_MIPS_SYMBOL_LIB:
14186       return "MIPS_SYMBOL_LIB";
14187     case DT_MIPS_LOCALPAGE_GOTIDX:
14188       return "MIPS_LOCALPAGE_GOTIDX";
14189     case DT_MIPS_LOCAL_GOTIDX:
14190       return "MIPS_LOCAL_GOTIDX";
14191     case DT_MIPS_HIDDEN_GOTIDX:
14192       return "MIPS_HIDDEN_GOTIDX";
14193     case DT_MIPS_PROTECTED_GOTIDX:
14194       return "MIPS_PROTECTED_GOT_IDX";
14195     case DT_MIPS_OPTIONS:
14196       return "MIPS_OPTIONS";
14197     case DT_MIPS_INTERFACE:
14198       return "MIPS_INTERFACE";
14199     case DT_MIPS_DYNSTR_ALIGN:
14200       return "DT_MIPS_DYNSTR_ALIGN";
14201     case DT_MIPS_INTERFACE_SIZE:
14202       return "DT_MIPS_INTERFACE_SIZE";
14203     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
14204       return "DT_MIPS_RLD_TEXT_RESOLVE_ADDR";
14205     case DT_MIPS_PERF_SUFFIX:
14206       return "DT_MIPS_PERF_SUFFIX";
14207     case DT_MIPS_COMPACT_SIZE:
14208       return "DT_MIPS_COMPACT_SIZE";
14209     case DT_MIPS_GP_VALUE:
14210       return "DT_MIPS_GP_VALUE";
14211     case DT_MIPS_AUX_DYNAMIC:
14212       return "DT_MIPS_AUX_DYNAMIC";
14213     case DT_MIPS_PLTGOT:
14214       return "DT_MIPS_PLTGOT";
14215     case DT_MIPS_RWPLT:
14216       return "DT_MIPS_RWPLT";
14217     }
14218 }
14219
14220 bfd_boolean
14221 _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr)
14222 {
14223   FILE *file = ptr;
14224
14225   BFD_ASSERT (abfd != NULL && ptr != NULL);
14226
14227   /* Print normal ELF private data.  */
14228   _bfd_elf_print_private_bfd_data (abfd, ptr);
14229
14230   /* xgettext:c-format */
14231   fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
14232
14233   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
14234     fprintf (file, _(" [abi=O32]"));
14235   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64)
14236     fprintf (file, _(" [abi=O64]"));
14237   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32)
14238     fprintf (file, _(" [abi=EABI32]"));
14239   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
14240     fprintf (file, _(" [abi=EABI64]"));
14241   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI))
14242     fprintf (file, _(" [abi unknown]"));
14243   else if (ABI_N32_P (abfd))
14244     fprintf (file, _(" [abi=N32]"));
14245   else if (ABI_64_P (abfd))
14246     fprintf (file, _(" [abi=64]"));
14247   else
14248     fprintf (file, _(" [no abi set]"));
14249
14250   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1)
14251     fprintf (file, " [mips1]");
14252   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2)
14253     fprintf (file, " [mips2]");
14254   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3)
14255     fprintf (file, " [mips3]");
14256   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4)
14257     fprintf (file, " [mips4]");
14258   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5)
14259     fprintf (file, " [mips5]");
14260   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32)
14261     fprintf (file, " [mips32]");
14262   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64)
14263     fprintf (file, " [mips64]");
14264   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2)
14265     fprintf (file, " [mips32r2]");
14266   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2)
14267     fprintf (file, " [mips64r2]");
14268   else
14269     fprintf (file, _(" [unknown ISA]"));
14270
14271   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
14272     fprintf (file, " [mdmx]");
14273
14274   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
14275     fprintf (file, " [mips16]");
14276
14277   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
14278     fprintf (file, " [micromips]");
14279
14280   if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE)
14281     fprintf (file, " [32bitmode]");
14282   else
14283     fprintf (file, _(" [not 32bitmode]"));
14284
14285   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NOREORDER)
14286     fprintf (file, " [noreorder]");
14287
14288   if (elf_elfheader (abfd)->e_flags & EF_MIPS_PIC)
14289     fprintf (file, " [PIC]");
14290
14291   if (elf_elfheader (abfd)->e_flags & EF_MIPS_CPIC)
14292     fprintf (file, " [CPIC]");
14293
14294   if (elf_elfheader (abfd)->e_flags & EF_MIPS_XGOT)
14295     fprintf (file, " [XGOT]");
14296
14297   if (elf_elfheader (abfd)->e_flags & EF_MIPS_UCODE)
14298     fprintf (file, " [UCODE]");
14299
14300   fputc ('\n', file);
14301
14302   return TRUE;
14303 }
14304
14305 const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] =
14306 {
14307   { STRING_COMMA_LEN (".lit4"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14308   { STRING_COMMA_LEN (".lit8"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14309   { STRING_COMMA_LEN (".mdebug"), 0, SHT_MIPS_DEBUG, 0 },
14310   { STRING_COMMA_LEN (".sbss"),  -2, SHT_NOBITS,     SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14311   { STRING_COMMA_LEN (".sdata"), -2, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14312   { STRING_COMMA_LEN (".ucode"),  0, SHT_MIPS_UCODE, 0 },
14313   { NULL,                     0,  0, 0,              0 }
14314 };
14315
14316 /* Merge non visibility st_other attributes.  Ensure that the
14317    STO_OPTIONAL flag is copied into h->other, even if this is not a
14318    definiton of the symbol.  */
14319 void
14320 _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
14321                                       const Elf_Internal_Sym *isym,
14322                                       bfd_boolean definition,
14323                                       bfd_boolean dynamic ATTRIBUTE_UNUSED)
14324 {
14325   if ((isym->st_other & ~ELF_ST_VISIBILITY (-1)) != 0)
14326     {
14327       unsigned char other;
14328
14329       other = (definition ? isym->st_other : h->other);
14330       other &= ~ELF_ST_VISIBILITY (-1);
14331       h->other = other | ELF_ST_VISIBILITY (h->other);
14332     }
14333
14334   if (!definition
14335       && ELF_MIPS_IS_OPTIONAL (isym->st_other))
14336     h->other |= STO_OPTIONAL;
14337 }
14338
14339 /* Decide whether an undefined symbol is special and can be ignored.
14340    This is the case for OPTIONAL symbols on IRIX.  */
14341 bfd_boolean
14342 _bfd_mips_elf_ignore_undef_symbol (struct elf_link_hash_entry *h)
14343 {
14344   return ELF_MIPS_IS_OPTIONAL (h->other) ? TRUE : FALSE;
14345 }
14346
14347 bfd_boolean
14348 _bfd_mips_elf_common_definition (Elf_Internal_Sym *sym)
14349 {
14350   return (sym->st_shndx == SHN_COMMON
14351           || sym->st_shndx == SHN_MIPS_ACOMMON
14352           || sym->st_shndx == SHN_MIPS_SCOMMON);
14353 }
14354
14355 /* Return address for Ith PLT stub in section PLT, for relocation REL
14356    or (bfd_vma) -1 if it should not be included.  */
14357
14358 bfd_vma
14359 _bfd_mips_elf_plt_sym_val (bfd_vma i, const asection *plt,
14360                            const arelent *rel ATTRIBUTE_UNUSED)
14361 {
14362   return (plt->vma
14363           + 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry)
14364           + i * 4 * ARRAY_SIZE (mips_exec_plt_entry));
14365 }
14366
14367 void
14368 _bfd_mips_post_process_headers (bfd *abfd, struct bfd_link_info *link_info)
14369 {
14370   struct mips_elf_link_hash_table *htab;
14371   Elf_Internal_Ehdr *i_ehdrp;
14372
14373   i_ehdrp = elf_elfheader (abfd);
14374   if (link_info)
14375     {
14376       htab = mips_elf_hash_table (link_info);
14377       BFD_ASSERT (htab != NULL);
14378
14379       if (htab->use_plts_and_copy_relocs && !htab->is_vxworks)
14380         i_ehdrp->e_ident[EI_ABIVERSION] = 1;
14381     }
14382 }