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 /* Returns the GOT index for the global symbol indicated by H.  */
3331
3332 static bfd_vma
3333 mips_elf_global_got_index (bfd *abfd, bfd *ibfd, struct elf_link_hash_entry *h,
3334                            int r_type, struct bfd_link_info *info)
3335 {
3336   struct mips_elf_link_hash_table *htab;
3337   bfd_vma got_index;
3338   struct mips_got_info *g, *gg;
3339   long global_got_dynindx = 0;
3340
3341   htab = mips_elf_hash_table (info);
3342   BFD_ASSERT (htab != NULL);
3343
3344   gg = g = htab->got_info;
3345   if (g->next && ibfd)
3346     {
3347       struct mips_got_entry e, *p;
3348
3349       BFD_ASSERT (h->dynindx >= 0);
3350
3351       g = mips_elf_bfd_got (ibfd, FALSE);
3352       BFD_ASSERT (g);
3353       if (g->next != gg || TLS_RELOC_P (r_type))
3354         {
3355           e.abfd = ibfd;
3356           e.symndx = -1;
3357           e.d.h = (struct mips_elf_link_hash_entry *)h;
3358           e.tls_type = mips_elf_reloc_tls_type (r_type);
3359
3360           p = htab_find (g->got_entries, &e);
3361
3362           BFD_ASSERT (p && p->gotidx > 0);
3363
3364           if (p->tls_type)
3365             {
3366               bfd_vma value = MINUS_ONE;
3367               if ((h->root.type == bfd_link_hash_defined
3368                    || h->root.type == bfd_link_hash_defweak)
3369                   && h->root.u.def.section->output_section)
3370                 value = (h->root.u.def.value
3371                          + h->root.u.def.section->output_offset
3372                          + h->root.u.def.section->output_section->vma);
3373
3374               return mips_tls_got_index (abfd, p->gotidx, &p->tls_type,
3375                                          info, e.d.h, value);
3376             }
3377           else
3378             return p->gotidx;
3379         }
3380     }
3381
3382   if (htab->global_gotsym != NULL)
3383     global_got_dynindx = htab->global_gotsym->dynindx;
3384
3385   if (TLS_RELOC_P (r_type))
3386     {
3387       struct mips_elf_link_hash_entry *hm
3388         = (struct mips_elf_link_hash_entry *) h;
3389       bfd_vma value = MINUS_ONE;
3390
3391       if ((h->root.type == bfd_link_hash_defined
3392            || h->root.type == bfd_link_hash_defweak)
3393           && h->root.u.def.section->output_section)
3394         value = (h->root.u.def.value
3395                  + h->root.u.def.section->output_offset
3396                  + h->root.u.def.section->output_section->vma);
3397
3398       got_index = mips_tls_single_got_index (abfd, r_type, info, hm, value);
3399     }
3400   else
3401     {
3402       /* Once we determine the global GOT entry with the lowest dynamic
3403          symbol table index, we must put all dynamic symbols with greater
3404          indices into the GOT.  That makes it easy to calculate the GOT
3405          offset.  */
3406       BFD_ASSERT (h->dynindx >= global_got_dynindx);
3407       got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3408                    * MIPS_ELF_GOT_SIZE (abfd));
3409     }
3410   BFD_ASSERT (got_index < htab->sgot->size);
3411
3412   return got_index;
3413 }
3414
3415 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3416    entries are supposed to be placed at small offsets in the GOT, i.e.,
3417    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3418    entry could be created.  If OFFSETP is nonnull, use it to return the
3419    offset of the GOT entry from VALUE.  */
3420
3421 static bfd_vma
3422 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3423                    bfd_vma value, bfd_vma *offsetp)
3424 {
3425   bfd_vma page, got_index;
3426   struct mips_got_entry *entry;
3427
3428   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3429   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3430                                            NULL, R_MIPS_GOT_PAGE);
3431
3432   if (!entry)
3433     return MINUS_ONE;
3434
3435   got_index = entry->gotidx;
3436
3437   if (offsetp)
3438     *offsetp = value - entry->d.address;
3439
3440   return got_index;
3441 }
3442
3443 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3444    EXTERNAL is true if the relocation was originally against a global
3445    symbol that binds locally.  */
3446
3447 static bfd_vma
3448 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3449                       bfd_vma value, bfd_boolean external)
3450 {
3451   struct mips_got_entry *entry;
3452
3453   /* GOT16 relocations against local symbols are followed by a LO16
3454      relocation; those against global symbols are not.  Thus if the
3455      symbol was originally local, the GOT16 relocation should load the
3456      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3457   if (! external)
3458     value = mips_elf_high (value) << 16;
3459
3460   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3461      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3462      same in all cases.  */
3463   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3464                                            NULL, R_MIPS_GOT16);
3465   if (entry)
3466     return entry->gotidx;
3467   else
3468     return MINUS_ONE;
3469 }
3470
3471 /* Returns the offset for the entry at the INDEXth position
3472    in the GOT.  */
3473
3474 static bfd_vma
3475 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3476                                 bfd *input_bfd, bfd_vma got_index)
3477 {
3478   struct mips_elf_link_hash_table *htab;
3479   asection *sgot;
3480   bfd_vma gp;
3481
3482   htab = mips_elf_hash_table (info);
3483   BFD_ASSERT (htab != NULL);
3484
3485   sgot = htab->sgot;
3486   gp = _bfd_get_gp_value (output_bfd)
3487     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3488
3489   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3490 }
3491
3492 /* Create and return a local GOT entry for VALUE, which was calculated
3493    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3494    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3495    instead.  */
3496
3497 static struct mips_got_entry *
3498 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3499                                  bfd *ibfd, bfd_vma value,
3500                                  unsigned long r_symndx,
3501                                  struct mips_elf_link_hash_entry *h,
3502                                  int r_type)
3503 {
3504   struct mips_got_entry entry, **loc;
3505   struct mips_got_info *g;
3506   struct mips_elf_link_hash_table *htab;
3507
3508   htab = mips_elf_hash_table (info);
3509   BFD_ASSERT (htab != NULL);
3510
3511   entry.abfd = NULL;
3512   entry.symndx = -1;
3513   entry.d.address = value;
3514   entry.tls_type = mips_elf_reloc_tls_type (r_type);
3515
3516   g = mips_elf_bfd_got (ibfd, FALSE);
3517   if (g == NULL)
3518     {
3519       g = mips_elf_bfd_got (abfd, FALSE);
3520       BFD_ASSERT (g != NULL);
3521     }
3522
3523   /* This function shouldn't be called for symbols that live in the global
3524      area of the GOT.  */
3525   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3526   if (entry.tls_type)
3527     {
3528       struct mips_got_entry *p;
3529
3530       entry.abfd = ibfd;
3531       if (tls_ldm_reloc_p (r_type))
3532         {
3533           entry.symndx = 0;
3534           entry.d.addend = 0;
3535         }
3536       else if (h == NULL)
3537         {
3538           entry.symndx = r_symndx;
3539           entry.d.addend = 0;
3540         }
3541       else
3542         entry.d.h = h;
3543
3544       p = (struct mips_got_entry *)
3545         htab_find (g->got_entries, &entry);
3546
3547       BFD_ASSERT (p);
3548       return p;
3549     }
3550
3551   loc = (struct mips_got_entry **) htab_find_slot (g->got_entries, &entry,
3552                                                    INSERT);
3553   if (*loc)
3554     return *loc;
3555
3556   entry.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_gotno++;
3557
3558   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3559
3560   if (! *loc)
3561     return NULL;
3562
3563   memcpy (*loc, &entry, sizeof entry);
3564
3565   if (g->assigned_gotno > g->local_gotno)
3566     {
3567       (*loc)->gotidx = -1;
3568       /* We didn't allocate enough space in the GOT.  */
3569       (*_bfd_error_handler)
3570         (_("not enough GOT space for local GOT entries"));
3571       bfd_set_error (bfd_error_bad_value);
3572       return NULL;
3573     }
3574
3575   MIPS_ELF_PUT_WORD (abfd, value,
3576                      (htab->sgot->contents + entry.gotidx));
3577
3578   /* These GOT entries need a dynamic relocation on VxWorks.  */
3579   if (htab->is_vxworks)
3580     {
3581       Elf_Internal_Rela outrel;
3582       asection *s;
3583       bfd_byte *rloc;
3584       bfd_vma got_address;
3585
3586       s = mips_elf_rel_dyn_section (info, FALSE);
3587       got_address = (htab->sgot->output_section->vma
3588                      + htab->sgot->output_offset
3589                      + entry.gotidx);
3590
3591       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3592       outrel.r_offset = got_address;
3593       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3594       outrel.r_addend = value;
3595       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3596     }
3597
3598   return *loc;
3599 }
3600
3601 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3602    The number might be exact or a worst-case estimate, depending on how
3603    much information is available to elf_backend_omit_section_dynsym at
3604    the current linking stage.  */
3605
3606 static bfd_size_type
3607 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3608 {
3609   bfd_size_type count;
3610
3611   count = 0;
3612   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
3613     {
3614       asection *p;
3615       const struct elf_backend_data *bed;
3616
3617       bed = get_elf_backend_data (output_bfd);
3618       for (p = output_bfd->sections; p ; p = p->next)
3619         if ((p->flags & SEC_EXCLUDE) == 0
3620             && (p->flags & SEC_ALLOC) != 0
3621             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3622           ++count;
3623     }
3624   return count;
3625 }
3626
3627 /* Sort the dynamic symbol table so that symbols that need GOT entries
3628    appear towards the end.  */
3629
3630 static bfd_boolean
3631 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3632 {
3633   struct mips_elf_link_hash_table *htab;
3634   struct mips_elf_hash_sort_data hsd;
3635   struct mips_got_info *g;
3636
3637   if (elf_hash_table (info)->dynsymcount == 0)
3638     return TRUE;
3639
3640   htab = mips_elf_hash_table (info);
3641   BFD_ASSERT (htab != NULL);
3642
3643   g = htab->got_info;
3644   if (g == NULL)
3645     return TRUE;
3646
3647   hsd.low = NULL;
3648   hsd.max_unref_got_dynindx
3649     = hsd.min_got_dynindx
3650     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3651   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3652   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3653                                 elf_hash_table (info)),
3654                                mips_elf_sort_hash_table_f,
3655                                &hsd);
3656
3657   /* There should have been enough room in the symbol table to
3658      accommodate both the GOT and non-GOT symbols.  */
3659   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3660   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3661               == elf_hash_table (info)->dynsymcount);
3662   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3663               == g->global_gotno);
3664
3665   /* Now we know which dynamic symbol has the lowest dynamic symbol
3666      table index in the GOT.  */
3667   htab->global_gotsym = hsd.low;
3668
3669   return TRUE;
3670 }
3671
3672 /* If H needs a GOT entry, assign it the highest available dynamic
3673    index.  Otherwise, assign it the lowest available dynamic
3674    index.  */
3675
3676 static bfd_boolean
3677 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3678 {
3679   struct mips_elf_hash_sort_data *hsd = data;
3680
3681   /* Symbols without dynamic symbol table entries aren't interesting
3682      at all.  */
3683   if (h->root.dynindx == -1)
3684     return TRUE;
3685
3686   switch (h->global_got_area)
3687     {
3688     case GGA_NONE:
3689       h->root.dynindx = hsd->max_non_got_dynindx++;
3690       break;
3691
3692     case GGA_NORMAL:
3693       h->root.dynindx = --hsd->min_got_dynindx;
3694       hsd->low = (struct elf_link_hash_entry *) h;
3695       break;
3696
3697     case GGA_RELOC_ONLY:
3698       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3699         hsd->low = (struct elf_link_hash_entry *) h;
3700       h->root.dynindx = hsd->max_unref_got_dynindx++;
3701       break;
3702     }
3703
3704   return TRUE;
3705 }
3706
3707 /* Record that input bfd ABFD requires a GOT entry like *LOOKUP
3708    (which is owned by the caller and shouldn't be added to the
3709    hash table directly).  */
3710
3711 static bfd_boolean
3712 mips_elf_record_got_entry (struct bfd_link_info *info, bfd *abfd,
3713                            struct mips_got_entry *lookup)
3714 {
3715   struct mips_elf_link_hash_table *htab;
3716   struct mips_got_entry *entry;
3717   struct mips_got_info *g;
3718   void **loc, **bfd_loc;
3719
3720   /* Make sure there's a slot for this entry in the master GOT.  */
3721   htab = mips_elf_hash_table (info);
3722   g = htab->got_info;
3723   loc = htab_find_slot (g->got_entries, lookup, INSERT);
3724   if (!loc)
3725     return FALSE;
3726
3727   /* Populate the entry if it isn't already.  */
3728   entry = (struct mips_got_entry *) *loc;
3729   if (!entry)
3730     {
3731       entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3732       if (!entry)
3733         return FALSE;
3734
3735       lookup->gotidx = -1;
3736       *entry = *lookup;
3737       *loc = entry;
3738     }
3739
3740   /* Reuse the same GOT entry for the BFD's GOT.  */
3741   g = mips_elf_bfd_got (abfd, TRUE);
3742   if (!g)
3743     return FALSE;
3744
3745   bfd_loc = htab_find_slot (g->got_entries, lookup, INSERT);
3746   if (!bfd_loc)
3747     return FALSE;
3748
3749   if (!*bfd_loc)
3750     *bfd_loc = entry;
3751   return TRUE;
3752 }
3753
3754 /* ABFD has a GOT relocation of type R_TYPE against H.  Reserve a GOT
3755    entry for it.  FOR_CALL is true if the caller is only interested in
3756    using the GOT entry for calls.  */
3757
3758 static bfd_boolean
3759 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3760                                    bfd *abfd, struct bfd_link_info *info,
3761                                    bfd_boolean for_call, int r_type)
3762 {
3763   struct mips_elf_link_hash_table *htab;
3764   struct mips_elf_link_hash_entry *hmips;
3765   struct mips_got_entry entry;
3766   unsigned char tls_type;
3767
3768   htab = mips_elf_hash_table (info);
3769   BFD_ASSERT (htab != NULL);
3770
3771   hmips = (struct mips_elf_link_hash_entry *) h;
3772   if (!for_call)
3773     hmips->got_only_for_calls = FALSE;
3774
3775   /* A global symbol in the GOT must also be in the dynamic symbol
3776      table.  */
3777   if (h->dynindx == -1)
3778     {
3779       switch (ELF_ST_VISIBILITY (h->other))
3780         {
3781         case STV_INTERNAL:
3782         case STV_HIDDEN:
3783           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3784           break;
3785         }
3786       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3787         return FALSE;
3788     }
3789
3790   tls_type = mips_elf_reloc_tls_type (r_type);
3791   if (tls_type == GOT_NORMAL && hmips->global_got_area > GGA_NORMAL)
3792     hmips->global_got_area = GGA_NORMAL;
3793   else if (tls_type == GOT_TLS_IE && hmips->tls_ie_type == 0)
3794     hmips->tls_ie_type = tls_type;
3795   else if (tls_type == GOT_TLS_GD && hmips->tls_gd_type == 0)
3796     hmips->tls_gd_type = tls_type;
3797
3798   entry.abfd = abfd;
3799   entry.symndx = -1;
3800   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3801   entry.tls_type = tls_type;
3802   return mips_elf_record_got_entry (info, abfd, &entry);
3803 }
3804
3805 /* ABFD has a GOT relocation of type R_TYPE against symbol SYMNDX + ADDEND,
3806    where SYMNDX is a local symbol.  Reserve a GOT entry for it.  */
3807
3808 static bfd_boolean
3809 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
3810                                   struct bfd_link_info *info, int r_type)
3811 {
3812   struct mips_elf_link_hash_table *htab;
3813   struct mips_got_info *g;
3814   struct mips_got_entry entry;
3815
3816   htab = mips_elf_hash_table (info);
3817   BFD_ASSERT (htab != NULL);
3818
3819   g = htab->got_info;
3820   BFD_ASSERT (g != NULL);
3821
3822   entry.abfd = abfd;
3823   entry.symndx = symndx;
3824   entry.d.addend = addend;
3825   entry.tls_type = mips_elf_reloc_tls_type (r_type);
3826   return mips_elf_record_got_entry (info, abfd, &entry);
3827 }
3828
3829 /* Return the maximum number of GOT page entries required for RANGE.  */
3830
3831 static bfd_vma
3832 mips_elf_pages_for_range (const struct mips_got_page_range *range)
3833 {
3834   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
3835 }
3836
3837 /* Record that ABFD has a page relocation against symbol SYMNDX and
3838    that ADDEND is the addend for that relocation.
3839
3840    This function creates an upper bound on the number of GOT slots
3841    required; no attempt is made to combine references to non-overridable
3842    global symbols across multiple input files.  */
3843
3844 static bfd_boolean
3845 mips_elf_record_got_page_entry (struct bfd_link_info *info, bfd *abfd,
3846                                 long symndx, bfd_signed_vma addend)
3847 {
3848   struct mips_elf_link_hash_table *htab;
3849   struct mips_got_info *g1, *g2;
3850   struct mips_got_page_entry lookup, *entry;
3851   struct mips_got_page_range **range_ptr, *range;
3852   bfd_vma old_pages, new_pages;
3853   void **loc, **bfd_loc;
3854
3855   htab = mips_elf_hash_table (info);
3856   BFD_ASSERT (htab != NULL);
3857
3858   g1 = htab->got_info;
3859   BFD_ASSERT (g1 != NULL);
3860
3861   /* Find the mips_got_page_entry hash table entry for this symbol.  */
3862   lookup.abfd = abfd;
3863   lookup.symndx = symndx;
3864   loc = htab_find_slot (g1->got_page_entries, &lookup, INSERT);
3865   if (loc == NULL)
3866     return FALSE;
3867
3868   /* Create a mips_got_page_entry if this is the first time we've
3869      seen the symbol.  */
3870   entry = (struct mips_got_page_entry *) *loc;
3871   if (!entry)
3872     {
3873       entry = bfd_alloc (abfd, sizeof (*entry));
3874       if (!entry)
3875         return FALSE;
3876
3877       entry->abfd = abfd;
3878       entry->symndx = symndx;
3879       entry->ranges = NULL;
3880       entry->num_pages = 0;
3881       *loc = entry;
3882     }
3883
3884   /* Add the same entry to the BFD's GOT.  */
3885   g2 = mips_elf_bfd_got (abfd, TRUE);
3886   if (!g2)
3887     return FALSE;
3888
3889   bfd_loc = htab_find_slot (g2->got_page_entries, &lookup, INSERT);
3890   if (!bfd_loc)
3891     return FALSE;
3892
3893   if (!*bfd_loc)
3894     *bfd_loc = entry;
3895
3896   /* Skip over ranges whose maximum extent cannot share a page entry
3897      with ADDEND.  */
3898   range_ptr = &entry->ranges;
3899   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
3900     range_ptr = &(*range_ptr)->next;
3901
3902   /* If we scanned to the end of the list, or found a range whose
3903      minimum extent cannot share a page entry with ADDEND, create
3904      a new singleton range.  */
3905   range = *range_ptr;
3906   if (!range || addend < range->min_addend - 0xffff)
3907     {
3908       range = bfd_alloc (abfd, sizeof (*range));
3909       if (!range)
3910         return FALSE;
3911
3912       range->next = *range_ptr;
3913       range->min_addend = addend;
3914       range->max_addend = addend;
3915
3916       *range_ptr = range;
3917       entry->num_pages++;
3918       g1->page_gotno++;
3919       g2->page_gotno++;
3920       return TRUE;
3921     }
3922
3923   /* Remember how many pages the old range contributed.  */
3924   old_pages = mips_elf_pages_for_range (range);
3925
3926   /* Update the ranges.  */
3927   if (addend < range->min_addend)
3928     range->min_addend = addend;
3929   else if (addend > range->max_addend)
3930     {
3931       if (range->next && addend >= range->next->min_addend - 0xffff)
3932         {
3933           old_pages += mips_elf_pages_for_range (range->next);
3934           range->max_addend = range->next->max_addend;
3935           range->next = range->next->next;
3936         }
3937       else
3938         range->max_addend = addend;
3939     }
3940
3941   /* Record any change in the total estimate.  */
3942   new_pages = mips_elf_pages_for_range (range);
3943   if (old_pages != new_pages)
3944     {
3945       entry->num_pages += new_pages - old_pages;
3946       g1->page_gotno += new_pages - old_pages;
3947       g2->page_gotno += new_pages - old_pages;
3948     }
3949
3950   return TRUE;
3951 }
3952
3953 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
3954
3955 static void
3956 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
3957                                        unsigned int n)
3958 {
3959   asection *s;
3960   struct mips_elf_link_hash_table *htab;
3961
3962   htab = mips_elf_hash_table (info);
3963   BFD_ASSERT (htab != NULL);
3964
3965   s = mips_elf_rel_dyn_section (info, FALSE);
3966   BFD_ASSERT (s != NULL);
3967
3968   if (htab->is_vxworks)
3969     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
3970   else
3971     {
3972       if (s->size == 0)
3973         {
3974           /* Make room for a null element.  */
3975           s->size += MIPS_ELF_REL_SIZE (abfd);
3976           ++s->reloc_count;
3977         }
3978       s->size += n * MIPS_ELF_REL_SIZE (abfd);
3979     }
3980 }
3981 \f
3982 /* A htab_traverse callback for GOT entries.  Set boolean *DATA to true
3983    if the GOT entry is for an indirect or warning symbol.  */
3984
3985 static int
3986 mips_elf_check_recreate_got (void **entryp, void *data)
3987 {
3988   struct mips_got_entry *entry;
3989   bfd_boolean *must_recreate;
3990
3991   entry = (struct mips_got_entry *) *entryp;
3992   must_recreate = (bfd_boolean *) data;
3993   if (entry->abfd != NULL && entry->symndx == -1)
3994     {
3995       struct mips_elf_link_hash_entry *h;
3996
3997       h = entry->d.h;
3998       if (h->root.root.type == bfd_link_hash_indirect
3999           || h->root.root.type == bfd_link_hash_warning)
4000         {
4001           *must_recreate = TRUE;
4002           return 0;
4003         }
4004     }
4005   return 1;
4006 }
4007
4008 /* A htab_traverse callback for GOT entries.  Add all entries to
4009    hash table *DATA, converting entries for indirect and warning
4010    symbols into entries for the target symbol.  Set *DATA to null
4011    on error.  */
4012
4013 static int
4014 mips_elf_recreate_got (void **entryp, void *data)
4015 {
4016   htab_t *new_got;
4017   struct mips_got_entry new_entry, *entry;
4018   void **slot;
4019
4020   new_got = (htab_t *) data;
4021   entry = (struct mips_got_entry *) *entryp;
4022   if (entry->abfd != NULL
4023       && entry->symndx == -1
4024       && (entry->d.h->root.root.type == bfd_link_hash_indirect
4025           || entry->d.h->root.root.type == bfd_link_hash_warning))
4026     {
4027       struct mips_elf_link_hash_entry *h;
4028
4029       new_entry = *entry;
4030       entry = &new_entry;
4031       h = entry->d.h;
4032       do
4033         {
4034           BFD_ASSERT (h->global_got_area == GGA_NONE);
4035           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
4036         }
4037       while (h->root.root.type == bfd_link_hash_indirect
4038              || h->root.root.type == bfd_link_hash_warning);
4039       entry->d.h = h;
4040     }
4041   slot = htab_find_slot (*new_got, entry, INSERT);
4042   if (slot == NULL)
4043     {
4044       *new_got = NULL;
4045       return 0;
4046     }
4047   if (*slot == NULL)
4048     {
4049       if (entry == &new_entry)
4050         {
4051           entry = bfd_alloc (entry->abfd, sizeof (*entry));
4052           if (!entry)
4053             {
4054               *new_got = NULL;
4055               return 0;
4056             }
4057           *entry = new_entry;
4058         }
4059       *slot = entry;
4060     }
4061   return 1;
4062 }
4063
4064 /* If any entries in G->got_entries are for indirect or warning symbols,
4065    replace them with entries for the target symbol.  */
4066
4067 static bfd_boolean
4068 mips_elf_resolve_final_got_entries (struct mips_got_info *g)
4069 {
4070   bfd_boolean must_recreate;
4071   htab_t new_got;
4072
4073   must_recreate = FALSE;
4074   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &must_recreate);
4075   if (must_recreate)
4076     {
4077       new_got = htab_create (htab_size (g->got_entries),
4078                              mips_elf_got_entry_hash,
4079                              mips_elf_got_entry_eq, NULL);
4080       htab_traverse (g->got_entries, mips_elf_recreate_got, &new_got);
4081       if (new_got == NULL)
4082         return FALSE;
4083
4084       htab_delete (g->got_entries);
4085       g->got_entries = new_got;
4086     }
4087   return TRUE;
4088 }
4089
4090 /* A mips_elf_link_hash_traverse callback for which DATA points
4091    to the link_info structure.  Count the number of type (3) entries
4092    in the master GOT.  */
4093
4094 static int
4095 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
4096 {
4097   struct bfd_link_info *info;
4098   struct mips_elf_link_hash_table *htab;
4099   struct mips_got_info *g;
4100
4101   info = (struct bfd_link_info *) data;
4102   htab = mips_elf_hash_table (info);
4103   g = htab->got_info;
4104   if (h->global_got_area != GGA_NONE)
4105     {
4106       /* Make a final decision about whether the symbol belongs in the
4107          local or global GOT.  Symbols that bind locally can (and in the
4108          case of forced-local symbols, must) live in the local GOT.
4109          Those that are aren't in the dynamic symbol table must also
4110          live in the local GOT.
4111
4112          Note that the former condition does not always imply the
4113          latter: symbols do not bind locally if they are completely
4114          undefined.  We'll report undefined symbols later if appropriate.  */
4115       if (h->root.dynindx == -1
4116           || (h->got_only_for_calls
4117               ? SYMBOL_CALLS_LOCAL (info, &h->root)
4118               : SYMBOL_REFERENCES_LOCAL (info, &h->root)))
4119         {
4120           /* The symbol belongs in the local GOT.  We no longer need this
4121              entry if it was only used for relocations; those relocations
4122              will be against the null or section symbol instead of H.  */
4123           if (h->global_got_area != GGA_RELOC_ONLY)
4124             g->local_gotno++;
4125           h->global_got_area = GGA_NONE;
4126         }
4127       else if (htab->is_vxworks
4128                && h->got_only_for_calls
4129                && h->root.plt.offset != MINUS_ONE)
4130         /* On VxWorks, calls can refer directly to the .got.plt entry;
4131            they don't need entries in the regular GOT.  .got.plt entries
4132            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4133         h->global_got_area = GGA_NONE;
4134       else
4135         {
4136           g->global_gotno++;
4137           if (h->global_got_area == GGA_RELOC_ONLY)
4138             g->reloc_only_gotno++;
4139         }
4140     }
4141   return 1;
4142 }
4143 \f
4144 /* A htab_traverse callback for GOT entries.  Add each one to the GOT
4145    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4146
4147 static int
4148 mips_elf_add_got_entry (void **entryp, void *data)
4149 {
4150   struct mips_got_entry *entry;
4151   struct mips_elf_traverse_got_arg *arg;
4152   void **slot;
4153
4154   entry = (struct mips_got_entry *) *entryp;
4155   arg = (struct mips_elf_traverse_got_arg *) data;
4156   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
4157   if (!slot)
4158     {
4159       arg->g = NULL;
4160       return 0;
4161     }
4162   if (!*slot)
4163     {
4164       *slot = entry;
4165       mips_elf_count_got_entry (arg->info, arg->g, entry);
4166     }
4167   return 1;
4168 }
4169
4170 /* A htab_traverse callback for GOT page entries.  Add each one to the GOT
4171    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4172
4173 static int
4174 mips_elf_add_got_page_entry (void **entryp, void *data)
4175 {
4176   struct mips_got_page_entry *entry;
4177   struct mips_elf_traverse_got_arg *arg;
4178   void **slot;
4179
4180   entry = (struct mips_got_page_entry *) *entryp;
4181   arg = (struct mips_elf_traverse_got_arg *) data;
4182   slot = htab_find_slot (arg->g->got_page_entries, entry, INSERT);
4183   if (!slot)
4184     {
4185       arg->g = NULL;
4186       return 0;
4187     }
4188   if (!*slot)
4189     {
4190       *slot = entry;
4191       arg->g->page_gotno += entry->num_pages;
4192     }
4193   return 1;
4194 }
4195
4196 /* Consider merging FROM, which is ABFD's GOT, into TO.  Return -1 if
4197    this would lead to overflow, 1 if they were merged successfully,
4198    and 0 if a merge failed due to lack of memory.  (These values are chosen
4199    so that nonnegative return values can be returned by a htab_traverse
4200    callback.)  */
4201
4202 static int
4203 mips_elf_merge_got_with (bfd *abfd, struct mips_got_info *from,
4204                          struct mips_got_info *to,
4205                          struct mips_elf_got_per_bfd_arg *arg)
4206 {
4207   struct mips_elf_traverse_got_arg tga;
4208   unsigned int estimate;
4209
4210   /* Work out how many page entries we would need for the combined GOT.  */
4211   estimate = arg->max_pages;
4212   if (estimate >= from->page_gotno + to->page_gotno)
4213     estimate = from->page_gotno + to->page_gotno;
4214
4215   /* And conservatively estimate how many local and TLS entries
4216      would be needed.  */
4217   estimate += from->local_gotno + to->local_gotno;
4218   estimate += from->tls_gotno + to->tls_gotno;
4219
4220   /* If we're merging with the primary got, any TLS relocations will
4221      come after the full set of global entries.  Otherwise estimate those
4222      conservatively as well.  */
4223   if (to == arg->primary && from->tls_gotno + to->tls_gotno)
4224     estimate += arg->global_count;
4225   else
4226     estimate += from->global_gotno + to->global_gotno;
4227
4228   /* Bail out if the combined GOT might be too big.  */
4229   if (estimate > arg->max_count)
4230     return -1;
4231
4232   /* Transfer the bfd's got information from FROM to TO.  */
4233   tga.info = arg->info;
4234   tga.g = to;
4235   htab_traverse (from->got_entries, mips_elf_add_got_entry, &tga);
4236   if (!tga.g)
4237     return 0;
4238
4239   htab_traverse (from->got_page_entries, mips_elf_add_got_page_entry, &tga);
4240   if (!tga.g)
4241     return 0;
4242
4243   mips_elf_replace_bfd_got (abfd, to);
4244   return 1;
4245 }
4246
4247 /* Attempt to merge GOT G, which belongs to ABFD.  Try to use as much
4248    as possible of the primary got, since it doesn't require explicit
4249    dynamic relocations, but don't use bfds that would reference global
4250    symbols out of the addressable range.  Failing the primary got,
4251    attempt to merge with the current got, or finish the current got
4252    and then make make the new got current.  */
4253
4254 static bfd_boolean
4255 mips_elf_merge_got (bfd *abfd, struct mips_got_info *g,
4256                     struct mips_elf_got_per_bfd_arg *arg)
4257 {
4258   struct mips_elf_traverse_got_arg tga;
4259   unsigned int estimate;
4260   int result;
4261
4262   if (!mips_elf_resolve_final_got_entries (g))
4263     return FALSE;
4264
4265   tga.info = arg->info;
4266   tga.g = g;
4267   htab_traverse (g->got_entries, mips_elf_count_got_entries, &tga);
4268
4269   /* Work out the number of page, local and TLS entries.  */
4270   estimate = arg->max_pages;
4271   if (estimate > g->page_gotno)
4272     estimate = g->page_gotno;
4273   estimate += g->local_gotno + g->tls_gotno;
4274
4275   /* We place TLS GOT entries after both locals and globals.  The globals
4276      for the primary GOT may overflow the normal GOT size limit, so be
4277      sure not to merge a GOT which requires TLS with the primary GOT in that
4278      case.  This doesn't affect non-primary GOTs.  */
4279   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4280
4281   if (estimate <= arg->max_count)
4282     {
4283       /* If we don't have a primary GOT, use it as
4284          a starting point for the primary GOT.  */
4285       if (!arg->primary)
4286         {
4287           arg->primary = g;
4288           return TRUE;
4289         }
4290
4291       /* Try merging with the primary GOT.  */
4292       result = mips_elf_merge_got_with (abfd, g, arg->primary, arg);
4293       if (result >= 0)
4294         return result;
4295     }
4296
4297   /* If we can merge with the last-created got, do it.  */
4298   if (arg->current)
4299     {
4300       result = mips_elf_merge_got_with (abfd, g, arg->current, arg);
4301       if (result >= 0)
4302         return result;
4303     }
4304
4305   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4306      fits; if it turns out that it doesn't, we'll get relocation
4307      overflows anyway.  */
4308   g->next = arg->current;
4309   arg->current = g;
4310
4311   return TRUE;
4312 }
4313
4314 /* ENTRYP is a hash table entry for a mips_got_entry.  Set its gotidx
4315    to GOTIDX, duplicating the entry if it has already been assigned
4316    an index in a different GOT.  */
4317
4318 static bfd_boolean
4319 mips_elf_set_gotidx (void **entryp, long gotidx)
4320 {
4321   struct mips_got_entry *entry;
4322
4323   entry = (struct mips_got_entry *) *entryp;
4324   if (entry->gotidx > 0)
4325     {
4326       struct mips_got_entry *new_entry;
4327
4328       new_entry = bfd_alloc (entry->abfd, sizeof (*entry));
4329       if (!new_entry)
4330         return FALSE;
4331
4332       *new_entry = *entry;
4333       *entryp = new_entry;
4334       entry = new_entry;
4335     }
4336   entry->gotidx = gotidx;
4337   return TRUE;
4338 }
4339
4340 /* Set the TLS GOT index for the GOT entry in ENTRYP.  DATA points to a
4341    mips_elf_traverse_got_arg in which DATA->value is the size of one
4342    GOT entry.  Set DATA->g to null on failure.  */
4343
4344 static int
4345 mips_elf_initialize_tls_index (void **entryp, void *data)
4346 {
4347   struct mips_got_entry *entry;
4348   struct mips_elf_traverse_got_arg *arg;
4349   struct mips_got_info *g;
4350   bfd_vma next_index;
4351   unsigned char tls_type;
4352
4353   /* We're only interested in TLS symbols.  */
4354   entry = (struct mips_got_entry *) *entryp;
4355   tls_type = (entry->tls_type & GOT_TLS_TYPE);
4356   if (tls_type == 0)
4357     return 1;
4358
4359   arg = (struct mips_elf_traverse_got_arg *) data;
4360   g = arg->g;
4361   next_index = arg->value * g->tls_assigned_gotno;
4362
4363   if (entry->symndx == -1 && g->next == NULL)
4364     {
4365       /* A type (3) got entry in the single-GOT case.  We use the symbol's
4366          hash table entry to track its index.  */
4367       if (tls_type == GOT_TLS_IE)
4368         {
4369           if (entry->d.h->tls_ie_type & GOT_TLS_OFFSET_DONE)
4370             return 1;
4371           entry->d.h->tls_ie_type |= GOT_TLS_OFFSET_DONE;
4372           entry->d.h->tls_ie_got_offset = next_index;
4373         }
4374       else
4375         {
4376           BFD_ASSERT (tls_type == GOT_TLS_GD);
4377           if (entry->d.h->tls_gd_type & GOT_TLS_OFFSET_DONE)
4378             return 1;
4379           entry->d.h->tls_gd_type |= GOT_TLS_OFFSET_DONE;
4380           entry->d.h->tls_gd_got_offset = next_index;
4381         }
4382     }
4383   else
4384     {
4385       if (tls_type == GOT_TLS_LDM)
4386         {
4387           /* There are separate mips_got_entry objects for each input bfd
4388              that requires an LDM entry.  Make sure that all LDM entries in
4389              a GOT resolve to the same index.  */
4390           if (g->tls_ldm_offset != MINUS_TWO && g->tls_ldm_offset != MINUS_ONE)
4391             {
4392               entry->gotidx = g->tls_ldm_offset;
4393               return 1;
4394             }
4395           g->tls_ldm_offset = next_index;
4396         }
4397       if (!mips_elf_set_gotidx (entryp, next_index))
4398         {
4399           arg->g = NULL;
4400           return 0;
4401         }
4402     }
4403
4404   /* Account for the entries we've just allocated.  */
4405   g->tls_assigned_gotno += mips_tls_got_entries (tls_type);
4406   return 1;
4407 }
4408
4409 /* A htab_traverse callback for GOT entries, where DATA points to a
4410    mips_elf_traverse_got_arg.  Set the global_got_area of each global
4411    symbol to DATA->value.  */
4412
4413 static int
4414 mips_elf_set_global_got_area (void **entryp, void *data)
4415 {
4416   struct mips_got_entry *entry;
4417   struct mips_elf_traverse_got_arg *arg;
4418
4419   entry = (struct mips_got_entry *) *entryp;
4420   arg = (struct mips_elf_traverse_got_arg *) data;
4421   if (entry->abfd != NULL
4422       && entry->symndx == -1
4423       && entry->d.h->global_got_area != GGA_NONE)
4424     entry->d.h->global_got_area = arg->value;
4425   return 1;
4426 }
4427
4428 /* A htab_traverse callback for secondary GOT entries, where DATA points
4429    to a mips_elf_traverse_got_arg.  Assign GOT indices to global entries
4430    and record the number of relocations they require.  DATA->value is
4431    the size of one GOT entry.  Set DATA->g to null on failure.  */
4432
4433 static int
4434 mips_elf_set_global_gotidx (void **entryp, void *data)
4435 {
4436   struct mips_got_entry *entry;
4437   struct mips_elf_traverse_got_arg *arg;
4438
4439   entry = (struct mips_got_entry *) *entryp;
4440   arg = (struct mips_elf_traverse_got_arg *) data;
4441   if (entry->abfd != NULL
4442       && entry->symndx == -1
4443       && entry->d.h->global_got_area != GGA_NONE)
4444     {
4445       if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->assigned_gotno))
4446         {
4447           arg->g = NULL;
4448           return 0;
4449         }
4450       arg->g->assigned_gotno += 1;
4451
4452       if (arg->info->shared
4453           || (elf_hash_table (arg->info)->dynamic_sections_created
4454               && entry->d.h->root.def_dynamic
4455               && !entry->d.h->root.def_regular))
4456         arg->g->relocs += 1;
4457     }
4458
4459   return 1;
4460 }
4461
4462 /* A htab_traverse callback for GOT entries for which DATA is the
4463    bfd_link_info.  Forbid any global symbols from having traditional
4464    lazy-binding stubs.  */
4465
4466 static int
4467 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4468 {
4469   struct bfd_link_info *info;
4470   struct mips_elf_link_hash_table *htab;
4471   struct mips_got_entry *entry;
4472
4473   entry = (struct mips_got_entry *) *entryp;
4474   info = (struct bfd_link_info *) data;
4475   htab = mips_elf_hash_table (info);
4476   BFD_ASSERT (htab != NULL);
4477
4478   if (entry->abfd != NULL
4479       && entry->symndx == -1
4480       && entry->d.h->needs_lazy_stub)
4481     {
4482       entry->d.h->needs_lazy_stub = FALSE;
4483       htab->lazy_stub_count--;
4484     }
4485
4486   return 1;
4487 }
4488
4489 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4490    the primary GOT.  */
4491 static bfd_vma
4492 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4493 {
4494   if (!g->next)
4495     return 0;
4496
4497   g = mips_elf_bfd_got (ibfd, FALSE);
4498   if (! g)
4499     return 0;
4500
4501   BFD_ASSERT (g->next);
4502
4503   g = g->next;
4504
4505   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4506     * MIPS_ELF_GOT_SIZE (abfd);
4507 }
4508
4509 /* Turn a single GOT that is too big for 16-bit addressing into
4510    a sequence of GOTs, each one 16-bit addressable.  */
4511
4512 static bfd_boolean
4513 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4514                     asection *got, bfd_size_type pages)
4515 {
4516   struct mips_elf_link_hash_table *htab;
4517   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4518   struct mips_elf_traverse_got_arg tga;
4519   struct mips_got_info *g, *gg;
4520   unsigned int assign, needed_relocs;
4521   bfd *dynobj, *ibfd;
4522
4523   dynobj = elf_hash_table (info)->dynobj;
4524   htab = mips_elf_hash_table (info);
4525   BFD_ASSERT (htab != NULL);
4526
4527   g = htab->got_info;
4528
4529   got_per_bfd_arg.obfd = abfd;
4530   got_per_bfd_arg.info = info;
4531   got_per_bfd_arg.current = NULL;
4532   got_per_bfd_arg.primary = NULL;
4533   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4534                                 / MIPS_ELF_GOT_SIZE (abfd))
4535                                - htab->reserved_gotno);
4536   got_per_bfd_arg.max_pages = pages;
4537   /* The number of globals that will be included in the primary GOT.
4538      See the calls to mips_elf_set_global_got_area below for more
4539      information.  */
4540   got_per_bfd_arg.global_count = g->global_gotno;
4541
4542   /* Try to merge the GOTs of input bfds together, as long as they
4543      don't seem to exceed the maximum GOT size, choosing one of them
4544      to be the primary GOT.  */
4545   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
4546     {
4547       gg = mips_elf_bfd_got (ibfd, FALSE);
4548       if (gg && !mips_elf_merge_got (ibfd, gg, &got_per_bfd_arg))
4549         return FALSE;
4550     }
4551
4552   /* If we do not find any suitable primary GOT, create an empty one.  */
4553   if (got_per_bfd_arg.primary == NULL)
4554     g->next = mips_elf_create_got_info (abfd);
4555   else
4556     g->next = got_per_bfd_arg.primary;
4557   g->next->next = got_per_bfd_arg.current;
4558
4559   /* GG is now the master GOT, and G is the primary GOT.  */
4560   gg = g;
4561   g = g->next;
4562
4563   /* Map the output bfd to the primary got.  That's what we're going
4564      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4565      didn't mark in check_relocs, and we want a quick way to find it.
4566      We can't just use gg->next because we're going to reverse the
4567      list.  */
4568   mips_elf_replace_bfd_got (abfd, g);
4569
4570   /* Every symbol that is referenced in a dynamic relocation must be
4571      present in the primary GOT, so arrange for them to appear after
4572      those that are actually referenced.  */
4573   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4574   g->global_gotno = gg->global_gotno;
4575
4576   tga.info = info;
4577   tga.value = GGA_RELOC_ONLY;
4578   htab_traverse (gg->got_entries, mips_elf_set_global_got_area, &tga);
4579   tga.value = GGA_NORMAL;
4580   htab_traverse (g->got_entries, mips_elf_set_global_got_area, &tga);
4581
4582   /* Now go through the GOTs assigning them offset ranges.
4583      [assigned_gotno, local_gotno[ will be set to the range of local
4584      entries in each GOT.  We can then compute the end of a GOT by
4585      adding local_gotno to global_gotno.  We reverse the list and make
4586      it circular since then we'll be able to quickly compute the
4587      beginning of a GOT, by computing the end of its predecessor.  To
4588      avoid special cases for the primary GOT, while still preserving
4589      assertions that are valid for both single- and multi-got links,
4590      we arrange for the main got struct to have the right number of
4591      global entries, but set its local_gotno such that the initial
4592      offset of the primary GOT is zero.  Remember that the primary GOT
4593      will become the last item in the circular linked list, so it
4594      points back to the master GOT.  */
4595   gg->local_gotno = -g->global_gotno;
4596   gg->global_gotno = g->global_gotno;
4597   gg->tls_gotno = 0;
4598   assign = 0;
4599   gg->next = gg;
4600
4601   do
4602     {
4603       struct mips_got_info *gn;
4604
4605       assign += htab->reserved_gotno;
4606       g->assigned_gotno = assign;
4607       g->local_gotno += assign;
4608       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4609       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4610
4611       /* Take g out of the direct list, and push it onto the reversed
4612          list that gg points to.  g->next is guaranteed to be nonnull after
4613          this operation, as required by mips_elf_initialize_tls_index. */
4614       gn = g->next;
4615       g->next = gg->next;
4616       gg->next = g;
4617
4618       /* Set up any TLS entries.  We always place the TLS entries after
4619          all non-TLS entries.  */
4620       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4621       tga.g = g;
4622       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4623       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
4624       if (!tga.g)
4625         return FALSE;
4626       BFD_ASSERT (g->tls_assigned_gotno == assign);
4627
4628       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4629       g = gn;
4630
4631       /* Forbid global symbols in every non-primary GOT from having
4632          lazy-binding stubs.  */
4633       if (g)
4634         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4635     }
4636   while (g);
4637
4638   got->size = assign * MIPS_ELF_GOT_SIZE (abfd);
4639
4640   needed_relocs = 0;
4641   for (g = gg->next; g && g->next != gg; g = g->next)
4642     {
4643       unsigned int save_assign;
4644
4645       /* Assign offsets to global GOT entries and count how many
4646          relocations they need.  */
4647       save_assign = g->assigned_gotno;
4648       g->assigned_gotno = g->local_gotno;
4649       tga.info = info;
4650       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4651       tga.g = g;
4652       htab_traverse (g->got_entries, mips_elf_set_global_gotidx, &tga);
4653       if (!tga.g)
4654         return FALSE;
4655       BFD_ASSERT (g->assigned_gotno == g->local_gotno + g->global_gotno);
4656       g->assigned_gotno = save_assign;
4657
4658       if (info->shared)
4659         {
4660           g->relocs += g->local_gotno - g->assigned_gotno;
4661           BFD_ASSERT (g->assigned_gotno == g->next->local_gotno
4662                       + g->next->global_gotno
4663                       + g->next->tls_gotno
4664                       + htab->reserved_gotno);
4665         }
4666       needed_relocs += g->relocs;
4667     }
4668   needed_relocs += g->relocs;
4669
4670   if (needed_relocs)
4671     mips_elf_allocate_dynamic_relocations (dynobj, info,
4672                                            needed_relocs);
4673
4674   return TRUE;
4675 }
4676
4677 \f
4678 /* Returns the first relocation of type r_type found, beginning with
4679    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4680
4681 static const Elf_Internal_Rela *
4682 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4683                           const Elf_Internal_Rela *relocation,
4684                           const Elf_Internal_Rela *relend)
4685 {
4686   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4687
4688   while (relocation < relend)
4689     {
4690       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4691           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4692         return relocation;
4693
4694       ++relocation;
4695     }
4696
4697   /* We didn't find it.  */
4698   return NULL;
4699 }
4700
4701 /* Return whether an input relocation is against a local symbol.  */
4702
4703 static bfd_boolean
4704 mips_elf_local_relocation_p (bfd *input_bfd,
4705                              const Elf_Internal_Rela *relocation,
4706                              asection **local_sections)
4707 {
4708   unsigned long r_symndx;
4709   Elf_Internal_Shdr *symtab_hdr;
4710   size_t extsymoff;
4711
4712   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4713   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4714   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
4715
4716   if (r_symndx < extsymoff)
4717     return TRUE;
4718   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
4719     return TRUE;
4720
4721   return FALSE;
4722 }
4723 \f
4724 /* Sign-extend VALUE, which has the indicated number of BITS.  */
4725
4726 bfd_vma
4727 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
4728 {
4729   if (value & ((bfd_vma) 1 << (bits - 1)))
4730     /* VALUE is negative.  */
4731     value |= ((bfd_vma) - 1) << bits;
4732
4733   return value;
4734 }
4735
4736 /* Return non-zero if the indicated VALUE has overflowed the maximum
4737    range expressible by a signed number with the indicated number of
4738    BITS.  */
4739
4740 static bfd_boolean
4741 mips_elf_overflow_p (bfd_vma value, int bits)
4742 {
4743   bfd_signed_vma svalue = (bfd_signed_vma) value;
4744
4745   if (svalue > (1 << (bits - 1)) - 1)
4746     /* The value is too big.  */
4747     return TRUE;
4748   else if (svalue < -(1 << (bits - 1)))
4749     /* The value is too small.  */
4750     return TRUE;
4751
4752   /* All is well.  */
4753   return FALSE;
4754 }
4755
4756 /* Calculate the %high function.  */
4757
4758 static bfd_vma
4759 mips_elf_high (bfd_vma value)
4760 {
4761   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
4762 }
4763
4764 /* Calculate the %higher function.  */
4765
4766 static bfd_vma
4767 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
4768 {
4769 #ifdef BFD64
4770   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
4771 #else
4772   abort ();
4773   return MINUS_ONE;
4774 #endif
4775 }
4776
4777 /* Calculate the %highest function.  */
4778
4779 static bfd_vma
4780 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
4781 {
4782 #ifdef BFD64
4783   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
4784 #else
4785   abort ();
4786   return MINUS_ONE;
4787 #endif
4788 }
4789 \f
4790 /* Create the .compact_rel section.  */
4791
4792 static bfd_boolean
4793 mips_elf_create_compact_rel_section
4794   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
4795 {
4796   flagword flags;
4797   register asection *s;
4798
4799   if (bfd_get_linker_section (abfd, ".compact_rel") == NULL)
4800     {
4801       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
4802                | SEC_READONLY);
4803
4804       s = bfd_make_section_anyway_with_flags (abfd, ".compact_rel", flags);
4805       if (s == NULL
4806           || ! bfd_set_section_alignment (abfd, s,
4807                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
4808         return FALSE;
4809
4810       s->size = sizeof (Elf32_External_compact_rel);
4811     }
4812
4813   return TRUE;
4814 }
4815
4816 /* Create the .got section to hold the global offset table.  */
4817
4818 static bfd_boolean
4819 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
4820 {
4821   flagword flags;
4822   register asection *s;
4823   struct elf_link_hash_entry *h;
4824   struct bfd_link_hash_entry *bh;
4825   struct mips_elf_link_hash_table *htab;
4826
4827   htab = mips_elf_hash_table (info);
4828   BFD_ASSERT (htab != NULL);
4829
4830   /* This function may be called more than once.  */
4831   if (htab->sgot)
4832     return TRUE;
4833
4834   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
4835            | SEC_LINKER_CREATED);
4836
4837   /* We have to use an alignment of 2**4 here because this is hardcoded
4838      in the function stub generation and in the linker script.  */
4839   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
4840   if (s == NULL
4841       || ! bfd_set_section_alignment (abfd, s, 4))
4842     return FALSE;
4843   htab->sgot = s;
4844
4845   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
4846      linker script because we don't want to define the symbol if we
4847      are not creating a global offset table.  */
4848   bh = NULL;
4849   if (! (_bfd_generic_link_add_one_symbol
4850          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
4851           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
4852     return FALSE;
4853
4854   h = (struct elf_link_hash_entry *) bh;
4855   h->non_elf = 0;
4856   h->def_regular = 1;
4857   h->type = STT_OBJECT;
4858   elf_hash_table (info)->hgot = h;
4859
4860   if (info->shared
4861       && ! bfd_elf_link_record_dynamic_symbol (info, h))
4862     return FALSE;
4863
4864   htab->got_info = mips_elf_create_got_info (abfd);
4865   mips_elf_section_data (s)->elf.this_hdr.sh_flags
4866     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
4867
4868   /* We also need a .got.plt section when generating PLTs.  */
4869   s = bfd_make_section_anyway_with_flags (abfd, ".got.plt",
4870                                           SEC_ALLOC | SEC_LOAD
4871                                           | SEC_HAS_CONTENTS
4872                                           | SEC_IN_MEMORY
4873                                           | SEC_LINKER_CREATED);
4874   if (s == NULL)
4875     return FALSE;
4876   htab->sgotplt = s;
4877
4878   return TRUE;
4879 }
4880 \f
4881 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
4882    __GOTT_INDEX__ symbols.  These symbols are only special for
4883    shared objects; they are not used in executables.  */
4884
4885 static bfd_boolean
4886 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
4887 {
4888   return (mips_elf_hash_table (info)->is_vxworks
4889           && info->shared
4890           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
4891               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
4892 }
4893
4894 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
4895    require an la25 stub.  See also mips_elf_local_pic_function_p,
4896    which determines whether the destination function ever requires a
4897    stub.  */
4898
4899 static bfd_boolean
4900 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type,
4901                                      bfd_boolean target_is_16_bit_code_p)
4902 {
4903   /* We specifically ignore branches and jumps from EF_PIC objects,
4904      where the onus is on the compiler or programmer to perform any
4905      necessary initialization of $25.  Sometimes such initialization
4906      is unnecessary; for example, -mno-shared functions do not use
4907      the incoming value of $25, and may therefore be called directly.  */
4908   if (PIC_OBJECT_P (input_bfd))
4909     return FALSE;
4910
4911   switch (r_type)
4912     {
4913     case R_MIPS_26:
4914     case R_MIPS_PC16:
4915     case R_MICROMIPS_26_S1:
4916     case R_MICROMIPS_PC7_S1:
4917     case R_MICROMIPS_PC10_S1:
4918     case R_MICROMIPS_PC16_S1:
4919     case R_MICROMIPS_PC23_S2:
4920       return TRUE;
4921
4922     case R_MIPS16_26:
4923       return !target_is_16_bit_code_p;
4924
4925     default:
4926       return FALSE;
4927     }
4928 }
4929 \f
4930 /* Calculate the value produced by the RELOCATION (which comes from
4931    the INPUT_BFD).  The ADDEND is the addend to use for this
4932    RELOCATION; RELOCATION->R_ADDEND is ignored.
4933
4934    The result of the relocation calculation is stored in VALUEP.
4935    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
4936    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
4937
4938    This function returns bfd_reloc_continue if the caller need take no
4939    further action regarding this relocation, bfd_reloc_notsupported if
4940    something goes dramatically wrong, bfd_reloc_overflow if an
4941    overflow occurs, and bfd_reloc_ok to indicate success.  */
4942
4943 static bfd_reloc_status_type
4944 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
4945                                asection *input_section,
4946                                struct bfd_link_info *info,
4947                                const Elf_Internal_Rela *relocation,
4948                                bfd_vma addend, reloc_howto_type *howto,
4949                                Elf_Internal_Sym *local_syms,
4950                                asection **local_sections, bfd_vma *valuep,
4951                                const char **namep,
4952                                bfd_boolean *cross_mode_jump_p,
4953                                bfd_boolean save_addend)
4954 {
4955   /* The eventual value we will return.  */
4956   bfd_vma value;
4957   /* The address of the symbol against which the relocation is
4958      occurring.  */
4959   bfd_vma symbol = 0;
4960   /* The final GP value to be used for the relocatable, executable, or
4961      shared object file being produced.  */
4962   bfd_vma gp;
4963   /* The place (section offset or address) of the storage unit being
4964      relocated.  */
4965   bfd_vma p;
4966   /* The value of GP used to create the relocatable object.  */
4967   bfd_vma gp0;
4968   /* The offset into the global offset table at which the address of
4969      the relocation entry symbol, adjusted by the addend, resides
4970      during execution.  */
4971   bfd_vma g = MINUS_ONE;
4972   /* The section in which the symbol referenced by the relocation is
4973      located.  */
4974   asection *sec = NULL;
4975   struct mips_elf_link_hash_entry *h = NULL;
4976   /* TRUE if the symbol referred to by this relocation is a local
4977      symbol.  */
4978   bfd_boolean local_p, was_local_p;
4979   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
4980   bfd_boolean gp_disp_p = FALSE;
4981   /* TRUE if the symbol referred to by this relocation is
4982      "__gnu_local_gp".  */
4983   bfd_boolean gnu_local_gp_p = FALSE;
4984   Elf_Internal_Shdr *symtab_hdr;
4985   size_t extsymoff;
4986   unsigned long r_symndx;
4987   int r_type;
4988   /* TRUE if overflow occurred during the calculation of the
4989      relocation value.  */
4990   bfd_boolean overflowed_p;
4991   /* TRUE if this relocation refers to a MIPS16 function.  */
4992   bfd_boolean target_is_16_bit_code_p = FALSE;
4993   bfd_boolean target_is_micromips_code_p = FALSE;
4994   struct mips_elf_link_hash_table *htab;
4995   bfd *dynobj;
4996
4997   dynobj = elf_hash_table (info)->dynobj;
4998   htab = mips_elf_hash_table (info);
4999   BFD_ASSERT (htab != NULL);
5000
5001   /* Parse the relocation.  */
5002   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
5003   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5004   p = (input_section->output_section->vma
5005        + input_section->output_offset
5006        + relocation->r_offset);
5007
5008   /* Assume that there will be no overflow.  */
5009   overflowed_p = FALSE;
5010
5011   /* Figure out whether or not the symbol is local, and get the offset
5012      used in the array of hash table entries.  */
5013   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
5014   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
5015                                          local_sections);
5016   was_local_p = local_p;
5017   if (! elf_bad_symtab (input_bfd))
5018     extsymoff = symtab_hdr->sh_info;
5019   else
5020     {
5021       /* The symbol table does not follow the rule that local symbols
5022          must come before globals.  */
5023       extsymoff = 0;
5024     }
5025
5026   /* Figure out the value of the symbol.  */
5027   if (local_p)
5028     {
5029       Elf_Internal_Sym *sym;
5030
5031       sym = local_syms + r_symndx;
5032       sec = local_sections[r_symndx];
5033
5034       symbol = sec->output_section->vma + sec->output_offset;
5035       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION
5036           || (sec->flags & SEC_MERGE))
5037         symbol += sym->st_value;
5038       if ((sec->flags & SEC_MERGE)
5039           && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
5040         {
5041           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
5042           addend -= symbol;
5043           addend += sec->output_section->vma + sec->output_offset;
5044         }
5045
5046       /* MIPS16/microMIPS text labels should be treated as odd.  */
5047       if (ELF_ST_IS_COMPRESSED (sym->st_other))
5048         ++symbol;
5049
5050       /* Record the name of this symbol, for our caller.  */
5051       *namep = bfd_elf_string_from_elf_section (input_bfd,
5052                                                 symtab_hdr->sh_link,
5053                                                 sym->st_name);
5054       if (*namep == '\0')
5055         *namep = bfd_section_name (input_bfd, sec);
5056
5057       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
5058       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
5059     }
5060   else
5061     {
5062       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
5063
5064       /* For global symbols we look up the symbol in the hash-table.  */
5065       h = ((struct mips_elf_link_hash_entry *)
5066            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
5067       /* Find the real hash-table entry for this symbol.  */
5068       while (h->root.root.type == bfd_link_hash_indirect
5069              || h->root.root.type == bfd_link_hash_warning)
5070         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
5071
5072       /* Record the name of this symbol, for our caller.  */
5073       *namep = h->root.root.root.string;
5074
5075       /* See if this is the special _gp_disp symbol.  Note that such a
5076          symbol must always be a global symbol.  */
5077       if (strcmp (*namep, "_gp_disp") == 0
5078           && ! NEWABI_P (input_bfd))
5079         {
5080           /* Relocations against _gp_disp are permitted only with
5081              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
5082           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
5083             return bfd_reloc_notsupported;
5084
5085           gp_disp_p = TRUE;
5086         }
5087       /* See if this is the special _gp symbol.  Note that such a
5088          symbol must always be a global symbol.  */
5089       else if (strcmp (*namep, "__gnu_local_gp") == 0)
5090         gnu_local_gp_p = TRUE;
5091
5092
5093       /* If this symbol is defined, calculate its address.  Note that
5094          _gp_disp is a magic symbol, always implicitly defined by the
5095          linker, so it's inappropriate to check to see whether or not
5096          its defined.  */
5097       else if ((h->root.root.type == bfd_link_hash_defined
5098                 || h->root.root.type == bfd_link_hash_defweak)
5099                && h->root.root.u.def.section)
5100         {
5101           sec = h->root.root.u.def.section;
5102           if (sec->output_section)
5103             symbol = (h->root.root.u.def.value
5104                       + sec->output_section->vma
5105                       + sec->output_offset);
5106           else
5107             symbol = h->root.root.u.def.value;
5108         }
5109       else if (h->root.root.type == bfd_link_hash_undefweak)
5110         /* We allow relocations against undefined weak symbols, giving
5111            it the value zero, so that you can undefined weak functions
5112            and check to see if they exist by looking at their
5113            addresses.  */
5114         symbol = 0;
5115       else if (info->unresolved_syms_in_objects == RM_IGNORE
5116                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5117         symbol = 0;
5118       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
5119                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
5120         {
5121           /* If this is a dynamic link, we should have created a
5122              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
5123              in in _bfd_mips_elf_create_dynamic_sections.
5124              Otherwise, we should define the symbol with a value of 0.
5125              FIXME: It should probably get into the symbol table
5126              somehow as well.  */
5127           BFD_ASSERT (! info->shared);
5128           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
5129           symbol = 0;
5130         }
5131       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
5132         {
5133           /* This is an optional symbol - an Irix specific extension to the
5134              ELF spec.  Ignore it for now.
5135              XXX - FIXME - there is more to the spec for OPTIONAL symbols
5136              than simply ignoring them, but we do not handle this for now.
5137              For information see the "64-bit ELF Object File Specification"
5138              which is available from here:
5139              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
5140           symbol = 0;
5141         }
5142       else if ((*info->callbacks->undefined_symbol)
5143                (info, h->root.root.root.string, input_bfd,
5144                 input_section, relocation->r_offset,
5145                 (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
5146                  || ELF_ST_VISIBILITY (h->root.other)))
5147         {
5148           return bfd_reloc_undefined;
5149         }
5150       else
5151         {
5152           return bfd_reloc_notsupported;
5153         }
5154
5155       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
5156       /* If the output section is the PLT section,
5157          then the target is not microMIPS.  */
5158       target_is_micromips_code_p = (htab->splt != sec
5159                                     && ELF_ST_IS_MICROMIPS (h->root.other));
5160     }
5161
5162   /* If this is a reference to a 16-bit function with a stub, we need
5163      to redirect the relocation to the stub unless:
5164
5165      (a) the relocation is for a MIPS16 JAL;
5166
5167      (b) the relocation is for a MIPS16 PIC call, and there are no
5168          non-MIPS16 uses of the GOT slot; or
5169
5170      (c) the section allows direct references to MIPS16 functions.  */
5171   if (r_type != R_MIPS16_26
5172       && !info->relocatable
5173       && ((h != NULL
5174            && h->fn_stub != NULL
5175            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5176           || (local_p
5177               && elf_tdata (input_bfd)->local_stubs != NULL
5178               && elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5179       && !section_allows_mips16_refs_p (input_section))
5180     {
5181       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5182          have already noticed that we were going to need the
5183          stub.  */
5184       if (local_p)
5185         {
5186           sec = elf_tdata (input_bfd)->local_stubs[r_symndx];
5187           value = 0;
5188         }
5189       else
5190         {
5191           BFD_ASSERT (h->need_fn_stub);
5192           if (h->la25_stub)
5193             {
5194               /* If a LA25 header for the stub itself exists, point to the
5195                  prepended LUI/ADDIU sequence.  */
5196               sec = h->la25_stub->stub_section;
5197               value = h->la25_stub->offset;
5198             }
5199           else
5200             {
5201               sec = h->fn_stub;
5202               value = 0;
5203             }
5204         }
5205
5206       symbol = sec->output_section->vma + sec->output_offset + value;
5207       /* The target is 16-bit, but the stub isn't.  */
5208       target_is_16_bit_code_p = FALSE;
5209     }
5210   /* If this is a 16-bit call to a 32- or 64-bit function with a stub, we
5211      need to redirect the call to the stub.  Note that we specifically
5212      exclude R_MIPS16_CALL16 from this behavior; indirect calls should
5213      use an indirect stub instead.  */
5214   else if (r_type == R_MIPS16_26 && !info->relocatable
5215            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5216                || (local_p
5217                    && elf_tdata (input_bfd)->local_call_stubs != NULL
5218                    && elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5219            && !target_is_16_bit_code_p)
5220     {
5221       if (local_p)
5222         sec = elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5223       else
5224         {
5225           /* If both call_stub and call_fp_stub are defined, we can figure
5226              out which one to use by checking which one appears in the input
5227              file.  */
5228           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5229             {
5230               asection *o;
5231
5232               sec = NULL;
5233               for (o = input_bfd->sections; o != NULL; o = o->next)
5234                 {
5235                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5236                     {
5237                       sec = h->call_fp_stub;
5238                       break;
5239                     }
5240                 }
5241               if (sec == NULL)
5242                 sec = h->call_stub;
5243             }
5244           else if (h->call_stub != NULL)
5245             sec = h->call_stub;
5246           else
5247             sec = h->call_fp_stub;
5248         }
5249
5250       BFD_ASSERT (sec->size > 0);
5251       symbol = sec->output_section->vma + sec->output_offset;
5252     }
5253   /* If this is a direct call to a PIC function, redirect to the
5254      non-PIC stub.  */
5255   else if (h != NULL && h->la25_stub
5256            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type,
5257                                                    target_is_16_bit_code_p))
5258     symbol = (h->la25_stub->stub_section->output_section->vma
5259               + h->la25_stub->stub_section->output_offset
5260               + h->la25_stub->offset);
5261
5262   /* Make sure MIPS16 and microMIPS are not used together.  */
5263   if ((r_type == R_MIPS16_26 && target_is_micromips_code_p)
5264       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5265    {
5266       (*_bfd_error_handler)
5267         (_("MIPS16 and microMIPS functions cannot call each other"));
5268       return bfd_reloc_notsupported;
5269    }
5270
5271   /* Calls from 16-bit code to 32-bit code and vice versa require the
5272      mode change.  However, we can ignore calls to undefined weak symbols,
5273      which should never be executed at runtime.  This exception is important
5274      because the assembly writer may have "known" that any definition of the
5275      symbol would be 16-bit code, and that direct jumps were therefore
5276      acceptable.  */
5277   *cross_mode_jump_p = (!info->relocatable
5278                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5279                         && ((r_type == R_MIPS16_26 && !target_is_16_bit_code_p)
5280                             || (r_type == R_MICROMIPS_26_S1
5281                                 && !target_is_micromips_code_p)
5282                             || ((r_type == R_MIPS_26 || r_type == R_MIPS_JALR)
5283                                 && (target_is_16_bit_code_p
5284                                     || target_is_micromips_code_p))));
5285
5286   local_p = (h == NULL
5287              || (h->got_only_for_calls
5288                  ? SYMBOL_CALLS_LOCAL (info, &h->root)
5289                  : SYMBOL_REFERENCES_LOCAL (info, &h->root)));
5290
5291   gp0 = _bfd_get_gp_value (input_bfd);
5292   gp = _bfd_get_gp_value (abfd);
5293   if (htab->got_info)
5294     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5295
5296   if (gnu_local_gp_p)
5297     symbol = gp;
5298
5299   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5300      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5301      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5302   if (got_page_reloc_p (r_type) && !local_p)
5303     {
5304       r_type = (micromips_reloc_p (r_type)
5305                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5306       addend = 0;
5307     }
5308
5309   /* If we haven't already determined the GOT offset, and we're going
5310      to need it, get it now.  */
5311   switch (r_type)
5312     {
5313     case R_MIPS16_CALL16:
5314     case R_MIPS16_GOT16:
5315     case R_MIPS_CALL16:
5316     case R_MIPS_GOT16:
5317     case R_MIPS_GOT_DISP:
5318     case R_MIPS_GOT_HI16:
5319     case R_MIPS_CALL_HI16:
5320     case R_MIPS_GOT_LO16:
5321     case R_MIPS_CALL_LO16:
5322     case R_MICROMIPS_CALL16:
5323     case R_MICROMIPS_GOT16:
5324     case R_MICROMIPS_GOT_DISP:
5325     case R_MICROMIPS_GOT_HI16:
5326     case R_MICROMIPS_CALL_HI16:
5327     case R_MICROMIPS_GOT_LO16:
5328     case R_MICROMIPS_CALL_LO16:
5329     case R_MIPS_TLS_GD:
5330     case R_MIPS_TLS_GOTTPREL:
5331     case R_MIPS_TLS_LDM:
5332     case R_MIPS16_TLS_GD:
5333     case R_MIPS16_TLS_GOTTPREL:
5334     case R_MIPS16_TLS_LDM:
5335     case R_MICROMIPS_TLS_GD:
5336     case R_MICROMIPS_TLS_GOTTPREL:
5337     case R_MICROMIPS_TLS_LDM:
5338       /* Find the index into the GOT where this value is located.  */
5339       if (tls_ldm_reloc_p (r_type))
5340         {
5341           g = mips_elf_local_got_index (abfd, input_bfd, info,
5342                                         0, 0, NULL, r_type);
5343           if (g == MINUS_ONE)
5344             return bfd_reloc_outofrange;
5345         }
5346       else if (!local_p)
5347         {
5348           /* On VxWorks, CALL relocations should refer to the .got.plt
5349              entry, which is initialized to point at the PLT stub.  */
5350           if (htab->is_vxworks
5351               && (call_hi16_reloc_p (r_type)
5352                   || call_lo16_reloc_p (r_type)
5353                   || call16_reloc_p (r_type)))
5354             {
5355               BFD_ASSERT (addend == 0);
5356               BFD_ASSERT (h->root.needs_plt);
5357               g = mips_elf_gotplt_index (info, &h->root);
5358             }
5359           else
5360             {
5361               BFD_ASSERT (addend == 0);
5362               g = mips_elf_global_got_index (dynobj, input_bfd,
5363                                              &h->root, r_type, info);
5364               if (!TLS_RELOC_P (r_type)
5365                   && !elf_hash_table (info)->dynamic_sections_created)
5366                 /* This is a static link.  We must initialize the GOT entry.  */
5367                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->sgot->contents + g);
5368             }
5369         }
5370       else if (!htab->is_vxworks
5371                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5372         /* The calculation below does not involve "g".  */
5373         break;
5374       else
5375         {
5376           g = mips_elf_local_got_index (abfd, input_bfd, info,
5377                                         symbol + addend, r_symndx, h, r_type);
5378           if (g == MINUS_ONE)
5379             return bfd_reloc_outofrange;
5380         }
5381
5382       /* Convert GOT indices to actual offsets.  */
5383       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5384       break;
5385     }
5386
5387   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5388      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5389   if (h != NULL && is_gott_symbol (info, &h->root))
5390     {
5391       Elf_Internal_Rela outrel;
5392       bfd_byte *loc;
5393       asection *s;
5394
5395       s = mips_elf_rel_dyn_section (info, FALSE);
5396       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5397
5398       outrel.r_offset = (input_section->output_section->vma
5399                          + input_section->output_offset
5400                          + relocation->r_offset);
5401       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5402       outrel.r_addend = addend;
5403       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5404
5405       /* If we've written this relocation for a readonly section,
5406          we need to set DF_TEXTREL again, so that we do not delete the
5407          DT_TEXTREL tag.  */
5408       if (MIPS_ELF_READONLY_SECTION (input_section))
5409         info->flags |= DF_TEXTREL;
5410
5411       *valuep = 0;
5412       return bfd_reloc_ok;
5413     }
5414
5415   /* Figure out what kind of relocation is being performed.  */
5416   switch (r_type)
5417     {
5418     case R_MIPS_NONE:
5419       return bfd_reloc_continue;
5420
5421     case R_MIPS_16:
5422       value = symbol + _bfd_mips_elf_sign_extend (addend, 16);
5423       overflowed_p = mips_elf_overflow_p (value, 16);
5424       break;
5425
5426     case R_MIPS_32:
5427     case R_MIPS_REL32:
5428     case R_MIPS_64:
5429       if ((info->shared
5430            || (htab->root.dynamic_sections_created
5431                && h != NULL
5432                && h->root.def_dynamic
5433                && !h->root.def_regular
5434                && !h->has_static_relocs))
5435           && r_symndx != STN_UNDEF
5436           && (h == NULL
5437               || h->root.root.type != bfd_link_hash_undefweak
5438               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5439           && (input_section->flags & SEC_ALLOC) != 0)
5440         {
5441           /* If we're creating a shared library, then we can't know
5442              where the symbol will end up.  So, we create a relocation
5443              record in the output, and leave the job up to the dynamic
5444              linker.  We must do the same for executable references to
5445              shared library symbols, unless we've decided to use copy
5446              relocs or PLTs instead.  */
5447           value = addend;
5448           if (!mips_elf_create_dynamic_relocation (abfd,
5449                                                    info,
5450                                                    relocation,
5451                                                    h,
5452                                                    sec,
5453                                                    symbol,
5454                                                    &value,
5455                                                    input_section))
5456             return bfd_reloc_undefined;
5457         }
5458       else
5459         {
5460           if (r_type != R_MIPS_REL32)
5461             value = symbol + addend;
5462           else
5463             value = addend;
5464         }
5465       value &= howto->dst_mask;
5466       break;
5467
5468     case R_MIPS_PC32:
5469       value = symbol + addend - p;
5470       value &= howto->dst_mask;
5471       break;
5472
5473     case R_MIPS16_26:
5474       /* The calculation for R_MIPS16_26 is just the same as for an
5475          R_MIPS_26.  It's only the storage of the relocated field into
5476          the output file that's different.  That's handled in
5477          mips_elf_perform_relocation.  So, we just fall through to the
5478          R_MIPS_26 case here.  */
5479     case R_MIPS_26:
5480     case R_MICROMIPS_26_S1:
5481       {
5482         unsigned int shift;
5483
5484         /* Make sure the target of JALX is word-aligned.  Bit 0 must be
5485            the correct ISA mode selector and bit 1 must be 0.  */
5486         if (*cross_mode_jump_p && (symbol & 3) != (r_type == R_MIPS_26))
5487           return bfd_reloc_outofrange;
5488
5489         /* Shift is 2, unusually, for microMIPS JALX.  */
5490         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5491
5492         if (was_local_p)
5493           value = addend | ((p + 4) & (0xfc000000 << shift));
5494         else
5495           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5496         value = (value + symbol) >> shift;
5497         if (!was_local_p && h->root.root.type != bfd_link_hash_undefweak)
5498           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5499         value &= howto->dst_mask;
5500       }
5501       break;
5502
5503     case R_MIPS_TLS_DTPREL_HI16:
5504     case R_MIPS16_TLS_DTPREL_HI16:
5505     case R_MICROMIPS_TLS_DTPREL_HI16:
5506       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5507                & howto->dst_mask);
5508       break;
5509
5510     case R_MIPS_TLS_DTPREL_LO16:
5511     case R_MIPS_TLS_DTPREL32:
5512     case R_MIPS_TLS_DTPREL64:
5513     case R_MIPS16_TLS_DTPREL_LO16:
5514     case R_MICROMIPS_TLS_DTPREL_LO16:
5515       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5516       break;
5517
5518     case R_MIPS_TLS_TPREL_HI16:
5519     case R_MIPS16_TLS_TPREL_HI16:
5520     case R_MICROMIPS_TLS_TPREL_HI16:
5521       value = (mips_elf_high (addend + symbol - tprel_base (info))
5522                & howto->dst_mask);
5523       break;
5524
5525     case R_MIPS_TLS_TPREL_LO16:
5526     case R_MIPS_TLS_TPREL32:
5527     case R_MIPS_TLS_TPREL64:
5528     case R_MIPS16_TLS_TPREL_LO16:
5529     case R_MICROMIPS_TLS_TPREL_LO16:
5530       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5531       break;
5532
5533     case R_MIPS_HI16:
5534     case R_MIPS16_HI16:
5535     case R_MICROMIPS_HI16:
5536       if (!gp_disp_p)
5537         {
5538           value = mips_elf_high (addend + symbol);
5539           value &= howto->dst_mask;
5540         }
5541       else
5542         {
5543           /* For MIPS16 ABI code we generate this sequence
5544                 0: li      $v0,%hi(_gp_disp)
5545                 4: addiupc $v1,%lo(_gp_disp)
5546                 8: sll     $v0,16
5547                12: addu    $v0,$v1
5548                14: move    $gp,$v0
5549              So the offsets of hi and lo relocs are the same, but the
5550              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5551              ADDIUPC clears the low two bits of the instruction address,
5552              so the base is ($t9 + 4) & ~3.  */
5553           if (r_type == R_MIPS16_HI16)
5554             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5555           /* The microMIPS .cpload sequence uses the same assembly
5556              instructions as the traditional psABI version, but the
5557              incoming $t9 has the low bit set.  */
5558           else if (r_type == R_MICROMIPS_HI16)
5559             value = mips_elf_high (addend + gp - p - 1);
5560           else
5561             value = mips_elf_high (addend + gp - p);
5562           overflowed_p = mips_elf_overflow_p (value, 16);
5563         }
5564       break;
5565
5566     case R_MIPS_LO16:
5567     case R_MIPS16_LO16:
5568     case R_MICROMIPS_LO16:
5569     case R_MICROMIPS_HI0_LO16:
5570       if (!gp_disp_p)
5571         value = (symbol + addend) & howto->dst_mask;
5572       else
5573         {
5574           /* See the comment for R_MIPS16_HI16 above for the reason
5575              for this conditional.  */
5576           if (r_type == R_MIPS16_LO16)
5577             value = addend + gp - (p & ~(bfd_vma) 0x3);
5578           else if (r_type == R_MICROMIPS_LO16
5579                    || r_type == R_MICROMIPS_HI0_LO16)
5580             value = addend + gp - p + 3;
5581           else
5582             value = addend + gp - p + 4;
5583           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5584              for overflow.  But, on, say, IRIX5, relocations against
5585              _gp_disp are normally generated from the .cpload
5586              pseudo-op.  It generates code that normally looks like
5587              this:
5588
5589                lui    $gp,%hi(_gp_disp)
5590                addiu  $gp,$gp,%lo(_gp_disp)
5591                addu   $gp,$gp,$t9
5592
5593              Here $t9 holds the address of the function being called,
5594              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5595              relocation can easily overflow in this situation, but the
5596              R_MIPS_HI16 relocation will handle the overflow.
5597              Therefore, we consider this a bug in the MIPS ABI, and do
5598              not check for overflow here.  */
5599         }
5600       break;
5601
5602     case R_MIPS_LITERAL:
5603     case R_MICROMIPS_LITERAL:
5604       /* Because we don't merge literal sections, we can handle this
5605          just like R_MIPS_GPREL16.  In the long run, we should merge
5606          shared literals, and then we will need to additional work
5607          here.  */
5608
5609       /* Fall through.  */
5610
5611     case R_MIPS16_GPREL:
5612       /* The R_MIPS16_GPREL performs the same calculation as
5613          R_MIPS_GPREL16, but stores the relocated bits in a different
5614          order.  We don't need to do anything special here; the
5615          differences are handled in mips_elf_perform_relocation.  */
5616     case R_MIPS_GPREL16:
5617     case R_MICROMIPS_GPREL7_S2:
5618     case R_MICROMIPS_GPREL16:
5619       /* Only sign-extend the addend if it was extracted from the
5620          instruction.  If the addend was separate, leave it alone,
5621          otherwise we may lose significant bits.  */
5622       if (howto->partial_inplace)
5623         addend = _bfd_mips_elf_sign_extend (addend, 16);
5624       value = symbol + addend - gp;
5625       /* If the symbol was local, any earlier relocatable links will
5626          have adjusted its addend with the gp offset, so compensate
5627          for that now.  Don't do it for symbols forced local in this
5628          link, though, since they won't have had the gp offset applied
5629          to them before.  */
5630       if (was_local_p)
5631         value += gp0;
5632       overflowed_p = mips_elf_overflow_p (value, 16);
5633       break;
5634
5635     case R_MIPS16_GOT16:
5636     case R_MIPS16_CALL16:
5637     case R_MIPS_GOT16:
5638     case R_MIPS_CALL16:
5639     case R_MICROMIPS_GOT16:
5640     case R_MICROMIPS_CALL16:
5641       /* VxWorks does not have separate local and global semantics for
5642          R_MIPS*_GOT16; every relocation evaluates to "G".  */
5643       if (!htab->is_vxworks && local_p)
5644         {
5645           value = mips_elf_got16_entry (abfd, input_bfd, info,
5646                                         symbol + addend, !was_local_p);
5647           if (value == MINUS_ONE)
5648             return bfd_reloc_outofrange;
5649           value
5650             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5651           overflowed_p = mips_elf_overflow_p (value, 16);
5652           break;
5653         }
5654
5655       /* Fall through.  */
5656
5657     case R_MIPS_TLS_GD:
5658     case R_MIPS_TLS_GOTTPREL:
5659     case R_MIPS_TLS_LDM:
5660     case R_MIPS_GOT_DISP:
5661     case R_MIPS16_TLS_GD:
5662     case R_MIPS16_TLS_GOTTPREL:
5663     case R_MIPS16_TLS_LDM:
5664     case R_MICROMIPS_TLS_GD:
5665     case R_MICROMIPS_TLS_GOTTPREL:
5666     case R_MICROMIPS_TLS_LDM:
5667     case R_MICROMIPS_GOT_DISP:
5668       value = g;
5669       overflowed_p = mips_elf_overflow_p (value, 16);
5670       break;
5671
5672     case R_MIPS_GPREL32:
5673       value = (addend + symbol + gp0 - gp);
5674       if (!save_addend)
5675         value &= howto->dst_mask;
5676       break;
5677
5678     case R_MIPS_PC16:
5679     case R_MIPS_GNU_REL16_S2:
5680       value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p;
5681       overflowed_p = mips_elf_overflow_p (value, 18);
5682       value >>= howto->rightshift;
5683       value &= howto->dst_mask;
5684       break;
5685
5686     case R_MICROMIPS_PC7_S1:
5687       value = symbol + _bfd_mips_elf_sign_extend (addend, 8) - p;
5688       overflowed_p = mips_elf_overflow_p (value, 8);
5689       value >>= howto->rightshift;
5690       value &= howto->dst_mask;
5691       break;
5692
5693     case R_MICROMIPS_PC10_S1:
5694       value = symbol + _bfd_mips_elf_sign_extend (addend, 11) - p;
5695       overflowed_p = mips_elf_overflow_p (value, 11);
5696       value >>= howto->rightshift;
5697       value &= howto->dst_mask;
5698       break;
5699
5700     case R_MICROMIPS_PC16_S1:
5701       value = symbol + _bfd_mips_elf_sign_extend (addend, 17) - p;
5702       overflowed_p = mips_elf_overflow_p (value, 17);
5703       value >>= howto->rightshift;
5704       value &= howto->dst_mask;
5705       break;
5706
5707     case R_MICROMIPS_PC23_S2:
5708       value = symbol + _bfd_mips_elf_sign_extend (addend, 25) - ((p | 3) ^ 3);
5709       overflowed_p = mips_elf_overflow_p (value, 25);
5710       value >>= howto->rightshift;
5711       value &= howto->dst_mask;
5712       break;
5713
5714     case R_MIPS_GOT_HI16:
5715     case R_MIPS_CALL_HI16:
5716     case R_MICROMIPS_GOT_HI16:
5717     case R_MICROMIPS_CALL_HI16:
5718       /* We're allowed to handle these two relocations identically.
5719          The dynamic linker is allowed to handle the CALL relocations
5720          differently by creating a lazy evaluation stub.  */
5721       value = g;
5722       value = mips_elf_high (value);
5723       value &= howto->dst_mask;
5724       break;
5725
5726     case R_MIPS_GOT_LO16:
5727     case R_MIPS_CALL_LO16:
5728     case R_MICROMIPS_GOT_LO16:
5729     case R_MICROMIPS_CALL_LO16:
5730       value = g & howto->dst_mask;
5731       break;
5732
5733     case R_MIPS_GOT_PAGE:
5734     case R_MICROMIPS_GOT_PAGE:
5735       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
5736       if (value == MINUS_ONE)
5737         return bfd_reloc_outofrange;
5738       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5739       overflowed_p = mips_elf_overflow_p (value, 16);
5740       break;
5741
5742     case R_MIPS_GOT_OFST:
5743     case R_MICROMIPS_GOT_OFST:
5744       if (local_p)
5745         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
5746       else
5747         value = addend;
5748       overflowed_p = mips_elf_overflow_p (value, 16);
5749       break;
5750
5751     case R_MIPS_SUB:
5752     case R_MICROMIPS_SUB:
5753       value = symbol - addend;
5754       value &= howto->dst_mask;
5755       break;
5756
5757     case R_MIPS_HIGHER:
5758     case R_MICROMIPS_HIGHER:
5759       value = mips_elf_higher (addend + symbol);
5760       value &= howto->dst_mask;
5761       break;
5762
5763     case R_MIPS_HIGHEST:
5764     case R_MICROMIPS_HIGHEST:
5765       value = mips_elf_highest (addend + symbol);
5766       value &= howto->dst_mask;
5767       break;
5768
5769     case R_MIPS_SCN_DISP:
5770     case R_MICROMIPS_SCN_DISP:
5771       value = symbol + addend - sec->output_offset;
5772       value &= howto->dst_mask;
5773       break;
5774
5775     case R_MIPS_JALR:
5776     case R_MICROMIPS_JALR:
5777       /* This relocation is only a hint.  In some cases, we optimize
5778          it into a bal instruction.  But we don't try to optimize
5779          when the symbol does not resolve locally.  */
5780       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
5781         return bfd_reloc_continue;
5782       value = symbol + addend;
5783       break;
5784
5785     case R_MIPS_PJUMP:
5786     case R_MIPS_GNU_VTINHERIT:
5787     case R_MIPS_GNU_VTENTRY:
5788       /* We don't do anything with these at present.  */
5789       return bfd_reloc_continue;
5790
5791     default:
5792       /* An unrecognized relocation type.  */
5793       return bfd_reloc_notsupported;
5794     }
5795
5796   /* Store the VALUE for our caller.  */
5797   *valuep = value;
5798   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
5799 }
5800
5801 /* Obtain the field relocated by RELOCATION.  */
5802
5803 static bfd_vma
5804 mips_elf_obtain_contents (reloc_howto_type *howto,
5805                           const Elf_Internal_Rela *relocation,
5806                           bfd *input_bfd, bfd_byte *contents)
5807 {
5808   bfd_vma x;
5809   bfd_byte *location = contents + relocation->r_offset;
5810
5811   /* Obtain the bytes.  */
5812   x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location);
5813
5814   return x;
5815 }
5816
5817 /* It has been determined that the result of the RELOCATION is the
5818    VALUE.  Use HOWTO to place VALUE into the output file at the
5819    appropriate position.  The SECTION is the section to which the
5820    relocation applies.
5821    CROSS_MODE_JUMP_P is true if the relocation field
5822    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5823
5824    Returns FALSE if anything goes wrong.  */
5825
5826 static bfd_boolean
5827 mips_elf_perform_relocation (struct bfd_link_info *info,
5828                              reloc_howto_type *howto,
5829                              const Elf_Internal_Rela *relocation,
5830                              bfd_vma value, bfd *input_bfd,
5831                              asection *input_section, bfd_byte *contents,
5832                              bfd_boolean cross_mode_jump_p)
5833 {
5834   bfd_vma x;
5835   bfd_byte *location;
5836   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5837
5838   /* Figure out where the relocation is occurring.  */
5839   location = contents + relocation->r_offset;
5840
5841   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
5842
5843   /* Obtain the current value.  */
5844   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
5845
5846   /* Clear the field we are setting.  */
5847   x &= ~howto->dst_mask;
5848
5849   /* Set the field.  */
5850   x |= (value & howto->dst_mask);
5851
5852   /* If required, turn JAL into JALX.  */
5853   if (cross_mode_jump_p && jal_reloc_p (r_type))
5854     {
5855       bfd_boolean ok;
5856       bfd_vma opcode = x >> 26;
5857       bfd_vma jalx_opcode;
5858
5859       /* Check to see if the opcode is already JAL or JALX.  */
5860       if (r_type == R_MIPS16_26)
5861         {
5862           ok = ((opcode == 0x6) || (opcode == 0x7));
5863           jalx_opcode = 0x7;
5864         }
5865       else if (r_type == R_MICROMIPS_26_S1)
5866         {
5867           ok = ((opcode == 0x3d) || (opcode == 0x3c));
5868           jalx_opcode = 0x3c;
5869         }
5870       else
5871         {
5872           ok = ((opcode == 0x3) || (opcode == 0x1d));
5873           jalx_opcode = 0x1d;
5874         }
5875
5876       /* If the opcode is not JAL or JALX, there's a problem.  We cannot
5877          convert J or JALS to JALX.  */
5878       if (!ok)
5879         {
5880           (*_bfd_error_handler)
5881             (_("%B: %A+0x%lx: Unsupported jump between ISA modes; consider recompiling with interlinking enabled."),
5882              input_bfd,
5883              input_section,
5884              (unsigned long) relocation->r_offset);
5885           bfd_set_error (bfd_error_bad_value);
5886           return FALSE;
5887         }
5888
5889       /* Make this the JALX opcode.  */
5890       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
5891     }
5892
5893   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
5894      range.  */
5895   if (!info->relocatable
5896       && !cross_mode_jump_p
5897       && ((JAL_TO_BAL_P (input_bfd)
5898            && r_type == R_MIPS_26
5899            && (x >> 26) == 0x3)         /* jal addr */
5900           || (JALR_TO_BAL_P (input_bfd)
5901               && r_type == R_MIPS_JALR
5902               && x == 0x0320f809)       /* jalr t9 */
5903           || (JR_TO_B_P (input_bfd)
5904               && r_type == R_MIPS_JALR
5905               && x == 0x03200008)))     /* jr t9 */
5906     {
5907       bfd_vma addr;
5908       bfd_vma dest;
5909       bfd_signed_vma off;
5910
5911       addr = (input_section->output_section->vma
5912               + input_section->output_offset
5913               + relocation->r_offset
5914               + 4);
5915       if (r_type == R_MIPS_26)
5916         dest = (value << 2) | ((addr >> 28) << 28);
5917       else
5918         dest = value;
5919       off = dest - addr;
5920       if (off <= 0x1ffff && off >= -0x20000)
5921         {
5922           if (x == 0x03200008)  /* jr t9 */
5923             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
5924           else
5925             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
5926         }
5927     }
5928
5929   /* Put the value into the output.  */
5930   bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location);
5931
5932   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !info->relocatable,
5933                                location);
5934
5935   return TRUE;
5936 }
5937 \f
5938 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
5939    is the original relocation, which is now being transformed into a
5940    dynamic relocation.  The ADDENDP is adjusted if necessary; the
5941    caller should store the result in place of the original addend.  */
5942
5943 static bfd_boolean
5944 mips_elf_create_dynamic_relocation (bfd *output_bfd,
5945                                     struct bfd_link_info *info,
5946                                     const Elf_Internal_Rela *rel,
5947                                     struct mips_elf_link_hash_entry *h,
5948                                     asection *sec, bfd_vma symbol,
5949                                     bfd_vma *addendp, asection *input_section)
5950 {
5951   Elf_Internal_Rela outrel[3];
5952   asection *sreloc;
5953   bfd *dynobj;
5954   int r_type;
5955   long indx;
5956   bfd_boolean defined_p;
5957   struct mips_elf_link_hash_table *htab;
5958
5959   htab = mips_elf_hash_table (info);
5960   BFD_ASSERT (htab != NULL);
5961
5962   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
5963   dynobj = elf_hash_table (info)->dynobj;
5964   sreloc = mips_elf_rel_dyn_section (info, FALSE);
5965   BFD_ASSERT (sreloc != NULL);
5966   BFD_ASSERT (sreloc->contents != NULL);
5967   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
5968               < sreloc->size);
5969
5970   outrel[0].r_offset =
5971     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
5972   if (ABI_64_P (output_bfd))
5973     {
5974       outrel[1].r_offset =
5975         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
5976       outrel[2].r_offset =
5977         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
5978     }
5979
5980   if (outrel[0].r_offset == MINUS_ONE)
5981     /* The relocation field has been deleted.  */
5982     return TRUE;
5983
5984   if (outrel[0].r_offset == MINUS_TWO)
5985     {
5986       /* The relocation field has been converted into a relative value of
5987          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
5988          the field to be fully relocated, so add in the symbol's value.  */
5989       *addendp += symbol;
5990       return TRUE;
5991     }
5992
5993   /* We must now calculate the dynamic symbol table index to use
5994      in the relocation.  */
5995   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
5996     {
5997       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
5998       indx = h->root.dynindx;
5999       if (SGI_COMPAT (output_bfd))
6000         defined_p = h->root.def_regular;
6001       else
6002         /* ??? glibc's ld.so just adds the final GOT entry to the
6003            relocation field.  It therefore treats relocs against
6004            defined symbols in the same way as relocs against
6005            undefined symbols.  */
6006         defined_p = FALSE;
6007     }
6008   else
6009     {
6010       if (sec != NULL && bfd_is_abs_section (sec))
6011         indx = 0;
6012       else if (sec == NULL || sec->owner == NULL)
6013         {
6014           bfd_set_error (bfd_error_bad_value);
6015           return FALSE;
6016         }
6017       else
6018         {
6019           indx = elf_section_data (sec->output_section)->dynindx;
6020           if (indx == 0)
6021             {
6022               asection *osec = htab->root.text_index_section;
6023               indx = elf_section_data (osec)->dynindx;
6024             }
6025           if (indx == 0)
6026             abort ();
6027         }
6028
6029       /* Instead of generating a relocation using the section
6030          symbol, we may as well make it a fully relative
6031          relocation.  We want to avoid generating relocations to
6032          local symbols because we used to generate them
6033          incorrectly, without adding the original symbol value,
6034          which is mandated by the ABI for section symbols.  In
6035          order to give dynamic loaders and applications time to
6036          phase out the incorrect use, we refrain from emitting
6037          section-relative relocations.  It's not like they're
6038          useful, after all.  This should be a bit more efficient
6039          as well.  */
6040       /* ??? Although this behavior is compatible with glibc's ld.so,
6041          the ABI says that relocations against STN_UNDEF should have
6042          a symbol value of 0.  Irix rld honors this, so relocations
6043          against STN_UNDEF have no effect.  */
6044       if (!SGI_COMPAT (output_bfd))
6045         indx = 0;
6046       defined_p = TRUE;
6047     }
6048
6049   /* If the relocation was previously an absolute relocation and
6050      this symbol will not be referred to by the relocation, we must
6051      adjust it by the value we give it in the dynamic symbol table.
6052      Otherwise leave the job up to the dynamic linker.  */
6053   if (defined_p && r_type != R_MIPS_REL32)
6054     *addendp += symbol;
6055
6056   if (htab->is_vxworks)
6057     /* VxWorks uses non-relative relocations for this.  */
6058     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
6059   else
6060     /* The relocation is always an REL32 relocation because we don't
6061        know where the shared library will wind up at load-time.  */
6062     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
6063                                    R_MIPS_REL32);
6064
6065   /* For strict adherence to the ABI specification, we should
6066      generate a R_MIPS_64 relocation record by itself before the
6067      _REL32/_64 record as well, such that the addend is read in as
6068      a 64-bit value (REL32 is a 32-bit relocation, after all).
6069      However, since none of the existing ELF64 MIPS dynamic
6070      loaders seems to care, we don't waste space with these
6071      artificial relocations.  If this turns out to not be true,
6072      mips_elf_allocate_dynamic_relocation() should be tweaked so
6073      as to make room for a pair of dynamic relocations per
6074      invocation if ABI_64_P, and here we should generate an
6075      additional relocation record with R_MIPS_64 by itself for a
6076      NULL symbol before this relocation record.  */
6077   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
6078                                  ABI_64_P (output_bfd)
6079                                  ? R_MIPS_64
6080                                  : R_MIPS_NONE);
6081   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
6082
6083   /* Adjust the output offset of the relocation to reference the
6084      correct location in the output file.  */
6085   outrel[0].r_offset += (input_section->output_section->vma
6086                          + input_section->output_offset);
6087   outrel[1].r_offset += (input_section->output_section->vma
6088                          + input_section->output_offset);
6089   outrel[2].r_offset += (input_section->output_section->vma
6090                          + input_section->output_offset);
6091
6092   /* Put the relocation back out.  We have to use the special
6093      relocation outputter in the 64-bit case since the 64-bit
6094      relocation format is non-standard.  */
6095   if (ABI_64_P (output_bfd))
6096     {
6097       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
6098         (output_bfd, &outrel[0],
6099          (sreloc->contents
6100           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
6101     }
6102   else if (htab->is_vxworks)
6103     {
6104       /* VxWorks uses RELA rather than REL dynamic relocations.  */
6105       outrel[0].r_addend = *addendp;
6106       bfd_elf32_swap_reloca_out
6107         (output_bfd, &outrel[0],
6108          (sreloc->contents
6109           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
6110     }
6111   else
6112     bfd_elf32_swap_reloc_out
6113       (output_bfd, &outrel[0],
6114        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
6115
6116   /* We've now added another relocation.  */
6117   ++sreloc->reloc_count;
6118
6119   /* Make sure the output section is writable.  The dynamic linker
6120      will be writing to it.  */
6121   elf_section_data (input_section->output_section)->this_hdr.sh_flags
6122     |= SHF_WRITE;
6123
6124   /* On IRIX5, make an entry of compact relocation info.  */
6125   if (IRIX_COMPAT (output_bfd) == ict_irix5)
6126     {
6127       asection *scpt = bfd_get_linker_section (dynobj, ".compact_rel");
6128       bfd_byte *cr;
6129
6130       if (scpt)
6131         {
6132           Elf32_crinfo cptrel;
6133
6134           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
6135           cptrel.vaddr = (rel->r_offset
6136                           + input_section->output_section->vma
6137                           + input_section->output_offset);
6138           if (r_type == R_MIPS_REL32)
6139             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
6140           else
6141             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
6142           mips_elf_set_cr_dist2to (cptrel, 0);
6143           cptrel.konst = *addendp;
6144
6145           cr = (scpt->contents
6146                 + sizeof (Elf32_External_compact_rel));
6147           mips_elf_set_cr_relvaddr (cptrel, 0);
6148           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
6149                                      ((Elf32_External_crinfo *) cr
6150                                       + scpt->reloc_count));
6151           ++scpt->reloc_count;
6152         }
6153     }
6154
6155   /* If we've written this relocation for a readonly section,
6156      we need to set DF_TEXTREL again, so that we do not delete the
6157      DT_TEXTREL tag.  */
6158   if (MIPS_ELF_READONLY_SECTION (input_section))
6159     info->flags |= DF_TEXTREL;
6160
6161   return TRUE;
6162 }
6163 \f
6164 /* Return the MACH for a MIPS e_flags value.  */
6165
6166 unsigned long
6167 _bfd_elf_mips_mach (flagword flags)
6168 {
6169   switch (flags & EF_MIPS_MACH)
6170     {
6171     case E_MIPS_MACH_3900:
6172       return bfd_mach_mips3900;
6173
6174     case E_MIPS_MACH_4010:
6175       return bfd_mach_mips4010;
6176
6177     case E_MIPS_MACH_4100:
6178       return bfd_mach_mips4100;
6179
6180     case E_MIPS_MACH_4111:
6181       return bfd_mach_mips4111;
6182
6183     case E_MIPS_MACH_4120:
6184       return bfd_mach_mips4120;
6185
6186     case E_MIPS_MACH_4650:
6187       return bfd_mach_mips4650;
6188
6189     case E_MIPS_MACH_5400:
6190       return bfd_mach_mips5400;
6191
6192     case E_MIPS_MACH_5500:
6193       return bfd_mach_mips5500;
6194
6195     case E_MIPS_MACH_5900:
6196       return bfd_mach_mips5900;
6197
6198     case E_MIPS_MACH_9000:
6199       return bfd_mach_mips9000;
6200
6201     case E_MIPS_MACH_SB1:
6202       return bfd_mach_mips_sb1;
6203
6204     case E_MIPS_MACH_LS2E:
6205       return bfd_mach_mips_loongson_2e;
6206
6207     case E_MIPS_MACH_LS2F:
6208       return bfd_mach_mips_loongson_2f;
6209
6210     case E_MIPS_MACH_LS3A:
6211       return bfd_mach_mips_loongson_3a;
6212
6213     case E_MIPS_MACH_OCTEON2:
6214       return bfd_mach_mips_octeon2;
6215
6216     case E_MIPS_MACH_OCTEON:
6217       return bfd_mach_mips_octeon;
6218
6219     case E_MIPS_MACH_XLR:
6220       return bfd_mach_mips_xlr;
6221
6222     default:
6223       switch (flags & EF_MIPS_ARCH)
6224         {
6225         default:
6226         case E_MIPS_ARCH_1:
6227           return bfd_mach_mips3000;
6228
6229         case E_MIPS_ARCH_2:
6230           return bfd_mach_mips6000;
6231
6232         case E_MIPS_ARCH_3:
6233           return bfd_mach_mips4000;
6234
6235         case E_MIPS_ARCH_4:
6236           return bfd_mach_mips8000;
6237
6238         case E_MIPS_ARCH_5:
6239           return bfd_mach_mips5;
6240
6241         case E_MIPS_ARCH_32:
6242           return bfd_mach_mipsisa32;
6243
6244         case E_MIPS_ARCH_64:
6245           return bfd_mach_mipsisa64;
6246
6247         case E_MIPS_ARCH_32R2:
6248           return bfd_mach_mipsisa32r2;
6249
6250         case E_MIPS_ARCH_64R2:
6251           return bfd_mach_mipsisa64r2;
6252         }
6253     }
6254
6255   return 0;
6256 }
6257
6258 /* Return printable name for ABI.  */
6259
6260 static INLINE char *
6261 elf_mips_abi_name (bfd *abfd)
6262 {
6263   flagword flags;
6264
6265   flags = elf_elfheader (abfd)->e_flags;
6266   switch (flags & EF_MIPS_ABI)
6267     {
6268     case 0:
6269       if (ABI_N32_P (abfd))
6270         return "N32";
6271       else if (ABI_64_P (abfd))
6272         return "64";
6273       else
6274         return "none";
6275     case E_MIPS_ABI_O32:
6276       return "O32";
6277     case E_MIPS_ABI_O64:
6278       return "O64";
6279     case E_MIPS_ABI_EABI32:
6280       return "EABI32";
6281     case E_MIPS_ABI_EABI64:
6282       return "EABI64";
6283     default:
6284       return "unknown abi";
6285     }
6286 }
6287 \f
6288 /* MIPS ELF uses two common sections.  One is the usual one, and the
6289    other is for small objects.  All the small objects are kept
6290    together, and then referenced via the gp pointer, which yields
6291    faster assembler code.  This is what we use for the small common
6292    section.  This approach is copied from ecoff.c.  */
6293 static asection mips_elf_scom_section;
6294 static asymbol mips_elf_scom_symbol;
6295 static asymbol *mips_elf_scom_symbol_ptr;
6296
6297 /* MIPS ELF also uses an acommon section, which represents an
6298    allocated common symbol which may be overridden by a
6299    definition in a shared library.  */
6300 static asection mips_elf_acom_section;
6301 static asymbol mips_elf_acom_symbol;
6302 static asymbol *mips_elf_acom_symbol_ptr;
6303
6304 /* This is used for both the 32-bit and the 64-bit ABI.  */
6305
6306 void
6307 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6308 {
6309   elf_symbol_type *elfsym;
6310
6311   /* Handle the special MIPS section numbers that a symbol may use.  */
6312   elfsym = (elf_symbol_type *) asym;
6313   switch (elfsym->internal_elf_sym.st_shndx)
6314     {
6315     case SHN_MIPS_ACOMMON:
6316       /* This section is used in a dynamically linked executable file.
6317          It is an allocated common section.  The dynamic linker can
6318          either resolve these symbols to something in a shared
6319          library, or it can just leave them here.  For our purposes,
6320          we can consider these symbols to be in a new section.  */
6321       if (mips_elf_acom_section.name == NULL)
6322         {
6323           /* Initialize the acommon section.  */
6324           mips_elf_acom_section.name = ".acommon";
6325           mips_elf_acom_section.flags = SEC_ALLOC;
6326           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6327           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6328           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6329           mips_elf_acom_symbol.name = ".acommon";
6330           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6331           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6332           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6333         }
6334       asym->section = &mips_elf_acom_section;
6335       break;
6336
6337     case SHN_COMMON:
6338       /* Common symbols less than the GP size are automatically
6339          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6340       if (asym->value > elf_gp_size (abfd)
6341           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6342           || IRIX_COMPAT (abfd) == ict_irix6)
6343         break;
6344       /* Fall through.  */
6345     case SHN_MIPS_SCOMMON:
6346       if (mips_elf_scom_section.name == NULL)
6347         {
6348           /* Initialize the small common section.  */
6349           mips_elf_scom_section.name = ".scommon";
6350           mips_elf_scom_section.flags = SEC_IS_COMMON;
6351           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6352           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6353           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6354           mips_elf_scom_symbol.name = ".scommon";
6355           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6356           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6357           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6358         }
6359       asym->section = &mips_elf_scom_section;
6360       asym->value = elfsym->internal_elf_sym.st_size;
6361       break;
6362
6363     case SHN_MIPS_SUNDEFINED:
6364       asym->section = bfd_und_section_ptr;
6365       break;
6366
6367     case SHN_MIPS_TEXT:
6368       {
6369         asection *section = bfd_get_section_by_name (abfd, ".text");
6370
6371         if (section != NULL)
6372           {
6373             asym->section = section;
6374             /* MIPS_TEXT is a bit special, the address is not an offset
6375                to the base of the .text section.  So substract the section
6376                base address to make it an offset.  */
6377             asym->value -= section->vma;
6378           }
6379       }
6380       break;
6381
6382     case SHN_MIPS_DATA:
6383       {
6384         asection *section = bfd_get_section_by_name (abfd, ".data");
6385
6386         if (section != NULL)
6387           {
6388             asym->section = section;
6389             /* MIPS_DATA is a bit special, the address is not an offset
6390                to the base of the .data section.  So substract the section
6391                base address to make it an offset.  */
6392             asym->value -= section->vma;
6393           }
6394       }
6395       break;
6396     }
6397
6398   /* If this is an odd-valued function symbol, assume it's a MIPS16
6399      or microMIPS one.  */
6400   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6401       && (asym->value & 1) != 0)
6402     {
6403       asym->value--;
6404       if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
6405         elfsym->internal_elf_sym.st_other
6406           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6407       else
6408         elfsym->internal_elf_sym.st_other
6409           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6410     }
6411 }
6412 \f
6413 /* Implement elf_backend_eh_frame_address_size.  This differs from
6414    the default in the way it handles EABI64.
6415
6416    EABI64 was originally specified as an LP64 ABI, and that is what
6417    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6418    historically accepted the combination of -mabi=eabi and -mlong32,
6419    and this ILP32 variation has become semi-official over time.
6420    Both forms use elf32 and have pointer-sized FDE addresses.
6421
6422    If an EABI object was generated by GCC 4.0 or above, it will have
6423    an empty .gcc_compiled_longXX section, where XX is the size of longs
6424    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6425    have no special marking to distinguish them from LP64 objects.
6426
6427    We don't want users of the official LP64 ABI to be punished for the
6428    existence of the ILP32 variant, but at the same time, we don't want
6429    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6430    We therefore take the following approach:
6431
6432       - If ABFD contains a .gcc_compiled_longXX section, use it to
6433         determine the pointer size.
6434
6435       - Otherwise check the type of the first relocation.  Assume that
6436         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
6437
6438       - Otherwise punt.
6439
6440    The second check is enough to detect LP64 objects generated by pre-4.0
6441    compilers because, in the kind of output generated by those compilers,
6442    the first relocation will be associated with either a CIE personality
6443    routine or an FDE start address.  Furthermore, the compilers never
6444    used a special (non-pointer) encoding for this ABI.
6445
6446    Checking the relocation type should also be safe because there is no
6447    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
6448    did so.  */
6449
6450 unsigned int
6451 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
6452 {
6453   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
6454     return 8;
6455   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
6456     {
6457       bfd_boolean long32_p, long64_p;
6458
6459       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
6460       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
6461       if (long32_p && long64_p)
6462         return 0;
6463       if (long32_p)
6464         return 4;
6465       if (long64_p)
6466         return 8;
6467
6468       if (sec->reloc_count > 0
6469           && elf_section_data (sec)->relocs != NULL
6470           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
6471               == R_MIPS_64))
6472         return 8;
6473
6474       return 0;
6475     }
6476   return 4;
6477 }
6478 \f
6479 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
6480    relocations against two unnamed section symbols to resolve to the
6481    same address.  For example, if we have code like:
6482
6483         lw      $4,%got_disp(.data)($gp)
6484         lw      $25,%got_disp(.text)($gp)
6485         jalr    $25
6486
6487    then the linker will resolve both relocations to .data and the program
6488    will jump there rather than to .text.
6489
6490    We can work around this problem by giving names to local section symbols.
6491    This is also what the MIPSpro tools do.  */
6492
6493 bfd_boolean
6494 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
6495 {
6496   return SGI_COMPAT (abfd);
6497 }
6498 \f
6499 /* Work over a section just before writing it out.  This routine is
6500    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
6501    sections that need the SHF_MIPS_GPREL flag by name; there has to be
6502    a better way.  */
6503
6504 bfd_boolean
6505 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
6506 {
6507   if (hdr->sh_type == SHT_MIPS_REGINFO
6508       && hdr->sh_size > 0)
6509     {
6510       bfd_byte buf[4];
6511
6512       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
6513       BFD_ASSERT (hdr->contents == NULL);
6514
6515       if (bfd_seek (abfd,
6516                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
6517                     SEEK_SET) != 0)
6518         return FALSE;
6519       H_PUT_32 (abfd, elf_gp (abfd), buf);
6520       if (bfd_bwrite (buf, 4, abfd) != 4)
6521         return FALSE;
6522     }
6523
6524   if (hdr->sh_type == SHT_MIPS_OPTIONS
6525       && hdr->bfd_section != NULL
6526       && mips_elf_section_data (hdr->bfd_section) != NULL
6527       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
6528     {
6529       bfd_byte *contents, *l, *lend;
6530
6531       /* We stored the section contents in the tdata field in the
6532          set_section_contents routine.  We save the section contents
6533          so that we don't have to read them again.
6534          At this point we know that elf_gp is set, so we can look
6535          through the section contents to see if there is an
6536          ODK_REGINFO structure.  */
6537
6538       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
6539       l = contents;
6540       lend = contents + hdr->sh_size;
6541       while (l + sizeof (Elf_External_Options) <= lend)
6542         {
6543           Elf_Internal_Options intopt;
6544
6545           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6546                                         &intopt);
6547           if (intopt.size < sizeof (Elf_External_Options))
6548             {
6549               (*_bfd_error_handler)
6550                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6551                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6552               break;
6553             }
6554           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6555             {
6556               bfd_byte buf[8];
6557
6558               if (bfd_seek (abfd,
6559                             (hdr->sh_offset
6560                              + (l - contents)
6561                              + sizeof (Elf_External_Options)
6562                              + (sizeof (Elf64_External_RegInfo) - 8)),
6563                              SEEK_SET) != 0)
6564                 return FALSE;
6565               H_PUT_64 (abfd, elf_gp (abfd), buf);
6566               if (bfd_bwrite (buf, 8, abfd) != 8)
6567                 return FALSE;
6568             }
6569           else if (intopt.kind == ODK_REGINFO)
6570             {
6571               bfd_byte buf[4];
6572
6573               if (bfd_seek (abfd,
6574                             (hdr->sh_offset
6575                              + (l - contents)
6576                              + sizeof (Elf_External_Options)
6577                              + (sizeof (Elf32_External_RegInfo) - 4)),
6578                             SEEK_SET) != 0)
6579                 return FALSE;
6580               H_PUT_32 (abfd, elf_gp (abfd), buf);
6581               if (bfd_bwrite (buf, 4, abfd) != 4)
6582                 return FALSE;
6583             }
6584           l += intopt.size;
6585         }
6586     }
6587
6588   if (hdr->bfd_section != NULL)
6589     {
6590       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
6591
6592       /* .sbss is not handled specially here because the GNU/Linux
6593          prelinker can convert .sbss from NOBITS to PROGBITS and
6594          changing it back to NOBITS breaks the binary.  The entry in
6595          _bfd_mips_elf_special_sections will ensure the correct flags
6596          are set on .sbss if BFD creates it without reading it from an
6597          input file, and without special handling here the flags set
6598          on it in an input file will be followed.  */
6599       if (strcmp (name, ".sdata") == 0
6600           || strcmp (name, ".lit8") == 0
6601           || strcmp (name, ".lit4") == 0)
6602         {
6603           hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
6604           hdr->sh_type = SHT_PROGBITS;
6605         }
6606       else if (strcmp (name, ".srdata") == 0)
6607         {
6608           hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
6609           hdr->sh_type = SHT_PROGBITS;
6610         }
6611       else if (strcmp (name, ".compact_rel") == 0)
6612         {
6613           hdr->sh_flags = 0;
6614           hdr->sh_type = SHT_PROGBITS;
6615         }
6616       else if (strcmp (name, ".rtproc") == 0)
6617         {
6618           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
6619             {
6620               unsigned int adjust;
6621
6622               adjust = hdr->sh_size % hdr->sh_addralign;
6623               if (adjust != 0)
6624                 hdr->sh_size += hdr->sh_addralign - adjust;
6625             }
6626         }
6627     }
6628
6629   return TRUE;
6630 }
6631
6632 /* Handle a MIPS specific section when reading an object file.  This
6633    is called when elfcode.h finds a section with an unknown type.
6634    This routine supports both the 32-bit and 64-bit ELF ABI.
6635
6636    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
6637    how to.  */
6638
6639 bfd_boolean
6640 _bfd_mips_elf_section_from_shdr (bfd *abfd,
6641                                  Elf_Internal_Shdr *hdr,
6642                                  const char *name,
6643                                  int shindex)
6644 {
6645   flagword flags = 0;
6646
6647   /* There ought to be a place to keep ELF backend specific flags, but
6648      at the moment there isn't one.  We just keep track of the
6649      sections by their name, instead.  Fortunately, the ABI gives
6650      suggested names for all the MIPS specific sections, so we will
6651      probably get away with this.  */
6652   switch (hdr->sh_type)
6653     {
6654     case SHT_MIPS_LIBLIST:
6655       if (strcmp (name, ".liblist") != 0)
6656         return FALSE;
6657       break;
6658     case SHT_MIPS_MSYM:
6659       if (strcmp (name, ".msym") != 0)
6660         return FALSE;
6661       break;
6662     case SHT_MIPS_CONFLICT:
6663       if (strcmp (name, ".conflict") != 0)
6664         return FALSE;
6665       break;
6666     case SHT_MIPS_GPTAB:
6667       if (! CONST_STRNEQ (name, ".gptab."))
6668         return FALSE;
6669       break;
6670     case SHT_MIPS_UCODE:
6671       if (strcmp (name, ".ucode") != 0)
6672         return FALSE;
6673       break;
6674     case SHT_MIPS_DEBUG:
6675       if (strcmp (name, ".mdebug") != 0)
6676         return FALSE;
6677       flags = SEC_DEBUGGING;
6678       break;
6679     case SHT_MIPS_REGINFO:
6680       if (strcmp (name, ".reginfo") != 0
6681           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
6682         return FALSE;
6683       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6684       break;
6685     case SHT_MIPS_IFACE:
6686       if (strcmp (name, ".MIPS.interfaces") != 0)
6687         return FALSE;
6688       break;
6689     case SHT_MIPS_CONTENT:
6690       if (! CONST_STRNEQ (name, ".MIPS.content"))
6691         return FALSE;
6692       break;
6693     case SHT_MIPS_OPTIONS:
6694       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6695         return FALSE;
6696       break;
6697     case SHT_MIPS_DWARF:
6698       if (! CONST_STRNEQ (name, ".debug_")
6699           && ! CONST_STRNEQ (name, ".zdebug_"))
6700         return FALSE;
6701       break;
6702     case SHT_MIPS_SYMBOL_LIB:
6703       if (strcmp (name, ".MIPS.symlib") != 0)
6704         return FALSE;
6705       break;
6706     case SHT_MIPS_EVENTS:
6707       if (! CONST_STRNEQ (name, ".MIPS.events")
6708           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
6709         return FALSE;
6710       break;
6711     default:
6712       break;
6713     }
6714
6715   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
6716     return FALSE;
6717
6718   if (flags)
6719     {
6720       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
6721                                    (bfd_get_section_flags (abfd,
6722                                                            hdr->bfd_section)
6723                                     | flags)))
6724         return FALSE;
6725     }
6726
6727   /* FIXME: We should record sh_info for a .gptab section.  */
6728
6729   /* For a .reginfo section, set the gp value in the tdata information
6730      from the contents of this section.  We need the gp value while
6731      processing relocs, so we just get it now.  The .reginfo section
6732      is not used in the 64-bit MIPS ELF ABI.  */
6733   if (hdr->sh_type == SHT_MIPS_REGINFO)
6734     {
6735       Elf32_External_RegInfo ext;
6736       Elf32_RegInfo s;
6737
6738       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
6739                                       &ext, 0, sizeof ext))
6740         return FALSE;
6741       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
6742       elf_gp (abfd) = s.ri_gp_value;
6743     }
6744
6745   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
6746      set the gp value based on what we find.  We may see both
6747      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
6748      they should agree.  */
6749   if (hdr->sh_type == SHT_MIPS_OPTIONS)
6750     {
6751       bfd_byte *contents, *l, *lend;
6752
6753       contents = bfd_malloc (hdr->sh_size);
6754       if (contents == NULL)
6755         return FALSE;
6756       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
6757                                       0, hdr->sh_size))
6758         {
6759           free (contents);
6760           return FALSE;
6761         }
6762       l = contents;
6763       lend = contents + hdr->sh_size;
6764       while (l + sizeof (Elf_External_Options) <= lend)
6765         {
6766           Elf_Internal_Options intopt;
6767
6768           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6769                                         &intopt);
6770           if (intopt.size < sizeof (Elf_External_Options))
6771             {
6772               (*_bfd_error_handler)
6773                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6774                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6775               break;
6776             }
6777           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6778             {
6779               Elf64_Internal_RegInfo intreg;
6780
6781               bfd_mips_elf64_swap_reginfo_in
6782                 (abfd,
6783                  ((Elf64_External_RegInfo *)
6784                   (l + sizeof (Elf_External_Options))),
6785                  &intreg);
6786               elf_gp (abfd) = intreg.ri_gp_value;
6787             }
6788           else if (intopt.kind == ODK_REGINFO)
6789             {
6790               Elf32_RegInfo intreg;
6791
6792               bfd_mips_elf32_swap_reginfo_in
6793                 (abfd,
6794                  ((Elf32_External_RegInfo *)
6795                   (l + sizeof (Elf_External_Options))),
6796                  &intreg);
6797               elf_gp (abfd) = intreg.ri_gp_value;
6798             }
6799           l += intopt.size;
6800         }
6801       free (contents);
6802     }
6803
6804   return TRUE;
6805 }
6806
6807 /* Set the correct type for a MIPS ELF section.  We do this by the
6808    section name, which is a hack, but ought to work.  This routine is
6809    used by both the 32-bit and the 64-bit ABI.  */
6810
6811 bfd_boolean
6812 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
6813 {
6814   const char *name = bfd_get_section_name (abfd, sec);
6815
6816   if (strcmp (name, ".liblist") == 0)
6817     {
6818       hdr->sh_type = SHT_MIPS_LIBLIST;
6819       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
6820       /* The sh_link field is set in final_write_processing.  */
6821     }
6822   else if (strcmp (name, ".conflict") == 0)
6823     hdr->sh_type = SHT_MIPS_CONFLICT;
6824   else if (CONST_STRNEQ (name, ".gptab."))
6825     {
6826       hdr->sh_type = SHT_MIPS_GPTAB;
6827       hdr->sh_entsize = sizeof (Elf32_External_gptab);
6828       /* The sh_info field is set in final_write_processing.  */
6829     }
6830   else if (strcmp (name, ".ucode") == 0)
6831     hdr->sh_type = SHT_MIPS_UCODE;
6832   else if (strcmp (name, ".mdebug") == 0)
6833     {
6834       hdr->sh_type = SHT_MIPS_DEBUG;
6835       /* In a shared object on IRIX 5.3, the .mdebug section has an
6836          entsize of 0.  FIXME: Does this matter?  */
6837       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
6838         hdr->sh_entsize = 0;
6839       else
6840         hdr->sh_entsize = 1;
6841     }
6842   else if (strcmp (name, ".reginfo") == 0)
6843     {
6844       hdr->sh_type = SHT_MIPS_REGINFO;
6845       /* In a shared object on IRIX 5.3, the .reginfo section has an
6846          entsize of 0x18.  FIXME: Does this matter?  */
6847       if (SGI_COMPAT (abfd))
6848         {
6849           if ((abfd->flags & DYNAMIC) != 0)
6850             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6851           else
6852             hdr->sh_entsize = 1;
6853         }
6854       else
6855         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6856     }
6857   else if (SGI_COMPAT (abfd)
6858            && (strcmp (name, ".hash") == 0
6859                || strcmp (name, ".dynamic") == 0
6860                || strcmp (name, ".dynstr") == 0))
6861     {
6862       if (SGI_COMPAT (abfd))
6863         hdr->sh_entsize = 0;
6864 #if 0
6865       /* This isn't how the IRIX6 linker behaves.  */
6866       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
6867 #endif
6868     }
6869   else if (strcmp (name, ".got") == 0
6870            || strcmp (name, ".srdata") == 0
6871            || strcmp (name, ".sdata") == 0
6872            || strcmp (name, ".sbss") == 0
6873            || strcmp (name, ".lit4") == 0
6874            || strcmp (name, ".lit8") == 0)
6875     hdr->sh_flags |= SHF_MIPS_GPREL;
6876   else if (strcmp (name, ".MIPS.interfaces") == 0)
6877     {
6878       hdr->sh_type = SHT_MIPS_IFACE;
6879       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6880     }
6881   else if (CONST_STRNEQ (name, ".MIPS.content"))
6882     {
6883       hdr->sh_type = SHT_MIPS_CONTENT;
6884       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6885       /* The sh_info field is set in final_write_processing.  */
6886     }
6887   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6888     {
6889       hdr->sh_type = SHT_MIPS_OPTIONS;
6890       hdr->sh_entsize = 1;
6891       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6892     }
6893   else if (CONST_STRNEQ (name, ".debug_")
6894            || CONST_STRNEQ (name, ".zdebug_"))
6895     {
6896       hdr->sh_type = SHT_MIPS_DWARF;
6897
6898       /* Irix facilities such as libexc expect a single .debug_frame
6899          per executable, the system ones have NOSTRIP set and the linker
6900          doesn't merge sections with different flags so ...  */
6901       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
6902         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6903     }
6904   else if (strcmp (name, ".MIPS.symlib") == 0)
6905     {
6906       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
6907       /* The sh_link and sh_info fields are set in
6908          final_write_processing.  */
6909     }
6910   else if (CONST_STRNEQ (name, ".MIPS.events")
6911            || CONST_STRNEQ (name, ".MIPS.post_rel"))
6912     {
6913       hdr->sh_type = SHT_MIPS_EVENTS;
6914       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6915       /* The sh_link field is set in final_write_processing.  */
6916     }
6917   else if (strcmp (name, ".msym") == 0)
6918     {
6919       hdr->sh_type = SHT_MIPS_MSYM;
6920       hdr->sh_flags |= SHF_ALLOC;
6921       hdr->sh_entsize = 8;
6922     }
6923
6924   /* The generic elf_fake_sections will set up REL_HDR using the default
6925    kind of relocations.  We used to set up a second header for the
6926    non-default kind of relocations here, but only NewABI would use
6927    these, and the IRIX ld doesn't like resulting empty RELA sections.
6928    Thus we create those header only on demand now.  */
6929
6930   return TRUE;
6931 }
6932
6933 /* Given a BFD section, try to locate the corresponding ELF section
6934    index.  This is used by both the 32-bit and the 64-bit ABI.
6935    Actually, it's not clear to me that the 64-bit ABI supports these,
6936    but for non-PIC objects we will certainly want support for at least
6937    the .scommon section.  */
6938
6939 bfd_boolean
6940 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
6941                                         asection *sec, int *retval)
6942 {
6943   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
6944     {
6945       *retval = SHN_MIPS_SCOMMON;
6946       return TRUE;
6947     }
6948   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
6949     {
6950       *retval = SHN_MIPS_ACOMMON;
6951       return TRUE;
6952     }
6953   return FALSE;
6954 }
6955 \f
6956 /* Hook called by the linker routine which adds symbols from an object
6957    file.  We must handle the special MIPS section numbers here.  */
6958
6959 bfd_boolean
6960 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
6961                                Elf_Internal_Sym *sym, const char **namep,
6962                                flagword *flagsp ATTRIBUTE_UNUSED,
6963                                asection **secp, bfd_vma *valp)
6964 {
6965   if (SGI_COMPAT (abfd)
6966       && (abfd->flags & DYNAMIC) != 0
6967       && strcmp (*namep, "_rld_new_interface") == 0)
6968     {
6969       /* Skip IRIX5 rld entry name.  */
6970       *namep = NULL;
6971       return TRUE;
6972     }
6973
6974   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
6975      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
6976      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
6977      a magic symbol resolved by the linker, we ignore this bogus definition
6978      of _gp_disp.  New ABI objects do not suffer from this problem so this
6979      is not done for them. */
6980   if (!NEWABI_P(abfd)
6981       && (sym->st_shndx == SHN_ABS)
6982       && (strcmp (*namep, "_gp_disp") == 0))
6983     {
6984       *namep = NULL;
6985       return TRUE;
6986     }
6987
6988   switch (sym->st_shndx)
6989     {
6990     case SHN_COMMON:
6991       /* Common symbols less than the GP size are automatically
6992          treated as SHN_MIPS_SCOMMON symbols.  */
6993       if (sym->st_size > elf_gp_size (abfd)
6994           || ELF_ST_TYPE (sym->st_info) == STT_TLS
6995           || IRIX_COMPAT (abfd) == ict_irix6)
6996         break;
6997       /* Fall through.  */
6998     case SHN_MIPS_SCOMMON:
6999       *secp = bfd_make_section_old_way (abfd, ".scommon");
7000       (*secp)->flags |= SEC_IS_COMMON;
7001       *valp = sym->st_size;
7002       break;
7003
7004     case SHN_MIPS_TEXT:
7005       /* This section is used in a shared object.  */
7006       if (elf_tdata (abfd)->elf_text_section == NULL)
7007         {
7008           asymbol *elf_text_symbol;
7009           asection *elf_text_section;
7010           bfd_size_type amt = sizeof (asection);
7011
7012           elf_text_section = bfd_zalloc (abfd, amt);
7013           if (elf_text_section == NULL)
7014             return FALSE;
7015
7016           amt = sizeof (asymbol);
7017           elf_text_symbol = bfd_zalloc (abfd, amt);
7018           if (elf_text_symbol == NULL)
7019             return FALSE;
7020
7021           /* Initialize the section.  */
7022
7023           elf_tdata (abfd)->elf_text_section = elf_text_section;
7024           elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
7025
7026           elf_text_section->symbol = elf_text_symbol;
7027           elf_text_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_text_symbol;
7028
7029           elf_text_section->name = ".text";
7030           elf_text_section->flags = SEC_NO_FLAGS;
7031           elf_text_section->output_section = NULL;
7032           elf_text_section->owner = abfd;
7033           elf_text_symbol->name = ".text";
7034           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7035           elf_text_symbol->section = elf_text_section;
7036         }
7037       /* This code used to do *secp = bfd_und_section_ptr if
7038          info->shared.  I don't know why, and that doesn't make sense,
7039          so I took it out.  */
7040       *secp = elf_tdata (abfd)->elf_text_section;
7041       break;
7042
7043     case SHN_MIPS_ACOMMON:
7044       /* Fall through. XXX Can we treat this as allocated data?  */
7045     case SHN_MIPS_DATA:
7046       /* This section is used in a shared object.  */
7047       if (elf_tdata (abfd)->elf_data_section == NULL)
7048         {
7049           asymbol *elf_data_symbol;
7050           asection *elf_data_section;
7051           bfd_size_type amt = sizeof (asection);
7052
7053           elf_data_section = bfd_zalloc (abfd, amt);
7054           if (elf_data_section == NULL)
7055             return FALSE;
7056
7057           amt = sizeof (asymbol);
7058           elf_data_symbol = bfd_zalloc (abfd, amt);
7059           if (elf_data_symbol == NULL)
7060             return FALSE;
7061
7062           /* Initialize the section.  */
7063
7064           elf_tdata (abfd)->elf_data_section = elf_data_section;
7065           elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
7066
7067           elf_data_section->symbol = elf_data_symbol;
7068           elf_data_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_data_symbol;
7069
7070           elf_data_section->name = ".data";
7071           elf_data_section->flags = SEC_NO_FLAGS;
7072           elf_data_section->output_section = NULL;
7073           elf_data_section->owner = abfd;
7074           elf_data_symbol->name = ".data";
7075           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7076           elf_data_symbol->section = elf_data_section;
7077         }
7078       /* This code used to do *secp = bfd_und_section_ptr if
7079          info->shared.  I don't know why, and that doesn't make sense,
7080          so I took it out.  */
7081       *secp = elf_tdata (abfd)->elf_data_section;
7082       break;
7083
7084     case SHN_MIPS_SUNDEFINED:
7085       *secp = bfd_und_section_ptr;
7086       break;
7087     }
7088
7089   if (SGI_COMPAT (abfd)
7090       && ! info->shared
7091       && info->output_bfd->xvec == abfd->xvec
7092       && strcmp (*namep, "__rld_obj_head") == 0)
7093     {
7094       struct elf_link_hash_entry *h;
7095       struct bfd_link_hash_entry *bh;
7096
7097       /* Mark __rld_obj_head as dynamic.  */
7098       bh = NULL;
7099       if (! (_bfd_generic_link_add_one_symbol
7100              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
7101               get_elf_backend_data (abfd)->collect, &bh)))
7102         return FALSE;
7103
7104       h = (struct elf_link_hash_entry *) bh;
7105       h->non_elf = 0;
7106       h->def_regular = 1;
7107       h->type = STT_OBJECT;
7108
7109       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7110         return FALSE;
7111
7112       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
7113       mips_elf_hash_table (info)->rld_symbol = h;
7114     }
7115
7116   /* If this is a mips16 text symbol, add 1 to the value to make it
7117      odd.  This will cause something like .word SYM to come up with
7118      the right value when it is loaded into the PC.  */
7119   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7120     ++*valp;
7121
7122   return TRUE;
7123 }
7124
7125 /* This hook function is called before the linker writes out a global
7126    symbol.  We mark symbols as small common if appropriate.  This is
7127    also where we undo the increment of the value for a mips16 symbol.  */
7128
7129 int
7130 _bfd_mips_elf_link_output_symbol_hook
7131   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
7132    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
7133    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
7134 {
7135   /* If we see a common symbol, which implies a relocatable link, then
7136      if a symbol was small common in an input file, mark it as small
7137      common in the output file.  */
7138   if (sym->st_shndx == SHN_COMMON
7139       && strcmp (input_sec->name, ".scommon") == 0)
7140     sym->st_shndx = SHN_MIPS_SCOMMON;
7141
7142   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7143     sym->st_value &= ~1;
7144
7145   return 1;
7146 }
7147 \f
7148 /* Functions for the dynamic linker.  */
7149
7150 /* Create dynamic sections when linking against a dynamic object.  */
7151
7152 bfd_boolean
7153 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
7154 {
7155   struct elf_link_hash_entry *h;
7156   struct bfd_link_hash_entry *bh;
7157   flagword flags;
7158   register asection *s;
7159   const char * const *namep;
7160   struct mips_elf_link_hash_table *htab;
7161
7162   htab = mips_elf_hash_table (info);
7163   BFD_ASSERT (htab != NULL);
7164
7165   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
7166            | SEC_LINKER_CREATED | SEC_READONLY);
7167
7168   /* The psABI requires a read-only .dynamic section, but the VxWorks
7169      EABI doesn't.  */
7170   if (!htab->is_vxworks)
7171     {
7172       s = bfd_get_linker_section (abfd, ".dynamic");
7173       if (s != NULL)
7174         {
7175           if (! bfd_set_section_flags (abfd, s, flags))
7176             return FALSE;
7177         }
7178     }
7179
7180   /* We need to create .got section.  */
7181   if (!mips_elf_create_got_section (abfd, info))
7182     return FALSE;
7183
7184   if (! mips_elf_rel_dyn_section (info, TRUE))
7185     return FALSE;
7186
7187   /* Create .stub section.  */
7188   s = bfd_make_section_anyway_with_flags (abfd,
7189                                           MIPS_ELF_STUB_SECTION_NAME (abfd),
7190                                           flags | SEC_CODE);
7191   if (s == NULL
7192       || ! bfd_set_section_alignment (abfd, s,
7193                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7194     return FALSE;
7195   htab->sstubs = s;
7196
7197   if (!mips_elf_hash_table (info)->use_rld_obj_head
7198       && !info->shared
7199       && bfd_get_linker_section (abfd, ".rld_map") == NULL)
7200     {
7201       s = bfd_make_section_anyway_with_flags (abfd, ".rld_map",
7202                                               flags &~ (flagword) SEC_READONLY);
7203       if (s == NULL
7204           || ! bfd_set_section_alignment (abfd, s,
7205                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7206         return FALSE;
7207     }
7208
7209   /* On IRIX5, we adjust add some additional symbols and change the
7210      alignments of several sections.  There is no ABI documentation
7211      indicating that this is necessary on IRIX6, nor any evidence that
7212      the linker takes such action.  */
7213   if (IRIX_COMPAT (abfd) == ict_irix5)
7214     {
7215       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7216         {
7217           bh = NULL;
7218           if (! (_bfd_generic_link_add_one_symbol
7219                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7220                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7221             return FALSE;
7222
7223           h = (struct elf_link_hash_entry *) bh;
7224           h->non_elf = 0;
7225           h->def_regular = 1;
7226           h->type = STT_SECTION;
7227
7228           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7229             return FALSE;
7230         }
7231
7232       /* We need to create a .compact_rel section.  */
7233       if (SGI_COMPAT (abfd))
7234         {
7235           if (!mips_elf_create_compact_rel_section (abfd, info))
7236             return FALSE;
7237         }
7238
7239       /* Change alignments of some sections.  */
7240       s = bfd_get_linker_section (abfd, ".hash");
7241       if (s != NULL)
7242         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7243       s = bfd_get_linker_section (abfd, ".dynsym");
7244       if (s != NULL)
7245         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7246       s = bfd_get_linker_section (abfd, ".dynstr");
7247       if (s != NULL)
7248         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7249       /* ??? */
7250       s = bfd_get_section_by_name (abfd, ".reginfo");
7251       if (s != NULL)
7252         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7253       s = bfd_get_linker_section (abfd, ".dynamic");
7254       if (s != NULL)
7255         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7256     }
7257
7258   if (!info->shared)
7259     {
7260       const char *name;
7261
7262       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7263       bh = NULL;
7264       if (!(_bfd_generic_link_add_one_symbol
7265             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7266              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7267         return FALSE;
7268
7269       h = (struct elf_link_hash_entry *) bh;
7270       h->non_elf = 0;
7271       h->def_regular = 1;
7272       h->type = STT_SECTION;
7273
7274       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7275         return FALSE;
7276
7277       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7278         {
7279           /* __rld_map is a four byte word located in the .data section
7280              and is filled in by the rtld to contain a pointer to
7281              the _r_debug structure. Its symbol value will be set in
7282              _bfd_mips_elf_finish_dynamic_symbol.  */
7283           s = bfd_get_linker_section (abfd, ".rld_map");
7284           BFD_ASSERT (s != NULL);
7285
7286           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7287           bh = NULL;
7288           if (!(_bfd_generic_link_add_one_symbol
7289                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7290                  get_elf_backend_data (abfd)->collect, &bh)))
7291             return FALSE;
7292
7293           h = (struct elf_link_hash_entry *) bh;
7294           h->non_elf = 0;
7295           h->def_regular = 1;
7296           h->type = STT_OBJECT;
7297
7298           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7299             return FALSE;
7300           mips_elf_hash_table (info)->rld_symbol = h;
7301         }
7302     }
7303
7304   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7305      Also create the _PROCEDURE_LINKAGE_TABLE symbol.  */
7306   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7307     return FALSE;
7308
7309   /* Cache the sections created above.  */
7310   htab->splt = bfd_get_linker_section (abfd, ".plt");
7311   htab->sdynbss = bfd_get_linker_section (abfd, ".dynbss");
7312   if (htab->is_vxworks)
7313     {
7314       htab->srelbss = bfd_get_linker_section (abfd, ".rela.bss");
7315       htab->srelplt = bfd_get_linker_section (abfd, ".rela.plt");
7316     }
7317   else
7318     htab->srelplt = bfd_get_linker_section (abfd, ".rel.plt");
7319   if (!htab->sdynbss
7320       || (htab->is_vxworks && !htab->srelbss && !info->shared)
7321       || !htab->srelplt
7322       || !htab->splt)
7323     abort ();
7324
7325   if (htab->is_vxworks)
7326     {
7327       /* Do the usual VxWorks handling.  */
7328       if (!elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7329         return FALSE;
7330
7331       /* Work out the PLT sizes.  */
7332       if (info->shared)
7333         {
7334           htab->plt_header_size
7335             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
7336           htab->plt_entry_size
7337             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
7338         }
7339       else
7340         {
7341           htab->plt_header_size
7342             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
7343           htab->plt_entry_size
7344             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
7345         }
7346     }
7347   else if (!info->shared)
7348     {
7349       /* All variants of the plt0 entry are the same size.  */
7350       htab->plt_header_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
7351       htab->plt_entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
7352     }
7353
7354   return TRUE;
7355 }
7356 \f
7357 /* Return true if relocation REL against section SEC is a REL rather than
7358    RELA relocation.  RELOCS is the first relocation in the section and
7359    ABFD is the bfd that contains SEC.  */
7360
7361 static bfd_boolean
7362 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7363                            const Elf_Internal_Rela *relocs,
7364                            const Elf_Internal_Rela *rel)
7365 {
7366   Elf_Internal_Shdr *rel_hdr;
7367   const struct elf_backend_data *bed;
7368
7369   /* To determine which flavor of relocation this is, we depend on the
7370      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7371   rel_hdr = elf_section_data (sec)->rel.hdr;
7372   if (rel_hdr == NULL)
7373     return FALSE;
7374   bed = get_elf_backend_data (abfd);
7375   return ((size_t) (rel - relocs)
7376           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7377 }
7378
7379 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7380    HOWTO is the relocation's howto and CONTENTS points to the contents
7381    of the section that REL is against.  */
7382
7383 static bfd_vma
7384 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7385                           reloc_howto_type *howto, bfd_byte *contents)
7386 {
7387   bfd_byte *location;
7388   unsigned int r_type;
7389   bfd_vma addend;
7390
7391   r_type = ELF_R_TYPE (abfd, rel->r_info);
7392   location = contents + rel->r_offset;
7393
7394   /* Get the addend, which is stored in the input file.  */
7395   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7396   addend = mips_elf_obtain_contents (howto, rel, abfd, contents);
7397   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7398
7399   return addend & howto->src_mask;
7400 }
7401
7402 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7403    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7404    and update *ADDEND with the final addend.  Return true on success
7405    or false if the LO16 could not be found.  RELEND is the exclusive
7406    upper bound on the relocations for REL's section.  */
7407
7408 static bfd_boolean
7409 mips_elf_add_lo16_rel_addend (bfd *abfd,
7410                               const Elf_Internal_Rela *rel,
7411                               const Elf_Internal_Rela *relend,
7412                               bfd_byte *contents, bfd_vma *addend)
7413 {
7414   unsigned int r_type, lo16_type;
7415   const Elf_Internal_Rela *lo16_relocation;
7416   reloc_howto_type *lo16_howto;
7417   bfd_vma l;
7418
7419   r_type = ELF_R_TYPE (abfd, rel->r_info);
7420   if (mips16_reloc_p (r_type))
7421     lo16_type = R_MIPS16_LO16;
7422   else if (micromips_reloc_p (r_type))
7423     lo16_type = R_MICROMIPS_LO16;
7424   else
7425     lo16_type = R_MIPS_LO16;
7426
7427   /* The combined value is the sum of the HI16 addend, left-shifted by
7428      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7429      code does a `lui' of the HI16 value, and then an `addiu' of the
7430      LO16 value.)
7431
7432      Scan ahead to find a matching LO16 relocation.
7433
7434      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7435      be immediately following.  However, for the IRIX6 ABI, the next
7436      relocation may be a composed relocation consisting of several
7437      relocations for the same address.  In that case, the R_MIPS_LO16
7438      relocation may occur as one of these.  We permit a similar
7439      extension in general, as that is useful for GCC.
7440
7441      In some cases GCC dead code elimination removes the LO16 but keeps
7442      the corresponding HI16.  This is strictly speaking a violation of
7443      the ABI but not immediately harmful.  */
7444   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
7445   if (lo16_relocation == NULL)
7446     return FALSE;
7447
7448   /* Obtain the addend kept there.  */
7449   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
7450   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
7451
7452   l <<= lo16_howto->rightshift;
7453   l = _bfd_mips_elf_sign_extend (l, 16);
7454
7455   *addend <<= 16;
7456   *addend += l;
7457   return TRUE;
7458 }
7459
7460 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
7461    store the contents in *CONTENTS on success.  Assume that *CONTENTS
7462    already holds the contents if it is nonull on entry.  */
7463
7464 static bfd_boolean
7465 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
7466 {
7467   if (*contents)
7468     return TRUE;
7469
7470   /* Get cached copy if it exists.  */
7471   if (elf_section_data (sec)->this_hdr.contents != NULL)
7472     {
7473       *contents = elf_section_data (sec)->this_hdr.contents;
7474       return TRUE;
7475     }
7476
7477   return bfd_malloc_and_get_section (abfd, sec, contents);
7478 }
7479
7480 /* Look through the relocs for a section during the first phase, and
7481    allocate space in the global offset table.  */
7482
7483 bfd_boolean
7484 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
7485                             asection *sec, const Elf_Internal_Rela *relocs)
7486 {
7487   const char *name;
7488   bfd *dynobj;
7489   Elf_Internal_Shdr *symtab_hdr;
7490   struct elf_link_hash_entry **sym_hashes;
7491   size_t extsymoff;
7492   const Elf_Internal_Rela *rel;
7493   const Elf_Internal_Rela *rel_end;
7494   asection *sreloc;
7495   const struct elf_backend_data *bed;
7496   struct mips_elf_link_hash_table *htab;
7497   bfd_byte *contents;
7498   bfd_vma addend;
7499   reloc_howto_type *howto;
7500
7501   if (info->relocatable)
7502     return TRUE;
7503
7504   htab = mips_elf_hash_table (info);
7505   BFD_ASSERT (htab != NULL);
7506
7507   dynobj = elf_hash_table (info)->dynobj;
7508   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7509   sym_hashes = elf_sym_hashes (abfd);
7510   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
7511
7512   bed = get_elf_backend_data (abfd);
7513   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
7514
7515   /* Check for the mips16 stub sections.  */
7516
7517   name = bfd_get_section_name (abfd, sec);
7518   if (FN_STUB_P (name))
7519     {
7520       unsigned long r_symndx;
7521
7522       /* Look at the relocation information to figure out which symbol
7523          this is for.  */
7524
7525       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7526       if (r_symndx == 0)
7527         {
7528           (*_bfd_error_handler)
7529             (_("%B: Warning: cannot determine the target function for"
7530                " stub section `%s'"),
7531              abfd, name);
7532           bfd_set_error (bfd_error_bad_value);
7533           return FALSE;
7534         }
7535
7536       if (r_symndx < extsymoff
7537           || sym_hashes[r_symndx - extsymoff] == NULL)
7538         {
7539           asection *o;
7540
7541           /* This stub is for a local symbol.  This stub will only be
7542              needed if there is some relocation in this BFD, other
7543              than a 16 bit function call, which refers to this symbol.  */
7544           for (o = abfd->sections; o != NULL; o = o->next)
7545             {
7546               Elf_Internal_Rela *sec_relocs;
7547               const Elf_Internal_Rela *r, *rend;
7548
7549               /* We can ignore stub sections when looking for relocs.  */
7550               if ((o->flags & SEC_RELOC) == 0
7551                   || o->reloc_count == 0
7552                   || section_allows_mips16_refs_p (o))
7553                 continue;
7554
7555               sec_relocs
7556                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7557                                              info->keep_memory);
7558               if (sec_relocs == NULL)
7559                 return FALSE;
7560
7561               rend = sec_relocs + o->reloc_count;
7562               for (r = sec_relocs; r < rend; r++)
7563                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7564                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
7565                   break;
7566
7567               if (elf_section_data (o)->relocs != sec_relocs)
7568                 free (sec_relocs);
7569
7570               if (r < rend)
7571                 break;
7572             }
7573
7574           if (o == NULL)
7575             {
7576               /* There is no non-call reloc for this stub, so we do
7577                  not need it.  Since this function is called before
7578                  the linker maps input sections to output sections, we
7579                  can easily discard it by setting the SEC_EXCLUDE
7580                  flag.  */
7581               sec->flags |= SEC_EXCLUDE;
7582               return TRUE;
7583             }
7584
7585           /* Record this stub in an array of local symbol stubs for
7586              this BFD.  */
7587           if (elf_tdata (abfd)->local_stubs == NULL)
7588             {
7589               unsigned long symcount;
7590               asection **n;
7591               bfd_size_type amt;
7592
7593               if (elf_bad_symtab (abfd))
7594                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7595               else
7596                 symcount = symtab_hdr->sh_info;
7597               amt = symcount * sizeof (asection *);
7598               n = bfd_zalloc (abfd, amt);
7599               if (n == NULL)
7600                 return FALSE;
7601               elf_tdata (abfd)->local_stubs = n;
7602             }
7603
7604           sec->flags |= SEC_KEEP;
7605           elf_tdata (abfd)->local_stubs[r_symndx] = sec;
7606
7607           /* We don't need to set mips16_stubs_seen in this case.
7608              That flag is used to see whether we need to look through
7609              the global symbol table for stubs.  We don't need to set
7610              it here, because we just have a local stub.  */
7611         }
7612       else
7613         {
7614           struct mips_elf_link_hash_entry *h;
7615
7616           h = ((struct mips_elf_link_hash_entry *)
7617                sym_hashes[r_symndx - extsymoff]);
7618
7619           while (h->root.root.type == bfd_link_hash_indirect
7620                  || h->root.root.type == bfd_link_hash_warning)
7621             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
7622
7623           /* H is the symbol this stub is for.  */
7624
7625           /* If we already have an appropriate stub for this function, we
7626              don't need another one, so we can discard this one.  Since
7627              this function is called before the linker maps input sections
7628              to output sections, we can easily discard it by setting the
7629              SEC_EXCLUDE flag.  */
7630           if (h->fn_stub != NULL)
7631             {
7632               sec->flags |= SEC_EXCLUDE;
7633               return TRUE;
7634             }
7635
7636           sec->flags |= SEC_KEEP;
7637           h->fn_stub = sec;
7638           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7639         }
7640     }
7641   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
7642     {
7643       unsigned long r_symndx;
7644       struct mips_elf_link_hash_entry *h;
7645       asection **loc;
7646
7647       /* Look at the relocation information to figure out which symbol
7648          this is for.  */
7649
7650       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7651       if (r_symndx == 0)
7652         {
7653           (*_bfd_error_handler)
7654             (_("%B: Warning: cannot determine the target function for"
7655                " stub section `%s'"),
7656              abfd, name);
7657           bfd_set_error (bfd_error_bad_value);
7658           return FALSE;
7659         }
7660
7661       if (r_symndx < extsymoff
7662           || sym_hashes[r_symndx - extsymoff] == NULL)
7663         {
7664           asection *o;
7665
7666           /* This stub is for a local symbol.  This stub will only be
7667              needed if there is some relocation (R_MIPS16_26) in this BFD
7668              that refers to this symbol.  */
7669           for (o = abfd->sections; o != NULL; o = o->next)
7670             {
7671               Elf_Internal_Rela *sec_relocs;
7672               const Elf_Internal_Rela *r, *rend;
7673
7674               /* We can ignore stub sections when looking for relocs.  */
7675               if ((o->flags & SEC_RELOC) == 0
7676                   || o->reloc_count == 0
7677                   || section_allows_mips16_refs_p (o))
7678                 continue;
7679
7680               sec_relocs
7681                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7682                                              info->keep_memory);
7683               if (sec_relocs == NULL)
7684                 return FALSE;
7685
7686               rend = sec_relocs + o->reloc_count;
7687               for (r = sec_relocs; r < rend; r++)
7688                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7689                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
7690                     break;
7691
7692               if (elf_section_data (o)->relocs != sec_relocs)
7693                 free (sec_relocs);
7694
7695               if (r < rend)
7696                 break;
7697             }
7698
7699           if (o == NULL)
7700             {
7701               /* There is no non-call reloc for this stub, so we do
7702                  not need it.  Since this function is called before
7703                  the linker maps input sections to output sections, we
7704                  can easily discard it by setting the SEC_EXCLUDE
7705                  flag.  */
7706               sec->flags |= SEC_EXCLUDE;
7707               return TRUE;
7708             }
7709
7710           /* Record this stub in an array of local symbol call_stubs for
7711              this BFD.  */
7712           if (elf_tdata (abfd)->local_call_stubs == NULL)
7713             {
7714               unsigned long symcount;
7715               asection **n;
7716               bfd_size_type amt;
7717
7718               if (elf_bad_symtab (abfd))
7719                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7720               else
7721                 symcount = symtab_hdr->sh_info;
7722               amt = symcount * sizeof (asection *);
7723               n = bfd_zalloc (abfd, amt);
7724               if (n == NULL)
7725                 return FALSE;
7726               elf_tdata (abfd)->local_call_stubs = n;
7727             }
7728
7729           sec->flags |= SEC_KEEP;
7730           elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
7731
7732           /* We don't need to set mips16_stubs_seen in this case.
7733              That flag is used to see whether we need to look through
7734              the global symbol table for stubs.  We don't need to set
7735              it here, because we just have a local stub.  */
7736         }
7737       else
7738         {
7739           h = ((struct mips_elf_link_hash_entry *)
7740                sym_hashes[r_symndx - extsymoff]);
7741
7742           /* H is the symbol this stub is for.  */
7743
7744           if (CALL_FP_STUB_P (name))
7745             loc = &h->call_fp_stub;
7746           else
7747             loc = &h->call_stub;
7748
7749           /* If we already have an appropriate stub for this function, we
7750              don't need another one, so we can discard this one.  Since
7751              this function is called before the linker maps input sections
7752              to output sections, we can easily discard it by setting the
7753              SEC_EXCLUDE flag.  */
7754           if (*loc != NULL)
7755             {
7756               sec->flags |= SEC_EXCLUDE;
7757               return TRUE;
7758             }
7759
7760           sec->flags |= SEC_KEEP;
7761           *loc = sec;
7762           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7763         }
7764     }
7765
7766   sreloc = NULL;
7767   contents = NULL;
7768   for (rel = relocs; rel < rel_end; ++rel)
7769     {
7770       unsigned long r_symndx;
7771       unsigned int r_type;
7772       struct elf_link_hash_entry *h;
7773       bfd_boolean can_make_dynamic_p;
7774
7775       r_symndx = ELF_R_SYM (abfd, rel->r_info);
7776       r_type = ELF_R_TYPE (abfd, rel->r_info);
7777
7778       if (r_symndx < extsymoff)
7779         h = NULL;
7780       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
7781         {
7782           (*_bfd_error_handler)
7783             (_("%B: Malformed reloc detected for section %s"),
7784              abfd, name);
7785           bfd_set_error (bfd_error_bad_value);
7786           return FALSE;
7787         }
7788       else
7789         {
7790           h = sym_hashes[r_symndx - extsymoff];
7791           while (h != NULL
7792                  && (h->root.type == bfd_link_hash_indirect
7793                      || h->root.type == bfd_link_hash_warning))
7794             h = (struct elf_link_hash_entry *) h->root.u.i.link;
7795         }
7796
7797       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
7798          relocation into a dynamic one.  */
7799       can_make_dynamic_p = FALSE;
7800       switch (r_type)
7801         {
7802         case R_MIPS_GOT16:
7803         case R_MIPS_CALL16:
7804         case R_MIPS_CALL_HI16:
7805         case R_MIPS_CALL_LO16:
7806         case R_MIPS_GOT_HI16:
7807         case R_MIPS_GOT_LO16:
7808         case R_MIPS_GOT_PAGE:
7809         case R_MIPS_GOT_OFST:
7810         case R_MIPS_GOT_DISP:
7811         case R_MIPS_TLS_GOTTPREL:
7812         case R_MIPS_TLS_GD:
7813         case R_MIPS_TLS_LDM:
7814         case R_MIPS16_GOT16:
7815         case R_MIPS16_CALL16:
7816         case R_MIPS16_TLS_GOTTPREL:
7817         case R_MIPS16_TLS_GD:
7818         case R_MIPS16_TLS_LDM:
7819         case R_MICROMIPS_GOT16:
7820         case R_MICROMIPS_CALL16:
7821         case R_MICROMIPS_CALL_HI16:
7822         case R_MICROMIPS_CALL_LO16:
7823         case R_MICROMIPS_GOT_HI16:
7824         case R_MICROMIPS_GOT_LO16:
7825         case R_MICROMIPS_GOT_PAGE:
7826         case R_MICROMIPS_GOT_OFST:
7827         case R_MICROMIPS_GOT_DISP:
7828         case R_MICROMIPS_TLS_GOTTPREL:
7829         case R_MICROMIPS_TLS_GD:
7830         case R_MICROMIPS_TLS_LDM:
7831           if (dynobj == NULL)
7832             elf_hash_table (info)->dynobj = dynobj = abfd;
7833           if (!mips_elf_create_got_section (dynobj, info))
7834             return FALSE;
7835           if (htab->is_vxworks && !info->shared)
7836             {
7837               (*_bfd_error_handler)
7838                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
7839                  abfd, (unsigned long) rel->r_offset);
7840               bfd_set_error (bfd_error_bad_value);
7841               return FALSE;
7842             }
7843           break;
7844
7845           /* This is just a hint; it can safely be ignored.  Don't set
7846              has_static_relocs for the corresponding symbol.  */
7847         case R_MIPS_JALR:
7848         case R_MICROMIPS_JALR:
7849           break;
7850
7851         case R_MIPS_32:
7852         case R_MIPS_REL32:
7853         case R_MIPS_64:
7854           /* In VxWorks executables, references to external symbols
7855              must be handled using copy relocs or PLT entries; it is not
7856              possible to convert this relocation into a dynamic one.
7857
7858              For executables that use PLTs and copy-relocs, we have a
7859              choice between converting the relocation into a dynamic
7860              one or using copy relocations or PLT entries.  It is
7861              usually better to do the former, unless the relocation is
7862              against a read-only section.  */
7863           if ((info->shared
7864                || (h != NULL
7865                    && !htab->is_vxworks
7866                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
7867                    && !(!info->nocopyreloc
7868                         && !PIC_OBJECT_P (abfd)
7869                         && MIPS_ELF_READONLY_SECTION (sec))))
7870               && (sec->flags & SEC_ALLOC) != 0)
7871             {
7872               can_make_dynamic_p = TRUE;
7873               if (dynobj == NULL)
7874                 elf_hash_table (info)->dynobj = dynobj = abfd;
7875               break;
7876             }
7877           /* For sections that are not SEC_ALLOC a copy reloc would be
7878              output if possible (implying questionable semantics for
7879              read-only data objects) or otherwise the final link would
7880              fail as ld.so will not process them and could not therefore
7881              handle any outstanding dynamic relocations.
7882
7883              For such sections that are also SEC_DEBUGGING, we can avoid
7884              these problems by simply ignoring any relocs as these
7885              sections have a predefined use and we know it is safe to do
7886              so.
7887
7888              This is needed in cases such as a global symbol definition
7889              in a shared library causing a common symbol from an object
7890              file to be converted to an undefined reference.  If that
7891              happens, then all the relocations against this symbol from
7892              SEC_DEBUGGING sections in the object file will resolve to
7893              nil.  */
7894           if ((sec->flags & SEC_DEBUGGING) != 0)
7895             break;
7896           /* Fall through.  */
7897
7898         default:
7899           /* Most static relocations require pointer equality, except
7900              for branches.  */
7901           if (h)
7902             h->pointer_equality_needed = TRUE;
7903           /* Fall through.  */
7904
7905         case R_MIPS_26:
7906         case R_MIPS_PC16:
7907         case R_MIPS16_26:
7908         case R_MICROMIPS_26_S1:
7909         case R_MICROMIPS_PC7_S1:
7910         case R_MICROMIPS_PC10_S1:
7911         case R_MICROMIPS_PC16_S1:
7912         case R_MICROMIPS_PC23_S2:
7913           if (h)
7914             ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = TRUE;
7915           break;
7916         }
7917
7918       if (h)
7919         {
7920           /* Relocations against the special VxWorks __GOTT_BASE__ and
7921              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
7922              room for them in .rela.dyn.  */
7923           if (is_gott_symbol (info, h))
7924             {
7925               if (sreloc == NULL)
7926                 {
7927                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
7928                   if (sreloc == NULL)
7929                     return FALSE;
7930                 }
7931               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
7932               if (MIPS_ELF_READONLY_SECTION (sec))
7933                 /* We tell the dynamic linker that there are
7934                    relocations against the text segment.  */
7935                 info->flags |= DF_TEXTREL;
7936             }
7937         }
7938       else if (call_lo16_reloc_p (r_type)
7939                || got_lo16_reloc_p (r_type)
7940                || got_disp_reloc_p (r_type)
7941                || (got16_reloc_p (r_type) && htab->is_vxworks))
7942         {
7943           /* We may need a local GOT entry for this relocation.  We
7944              don't count R_MIPS_GOT_PAGE because we can estimate the
7945              maximum number of pages needed by looking at the size of
7946              the segment.  Similar comments apply to R_MIPS*_GOT16 and
7947              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
7948              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
7949              R_MIPS_CALL_HI16 because these are always followed by an
7950              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
7951           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
7952                                                  rel->r_addend, info, r_type))
7953             return FALSE;
7954         }
7955
7956       if (h != NULL
7957           && mips_elf_relocation_needs_la25_stub (abfd, r_type,
7958                                                   ELF_ST_IS_MIPS16 (h->other)))
7959         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
7960
7961       switch (r_type)
7962         {
7963         case R_MIPS_CALL16:
7964         case R_MIPS16_CALL16:
7965         case R_MICROMIPS_CALL16:
7966           if (h == NULL)
7967             {
7968               (*_bfd_error_handler)
7969                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
7970                  abfd, (unsigned long) rel->r_offset);
7971               bfd_set_error (bfd_error_bad_value);
7972               return FALSE;
7973             }
7974           /* Fall through.  */
7975
7976         case R_MIPS_CALL_HI16:
7977         case R_MIPS_CALL_LO16:
7978         case R_MICROMIPS_CALL_HI16:
7979         case R_MICROMIPS_CALL_LO16:
7980           if (h != NULL)
7981             {
7982               /* Make sure there is room in the regular GOT to hold the
7983                  function's address.  We may eliminate it in favour of
7984                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
7985               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE,
7986                                                       r_type))
7987                 return FALSE;
7988
7989               /* We need a stub, not a plt entry for the undefined
7990                  function.  But we record it as if it needs plt.  See
7991                  _bfd_elf_adjust_dynamic_symbol.  */
7992               h->needs_plt = 1;
7993               h->type = STT_FUNC;
7994             }
7995           break;
7996
7997         case R_MIPS_GOT_PAGE:
7998         case R_MICROMIPS_GOT_PAGE:
7999           /* If this is a global, overridable symbol, GOT_PAGE will
8000              decay to GOT_DISP, so we'll need a GOT entry for it.  */
8001           if (h)
8002             {
8003               struct mips_elf_link_hash_entry *hmips =
8004                 (struct mips_elf_link_hash_entry *) h;
8005
8006               /* This symbol is definitely not overridable.  */
8007               if (hmips->root.def_regular
8008                   && ! (info->shared && ! info->symbolic
8009                         && ! hmips->root.forced_local))
8010                 h = NULL;
8011             }
8012           /* Fall through.  */
8013
8014         case R_MIPS16_GOT16:
8015         case R_MIPS_GOT16:
8016         case R_MIPS_GOT_HI16:
8017         case R_MIPS_GOT_LO16:
8018         case R_MICROMIPS_GOT16:
8019         case R_MICROMIPS_GOT_HI16:
8020         case R_MICROMIPS_GOT_LO16:
8021           if (!h || got_page_reloc_p (r_type))
8022             {
8023               /* This relocation needs (or may need, if h != NULL) a
8024                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
8025                  know for sure until we know whether the symbol is
8026                  preemptible.  */
8027               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
8028                 {
8029                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
8030                     return FALSE;
8031                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8032                   addend = mips_elf_read_rel_addend (abfd, rel,
8033                                                      howto, contents);
8034                   if (got16_reloc_p (r_type))
8035                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
8036                                                   contents, &addend);
8037                   else
8038                     addend <<= howto->rightshift;
8039                 }
8040               else
8041                 addend = rel->r_addend;
8042               if (!mips_elf_record_got_page_entry (info, abfd, r_symndx,
8043                                                    addend))
8044                 return FALSE;
8045             }
8046           /* Fall through.  */
8047
8048         case R_MIPS_GOT_DISP:
8049         case R_MICROMIPS_GOT_DISP:
8050           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8051                                                        FALSE, r_type))
8052             return FALSE;
8053           break;
8054
8055         case R_MIPS_TLS_GOTTPREL:
8056         case R_MIPS16_TLS_GOTTPREL:
8057         case R_MICROMIPS_TLS_GOTTPREL:
8058           if (info->shared)
8059             info->flags |= DF_STATIC_TLS;
8060           /* Fall through */
8061
8062         case R_MIPS_TLS_LDM:
8063         case R_MIPS16_TLS_LDM:
8064         case R_MICROMIPS_TLS_LDM:
8065           if (tls_ldm_reloc_p (r_type))
8066             {
8067               r_symndx = STN_UNDEF;
8068               h = NULL;
8069             }
8070           /* Fall through */
8071
8072         case R_MIPS_TLS_GD:
8073         case R_MIPS16_TLS_GD:
8074         case R_MICROMIPS_TLS_GD:
8075           /* This symbol requires a global offset table entry, or two
8076              for TLS GD relocations.  */
8077           if (h != NULL)
8078             {
8079               if (!mips_elf_record_global_got_symbol (h, abfd, info,
8080                                                       FALSE, r_type))
8081                 return FALSE;
8082             }
8083           else
8084             {
8085               if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8086                                                      rel->r_addend,
8087                                                      info, r_type))
8088                 return FALSE;
8089             }
8090           break;
8091
8092         case R_MIPS_32:
8093         case R_MIPS_REL32:
8094         case R_MIPS_64:
8095           /* In VxWorks executables, references to external symbols
8096              are handled using copy relocs or PLT stubs, so there's
8097              no need to add a .rela.dyn entry for this relocation.  */
8098           if (can_make_dynamic_p)
8099             {
8100               if (sreloc == NULL)
8101                 {
8102                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8103                   if (sreloc == NULL)
8104                     return FALSE;
8105                 }
8106               if (info->shared && h == NULL)
8107                 {
8108                   /* When creating a shared object, we must copy these
8109                      reloc types into the output file as R_MIPS_REL32
8110                      relocs.  Make room for this reloc in .rel(a).dyn.  */
8111                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8112                   if (MIPS_ELF_READONLY_SECTION (sec))
8113                     /* We tell the dynamic linker that there are
8114                        relocations against the text segment.  */
8115                     info->flags |= DF_TEXTREL;
8116                 }
8117               else
8118                 {
8119                   struct mips_elf_link_hash_entry *hmips;
8120
8121                   /* For a shared object, we must copy this relocation
8122                      unless the symbol turns out to be undefined and
8123                      weak with non-default visibility, in which case
8124                      it will be left as zero.
8125
8126                      We could elide R_MIPS_REL32 for locally binding symbols
8127                      in shared libraries, but do not yet do so.
8128
8129                      For an executable, we only need to copy this
8130                      reloc if the symbol is defined in a dynamic
8131                      object.  */
8132                   hmips = (struct mips_elf_link_hash_entry *) h;
8133                   ++hmips->possibly_dynamic_relocs;
8134                   if (MIPS_ELF_READONLY_SECTION (sec))
8135                     /* We need it to tell the dynamic linker if there
8136                        are relocations against the text segment.  */
8137                     hmips->readonly_reloc = TRUE;
8138                 }
8139             }
8140
8141           if (SGI_COMPAT (abfd))
8142             mips_elf_hash_table (info)->compact_rel_size +=
8143               sizeof (Elf32_External_crinfo);
8144           break;
8145
8146         case R_MIPS_26:
8147         case R_MIPS_GPREL16:
8148         case R_MIPS_LITERAL:
8149         case R_MIPS_GPREL32:
8150         case R_MICROMIPS_26_S1:
8151         case R_MICROMIPS_GPREL16:
8152         case R_MICROMIPS_LITERAL:
8153         case R_MICROMIPS_GPREL7_S2:
8154           if (SGI_COMPAT (abfd))
8155             mips_elf_hash_table (info)->compact_rel_size +=
8156               sizeof (Elf32_External_crinfo);
8157           break;
8158
8159           /* This relocation describes the C++ object vtable hierarchy.
8160              Reconstruct it for later use during GC.  */
8161         case R_MIPS_GNU_VTINHERIT:
8162           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
8163             return FALSE;
8164           break;
8165
8166           /* This relocation describes which C++ vtable entries are actually
8167              used.  Record for later use during GC.  */
8168         case R_MIPS_GNU_VTENTRY:
8169           BFD_ASSERT (h != NULL);
8170           if (h != NULL
8171               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
8172             return FALSE;
8173           break;
8174
8175         default:
8176           break;
8177         }
8178
8179       /* We must not create a stub for a symbol that has relocations
8180          related to taking the function's address.  This doesn't apply to
8181          VxWorks, where CALL relocs refer to a .got.plt entry instead of
8182          a normal .got entry.  */
8183       if (!htab->is_vxworks && h != NULL)
8184         switch (r_type)
8185           {
8186           default:
8187             ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8188             break;
8189           case R_MIPS16_CALL16:
8190           case R_MIPS_CALL16:
8191           case R_MIPS_CALL_HI16:
8192           case R_MIPS_CALL_LO16:
8193           case R_MIPS_JALR:
8194           case R_MICROMIPS_CALL16:
8195           case R_MICROMIPS_CALL_HI16:
8196           case R_MICROMIPS_CALL_LO16:
8197           case R_MICROMIPS_JALR:
8198             break;
8199           }
8200
8201       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8202          if there is one.  We only need to handle global symbols here;
8203          we decide whether to keep or delete stubs for local symbols
8204          when processing the stub's relocations.  */
8205       if (h != NULL
8206           && !mips16_call_reloc_p (r_type)
8207           && !section_allows_mips16_refs_p (sec))
8208         {
8209           struct mips_elf_link_hash_entry *mh;
8210
8211           mh = (struct mips_elf_link_hash_entry *) h;
8212           mh->need_fn_stub = TRUE;
8213         }
8214
8215       /* Refuse some position-dependent relocations when creating a
8216          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8217          not PIC, but we can create dynamic relocations and the result
8218          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8219          combined with R_MIPS_GOT16.  */
8220       if (info->shared)
8221         {
8222           switch (r_type)
8223             {
8224             case R_MIPS16_HI16:
8225             case R_MIPS_HI16:
8226             case R_MIPS_HIGHER:
8227             case R_MIPS_HIGHEST:
8228             case R_MICROMIPS_HI16:
8229             case R_MICROMIPS_HIGHER:
8230             case R_MICROMIPS_HIGHEST:
8231               /* Don't refuse a high part relocation if it's against
8232                  no symbol (e.g. part of a compound relocation).  */
8233               if (r_symndx == STN_UNDEF)
8234                 break;
8235
8236               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8237                  and has a special meaning.  */
8238               if (!NEWABI_P (abfd) && h != NULL
8239                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8240                 break;
8241
8242               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8243               if (is_gott_symbol (info, h))
8244                 break;
8245
8246               /* FALLTHROUGH */
8247
8248             case R_MIPS16_26:
8249             case R_MIPS_26:
8250             case R_MICROMIPS_26_S1:
8251               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8252               (*_bfd_error_handler)
8253                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8254                  abfd, howto->name,
8255                  (h) ? h->root.root.string : "a local symbol");
8256               bfd_set_error (bfd_error_bad_value);
8257               return FALSE;
8258             default:
8259               break;
8260             }
8261         }
8262     }
8263
8264   return TRUE;
8265 }
8266 \f
8267 bfd_boolean
8268 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8269                          struct bfd_link_info *link_info,
8270                          bfd_boolean *again)
8271 {
8272   Elf_Internal_Rela *internal_relocs;
8273   Elf_Internal_Rela *irel, *irelend;
8274   Elf_Internal_Shdr *symtab_hdr;
8275   bfd_byte *contents = NULL;
8276   size_t extsymoff;
8277   bfd_boolean changed_contents = FALSE;
8278   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8279   Elf_Internal_Sym *isymbuf = NULL;
8280
8281   /* We are not currently changing any sizes, so only one pass.  */
8282   *again = FALSE;
8283
8284   if (link_info->relocatable)
8285     return TRUE;
8286
8287   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8288                                                link_info->keep_memory);
8289   if (internal_relocs == NULL)
8290     return TRUE;
8291
8292   irelend = internal_relocs + sec->reloc_count
8293     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8294   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8295   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8296
8297   for (irel = internal_relocs; irel < irelend; irel++)
8298     {
8299       bfd_vma symval;
8300       bfd_signed_vma sym_offset;
8301       unsigned int r_type;
8302       unsigned long r_symndx;
8303       asection *sym_sec;
8304       unsigned long instruction;
8305
8306       /* Turn jalr into bgezal, and jr into beq, if they're marked
8307          with a JALR relocation, that indicate where they jump to.
8308          This saves some pipeline bubbles.  */
8309       r_type = ELF_R_TYPE (abfd, irel->r_info);
8310       if (r_type != R_MIPS_JALR)
8311         continue;
8312
8313       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8314       /* Compute the address of the jump target.  */
8315       if (r_symndx >= extsymoff)
8316         {
8317           struct mips_elf_link_hash_entry *h
8318             = ((struct mips_elf_link_hash_entry *)
8319                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8320
8321           while (h->root.root.type == bfd_link_hash_indirect
8322                  || h->root.root.type == bfd_link_hash_warning)
8323             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8324
8325           /* If a symbol is undefined, or if it may be overridden,
8326              skip it.  */
8327           if (! ((h->root.root.type == bfd_link_hash_defined
8328                   || h->root.root.type == bfd_link_hash_defweak)
8329                  && h->root.root.u.def.section)
8330               || (link_info->shared && ! link_info->symbolic
8331                   && !h->root.forced_local))
8332             continue;
8333
8334           sym_sec = h->root.root.u.def.section;
8335           if (sym_sec->output_section)
8336             symval = (h->root.root.u.def.value
8337                       + sym_sec->output_section->vma
8338                       + sym_sec->output_offset);
8339           else
8340             symval = h->root.root.u.def.value;
8341         }
8342       else
8343         {
8344           Elf_Internal_Sym *isym;
8345
8346           /* Read this BFD's symbols if we haven't done so already.  */
8347           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8348             {
8349               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8350               if (isymbuf == NULL)
8351                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8352                                                 symtab_hdr->sh_info, 0,
8353                                                 NULL, NULL, NULL);
8354               if (isymbuf == NULL)
8355                 goto relax_return;
8356             }
8357
8358           isym = isymbuf + r_symndx;
8359           if (isym->st_shndx == SHN_UNDEF)
8360             continue;
8361           else if (isym->st_shndx == SHN_ABS)
8362             sym_sec = bfd_abs_section_ptr;
8363           else if (isym->st_shndx == SHN_COMMON)
8364             sym_sec = bfd_com_section_ptr;
8365           else
8366             sym_sec
8367               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8368           symval = isym->st_value
8369             + sym_sec->output_section->vma
8370             + sym_sec->output_offset;
8371         }
8372
8373       /* Compute branch offset, from delay slot of the jump to the
8374          branch target.  */
8375       sym_offset = (symval + irel->r_addend)
8376         - (sec_start + irel->r_offset + 4);
8377
8378       /* Branch offset must be properly aligned.  */
8379       if ((sym_offset & 3) != 0)
8380         continue;
8381
8382       sym_offset >>= 2;
8383
8384       /* Check that it's in range.  */
8385       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
8386         continue;
8387
8388       /* Get the section contents if we haven't done so already.  */
8389       if (!mips_elf_get_section_contents (abfd, sec, &contents))
8390         goto relax_return;
8391
8392       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
8393
8394       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
8395       if ((instruction & 0xfc1fffff) == 0x0000f809)
8396         instruction = 0x04110000;
8397       /* If it was jr <reg>, turn it into b <target>.  */
8398       else if ((instruction & 0xfc1fffff) == 0x00000008)
8399         instruction = 0x10000000;
8400       else
8401         continue;
8402
8403       instruction |= (sym_offset & 0xffff);
8404       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
8405       changed_contents = TRUE;
8406     }
8407
8408   if (contents != NULL
8409       && elf_section_data (sec)->this_hdr.contents != contents)
8410     {
8411       if (!changed_contents && !link_info->keep_memory)
8412         free (contents);
8413       else
8414         {
8415           /* Cache the section contents for elf_link_input_bfd.  */
8416           elf_section_data (sec)->this_hdr.contents = contents;
8417         }
8418     }
8419   return TRUE;
8420
8421  relax_return:
8422   if (contents != NULL
8423       && elf_section_data (sec)->this_hdr.contents != contents)
8424     free (contents);
8425   return FALSE;
8426 }
8427 \f
8428 /* Allocate space for global sym dynamic relocs.  */
8429
8430 static bfd_boolean
8431 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
8432 {
8433   struct bfd_link_info *info = inf;
8434   bfd *dynobj;
8435   struct mips_elf_link_hash_entry *hmips;
8436   struct mips_elf_link_hash_table *htab;
8437
8438   htab = mips_elf_hash_table (info);
8439   BFD_ASSERT (htab != NULL);
8440
8441   dynobj = elf_hash_table (info)->dynobj;
8442   hmips = (struct mips_elf_link_hash_entry *) h;
8443
8444   /* VxWorks executables are handled elsewhere; we only need to
8445      allocate relocations in shared objects.  */
8446   if (htab->is_vxworks && !info->shared)
8447     return TRUE;
8448
8449   /* Ignore indirect symbols.  All relocations against such symbols
8450      will be redirected to the target symbol.  */
8451   if (h->root.type == bfd_link_hash_indirect)
8452     return TRUE;
8453
8454   /* If this symbol is defined in a dynamic object, or we are creating
8455      a shared library, we will need to copy any R_MIPS_32 or
8456      R_MIPS_REL32 relocs against it into the output file.  */
8457   if (! info->relocatable
8458       && hmips->possibly_dynamic_relocs != 0
8459       && (h->root.type == bfd_link_hash_defweak
8460           || (!h->def_regular && !ELF_COMMON_DEF_P (h))
8461           || info->shared))
8462     {
8463       bfd_boolean do_copy = TRUE;
8464
8465       if (h->root.type == bfd_link_hash_undefweak)
8466         {
8467           /* Do not copy relocations for undefined weak symbols with
8468              non-default visibility.  */
8469           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
8470             do_copy = FALSE;
8471
8472           /* Make sure undefined weak symbols are output as a dynamic
8473              symbol in PIEs.  */
8474           else if (h->dynindx == -1 && !h->forced_local)
8475             {
8476               if (! bfd_elf_link_record_dynamic_symbol (info, h))
8477                 return FALSE;
8478             }
8479         }
8480
8481       if (do_copy)
8482         {
8483           /* Even though we don't directly need a GOT entry for this symbol,
8484              the SVR4 psABI requires it to have a dynamic symbol table
8485              index greater that DT_MIPS_GOTSYM if there are dynamic
8486              relocations against it.
8487
8488              VxWorks does not enforce the same mapping between the GOT
8489              and the symbol table, so the same requirement does not
8490              apply there.  */
8491           if (!htab->is_vxworks)
8492             {
8493               if (hmips->global_got_area > GGA_RELOC_ONLY)
8494                 hmips->global_got_area = GGA_RELOC_ONLY;
8495               hmips->got_only_for_calls = FALSE;
8496             }
8497
8498           mips_elf_allocate_dynamic_relocations
8499             (dynobj, info, hmips->possibly_dynamic_relocs);
8500           if (hmips->readonly_reloc)
8501             /* We tell the dynamic linker that there are relocations
8502                against the text segment.  */
8503             info->flags |= DF_TEXTREL;
8504         }
8505     }
8506
8507   return TRUE;
8508 }
8509
8510 /* Adjust a symbol defined by a dynamic object and referenced by a
8511    regular object.  The current definition is in some section of the
8512    dynamic object, but we're not including those sections.  We have to
8513    change the definition to something the rest of the link can
8514    understand.  */
8515
8516 bfd_boolean
8517 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
8518                                      struct elf_link_hash_entry *h)
8519 {
8520   bfd *dynobj;
8521   struct mips_elf_link_hash_entry *hmips;
8522   struct mips_elf_link_hash_table *htab;
8523
8524   htab = mips_elf_hash_table (info);
8525   BFD_ASSERT (htab != NULL);
8526
8527   dynobj = elf_hash_table (info)->dynobj;
8528   hmips = (struct mips_elf_link_hash_entry *) h;
8529
8530   /* Make sure we know what is going on here.  */
8531   BFD_ASSERT (dynobj != NULL
8532               && (h->needs_plt
8533                   || h->u.weakdef != NULL
8534                   || (h->def_dynamic
8535                       && h->ref_regular
8536                       && !h->def_regular)));
8537
8538   hmips = (struct mips_elf_link_hash_entry *) h;
8539
8540   /* If there are call relocations against an externally-defined symbol,
8541      see whether we can create a MIPS lazy-binding stub for it.  We can
8542      only do this if all references to the function are through call
8543      relocations, and in that case, the traditional lazy-binding stubs
8544      are much more efficient than PLT entries.
8545
8546      Traditional stubs are only available on SVR4 psABI-based systems;
8547      VxWorks always uses PLTs instead.  */
8548   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
8549     {
8550       if (! elf_hash_table (info)->dynamic_sections_created)
8551         return TRUE;
8552
8553       /* If this symbol is not defined in a regular file, then set
8554          the symbol to the stub location.  This is required to make
8555          function pointers compare as equal between the normal
8556          executable and the shared library.  */
8557       if (!h->def_regular)
8558         {
8559           hmips->needs_lazy_stub = TRUE;
8560           htab->lazy_stub_count++;
8561           return TRUE;
8562         }
8563     }
8564   /* As above, VxWorks requires PLT entries for externally-defined
8565      functions that are only accessed through call relocations.
8566
8567      Both VxWorks and non-VxWorks targets also need PLT entries if there
8568      are static-only relocations against an externally-defined function.
8569      This can technically occur for shared libraries if there are
8570      branches to the symbol, although it is unlikely that this will be
8571      used in practice due to the short ranges involved.  It can occur
8572      for any relative or absolute relocation in executables; in that
8573      case, the PLT entry becomes the function's canonical address.  */
8574   else if (((h->needs_plt && !hmips->no_fn_stub)
8575             || (h->type == STT_FUNC && hmips->has_static_relocs))
8576            && htab->use_plts_and_copy_relocs
8577            && !SYMBOL_CALLS_LOCAL (info, h)
8578            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
8579                 && h->root.type == bfd_link_hash_undefweak))
8580     {
8581       /* If this is the first symbol to need a PLT entry, allocate room
8582          for the header.  */
8583       if (htab->splt->size == 0)
8584         {
8585           BFD_ASSERT (htab->sgotplt->size == 0);
8586
8587           /* If we're using the PLT additions to the psABI, each PLT
8588              entry is 16 bytes and the PLT0 entry is 32 bytes.
8589              Encourage better cache usage by aligning.  We do this
8590              lazily to avoid pessimizing traditional objects.  */
8591           if (!htab->is_vxworks
8592               && !bfd_set_section_alignment (dynobj, htab->splt, 5))
8593             return FALSE;
8594
8595           /* Make sure that .got.plt is word-aligned.  We do this lazily
8596              for the same reason as above.  */
8597           if (!bfd_set_section_alignment (dynobj, htab->sgotplt,
8598                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
8599             return FALSE;
8600
8601           htab->splt->size += htab->plt_header_size;
8602
8603           /* On non-VxWorks targets, the first two entries in .got.plt
8604              are reserved.  */
8605           if (!htab->is_vxworks)
8606             htab->sgotplt->size
8607               += get_elf_backend_data (dynobj)->got_header_size;
8608
8609           /* On VxWorks, also allocate room for the header's
8610              .rela.plt.unloaded entries.  */
8611           if (htab->is_vxworks && !info->shared)
8612             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
8613         }
8614
8615       /* Assign the next .plt entry to this symbol.  */
8616       h->plt.offset = htab->splt->size;
8617       htab->splt->size += htab->plt_entry_size;
8618
8619       /* If the output file has no definition of the symbol, set the
8620          symbol's value to the address of the stub.  */
8621       if (!info->shared && !h->def_regular)
8622         {
8623           h->root.u.def.section = htab->splt;
8624           h->root.u.def.value = h->plt.offset;
8625           /* For VxWorks, point at the PLT load stub rather than the
8626              lazy resolution stub; this stub will become the canonical
8627              function address.  */
8628           if (htab->is_vxworks)
8629             h->root.u.def.value += 8;
8630         }
8631
8632       /* Make room for the .got.plt entry and the R_MIPS_JUMP_SLOT
8633          relocation.  */
8634       htab->sgotplt->size += MIPS_ELF_GOT_SIZE (dynobj);
8635       htab->srelplt->size += (htab->is_vxworks
8636                               ? MIPS_ELF_RELA_SIZE (dynobj)
8637                               : MIPS_ELF_REL_SIZE (dynobj));
8638
8639       /* Make room for the .rela.plt.unloaded relocations.  */
8640       if (htab->is_vxworks && !info->shared)
8641         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
8642
8643       /* All relocations against this symbol that could have been made
8644          dynamic will now refer to the PLT entry instead.  */
8645       hmips->possibly_dynamic_relocs = 0;
8646
8647       return TRUE;
8648     }
8649
8650   /* If this is a weak symbol, and there is a real definition, the
8651      processor independent code will have arranged for us to see the
8652      real definition first, and we can just use the same value.  */
8653   if (h->u.weakdef != NULL)
8654     {
8655       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
8656                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
8657       h->root.u.def.section = h->u.weakdef->root.u.def.section;
8658       h->root.u.def.value = h->u.weakdef->root.u.def.value;
8659       return TRUE;
8660     }
8661
8662   /* Otherwise, there is nothing further to do for symbols defined
8663      in regular objects.  */
8664   if (h->def_regular)
8665     return TRUE;
8666
8667   /* There's also nothing more to do if we'll convert all relocations
8668      against this symbol into dynamic relocations.  */
8669   if (!hmips->has_static_relocs)
8670     return TRUE;
8671
8672   /* We're now relying on copy relocations.  Complain if we have
8673      some that we can't convert.  */
8674   if (!htab->use_plts_and_copy_relocs || info->shared)
8675     {
8676       (*_bfd_error_handler) (_("non-dynamic relocations refer to "
8677                                "dynamic symbol %s"),
8678                              h->root.root.string);
8679       bfd_set_error (bfd_error_bad_value);
8680       return FALSE;
8681     }
8682
8683   /* We must allocate the symbol in our .dynbss section, which will
8684      become part of the .bss section of the executable.  There will be
8685      an entry for this symbol in the .dynsym section.  The dynamic
8686      object will contain position independent code, so all references
8687      from the dynamic object to this symbol will go through the global
8688      offset table.  The dynamic linker will use the .dynsym entry to
8689      determine the address it must put in the global offset table, so
8690      both the dynamic object and the regular object will refer to the
8691      same memory location for the variable.  */
8692
8693   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
8694     {
8695       if (htab->is_vxworks)
8696         htab->srelbss->size += sizeof (Elf32_External_Rela);
8697       else
8698         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8699       h->needs_copy = 1;
8700     }
8701
8702   /* All relocations against this symbol that could have been made
8703      dynamic will now refer to the local copy instead.  */
8704   hmips->possibly_dynamic_relocs = 0;
8705
8706   return _bfd_elf_adjust_dynamic_copy (h, htab->sdynbss);
8707 }
8708 \f
8709 /* This function is called after all the input files have been read,
8710    and the input sections have been assigned to output sections.  We
8711    check for any mips16 stub sections that we can discard.  */
8712
8713 bfd_boolean
8714 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
8715                                     struct bfd_link_info *info)
8716 {
8717   asection *ri;
8718   struct mips_elf_link_hash_table *htab;
8719   struct mips_htab_traverse_info hti;
8720
8721   htab = mips_elf_hash_table (info);
8722   BFD_ASSERT (htab != NULL);
8723
8724   /* The .reginfo section has a fixed size.  */
8725   ri = bfd_get_section_by_name (output_bfd, ".reginfo");
8726   if (ri != NULL)
8727     bfd_set_section_size (output_bfd, ri, sizeof (Elf32_External_RegInfo));
8728
8729   hti.info = info;
8730   hti.output_bfd = output_bfd;
8731   hti.error = FALSE;
8732   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
8733                                mips_elf_check_symbols, &hti);
8734   if (hti.error)
8735     return FALSE;
8736
8737   return TRUE;
8738 }
8739
8740 /* If the link uses a GOT, lay it out and work out its size.  */
8741
8742 static bfd_boolean
8743 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
8744 {
8745   bfd *dynobj;
8746   asection *s;
8747   struct mips_got_info *g;
8748   bfd_size_type loadable_size = 0;
8749   bfd_size_type page_gotno;
8750   bfd *ibfd;
8751   struct mips_elf_traverse_got_arg tga;
8752   struct mips_elf_link_hash_table *htab;
8753
8754   htab = mips_elf_hash_table (info);
8755   BFD_ASSERT (htab != NULL);
8756
8757   s = htab->sgot;
8758   if (s == NULL)
8759     return TRUE;
8760
8761   dynobj = elf_hash_table (info)->dynobj;
8762   g = htab->got_info;
8763
8764   /* Allocate room for the reserved entries.  VxWorks always reserves
8765      3 entries; other objects only reserve 2 entries.  */
8766   BFD_ASSERT (g->assigned_gotno == 0);
8767   if (htab->is_vxworks)
8768     htab->reserved_gotno = 3;
8769   else
8770     htab->reserved_gotno = 2;
8771   g->local_gotno += htab->reserved_gotno;
8772   g->assigned_gotno = htab->reserved_gotno;
8773
8774   /* Replace entries for indirect and warning symbols with entries for
8775      the target symbol.  */
8776   if (!mips_elf_resolve_final_got_entries (g))
8777     return FALSE;
8778
8779   /* Count the number of GOT symbols.  */
8780   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
8781
8782   /* Calculate the total loadable size of the output.  That
8783      will give us the maximum number of GOT_PAGE entries
8784      required.  */
8785   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
8786     {
8787       asection *subsection;
8788
8789       for (subsection = ibfd->sections;
8790            subsection;
8791            subsection = subsection->next)
8792         {
8793           if ((subsection->flags & SEC_ALLOC) == 0)
8794             continue;
8795           loadable_size += ((subsection->size + 0xf)
8796                             &~ (bfd_size_type) 0xf);
8797         }
8798     }
8799
8800   if (htab->is_vxworks)
8801     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
8802        relocations against local symbols evaluate to "G", and the EABI does
8803        not include R_MIPS_GOT_PAGE.  */
8804     page_gotno = 0;
8805   else
8806     /* Assume there are two loadable segments consisting of contiguous
8807        sections.  Is 5 enough?  */
8808     page_gotno = (loadable_size >> 16) + 5;
8809
8810   /* Choose the smaller of the two estimates; both are intended to be
8811      conservative.  */
8812   if (page_gotno > g->page_gotno)
8813     page_gotno = g->page_gotno;
8814
8815   g->local_gotno += page_gotno;
8816
8817   /* Count the number of local GOT entries and TLS relocs.  */
8818   tga.info = info;
8819   tga.g = g;
8820   htab_traverse (g->got_entries, mips_elf_count_local_got_entries, &tga);
8821
8822   /* We need to calculate tls_gotno for global symbols at this point
8823      instead of building it up earlier, to avoid doublecounting
8824      entries for one global symbol from multiple input files.  */
8825   elf_link_hash_traverse (elf_hash_table (info),
8826                           mips_elf_count_global_tls_entries,
8827                           &tga);
8828
8829   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8830   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8831   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8832
8833   /* VxWorks does not support multiple GOTs.  It initializes $gp to
8834      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
8835      dynamic loader.  */
8836   if (htab->is_vxworks)
8837     {
8838       /* VxWorks executables do not need a GOT.  */
8839       if (info->shared)
8840         {
8841           /* Each VxWorks GOT entry needs an explicit relocation.  */
8842           unsigned int count;
8843
8844           count = g->global_gotno + g->local_gotno - htab->reserved_gotno;
8845           if (count)
8846             mips_elf_allocate_dynamic_relocations (dynobj, info, count);
8847         }
8848     }
8849   else if (s->size > MIPS_ELF_GOT_MAX_SIZE (info))
8850     {
8851       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
8852         return FALSE;
8853     }
8854   else
8855     {
8856       /* Record that all bfds use G.  This also has the effect of freeing
8857          the per-bfd GOTs, which we no longer need.  */
8858       for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
8859         if (mips_elf_bfd_got (ibfd, FALSE))
8860           mips_elf_replace_bfd_got (ibfd, g);
8861       mips_elf_replace_bfd_got (output_bfd, g);
8862
8863       /* Set up TLS entries.  */
8864       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
8865       tga.info = info;
8866       tga.g = g;
8867       tga.value = MIPS_ELF_GOT_SIZE (output_bfd);
8868       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
8869       if (!tga.g)
8870         return FALSE;
8871       BFD_ASSERT (g->tls_assigned_gotno
8872                   == g->global_gotno + g->local_gotno + g->tls_gotno);
8873
8874       /* Allocate room for the TLS relocations.  */
8875       if (g->relocs)
8876         mips_elf_allocate_dynamic_relocations (dynobj, info, g->relocs);
8877     }
8878
8879   return TRUE;
8880 }
8881
8882 /* Estimate the size of the .MIPS.stubs section.  */
8883
8884 static void
8885 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
8886 {
8887   struct mips_elf_link_hash_table *htab;
8888   bfd_size_type dynsymcount;
8889
8890   htab = mips_elf_hash_table (info);
8891   BFD_ASSERT (htab != NULL);
8892
8893   if (htab->lazy_stub_count == 0)
8894     return;
8895
8896   /* IRIX rld assumes that a function stub isn't at the end of the .text
8897      section, so add a dummy entry to the end.  */
8898   htab->lazy_stub_count++;
8899
8900   /* Get a worst-case estimate of the number of dynamic symbols needed.
8901      At this point, dynsymcount does not account for section symbols
8902      and count_section_dynsyms may overestimate the number that will
8903      be needed.  */
8904   dynsymcount = (elf_hash_table (info)->dynsymcount
8905                  + count_section_dynsyms (output_bfd, info));
8906
8907   /* Determine the size of one stub entry.  */
8908   htab->function_stub_size = (dynsymcount > 0x10000
8909                               ? MIPS_FUNCTION_STUB_BIG_SIZE
8910                               : MIPS_FUNCTION_STUB_NORMAL_SIZE);
8911
8912   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
8913 }
8914
8915 /* A mips_elf_link_hash_traverse callback for which DATA points to the
8916    MIPS hash table.  If H needs a traditional MIPS lazy-binding stub,
8917    allocate an entry in the stubs section.  */
8918
8919 static bfd_boolean
8920 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void **data)
8921 {
8922   struct mips_elf_link_hash_table *htab;
8923
8924   htab = (struct mips_elf_link_hash_table *) data;
8925   if (h->needs_lazy_stub)
8926     {
8927       h->root.root.u.def.section = htab->sstubs;
8928       h->root.root.u.def.value = htab->sstubs->size;
8929       h->root.plt.offset = htab->sstubs->size;
8930       htab->sstubs->size += htab->function_stub_size;
8931     }
8932   return TRUE;
8933 }
8934
8935 /* Allocate offsets in the stubs section to each symbol that needs one.
8936    Set the final size of the .MIPS.stub section.  */
8937
8938 static void
8939 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
8940 {
8941   struct mips_elf_link_hash_table *htab;
8942
8943   htab = mips_elf_hash_table (info);
8944   BFD_ASSERT (htab != NULL);
8945
8946   if (htab->lazy_stub_count == 0)
8947     return;
8948
8949   htab->sstubs->size = 0;
8950   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, htab);
8951   htab->sstubs->size += htab->function_stub_size;
8952   BFD_ASSERT (htab->sstubs->size
8953               == htab->lazy_stub_count * htab->function_stub_size);
8954 }
8955
8956 /* Set the sizes of the dynamic sections.  */
8957
8958 bfd_boolean
8959 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
8960                                      struct bfd_link_info *info)
8961 {
8962   bfd *dynobj;
8963   asection *s, *sreldyn;
8964   bfd_boolean reltext;
8965   struct mips_elf_link_hash_table *htab;
8966
8967   htab = mips_elf_hash_table (info);
8968   BFD_ASSERT (htab != NULL);
8969   dynobj = elf_hash_table (info)->dynobj;
8970   BFD_ASSERT (dynobj != NULL);
8971
8972   if (elf_hash_table (info)->dynamic_sections_created)
8973     {
8974       /* Set the contents of the .interp section to the interpreter.  */
8975       if (info->executable)
8976         {
8977           s = bfd_get_linker_section (dynobj, ".interp");
8978           BFD_ASSERT (s != NULL);
8979           s->size
8980             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
8981           s->contents
8982             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
8983         }
8984
8985       /* Create a symbol for the PLT, if we know that we are using it.  */
8986       if (htab->splt && htab->splt->size > 0 && htab->root.hplt == NULL)
8987         {
8988           struct elf_link_hash_entry *h;
8989
8990           BFD_ASSERT (htab->use_plts_and_copy_relocs);
8991
8992           h = _bfd_elf_define_linkage_sym (dynobj, info, htab->splt,
8993                                            "_PROCEDURE_LINKAGE_TABLE_");
8994           htab->root.hplt = h;
8995           if (h == NULL)
8996             return FALSE;
8997           h->type = STT_FUNC;
8998         }
8999     }
9000
9001   /* Allocate space for global sym dynamic relocs.  */
9002   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, info);
9003
9004   mips_elf_estimate_stub_size (output_bfd, info);
9005
9006   if (!mips_elf_lay_out_got (output_bfd, info))
9007     return FALSE;
9008
9009   mips_elf_lay_out_lazy_stubs (info);
9010
9011   /* The check_relocs and adjust_dynamic_symbol entry points have
9012      determined the sizes of the various dynamic sections.  Allocate
9013      memory for them.  */
9014   reltext = FALSE;
9015   for (s = dynobj->sections; s != NULL; s = s->next)
9016     {
9017       const char *name;
9018
9019       /* It's OK to base decisions on the section name, because none
9020          of the dynobj section names depend upon the input files.  */
9021       name = bfd_get_section_name (dynobj, s);
9022
9023       if ((s->flags & SEC_LINKER_CREATED) == 0)
9024         continue;
9025
9026       if (CONST_STRNEQ (name, ".rel"))
9027         {
9028           if (s->size != 0)
9029             {
9030               const char *outname;
9031               asection *target;
9032
9033               /* If this relocation section applies to a read only
9034                  section, then we probably need a DT_TEXTREL entry.
9035                  If the relocation section is .rel(a).dyn, we always
9036                  assert a DT_TEXTREL entry rather than testing whether
9037                  there exists a relocation to a read only section or
9038                  not.  */
9039               outname = bfd_get_section_name (output_bfd,
9040                                               s->output_section);
9041               target = bfd_get_section_by_name (output_bfd, outname + 4);
9042               if ((target != NULL
9043                    && (target->flags & SEC_READONLY) != 0
9044                    && (target->flags & SEC_ALLOC) != 0)
9045                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
9046                 reltext = TRUE;
9047
9048               /* We use the reloc_count field as a counter if we need
9049                  to copy relocs into the output file.  */
9050               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
9051                 s->reloc_count = 0;
9052
9053               /* If combreloc is enabled, elf_link_sort_relocs() will
9054                  sort relocations, but in a different way than we do,
9055                  and before we're done creating relocations.  Also, it
9056                  will move them around between input sections'
9057                  relocation's contents, so our sorting would be
9058                  broken, so don't let it run.  */
9059               info->combreloc = 0;
9060             }
9061         }
9062       else if (! info->shared
9063                && ! mips_elf_hash_table (info)->use_rld_obj_head
9064                && CONST_STRNEQ (name, ".rld_map"))
9065         {
9066           /* We add a room for __rld_map.  It will be filled in by the
9067              rtld to contain a pointer to the _r_debug structure.  */
9068           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
9069         }
9070       else if (SGI_COMPAT (output_bfd)
9071                && CONST_STRNEQ (name, ".compact_rel"))
9072         s->size += mips_elf_hash_table (info)->compact_rel_size;
9073       else if (s == htab->splt)
9074         {
9075           /* If the last PLT entry has a branch delay slot, allocate
9076              room for an extra nop to fill the delay slot.  This is
9077              for CPUs without load interlocking.  */
9078           if (! LOAD_INTERLOCKS_P (output_bfd)
9079               && ! htab->is_vxworks && s->size > 0)
9080             s->size += 4;
9081         }
9082       else if (! CONST_STRNEQ (name, ".init")
9083                && s != htab->sgot
9084                && s != htab->sgotplt
9085                && s != htab->sstubs
9086                && s != htab->sdynbss)
9087         {
9088           /* It's not one of our sections, so don't allocate space.  */
9089           continue;
9090         }
9091
9092       if (s->size == 0)
9093         {
9094           s->flags |= SEC_EXCLUDE;
9095           continue;
9096         }
9097
9098       if ((s->flags & SEC_HAS_CONTENTS) == 0)
9099         continue;
9100
9101       /* Allocate memory for the section contents.  */
9102       s->contents = bfd_zalloc (dynobj, s->size);
9103       if (s->contents == NULL)
9104         {
9105           bfd_set_error (bfd_error_no_memory);
9106           return FALSE;
9107         }
9108     }
9109
9110   if (elf_hash_table (info)->dynamic_sections_created)
9111     {
9112       /* Add some entries to the .dynamic section.  We fill in the
9113          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
9114          must add the entries now so that we get the correct size for
9115          the .dynamic section.  */
9116
9117       /* SGI object has the equivalence of DT_DEBUG in the
9118          DT_MIPS_RLD_MAP entry.  This must come first because glibc
9119          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and some tools
9120          may only look at the first one they see.  */
9121       if (!info->shared
9122           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
9123         return FALSE;
9124
9125       /* The DT_DEBUG entry may be filled in by the dynamic linker and
9126          used by the debugger.  */
9127       if (info->executable
9128           && !SGI_COMPAT (output_bfd)
9129           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
9130         return FALSE;
9131
9132       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
9133         info->flags |= DF_TEXTREL;
9134
9135       if ((info->flags & DF_TEXTREL) != 0)
9136         {
9137           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
9138             return FALSE;
9139
9140           /* Clear the DF_TEXTREL flag.  It will be set again if we
9141              write out an actual text relocation; we may not, because
9142              at this point we do not know whether e.g. any .eh_frame
9143              absolute relocations have been converted to PC-relative.  */
9144           info->flags &= ~DF_TEXTREL;
9145         }
9146
9147       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
9148         return FALSE;
9149
9150       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
9151       if (htab->is_vxworks)
9152         {
9153           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
9154              use any of the DT_MIPS_* tags.  */
9155           if (sreldyn && sreldyn->size > 0)
9156             {
9157               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
9158                 return FALSE;
9159
9160               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
9161                 return FALSE;
9162
9163               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
9164                 return FALSE;
9165             }
9166         }
9167       else
9168         {
9169           if (sreldyn && sreldyn->size > 0)
9170             {
9171               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
9172                 return FALSE;
9173
9174               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
9175                 return FALSE;
9176
9177               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
9178                 return FALSE;
9179             }
9180
9181           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
9182             return FALSE;
9183
9184           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
9185             return FALSE;
9186
9187           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
9188             return FALSE;
9189
9190           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
9191             return FALSE;
9192
9193           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
9194             return FALSE;
9195
9196           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
9197             return FALSE;
9198
9199           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
9200             return FALSE;
9201
9202           if (IRIX_COMPAT (dynobj) == ict_irix5
9203               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
9204             return FALSE;
9205
9206           if (IRIX_COMPAT (dynobj) == ict_irix6
9207               && (bfd_get_section_by_name
9208                   (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
9209               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
9210             return FALSE;
9211         }
9212       if (htab->splt->size > 0)
9213         {
9214           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
9215             return FALSE;
9216
9217           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
9218             return FALSE;
9219
9220           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
9221             return FALSE;
9222
9223           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
9224             return FALSE;
9225         }
9226       if (htab->is_vxworks
9227           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
9228         return FALSE;
9229     }
9230
9231   return TRUE;
9232 }
9233 \f
9234 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
9235    Adjust its R_ADDEND field so that it is correct for the output file.
9236    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
9237    and sections respectively; both use symbol indexes.  */
9238
9239 static void
9240 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
9241                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
9242                         asection **local_sections, Elf_Internal_Rela *rel)
9243 {
9244   unsigned int r_type, r_symndx;
9245   Elf_Internal_Sym *sym;
9246   asection *sec;
9247
9248   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9249     {
9250       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9251       if (gprel16_reloc_p (r_type)
9252           || r_type == R_MIPS_GPREL32
9253           || literal_reloc_p (r_type))
9254         {
9255           rel->r_addend += _bfd_get_gp_value (input_bfd);
9256           rel->r_addend -= _bfd_get_gp_value (output_bfd);
9257         }
9258
9259       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
9260       sym = local_syms + r_symndx;
9261
9262       /* Adjust REL's addend to account for section merging.  */
9263       if (!info->relocatable)
9264         {
9265           sec = local_sections[r_symndx];
9266           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
9267         }
9268
9269       /* This would normally be done by the rela_normal code in elflink.c.  */
9270       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
9271         rel->r_addend += local_sections[r_symndx]->output_offset;
9272     }
9273 }
9274
9275 /* Handle relocations against symbols from removed linkonce sections,
9276    or sections discarded by a linker script.  We use this wrapper around
9277    RELOC_AGAINST_DISCARDED_SECTION to handle triplets of compound relocs
9278    on 64-bit ELF targets.  In this case for any relocation handled, which
9279    always be the first in a triplet, the remaining two have to be processed
9280    together with the first, even if they are R_MIPS_NONE.  It is the symbol
9281    index referred by the first reloc that applies to all the three and the
9282    remaining two never refer to an object symbol.  And it is the final
9283    relocation (the last non-null one) that determines the output field of
9284    the whole relocation so retrieve the corresponding howto structure for
9285    the relocatable field to be cleared by RELOC_AGAINST_DISCARDED_SECTION.
9286
9287    Note that RELOC_AGAINST_DISCARDED_SECTION is a macro that uses "continue"
9288    and therefore requires to be pasted in a loop.  It also defines a block
9289    and does not protect any of its arguments, hence the extra brackets.  */
9290
9291 static void
9292 mips_reloc_against_discarded_section (bfd *output_bfd,
9293                                       struct bfd_link_info *info,
9294                                       bfd *input_bfd, asection *input_section,
9295                                       Elf_Internal_Rela **rel,
9296                                       const Elf_Internal_Rela **relend,
9297                                       bfd_boolean rel_reloc,
9298                                       reloc_howto_type *howto,
9299                                       bfd_byte *contents)
9300 {
9301   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
9302   int count = bed->s->int_rels_per_ext_rel;
9303   unsigned int r_type;
9304   int i;
9305
9306   for (i = count - 1; i > 0; i--)
9307     {
9308       r_type = ELF_R_TYPE (output_bfd, (*rel)[i].r_info);
9309       if (r_type != R_MIPS_NONE)
9310         {
9311           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9312           break;
9313         }
9314     }
9315   do
9316     {
9317        RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
9318                                         (*rel), count, (*relend),
9319                                         howto, i, contents);
9320     }
9321   while (0);
9322 }
9323
9324 /* Relocate a MIPS ELF section.  */
9325
9326 bfd_boolean
9327 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
9328                                 bfd *input_bfd, asection *input_section,
9329                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
9330                                 Elf_Internal_Sym *local_syms,
9331                                 asection **local_sections)
9332 {
9333   Elf_Internal_Rela *rel;
9334   const Elf_Internal_Rela *relend;
9335   bfd_vma addend = 0;
9336   bfd_boolean use_saved_addend_p = FALSE;
9337   const struct elf_backend_data *bed;
9338
9339   bed = get_elf_backend_data (output_bfd);
9340   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
9341   for (rel = relocs; rel < relend; ++rel)
9342     {
9343       const char *name;
9344       bfd_vma value = 0;
9345       reloc_howto_type *howto;
9346       bfd_boolean cross_mode_jump_p;
9347       /* TRUE if the relocation is a RELA relocation, rather than a
9348          REL relocation.  */
9349       bfd_boolean rela_relocation_p = TRUE;
9350       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9351       const char *msg;
9352       unsigned long r_symndx;
9353       asection *sec;
9354       Elf_Internal_Shdr *symtab_hdr;
9355       struct elf_link_hash_entry *h;
9356       bfd_boolean rel_reloc;
9357
9358       rel_reloc = (NEWABI_P (input_bfd)
9359                    && mips_elf_rel_relocation_p (input_bfd, input_section,
9360                                                  relocs, rel));
9361       /* Find the relocation howto for this relocation.  */
9362       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9363
9364       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
9365       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9366       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9367         {
9368           sec = local_sections[r_symndx];
9369           h = NULL;
9370         }
9371       else
9372         {
9373           unsigned long extsymoff;
9374
9375           extsymoff = 0;
9376           if (!elf_bad_symtab (input_bfd))
9377             extsymoff = symtab_hdr->sh_info;
9378           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
9379           while (h->root.type == bfd_link_hash_indirect
9380                  || h->root.type == bfd_link_hash_warning)
9381             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9382
9383           sec = NULL;
9384           if (h->root.type == bfd_link_hash_defined
9385               || h->root.type == bfd_link_hash_defweak)
9386             sec = h->root.u.def.section;
9387         }
9388
9389       if (sec != NULL && discarded_section (sec))
9390         {
9391           mips_reloc_against_discarded_section (output_bfd, info, input_bfd,
9392                                                 input_section, &rel, &relend,
9393                                                 rel_reloc, howto, contents);
9394           continue;
9395         }
9396
9397       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
9398         {
9399           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
9400              64-bit code, but make sure all their addresses are in the
9401              lowermost or uppermost 32-bit section of the 64-bit address
9402              space.  Thus, when they use an R_MIPS_64 they mean what is
9403              usually meant by R_MIPS_32, with the exception that the
9404              stored value is sign-extended to 64 bits.  */
9405           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
9406
9407           /* On big-endian systems, we need to lie about the position
9408              of the reloc.  */
9409           if (bfd_big_endian (input_bfd))
9410             rel->r_offset += 4;
9411         }
9412
9413       if (!use_saved_addend_p)
9414         {
9415           /* If these relocations were originally of the REL variety,
9416              we must pull the addend out of the field that will be
9417              relocated.  Otherwise, we simply use the contents of the
9418              RELA relocation.  */
9419           if (mips_elf_rel_relocation_p (input_bfd, input_section,
9420                                          relocs, rel))
9421             {
9422               rela_relocation_p = FALSE;
9423               addend = mips_elf_read_rel_addend (input_bfd, rel,
9424                                                  howto, contents);
9425               if (hi16_reloc_p (r_type)
9426                   || (got16_reloc_p (r_type)
9427                       && mips_elf_local_relocation_p (input_bfd, rel,
9428                                                       local_sections)))
9429                 {
9430                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
9431                                                      contents, &addend))
9432                     {
9433                       if (h)
9434                         name = h->root.root.string;
9435                       else
9436                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9437                                                  local_syms + r_symndx,
9438                                                  sec);
9439                       (*_bfd_error_handler)
9440                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
9441                          input_bfd, input_section, name, howto->name,
9442                          rel->r_offset);
9443                     }
9444                 }
9445               else
9446                 addend <<= howto->rightshift;
9447             }
9448           else
9449             addend = rel->r_addend;
9450           mips_elf_adjust_addend (output_bfd, info, input_bfd,
9451                                   local_syms, local_sections, rel);
9452         }
9453
9454       if (info->relocatable)
9455         {
9456           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
9457               && bfd_big_endian (input_bfd))
9458             rel->r_offset -= 4;
9459
9460           if (!rela_relocation_p && rel->r_addend)
9461             {
9462               addend += rel->r_addend;
9463               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
9464                 addend = mips_elf_high (addend);
9465               else if (r_type == R_MIPS_HIGHER)
9466                 addend = mips_elf_higher (addend);
9467               else if (r_type == R_MIPS_HIGHEST)
9468                 addend = mips_elf_highest (addend);
9469               else
9470                 addend >>= howto->rightshift;
9471
9472               /* We use the source mask, rather than the destination
9473                  mask because the place to which we are writing will be
9474                  source of the addend in the final link.  */
9475               addend &= howto->src_mask;
9476
9477               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9478                 /* See the comment above about using R_MIPS_64 in the 32-bit
9479                    ABI.  Here, we need to update the addend.  It would be
9480                    possible to get away with just using the R_MIPS_32 reloc
9481                    but for endianness.  */
9482                 {
9483                   bfd_vma sign_bits;
9484                   bfd_vma low_bits;
9485                   bfd_vma high_bits;
9486
9487                   if (addend & ((bfd_vma) 1 << 31))
9488 #ifdef BFD64
9489                     sign_bits = ((bfd_vma) 1 << 32) - 1;
9490 #else
9491                     sign_bits = -1;
9492 #endif
9493                   else
9494                     sign_bits = 0;
9495
9496                   /* If we don't know that we have a 64-bit type,
9497                      do two separate stores.  */
9498                   if (bfd_big_endian (input_bfd))
9499                     {
9500                       /* Store the sign-bits (which are most significant)
9501                          first.  */
9502                       low_bits = sign_bits;
9503                       high_bits = addend;
9504                     }
9505                   else
9506                     {
9507                       low_bits = addend;
9508                       high_bits = sign_bits;
9509                     }
9510                   bfd_put_32 (input_bfd, low_bits,
9511                               contents + rel->r_offset);
9512                   bfd_put_32 (input_bfd, high_bits,
9513                               contents + rel->r_offset + 4);
9514                   continue;
9515                 }
9516
9517               if (! mips_elf_perform_relocation (info, howto, rel, addend,
9518                                                  input_bfd, input_section,
9519                                                  contents, FALSE))
9520                 return FALSE;
9521             }
9522
9523           /* Go on to the next relocation.  */
9524           continue;
9525         }
9526
9527       /* In the N32 and 64-bit ABIs there may be multiple consecutive
9528          relocations for the same offset.  In that case we are
9529          supposed to treat the output of each relocation as the addend
9530          for the next.  */
9531       if (rel + 1 < relend
9532           && rel->r_offset == rel[1].r_offset
9533           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
9534         use_saved_addend_p = TRUE;
9535       else
9536         use_saved_addend_p = FALSE;
9537
9538       /* Figure out what value we are supposed to relocate.  */
9539       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
9540                                              input_section, info, rel,
9541                                              addend, howto, local_syms,
9542                                              local_sections, &value,
9543                                              &name, &cross_mode_jump_p,
9544                                              use_saved_addend_p))
9545         {
9546         case bfd_reloc_continue:
9547           /* There's nothing to do.  */
9548           continue;
9549
9550         case bfd_reloc_undefined:
9551           /* mips_elf_calculate_relocation already called the
9552              undefined_symbol callback.  There's no real point in
9553              trying to perform the relocation at this point, so we
9554              just skip ahead to the next relocation.  */
9555           continue;
9556
9557         case bfd_reloc_notsupported:
9558           msg = _("internal error: unsupported relocation error");
9559           info->callbacks->warning
9560             (info, msg, name, input_bfd, input_section, rel->r_offset);
9561           return FALSE;
9562
9563         case bfd_reloc_overflow:
9564           if (use_saved_addend_p)
9565             /* Ignore overflow until we reach the last relocation for
9566                a given location.  */
9567             ;
9568           else
9569             {
9570               struct mips_elf_link_hash_table *htab;
9571
9572               htab = mips_elf_hash_table (info);
9573               BFD_ASSERT (htab != NULL);
9574               BFD_ASSERT (name != NULL);
9575               if (!htab->small_data_overflow_reported
9576                   && (gprel16_reloc_p (howto->type)
9577                       || literal_reloc_p (howto->type)))
9578                 {
9579                   msg = _("small-data section exceeds 64KB;"
9580                           " lower small-data size limit (see option -G)");
9581
9582                   htab->small_data_overflow_reported = TRUE;
9583                   (*info->callbacks->einfo) ("%P: %s\n", msg);
9584                 }
9585               if (! ((*info->callbacks->reloc_overflow)
9586                      (info, NULL, name, howto->name, (bfd_vma) 0,
9587                       input_bfd, input_section, rel->r_offset)))
9588                 return FALSE;
9589             }
9590           break;
9591
9592         case bfd_reloc_ok:
9593           break;
9594
9595         case bfd_reloc_outofrange:
9596           if (jal_reloc_p (howto->type))
9597             {
9598               msg = _("JALX to a non-word-aligned address");
9599               info->callbacks->warning
9600                 (info, msg, name, input_bfd, input_section, rel->r_offset);
9601               return FALSE;
9602             }
9603           /* Fall through.  */
9604
9605         default:
9606           abort ();
9607           break;
9608         }
9609
9610       /* If we've got another relocation for the address, keep going
9611          until we reach the last one.  */
9612       if (use_saved_addend_p)
9613         {
9614           addend = value;
9615           continue;
9616         }
9617
9618       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9619         /* See the comment above about using R_MIPS_64 in the 32-bit
9620            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
9621            that calculated the right value.  Now, however, we
9622            sign-extend the 32-bit result to 64-bits, and store it as a
9623            64-bit value.  We are especially generous here in that we
9624            go to extreme lengths to support this usage on systems with
9625            only a 32-bit VMA.  */
9626         {
9627           bfd_vma sign_bits;
9628           bfd_vma low_bits;
9629           bfd_vma high_bits;
9630
9631           if (value & ((bfd_vma) 1 << 31))
9632 #ifdef BFD64
9633             sign_bits = ((bfd_vma) 1 << 32) - 1;
9634 #else
9635             sign_bits = -1;
9636 #endif
9637           else
9638             sign_bits = 0;
9639
9640           /* If we don't know that we have a 64-bit type,
9641              do two separate stores.  */
9642           if (bfd_big_endian (input_bfd))
9643             {
9644               /* Undo what we did above.  */
9645               rel->r_offset -= 4;
9646               /* Store the sign-bits (which are most significant)
9647                  first.  */
9648               low_bits = sign_bits;
9649               high_bits = value;
9650             }
9651           else
9652             {
9653               low_bits = value;
9654               high_bits = sign_bits;
9655             }
9656           bfd_put_32 (input_bfd, low_bits,
9657                       contents + rel->r_offset);
9658           bfd_put_32 (input_bfd, high_bits,
9659                       contents + rel->r_offset + 4);
9660           continue;
9661         }
9662
9663       /* Actually perform the relocation.  */
9664       if (! mips_elf_perform_relocation (info, howto, rel, value,
9665                                          input_bfd, input_section,
9666                                          contents, cross_mode_jump_p))
9667         return FALSE;
9668     }
9669
9670   return TRUE;
9671 }
9672 \f
9673 /* A function that iterates over each entry in la25_stubs and fills
9674    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
9675
9676 static int
9677 mips_elf_create_la25_stub (void **slot, void *data)
9678 {
9679   struct mips_htab_traverse_info *hti;
9680   struct mips_elf_link_hash_table *htab;
9681   struct mips_elf_la25_stub *stub;
9682   asection *s;
9683   bfd_byte *loc;
9684   bfd_vma offset, target, target_high, target_low;
9685
9686   stub = (struct mips_elf_la25_stub *) *slot;
9687   hti = (struct mips_htab_traverse_info *) data;
9688   htab = mips_elf_hash_table (hti->info);
9689   BFD_ASSERT (htab != NULL);
9690
9691   /* Create the section contents, if we haven't already.  */
9692   s = stub->stub_section;
9693   loc = s->contents;
9694   if (loc == NULL)
9695     {
9696       loc = bfd_malloc (s->size);
9697       if (loc == NULL)
9698         {
9699           hti->error = TRUE;
9700           return FALSE;
9701         }
9702       s->contents = loc;
9703     }
9704
9705   /* Work out where in the section this stub should go.  */
9706   offset = stub->offset;
9707
9708   /* Work out the target address.  */
9709   target = mips_elf_get_la25_target (stub, &s);
9710   target += s->output_section->vma + s->output_offset;
9711
9712   target_high = ((target + 0x8000) >> 16) & 0xffff;
9713   target_low = (target & 0xffff);
9714
9715   if (stub->stub_section != htab->strampoline)
9716     {
9717       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
9718          of the section and write the two instructions at the end.  */
9719       memset (loc, 0, offset);
9720       loc += offset;
9721       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9722         {
9723           bfd_put_micromips_32 (hti->output_bfd,
9724                                 LA25_LUI_MICROMIPS (target_high),
9725                                 loc);
9726           bfd_put_micromips_32 (hti->output_bfd,
9727                                 LA25_ADDIU_MICROMIPS (target_low),
9728                                 loc + 4);
9729         }
9730       else
9731         {
9732           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9733           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
9734         }
9735     }
9736   else
9737     {
9738       /* This is trampoline.  */
9739       loc += offset;
9740       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9741         {
9742           bfd_put_micromips_32 (hti->output_bfd,
9743                                 LA25_LUI_MICROMIPS (target_high), loc);
9744           bfd_put_micromips_32 (hti->output_bfd,
9745                                 LA25_J_MICROMIPS (target), loc + 4);
9746           bfd_put_micromips_32 (hti->output_bfd,
9747                                 LA25_ADDIU_MICROMIPS (target_low), loc + 8);
9748           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9749         }
9750       else
9751         {
9752           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9753           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
9754           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
9755           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9756         }
9757     }
9758   return TRUE;
9759 }
9760
9761 /* If NAME is one of the special IRIX6 symbols defined by the linker,
9762    adjust it appropriately now.  */
9763
9764 static void
9765 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
9766                                       const char *name, Elf_Internal_Sym *sym)
9767 {
9768   /* The linker script takes care of providing names and values for
9769      these, but we must place them into the right sections.  */
9770   static const char* const text_section_symbols[] = {
9771     "_ftext",
9772     "_etext",
9773     "__dso_displacement",
9774     "__elf_header",
9775     "__program_header_table",
9776     NULL
9777   };
9778
9779   static const char* const data_section_symbols[] = {
9780     "_fdata",
9781     "_edata",
9782     "_end",
9783     "_fbss",
9784     NULL
9785   };
9786
9787   const char* const *p;
9788   int i;
9789
9790   for (i = 0; i < 2; ++i)
9791     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
9792          *p;
9793          ++p)
9794       if (strcmp (*p, name) == 0)
9795         {
9796           /* All of these symbols are given type STT_SECTION by the
9797              IRIX6 linker.  */
9798           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9799           sym->st_other = STO_PROTECTED;
9800
9801           /* The IRIX linker puts these symbols in special sections.  */
9802           if (i == 0)
9803             sym->st_shndx = SHN_MIPS_TEXT;
9804           else
9805             sym->st_shndx = SHN_MIPS_DATA;
9806
9807           break;
9808         }
9809 }
9810
9811 /* Finish up dynamic symbol handling.  We set the contents of various
9812    dynamic sections here.  */
9813
9814 bfd_boolean
9815 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
9816                                      struct bfd_link_info *info,
9817                                      struct elf_link_hash_entry *h,
9818                                      Elf_Internal_Sym *sym)
9819 {
9820   bfd *dynobj;
9821   asection *sgot;
9822   struct mips_got_info *g, *gg;
9823   const char *name;
9824   int idx;
9825   struct mips_elf_link_hash_table *htab;
9826   struct mips_elf_link_hash_entry *hmips;
9827
9828   htab = mips_elf_hash_table (info);
9829   BFD_ASSERT (htab != NULL);
9830   dynobj = elf_hash_table (info)->dynobj;
9831   hmips = (struct mips_elf_link_hash_entry *) h;
9832
9833   BFD_ASSERT (!htab->is_vxworks);
9834
9835   if (h->plt.offset != MINUS_ONE && hmips->no_fn_stub)
9836     {
9837       /* We've decided to create a PLT entry for this symbol.  */
9838       bfd_byte *loc;
9839       bfd_vma header_address, plt_index, got_address;
9840       bfd_vma got_address_high, got_address_low, load;
9841       const bfd_vma *plt_entry;
9842
9843       BFD_ASSERT (htab->use_plts_and_copy_relocs);
9844       BFD_ASSERT (h->dynindx != -1);
9845       BFD_ASSERT (htab->splt != NULL);
9846       BFD_ASSERT (h->plt.offset <= htab->splt->size);
9847       BFD_ASSERT (!h->def_regular);
9848
9849       /* Calculate the address of the PLT header.  */
9850       header_address = (htab->splt->output_section->vma
9851                         + htab->splt->output_offset);
9852
9853       /* Calculate the index of the entry.  */
9854       plt_index = ((h->plt.offset - htab->plt_header_size)
9855                    / htab->plt_entry_size);
9856
9857       /* Calculate the address of the .got.plt entry.  */
9858       got_address = (htab->sgotplt->output_section->vma
9859                      + htab->sgotplt->output_offset
9860                      + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9861       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
9862       got_address_low = got_address & 0xffff;
9863
9864       /* Initially point the .got.plt entry at the PLT header.  */
9865       loc = (htab->sgotplt->contents
9866              + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9867       if (ABI_64_P (output_bfd))
9868         bfd_put_64 (output_bfd, header_address, loc);
9869       else
9870         bfd_put_32 (output_bfd, header_address, loc);
9871
9872       /* Find out where the .plt entry should go.  */
9873       loc = htab->splt->contents + h->plt.offset;
9874
9875       /* Pick the load opcode.  */
9876       load = MIPS_ELF_LOAD_WORD (output_bfd);
9877
9878       /* Fill in the PLT entry itself.  */
9879       plt_entry = mips_exec_plt_entry;
9880       bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
9881       bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load, loc + 4);
9882
9883       if (! LOAD_INTERLOCKS_P (output_bfd))
9884         {
9885           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
9886           bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
9887         }
9888       else
9889         {
9890           bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
9891           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 12);
9892         }
9893
9894       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
9895       mips_elf_output_dynamic_relocation (output_bfd, htab->srelplt,
9896                                           plt_index, h->dynindx,
9897                                           R_MIPS_JUMP_SLOT, got_address);
9898
9899       /* We distinguish between PLT entries and lazy-binding stubs by
9900          giving the former an st_other value of STO_MIPS_PLT.  Set the
9901          flag and leave the value if there are any relocations in the
9902          binary where pointer equality matters.  */
9903       sym->st_shndx = SHN_UNDEF;
9904       if (h->pointer_equality_needed)
9905         sym->st_other = STO_MIPS_PLT;
9906       else
9907         sym->st_value = 0;
9908     }
9909   else if (h->plt.offset != MINUS_ONE)
9910     {
9911       /* We've decided to create a lazy-binding stub.  */
9912       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
9913
9914       /* This symbol has a stub.  Set it up.  */
9915
9916       BFD_ASSERT (h->dynindx != -1);
9917
9918       BFD_ASSERT ((htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9919                   || (h->dynindx <= 0xffff));
9920
9921       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
9922          sign extension at runtime in the stub, resulting in a negative
9923          index value.  */
9924       if (h->dynindx & ~0x7fffffff)
9925         return FALSE;
9926
9927       /* Fill the stub.  */
9928       idx = 0;
9929       bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
9930       idx += 4;
9931       bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + idx);
9932       idx += 4;
9933       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9934         {
9935           bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
9936                       stub + idx);
9937           idx += 4;
9938         }
9939       bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
9940       idx += 4;
9941
9942       /* If a large stub is not required and sign extension is not a
9943          problem, then use legacy code in the stub.  */
9944       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9945         bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff), stub + idx);
9946       else if (h->dynindx & ~0x7fff)
9947         bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff), stub + idx);
9948       else
9949         bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
9950                     stub + idx);
9951
9952       BFD_ASSERT (h->plt.offset <= htab->sstubs->size);
9953       memcpy (htab->sstubs->contents + h->plt.offset,
9954               stub, htab->function_stub_size);
9955
9956       /* Mark the symbol as undefined.  plt.offset != -1 occurs
9957          only for the referenced symbol.  */
9958       sym->st_shndx = SHN_UNDEF;
9959
9960       /* The run-time linker uses the st_value field of the symbol
9961          to reset the global offset table entry for this external
9962          to its stub address when unlinking a shared object.  */
9963       sym->st_value = (htab->sstubs->output_section->vma
9964                        + htab->sstubs->output_offset
9965                        + h->plt.offset);
9966     }
9967
9968   /* If we have a MIPS16 function with a stub, the dynamic symbol must
9969      refer to the stub, since only the stub uses the standard calling
9970      conventions.  */
9971   if (h->dynindx != -1 && hmips->fn_stub != NULL)
9972     {
9973       BFD_ASSERT (hmips->need_fn_stub);
9974       sym->st_value = (hmips->fn_stub->output_section->vma
9975                        + hmips->fn_stub->output_offset);
9976       sym->st_size = hmips->fn_stub->size;
9977       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
9978     }
9979
9980   BFD_ASSERT (h->dynindx != -1
9981               || h->forced_local);
9982
9983   sgot = htab->sgot;
9984   g = htab->got_info;
9985   BFD_ASSERT (g != NULL);
9986
9987   /* Run through the global symbol table, creating GOT entries for all
9988      the symbols that need them.  */
9989   if (hmips->global_got_area != GGA_NONE)
9990     {
9991       bfd_vma offset;
9992       bfd_vma value;
9993
9994       value = sym->st_value;
9995       offset = mips_elf_global_got_index (dynobj, output_bfd, h,
9996                                           R_MIPS_GOT16, info);
9997       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
9998     }
9999
10000   if (hmips->global_got_area != GGA_NONE && g->next)
10001     {
10002       struct mips_got_entry e, *p;
10003       bfd_vma entry;
10004       bfd_vma offset;
10005
10006       gg = g;
10007
10008       e.abfd = output_bfd;
10009       e.symndx = -1;
10010       e.d.h = hmips;
10011       e.tls_type = 0;
10012
10013       for (g = g->next; g->next != gg; g = g->next)
10014         {
10015           if (g->got_entries
10016               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
10017                                                            &e)))
10018             {
10019               offset = p->gotidx;
10020               if (info->shared
10021                   || (elf_hash_table (info)->dynamic_sections_created
10022                       && p->d.h != NULL
10023                       && p->d.h->root.def_dynamic
10024                       && !p->d.h->root.def_regular))
10025                 {
10026                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
10027                      the various compatibility problems, it's easier to mock
10028                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
10029                      mips_elf_create_dynamic_relocation to calculate the
10030                      appropriate addend.  */
10031                   Elf_Internal_Rela rel[3];
10032
10033                   memset (rel, 0, sizeof (rel));
10034                   if (ABI_64_P (output_bfd))
10035                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
10036                   else
10037                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
10038                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
10039
10040                   entry = 0;
10041                   if (! (mips_elf_create_dynamic_relocation
10042                          (output_bfd, info, rel,
10043                           e.d.h, NULL, sym->st_value, &entry, sgot)))
10044                     return FALSE;
10045                 }
10046               else
10047                 entry = sym->st_value;
10048               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
10049             }
10050         }
10051     }
10052
10053   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
10054   name = h->root.root.string;
10055   if (h == elf_hash_table (info)->hdynamic
10056       || h == elf_hash_table (info)->hgot)
10057     sym->st_shndx = SHN_ABS;
10058   else if (strcmp (name, "_DYNAMIC_LINK") == 0
10059            || strcmp (name, "_DYNAMIC_LINKING") == 0)
10060     {
10061       sym->st_shndx = SHN_ABS;
10062       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10063       sym->st_value = 1;
10064     }
10065   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
10066     {
10067       sym->st_shndx = SHN_ABS;
10068       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10069       sym->st_value = elf_gp (output_bfd);
10070     }
10071   else if (SGI_COMPAT (output_bfd))
10072     {
10073       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
10074           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
10075         {
10076           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10077           sym->st_other = STO_PROTECTED;
10078           sym->st_value = 0;
10079           sym->st_shndx = SHN_MIPS_DATA;
10080         }
10081       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
10082         {
10083           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10084           sym->st_other = STO_PROTECTED;
10085           sym->st_value = mips_elf_hash_table (info)->procedure_count;
10086           sym->st_shndx = SHN_ABS;
10087         }
10088       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
10089         {
10090           if (h->type == STT_FUNC)
10091             sym->st_shndx = SHN_MIPS_TEXT;
10092           else if (h->type == STT_OBJECT)
10093             sym->st_shndx = SHN_MIPS_DATA;
10094         }
10095     }
10096
10097   /* Emit a copy reloc, if needed.  */
10098   if (h->needs_copy)
10099     {
10100       asection *s;
10101       bfd_vma symval;
10102
10103       BFD_ASSERT (h->dynindx != -1);
10104       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10105
10106       s = mips_elf_rel_dyn_section (info, FALSE);
10107       symval = (h->root.u.def.section->output_section->vma
10108                 + h->root.u.def.section->output_offset
10109                 + h->root.u.def.value);
10110       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
10111                                           h->dynindx, R_MIPS_COPY, symval);
10112     }
10113
10114   /* Handle the IRIX6-specific symbols.  */
10115   if (IRIX_COMPAT (output_bfd) == ict_irix6)
10116     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
10117
10118   /* Keep dynamic MIPS16 symbols odd.  This allows the dynamic linker to
10119      treat MIPS16 symbols like any other.  */
10120   if (ELF_ST_IS_MIPS16 (sym->st_other))
10121     {
10122       BFD_ASSERT (sym->st_value & 1);
10123       sym->st_other -= STO_MIPS16;
10124     }
10125
10126   return TRUE;
10127 }
10128
10129 /* Likewise, for VxWorks.  */
10130
10131 bfd_boolean
10132 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
10133                                          struct bfd_link_info *info,
10134                                          struct elf_link_hash_entry *h,
10135                                          Elf_Internal_Sym *sym)
10136 {
10137   bfd *dynobj;
10138   asection *sgot;
10139   struct mips_got_info *g;
10140   struct mips_elf_link_hash_table *htab;
10141   struct mips_elf_link_hash_entry *hmips;
10142
10143   htab = mips_elf_hash_table (info);
10144   BFD_ASSERT (htab != NULL);
10145   dynobj = elf_hash_table (info)->dynobj;
10146   hmips = (struct mips_elf_link_hash_entry *) h;
10147
10148   if (h->plt.offset != (bfd_vma) -1)
10149     {
10150       bfd_byte *loc;
10151       bfd_vma plt_address, plt_index, got_address, got_offset, branch_offset;
10152       Elf_Internal_Rela rel;
10153       static const bfd_vma *plt_entry;
10154
10155       BFD_ASSERT (h->dynindx != -1);
10156       BFD_ASSERT (htab->splt != NULL);
10157       BFD_ASSERT (h->plt.offset <= htab->splt->size);
10158
10159       /* Calculate the address of the .plt entry.  */
10160       plt_address = (htab->splt->output_section->vma
10161                      + htab->splt->output_offset
10162                      + h->plt.offset);
10163
10164       /* Calculate the index of the entry.  */
10165       plt_index = ((h->plt.offset - htab->plt_header_size)
10166                    / htab->plt_entry_size);
10167
10168       /* Calculate the address of the .got.plt entry.  */
10169       got_address = (htab->sgotplt->output_section->vma
10170                      + htab->sgotplt->output_offset
10171                      + plt_index * 4);
10172
10173       /* Calculate the offset of the .got.plt entry from
10174          _GLOBAL_OFFSET_TABLE_.  */
10175       got_offset = mips_elf_gotplt_index (info, h);
10176
10177       /* Calculate the offset for the branch at the start of the PLT
10178          entry.  The branch jumps to the beginning of .plt.  */
10179       branch_offset = -(h->plt.offset / 4 + 1) & 0xffff;
10180
10181       /* Fill in the initial value of the .got.plt entry.  */
10182       bfd_put_32 (output_bfd, plt_address,
10183                   htab->sgotplt->contents + plt_index * 4);
10184
10185       /* Find out where the .plt entry should go.  */
10186       loc = htab->splt->contents + h->plt.offset;
10187
10188       if (info->shared)
10189         {
10190           plt_entry = mips_vxworks_shared_plt_entry;
10191           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10192           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10193         }
10194       else
10195         {
10196           bfd_vma got_address_high, got_address_low;
10197
10198           plt_entry = mips_vxworks_exec_plt_entry;
10199           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10200           got_address_low = got_address & 0xffff;
10201
10202           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10203           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10204           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
10205           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
10206           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10207           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10208           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10209           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10210
10211           loc = (htab->srelplt2->contents
10212                  + (plt_index * 3 + 2) * sizeof (Elf32_External_Rela));
10213
10214           /* Emit a relocation for the .got.plt entry.  */
10215           rel.r_offset = got_address;
10216           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10217           rel.r_addend = h->plt.offset;
10218           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10219
10220           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
10221           loc += sizeof (Elf32_External_Rela);
10222           rel.r_offset = plt_address + 8;
10223           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10224           rel.r_addend = got_offset;
10225           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10226
10227           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
10228           loc += sizeof (Elf32_External_Rela);
10229           rel.r_offset += 4;
10230           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10231           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10232         }
10233
10234       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10235       loc = htab->srelplt->contents + plt_index * sizeof (Elf32_External_Rela);
10236       rel.r_offset = got_address;
10237       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
10238       rel.r_addend = 0;
10239       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10240
10241       if (!h->def_regular)
10242         sym->st_shndx = SHN_UNDEF;
10243     }
10244
10245   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
10246
10247   sgot = htab->sgot;
10248   g = htab->got_info;
10249   BFD_ASSERT (g != NULL);
10250
10251   /* See if this symbol has an entry in the GOT.  */
10252   if (hmips->global_got_area != GGA_NONE)
10253     {
10254       bfd_vma offset;
10255       Elf_Internal_Rela outrel;
10256       bfd_byte *loc;
10257       asection *s;
10258
10259       /* Install the symbol value in the GOT.   */
10260       offset = mips_elf_global_got_index (dynobj, output_bfd, h,
10261                                           R_MIPS_GOT16, info);
10262       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
10263
10264       /* Add a dynamic relocation for it.  */
10265       s = mips_elf_rel_dyn_section (info, FALSE);
10266       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
10267       outrel.r_offset = (sgot->output_section->vma
10268                          + sgot->output_offset
10269                          + offset);
10270       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
10271       outrel.r_addend = 0;
10272       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
10273     }
10274
10275   /* Emit a copy reloc, if needed.  */
10276   if (h->needs_copy)
10277     {
10278       Elf_Internal_Rela rel;
10279
10280       BFD_ASSERT (h->dynindx != -1);
10281
10282       rel.r_offset = (h->root.u.def.section->output_section->vma
10283                       + h->root.u.def.section->output_offset
10284                       + h->root.u.def.value);
10285       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
10286       rel.r_addend = 0;
10287       bfd_elf32_swap_reloca_out (output_bfd, &rel,
10288                                  htab->srelbss->contents
10289                                  + (htab->srelbss->reloc_count
10290                                     * sizeof (Elf32_External_Rela)));
10291       ++htab->srelbss->reloc_count;
10292     }
10293
10294   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
10295   if (ELF_ST_IS_COMPRESSED (sym->st_other))
10296     sym->st_value &= ~1;
10297
10298   return TRUE;
10299 }
10300
10301 /* Write out a plt0 entry to the beginning of .plt.  */
10302
10303 static void
10304 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10305 {
10306   bfd_byte *loc;
10307   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
10308   static const bfd_vma *plt_entry;
10309   struct mips_elf_link_hash_table *htab;
10310
10311   htab = mips_elf_hash_table (info);
10312   BFD_ASSERT (htab != NULL);
10313
10314   if (ABI_64_P (output_bfd))
10315     plt_entry = mips_n64_exec_plt0_entry;
10316   else if (ABI_N32_P (output_bfd))
10317     plt_entry = mips_n32_exec_plt0_entry;
10318   else
10319     plt_entry = mips_o32_exec_plt0_entry;
10320
10321   /* Calculate the value of .got.plt.  */
10322   gotplt_value = (htab->sgotplt->output_section->vma
10323                   + htab->sgotplt->output_offset);
10324   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
10325   gotplt_value_low = gotplt_value & 0xffff;
10326
10327   /* The PLT sequence is not safe for N64 if .got.plt's address can
10328      not be loaded in two instructions.  */
10329   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
10330               || ~(gotplt_value | 0x7fffffff) == 0);
10331
10332   /* Install the PLT header.  */
10333   loc = htab->splt->contents;
10334   bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
10335   bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
10336   bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
10337   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10338   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10339   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10340   bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10341   bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10342 }
10343
10344 /* Install the PLT header for a VxWorks executable and finalize the
10345    contents of .rela.plt.unloaded.  */
10346
10347 static void
10348 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10349 {
10350   Elf_Internal_Rela rela;
10351   bfd_byte *loc;
10352   bfd_vma got_value, got_value_high, got_value_low, plt_address;
10353   static const bfd_vma *plt_entry;
10354   struct mips_elf_link_hash_table *htab;
10355
10356   htab = mips_elf_hash_table (info);
10357   BFD_ASSERT (htab != NULL);
10358
10359   plt_entry = mips_vxworks_exec_plt0_entry;
10360
10361   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
10362   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
10363                + htab->root.hgot->root.u.def.section->output_offset
10364                + htab->root.hgot->root.u.def.value);
10365
10366   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
10367   got_value_low = got_value & 0xffff;
10368
10369   /* Calculate the address of the PLT header.  */
10370   plt_address = htab->splt->output_section->vma + htab->splt->output_offset;
10371
10372   /* Install the PLT header.  */
10373   loc = htab->splt->contents;
10374   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
10375   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
10376   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
10377   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10378   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10379   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10380
10381   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
10382   loc = htab->srelplt2->contents;
10383   rela.r_offset = plt_address;
10384   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10385   rela.r_addend = 0;
10386   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10387   loc += sizeof (Elf32_External_Rela);
10388
10389   /* Output the relocation for the following addiu of
10390      %lo(_GLOBAL_OFFSET_TABLE_).  */
10391   rela.r_offset += 4;
10392   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10393   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10394   loc += sizeof (Elf32_External_Rela);
10395
10396   /* Fix up the remaining relocations.  They may have the wrong
10397      symbol index for _G_O_T_ or _P_L_T_ depending on the order
10398      in which symbols were output.  */
10399   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
10400     {
10401       Elf_Internal_Rela rel;
10402
10403       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10404       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10405       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10406       loc += sizeof (Elf32_External_Rela);
10407
10408       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10409       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10410       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10411       loc += sizeof (Elf32_External_Rela);
10412
10413       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10414       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10415       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10416       loc += sizeof (Elf32_External_Rela);
10417     }
10418 }
10419
10420 /* Install the PLT header for a VxWorks shared library.  */
10421
10422 static void
10423 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
10424 {
10425   unsigned int i;
10426   struct mips_elf_link_hash_table *htab;
10427
10428   htab = mips_elf_hash_table (info);
10429   BFD_ASSERT (htab != NULL);
10430
10431   /* We just need to copy the entry byte-by-byte.  */
10432   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
10433     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
10434                 htab->splt->contents + i * 4);
10435 }
10436
10437 /* Finish up the dynamic sections.  */
10438
10439 bfd_boolean
10440 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
10441                                        struct bfd_link_info *info)
10442 {
10443   bfd *dynobj;
10444   asection *sdyn;
10445   asection *sgot;
10446   struct mips_got_info *gg, *g;
10447   struct mips_elf_link_hash_table *htab;
10448
10449   htab = mips_elf_hash_table (info);
10450   BFD_ASSERT (htab != NULL);
10451
10452   dynobj = elf_hash_table (info)->dynobj;
10453
10454   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
10455
10456   sgot = htab->sgot;
10457   gg = htab->got_info;
10458
10459   if (elf_hash_table (info)->dynamic_sections_created)
10460     {
10461       bfd_byte *b;
10462       int dyn_to_skip = 0, dyn_skipped = 0;
10463
10464       BFD_ASSERT (sdyn != NULL);
10465       BFD_ASSERT (gg != NULL);
10466
10467       g = mips_elf_bfd_got (output_bfd, FALSE);
10468       BFD_ASSERT (g != NULL);
10469
10470       for (b = sdyn->contents;
10471            b < sdyn->contents + sdyn->size;
10472            b += MIPS_ELF_DYN_SIZE (dynobj))
10473         {
10474           Elf_Internal_Dyn dyn;
10475           const char *name;
10476           size_t elemsize;
10477           asection *s;
10478           bfd_boolean swap_out_p;
10479
10480           /* Read in the current dynamic entry.  */
10481           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10482
10483           /* Assume that we're going to modify it and write it out.  */
10484           swap_out_p = TRUE;
10485
10486           switch (dyn.d_tag)
10487             {
10488             case DT_RELENT:
10489               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
10490               break;
10491
10492             case DT_RELAENT:
10493               BFD_ASSERT (htab->is_vxworks);
10494               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
10495               break;
10496
10497             case DT_STRSZ:
10498               /* Rewrite DT_STRSZ.  */
10499               dyn.d_un.d_val =
10500                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
10501               break;
10502
10503             case DT_PLTGOT:
10504               s = htab->sgot;
10505               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10506               break;
10507
10508             case DT_MIPS_PLTGOT:
10509               s = htab->sgotplt;
10510               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10511               break;
10512
10513             case DT_MIPS_RLD_VERSION:
10514               dyn.d_un.d_val = 1; /* XXX */
10515               break;
10516
10517             case DT_MIPS_FLAGS:
10518               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
10519               break;
10520
10521             case DT_MIPS_TIME_STAMP:
10522               {
10523                 time_t t;
10524                 time (&t);
10525                 dyn.d_un.d_val = t;
10526               }
10527               break;
10528
10529             case DT_MIPS_ICHECKSUM:
10530               /* XXX FIXME: */
10531               swap_out_p = FALSE;
10532               break;
10533
10534             case DT_MIPS_IVERSION:
10535               /* XXX FIXME: */
10536               swap_out_p = FALSE;
10537               break;
10538
10539             case DT_MIPS_BASE_ADDRESS:
10540               s = output_bfd->sections;
10541               BFD_ASSERT (s != NULL);
10542               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
10543               break;
10544
10545             case DT_MIPS_LOCAL_GOTNO:
10546               dyn.d_un.d_val = g->local_gotno;
10547               break;
10548
10549             case DT_MIPS_UNREFEXTNO:
10550               /* The index into the dynamic symbol table which is the
10551                  entry of the first external symbol that is not
10552                  referenced within the same object.  */
10553               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
10554               break;
10555
10556             case DT_MIPS_GOTSYM:
10557               if (htab->global_gotsym)
10558                 {
10559                   dyn.d_un.d_val = htab->global_gotsym->dynindx;
10560                   break;
10561                 }
10562               /* In case if we don't have global got symbols we default
10563                  to setting DT_MIPS_GOTSYM to the same value as
10564                  DT_MIPS_SYMTABNO, so we just fall through.  */
10565
10566             case DT_MIPS_SYMTABNO:
10567               name = ".dynsym";
10568               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
10569               s = bfd_get_section_by_name (output_bfd, name);
10570               BFD_ASSERT (s != NULL);
10571
10572               dyn.d_un.d_val = s->size / elemsize;
10573               break;
10574
10575             case DT_MIPS_HIPAGENO:
10576               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
10577               break;
10578
10579             case DT_MIPS_RLD_MAP:
10580               {
10581                 struct elf_link_hash_entry *h;
10582                 h = mips_elf_hash_table (info)->rld_symbol;
10583                 if (!h)
10584                   {
10585                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10586                     swap_out_p = FALSE;
10587                     break;
10588                   }
10589                 s = h->root.u.def.section;
10590                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
10591                                   + h->root.u.def.value);
10592               }
10593               break;
10594
10595             case DT_MIPS_OPTIONS:
10596               s = (bfd_get_section_by_name
10597                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
10598               dyn.d_un.d_ptr = s->vma;
10599               break;
10600
10601             case DT_RELASZ:
10602               BFD_ASSERT (htab->is_vxworks);
10603               /* The count does not include the JUMP_SLOT relocations.  */
10604               if (htab->srelplt)
10605                 dyn.d_un.d_val -= htab->srelplt->size;
10606               break;
10607
10608             case DT_PLTREL:
10609               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10610               if (htab->is_vxworks)
10611                 dyn.d_un.d_val = DT_RELA;
10612               else
10613                 dyn.d_un.d_val = DT_REL;
10614               break;
10615
10616             case DT_PLTRELSZ:
10617               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10618               dyn.d_un.d_val = htab->srelplt->size;
10619               break;
10620
10621             case DT_JMPREL:
10622               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10623               dyn.d_un.d_ptr = (htab->srelplt->output_section->vma
10624                                 + htab->srelplt->output_offset);
10625               break;
10626
10627             case DT_TEXTREL:
10628               /* If we didn't need any text relocations after all, delete
10629                  the dynamic tag.  */
10630               if (!(info->flags & DF_TEXTREL))
10631                 {
10632                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10633                   swap_out_p = FALSE;
10634                 }
10635               break;
10636
10637             case DT_FLAGS:
10638               /* If we didn't need any text relocations after all, clear
10639                  DF_TEXTREL from DT_FLAGS.  */
10640               if (!(info->flags & DF_TEXTREL))
10641                 dyn.d_un.d_val &= ~DF_TEXTREL;
10642               else
10643                 swap_out_p = FALSE;
10644               break;
10645
10646             default:
10647               swap_out_p = FALSE;
10648               if (htab->is_vxworks
10649                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
10650                 swap_out_p = TRUE;
10651               break;
10652             }
10653
10654           if (swap_out_p || dyn_skipped)
10655             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10656               (dynobj, &dyn, b - dyn_skipped);
10657
10658           if (dyn_to_skip)
10659             {
10660               dyn_skipped += dyn_to_skip;
10661               dyn_to_skip = 0;
10662             }
10663         }
10664
10665       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
10666       if (dyn_skipped > 0)
10667         memset (b - dyn_skipped, 0, dyn_skipped);
10668     }
10669
10670   if (sgot != NULL && sgot->size > 0
10671       && !bfd_is_abs_section (sgot->output_section))
10672     {
10673       if (htab->is_vxworks)
10674         {
10675           /* The first entry of the global offset table points to the
10676              ".dynamic" section.  The second is initialized by the
10677              loader and contains the shared library identifier.
10678              The third is also initialized by the loader and points
10679              to the lazy resolution stub.  */
10680           MIPS_ELF_PUT_WORD (output_bfd,
10681                              sdyn->output_offset + sdyn->output_section->vma,
10682                              sgot->contents);
10683           MIPS_ELF_PUT_WORD (output_bfd, 0,
10684                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10685           MIPS_ELF_PUT_WORD (output_bfd, 0,
10686                              sgot->contents
10687                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
10688         }
10689       else
10690         {
10691           /* The first entry of the global offset table will be filled at
10692              runtime. The second entry will be used by some runtime loaders.
10693              This isn't the case of IRIX rld.  */
10694           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
10695           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10696                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10697         }
10698
10699       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
10700          = MIPS_ELF_GOT_SIZE (output_bfd);
10701     }
10702
10703   /* Generate dynamic relocations for the non-primary gots.  */
10704   if (gg != NULL && gg->next)
10705     {
10706       Elf_Internal_Rela rel[3];
10707       bfd_vma addend = 0;
10708
10709       memset (rel, 0, sizeof (rel));
10710       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
10711
10712       for (g = gg->next; g->next != gg; g = g->next)
10713         {
10714           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
10715             + g->next->tls_gotno;
10716
10717           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
10718                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10719           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10720                              sgot->contents
10721                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10722
10723           if (! info->shared)
10724             continue;
10725
10726           while (got_index < g->assigned_gotno)
10727             {
10728               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
10729                 = got_index++ * MIPS_ELF_GOT_SIZE (output_bfd);
10730               if (!(mips_elf_create_dynamic_relocation
10731                     (output_bfd, info, rel, NULL,
10732                      bfd_abs_section_ptr,
10733                      0, &addend, sgot)))
10734                 return FALSE;
10735               BFD_ASSERT (addend == 0);
10736             }
10737         }
10738     }
10739
10740   /* The generation of dynamic relocations for the non-primary gots
10741      adds more dynamic relocations.  We cannot count them until
10742      here.  */
10743
10744   if (elf_hash_table (info)->dynamic_sections_created)
10745     {
10746       bfd_byte *b;
10747       bfd_boolean swap_out_p;
10748
10749       BFD_ASSERT (sdyn != NULL);
10750
10751       for (b = sdyn->contents;
10752            b < sdyn->contents + sdyn->size;
10753            b += MIPS_ELF_DYN_SIZE (dynobj))
10754         {
10755           Elf_Internal_Dyn dyn;
10756           asection *s;
10757
10758           /* Read in the current dynamic entry.  */
10759           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10760
10761           /* Assume that we're going to modify it and write it out.  */
10762           swap_out_p = TRUE;
10763
10764           switch (dyn.d_tag)
10765             {
10766             case DT_RELSZ:
10767               /* Reduce DT_RELSZ to account for any relocations we
10768                  decided not to make.  This is for the n64 irix rld,
10769                  which doesn't seem to apply any relocations if there
10770                  are trailing null entries.  */
10771               s = mips_elf_rel_dyn_section (info, FALSE);
10772               dyn.d_un.d_val = (s->reloc_count
10773                                 * (ABI_64_P (output_bfd)
10774                                    ? sizeof (Elf64_Mips_External_Rel)
10775                                    : sizeof (Elf32_External_Rel)));
10776               /* Adjust the section size too.  Tools like the prelinker
10777                  can reasonably expect the values to the same.  */
10778               elf_section_data (s->output_section)->this_hdr.sh_size
10779                 = dyn.d_un.d_val;
10780               break;
10781
10782             default:
10783               swap_out_p = FALSE;
10784               break;
10785             }
10786
10787           if (swap_out_p)
10788             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10789               (dynobj, &dyn, b);
10790         }
10791     }
10792
10793   {
10794     asection *s;
10795     Elf32_compact_rel cpt;
10796
10797     if (SGI_COMPAT (output_bfd))
10798       {
10799         /* Write .compact_rel section out.  */
10800         s = bfd_get_linker_section (dynobj, ".compact_rel");
10801         if (s != NULL)
10802           {
10803             cpt.id1 = 1;
10804             cpt.num = s->reloc_count;
10805             cpt.id2 = 2;
10806             cpt.offset = (s->output_section->filepos
10807                           + sizeof (Elf32_External_compact_rel));
10808             cpt.reserved0 = 0;
10809             cpt.reserved1 = 0;
10810             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
10811                                             ((Elf32_External_compact_rel *)
10812                                              s->contents));
10813
10814             /* Clean up a dummy stub function entry in .text.  */
10815             if (htab->sstubs != NULL)
10816               {
10817                 file_ptr dummy_offset;
10818
10819                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
10820                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
10821                 memset (htab->sstubs->contents + dummy_offset, 0,
10822                         htab->function_stub_size);
10823               }
10824           }
10825       }
10826
10827     /* The psABI says that the dynamic relocations must be sorted in
10828        increasing order of r_symndx.  The VxWorks EABI doesn't require
10829        this, and because the code below handles REL rather than RELA
10830        relocations, using it for VxWorks would be outright harmful.  */
10831     if (!htab->is_vxworks)
10832       {
10833         s = mips_elf_rel_dyn_section (info, FALSE);
10834         if (s != NULL
10835             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
10836           {
10837             reldyn_sorting_bfd = output_bfd;
10838
10839             if (ABI_64_P (output_bfd))
10840               qsort ((Elf64_External_Rel *) s->contents + 1,
10841                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
10842                      sort_dynamic_relocs_64);
10843             else
10844               qsort ((Elf32_External_Rel *) s->contents + 1,
10845                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
10846                      sort_dynamic_relocs);
10847           }
10848       }
10849   }
10850
10851   if (htab->splt && htab->splt->size > 0)
10852     {
10853       if (htab->is_vxworks)
10854         {
10855           if (info->shared)
10856             mips_vxworks_finish_shared_plt (output_bfd, info);
10857           else
10858             mips_vxworks_finish_exec_plt (output_bfd, info);
10859         }
10860       else
10861         {
10862           BFD_ASSERT (!info->shared);
10863           mips_finish_exec_plt (output_bfd, info);
10864         }
10865     }
10866   return TRUE;
10867 }
10868
10869
10870 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
10871
10872 static void
10873 mips_set_isa_flags (bfd *abfd)
10874 {
10875   flagword val;
10876
10877   switch (bfd_get_mach (abfd))
10878     {
10879     default:
10880     case bfd_mach_mips3000:
10881       val = E_MIPS_ARCH_1;
10882       break;
10883
10884     case bfd_mach_mips3900:
10885       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
10886       break;
10887
10888     case bfd_mach_mips6000:
10889       val = E_MIPS_ARCH_2;
10890       break;
10891
10892     case bfd_mach_mips4000:
10893     case bfd_mach_mips4300:
10894     case bfd_mach_mips4400:
10895     case bfd_mach_mips4600:
10896       val = E_MIPS_ARCH_3;
10897       break;
10898
10899     case bfd_mach_mips4010:
10900       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
10901       break;
10902
10903     case bfd_mach_mips4100:
10904       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
10905       break;
10906
10907     case bfd_mach_mips4111:
10908       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
10909       break;
10910
10911     case bfd_mach_mips4120:
10912       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
10913       break;
10914
10915     case bfd_mach_mips4650:
10916       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
10917       break;
10918
10919     case bfd_mach_mips5400:
10920       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
10921       break;
10922
10923     case bfd_mach_mips5500:
10924       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
10925       break;
10926
10927     case bfd_mach_mips5900:
10928       val = E_MIPS_ARCH_3 | E_MIPS_MACH_5900;
10929       break;
10930
10931     case bfd_mach_mips9000:
10932       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
10933       break;
10934
10935     case bfd_mach_mips5000:
10936     case bfd_mach_mips7000:
10937     case bfd_mach_mips8000:
10938     case bfd_mach_mips10000:
10939     case bfd_mach_mips12000:
10940     case bfd_mach_mips14000:
10941     case bfd_mach_mips16000:
10942       val = E_MIPS_ARCH_4;
10943       break;
10944
10945     case bfd_mach_mips5:
10946       val = E_MIPS_ARCH_5;
10947       break;
10948
10949     case bfd_mach_mips_loongson_2e:
10950       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
10951       break;
10952
10953     case bfd_mach_mips_loongson_2f:
10954       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
10955       break;
10956
10957     case bfd_mach_mips_sb1:
10958       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
10959       break;
10960
10961     case bfd_mach_mips_loongson_3a:
10962       val = E_MIPS_ARCH_64 | E_MIPS_MACH_LS3A;
10963       break;
10964
10965     case bfd_mach_mips_octeon:
10966     case bfd_mach_mips_octeonp:
10967       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
10968       break;
10969
10970     case bfd_mach_mips_xlr:
10971       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
10972       break;
10973
10974     case bfd_mach_mips_octeon2:
10975       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
10976       break;
10977
10978     case bfd_mach_mipsisa32:
10979       val = E_MIPS_ARCH_32;
10980       break;
10981
10982     case bfd_mach_mipsisa64:
10983       val = E_MIPS_ARCH_64;
10984       break;
10985
10986     case bfd_mach_mipsisa32r2:
10987       val = E_MIPS_ARCH_32R2;
10988       break;
10989
10990     case bfd_mach_mipsisa64r2:
10991       val = E_MIPS_ARCH_64R2;
10992       break;
10993     }
10994   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
10995   elf_elfheader (abfd)->e_flags |= val;
10996
10997 }
10998
10999
11000 /* The final processing done just before writing out a MIPS ELF object
11001    file.  This gets the MIPS architecture right based on the machine
11002    number.  This is used by both the 32-bit and the 64-bit ABI.  */
11003
11004 void
11005 _bfd_mips_elf_final_write_processing (bfd *abfd,
11006                                       bfd_boolean linker ATTRIBUTE_UNUSED)
11007 {
11008   unsigned int i;
11009   Elf_Internal_Shdr **hdrpp;
11010   const char *name;
11011   asection *sec;
11012
11013   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
11014      is nonzero.  This is for compatibility with old objects, which used
11015      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
11016   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
11017     mips_set_isa_flags (abfd);
11018
11019   /* Set the sh_info field for .gptab sections and other appropriate
11020      info for each special section.  */
11021   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
11022        i < elf_numsections (abfd);
11023        i++, hdrpp++)
11024     {
11025       switch ((*hdrpp)->sh_type)
11026         {
11027         case SHT_MIPS_MSYM:
11028         case SHT_MIPS_LIBLIST:
11029           sec = bfd_get_section_by_name (abfd, ".dynstr");
11030           if (sec != NULL)
11031             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11032           break;
11033
11034         case SHT_MIPS_GPTAB:
11035           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11036           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11037           BFD_ASSERT (name != NULL
11038                       && CONST_STRNEQ (name, ".gptab."));
11039           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
11040           BFD_ASSERT (sec != NULL);
11041           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11042           break;
11043
11044         case SHT_MIPS_CONTENT:
11045           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11046           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11047           BFD_ASSERT (name != NULL
11048                       && CONST_STRNEQ (name, ".MIPS.content"));
11049           sec = bfd_get_section_by_name (abfd,
11050                                          name + sizeof ".MIPS.content" - 1);
11051           BFD_ASSERT (sec != NULL);
11052           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11053           break;
11054
11055         case SHT_MIPS_SYMBOL_LIB:
11056           sec = bfd_get_section_by_name (abfd, ".dynsym");
11057           if (sec != NULL)
11058             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11059           sec = bfd_get_section_by_name (abfd, ".liblist");
11060           if (sec != NULL)
11061             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11062           break;
11063
11064         case SHT_MIPS_EVENTS:
11065           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11066           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11067           BFD_ASSERT (name != NULL);
11068           if (CONST_STRNEQ (name, ".MIPS.events"))
11069             sec = bfd_get_section_by_name (abfd,
11070                                            name + sizeof ".MIPS.events" - 1);
11071           else
11072             {
11073               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
11074               sec = bfd_get_section_by_name (abfd,
11075                                              (name
11076                                               + sizeof ".MIPS.post_rel" - 1));
11077             }
11078           BFD_ASSERT (sec != NULL);
11079           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11080           break;
11081
11082         }
11083     }
11084 }
11085 \f
11086 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
11087    segments.  */
11088
11089 int
11090 _bfd_mips_elf_additional_program_headers (bfd *abfd,
11091                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
11092 {
11093   asection *s;
11094   int ret = 0;
11095
11096   /* See if we need a PT_MIPS_REGINFO segment.  */
11097   s = bfd_get_section_by_name (abfd, ".reginfo");
11098   if (s && (s->flags & SEC_LOAD))
11099     ++ret;
11100
11101   /* See if we need a PT_MIPS_OPTIONS segment.  */
11102   if (IRIX_COMPAT (abfd) == ict_irix6
11103       && bfd_get_section_by_name (abfd,
11104                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
11105     ++ret;
11106
11107   /* See if we need a PT_MIPS_RTPROC segment.  */
11108   if (IRIX_COMPAT (abfd) == ict_irix5
11109       && bfd_get_section_by_name (abfd, ".dynamic")
11110       && bfd_get_section_by_name (abfd, ".mdebug"))
11111     ++ret;
11112
11113   /* Allocate a PT_NULL header in dynamic objects.  See
11114      _bfd_mips_elf_modify_segment_map for details.  */
11115   if (!SGI_COMPAT (abfd)
11116       && bfd_get_section_by_name (abfd, ".dynamic"))
11117     ++ret;
11118
11119   return ret;
11120 }
11121
11122 /* Modify the segment map for an IRIX5 executable.  */
11123
11124 bfd_boolean
11125 _bfd_mips_elf_modify_segment_map (bfd *abfd,
11126                                   struct bfd_link_info *info)
11127 {
11128   asection *s;
11129   struct elf_segment_map *m, **pm;
11130   bfd_size_type amt;
11131
11132   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
11133      segment.  */
11134   s = bfd_get_section_by_name (abfd, ".reginfo");
11135   if (s != NULL && (s->flags & SEC_LOAD) != 0)
11136     {
11137       for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11138         if (m->p_type == PT_MIPS_REGINFO)
11139           break;
11140       if (m == NULL)
11141         {
11142           amt = sizeof *m;
11143           m = bfd_zalloc (abfd, amt);
11144           if (m == NULL)
11145             return FALSE;
11146
11147           m->p_type = PT_MIPS_REGINFO;
11148           m->count = 1;
11149           m->sections[0] = s;
11150
11151           /* We want to put it after the PHDR and INTERP segments.  */
11152           pm = &elf_tdata (abfd)->segment_map;
11153           while (*pm != NULL
11154                  && ((*pm)->p_type == PT_PHDR
11155                      || (*pm)->p_type == PT_INTERP))
11156             pm = &(*pm)->next;
11157
11158           m->next = *pm;
11159           *pm = m;
11160         }
11161     }
11162
11163   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
11164      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
11165      PT_MIPS_OPTIONS segment immediately following the program header
11166      table.  */
11167   if (NEWABI_P (abfd)
11168       /* On non-IRIX6 new abi, we'll have already created a segment
11169          for this section, so don't create another.  I'm not sure this
11170          is not also the case for IRIX 6, but I can't test it right
11171          now.  */
11172       && IRIX_COMPAT (abfd) == ict_irix6)
11173     {
11174       for (s = abfd->sections; s; s = s->next)
11175         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
11176           break;
11177
11178       if (s)
11179         {
11180           struct elf_segment_map *options_segment;
11181
11182           pm = &elf_tdata (abfd)->segment_map;
11183           while (*pm != NULL
11184                  && ((*pm)->p_type == PT_PHDR
11185                      || (*pm)->p_type == PT_INTERP))
11186             pm = &(*pm)->next;
11187
11188           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
11189             {
11190               amt = sizeof (struct elf_segment_map);
11191               options_segment = bfd_zalloc (abfd, amt);
11192               options_segment->next = *pm;
11193               options_segment->p_type = PT_MIPS_OPTIONS;
11194               options_segment->p_flags = PF_R;
11195               options_segment->p_flags_valid = TRUE;
11196               options_segment->count = 1;
11197               options_segment->sections[0] = s;
11198               *pm = options_segment;
11199             }
11200         }
11201     }
11202   else
11203     {
11204       if (IRIX_COMPAT (abfd) == ict_irix5)
11205         {
11206           /* If there are .dynamic and .mdebug sections, we make a room
11207              for the RTPROC header.  FIXME: Rewrite without section names.  */
11208           if (bfd_get_section_by_name (abfd, ".interp") == NULL
11209               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
11210               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
11211             {
11212               for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11213                 if (m->p_type == PT_MIPS_RTPROC)
11214                   break;
11215               if (m == NULL)
11216                 {
11217                   amt = sizeof *m;
11218                   m = bfd_zalloc (abfd, amt);
11219                   if (m == NULL)
11220                     return FALSE;
11221
11222                   m->p_type = PT_MIPS_RTPROC;
11223
11224                   s = bfd_get_section_by_name (abfd, ".rtproc");
11225                   if (s == NULL)
11226                     {
11227                       m->count = 0;
11228                       m->p_flags = 0;
11229                       m->p_flags_valid = 1;
11230                     }
11231                   else
11232                     {
11233                       m->count = 1;
11234                       m->sections[0] = s;
11235                     }
11236
11237                   /* We want to put it after the DYNAMIC segment.  */
11238                   pm = &elf_tdata (abfd)->segment_map;
11239                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
11240                     pm = &(*pm)->next;
11241                   if (*pm != NULL)
11242                     pm = &(*pm)->next;
11243
11244                   m->next = *pm;
11245                   *pm = m;
11246                 }
11247             }
11248         }
11249       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
11250          .dynstr, .dynsym, and .hash sections, and everything in
11251          between.  */
11252       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL;
11253            pm = &(*pm)->next)
11254         if ((*pm)->p_type == PT_DYNAMIC)
11255           break;
11256       m = *pm;
11257       if (m != NULL && IRIX_COMPAT (abfd) == ict_none)
11258         {
11259           /* For a normal mips executable the permissions for the PT_DYNAMIC
11260              segment are read, write and execute. We do that here since
11261              the code in elf.c sets only the read permission. This matters
11262              sometimes for the dynamic linker.  */
11263           if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
11264             {
11265               m->p_flags = PF_R | PF_W | PF_X;
11266               m->p_flags_valid = 1;
11267             }
11268         }
11269       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
11270          glibc's dynamic linker has traditionally derived the number of
11271          tags from the p_filesz field, and sometimes allocates stack
11272          arrays of that size.  An overly-big PT_DYNAMIC segment can
11273          be actively harmful in such cases.  Making PT_DYNAMIC contain
11274          other sections can also make life hard for the prelinker,
11275          which might move one of the other sections to a different
11276          PT_LOAD segment.  */
11277       if (SGI_COMPAT (abfd)
11278           && m != NULL
11279           && m->count == 1
11280           && strcmp (m->sections[0]->name, ".dynamic") == 0)
11281         {
11282           static const char *sec_names[] =
11283           {
11284             ".dynamic", ".dynstr", ".dynsym", ".hash"
11285           };
11286           bfd_vma low, high;
11287           unsigned int i, c;
11288           struct elf_segment_map *n;
11289
11290           low = ~(bfd_vma) 0;
11291           high = 0;
11292           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
11293             {
11294               s = bfd_get_section_by_name (abfd, sec_names[i]);
11295               if (s != NULL && (s->flags & SEC_LOAD) != 0)
11296                 {
11297                   bfd_size_type sz;
11298
11299                   if (low > s->vma)
11300                     low = s->vma;
11301                   sz = s->size;
11302                   if (high < s->vma + sz)
11303                     high = s->vma + sz;
11304                 }
11305             }
11306
11307           c = 0;
11308           for (s = abfd->sections; s != NULL; s = s->next)
11309             if ((s->flags & SEC_LOAD) != 0
11310                 && s->vma >= low
11311                 && s->vma + s->size <= high)
11312               ++c;
11313
11314           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
11315           n = bfd_zalloc (abfd, amt);
11316           if (n == NULL)
11317             return FALSE;
11318           *n = *m;
11319           n->count = c;
11320
11321           i = 0;
11322           for (s = abfd->sections; s != NULL; s = s->next)
11323             {
11324               if ((s->flags & SEC_LOAD) != 0
11325                   && s->vma >= low
11326                   && s->vma + s->size <= high)
11327                 {
11328                   n->sections[i] = s;
11329                   ++i;
11330                 }
11331             }
11332
11333           *pm = n;
11334         }
11335     }
11336
11337   /* Allocate a spare program header in dynamic objects so that tools
11338      like the prelinker can add an extra PT_LOAD entry.
11339
11340      If the prelinker needs to make room for a new PT_LOAD entry, its
11341      standard procedure is to move the first (read-only) sections into
11342      the new (writable) segment.  However, the MIPS ABI requires
11343      .dynamic to be in a read-only segment, and the section will often
11344      start within sizeof (ElfNN_Phdr) bytes of the last program header.
11345
11346      Although the prelinker could in principle move .dynamic to a
11347      writable segment, it seems better to allocate a spare program
11348      header instead, and avoid the need to move any sections.
11349      There is a long tradition of allocating spare dynamic tags,
11350      so allocating a spare program header seems like a natural
11351      extension.
11352
11353      If INFO is NULL, we may be copying an already prelinked binary
11354      with objcopy or strip, so do not add this header.  */
11355   if (info != NULL
11356       && !SGI_COMPAT (abfd)
11357       && bfd_get_section_by_name (abfd, ".dynamic"))
11358     {
11359       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL; pm = &(*pm)->next)
11360         if ((*pm)->p_type == PT_NULL)
11361           break;
11362       if (*pm == NULL)
11363         {
11364           m = bfd_zalloc (abfd, sizeof (*m));
11365           if (m == NULL)
11366             return FALSE;
11367
11368           m->p_type = PT_NULL;
11369           *pm = m;
11370         }
11371     }
11372
11373   return TRUE;
11374 }
11375 \f
11376 /* Return the section that should be marked against GC for a given
11377    relocation.  */
11378
11379 asection *
11380 _bfd_mips_elf_gc_mark_hook (asection *sec,
11381                             struct bfd_link_info *info,
11382                             Elf_Internal_Rela *rel,
11383                             struct elf_link_hash_entry *h,
11384                             Elf_Internal_Sym *sym)
11385 {
11386   /* ??? Do mips16 stub sections need to be handled special?  */
11387
11388   if (h != NULL)
11389     switch (ELF_R_TYPE (sec->owner, rel->r_info))
11390       {
11391       case R_MIPS_GNU_VTINHERIT:
11392       case R_MIPS_GNU_VTENTRY:
11393         return NULL;
11394       }
11395
11396   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
11397 }
11398
11399 /* Update the got entry reference counts for the section being removed.  */
11400
11401 bfd_boolean
11402 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
11403                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
11404                              asection *sec ATTRIBUTE_UNUSED,
11405                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
11406 {
11407 #if 0
11408   Elf_Internal_Shdr *symtab_hdr;
11409   struct elf_link_hash_entry **sym_hashes;
11410   bfd_signed_vma *local_got_refcounts;
11411   const Elf_Internal_Rela *rel, *relend;
11412   unsigned long r_symndx;
11413   struct elf_link_hash_entry *h;
11414
11415   if (info->relocatable)
11416     return TRUE;
11417
11418   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11419   sym_hashes = elf_sym_hashes (abfd);
11420   local_got_refcounts = elf_local_got_refcounts (abfd);
11421
11422   relend = relocs + sec->reloc_count;
11423   for (rel = relocs; rel < relend; rel++)
11424     switch (ELF_R_TYPE (abfd, rel->r_info))
11425       {
11426       case R_MIPS16_GOT16:
11427       case R_MIPS16_CALL16:
11428       case R_MIPS_GOT16:
11429       case R_MIPS_CALL16:
11430       case R_MIPS_CALL_HI16:
11431       case R_MIPS_CALL_LO16:
11432       case R_MIPS_GOT_HI16:
11433       case R_MIPS_GOT_LO16:
11434       case R_MIPS_GOT_DISP:
11435       case R_MIPS_GOT_PAGE:
11436       case R_MIPS_GOT_OFST:
11437       case R_MICROMIPS_GOT16:
11438       case R_MICROMIPS_CALL16:
11439       case R_MICROMIPS_CALL_HI16:
11440       case R_MICROMIPS_CALL_LO16:
11441       case R_MICROMIPS_GOT_HI16:
11442       case R_MICROMIPS_GOT_LO16:
11443       case R_MICROMIPS_GOT_DISP:
11444       case R_MICROMIPS_GOT_PAGE:
11445       case R_MICROMIPS_GOT_OFST:
11446         /* ??? It would seem that the existing MIPS code does no sort
11447            of reference counting or whatnot on its GOT and PLT entries,
11448            so it is not possible to garbage collect them at this time.  */
11449         break;
11450
11451       default:
11452         break;
11453       }
11454 #endif
11455
11456   return TRUE;
11457 }
11458 \f
11459 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
11460    hiding the old indirect symbol.  Process additional relocation
11461    information.  Also called for weakdefs, in which case we just let
11462    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
11463
11464 void
11465 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
11466                                     struct elf_link_hash_entry *dir,
11467                                     struct elf_link_hash_entry *ind)
11468 {
11469   struct mips_elf_link_hash_entry *dirmips, *indmips;
11470
11471   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
11472
11473   dirmips = (struct mips_elf_link_hash_entry *) dir;
11474   indmips = (struct mips_elf_link_hash_entry *) ind;
11475   /* Any absolute non-dynamic relocations against an indirect or weak
11476      definition will be against the target symbol.  */
11477   if (indmips->has_static_relocs)
11478     dirmips->has_static_relocs = TRUE;
11479
11480   if (ind->root.type != bfd_link_hash_indirect)
11481     return;
11482
11483   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
11484   if (indmips->readonly_reloc)
11485     dirmips->readonly_reloc = TRUE;
11486   if (indmips->no_fn_stub)
11487     dirmips->no_fn_stub = TRUE;
11488   if (indmips->fn_stub)
11489     {
11490       dirmips->fn_stub = indmips->fn_stub;
11491       indmips->fn_stub = NULL;
11492     }
11493   if (indmips->need_fn_stub)
11494     {
11495       dirmips->need_fn_stub = TRUE;
11496       indmips->need_fn_stub = FALSE;
11497     }
11498   if (indmips->call_stub)
11499     {
11500       dirmips->call_stub = indmips->call_stub;
11501       indmips->call_stub = NULL;
11502     }
11503   if (indmips->call_fp_stub)
11504     {
11505       dirmips->call_fp_stub = indmips->call_fp_stub;
11506       indmips->call_fp_stub = NULL;
11507     }
11508   if (indmips->global_got_area < dirmips->global_got_area)
11509     dirmips->global_got_area = indmips->global_got_area;
11510   if (indmips->global_got_area < GGA_NONE)
11511     indmips->global_got_area = GGA_NONE;
11512   if (indmips->has_nonpic_branches)
11513     dirmips->has_nonpic_branches = TRUE;
11514
11515   if (dirmips->tls_ie_type == 0)
11516     dirmips->tls_ie_type = indmips->tls_ie_type;
11517   if (dirmips->tls_gd_type == 0)
11518     dirmips->tls_gd_type = indmips->tls_gd_type;
11519 }
11520 \f
11521 #define PDR_SIZE 32
11522
11523 bfd_boolean
11524 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
11525                             struct bfd_link_info *info)
11526 {
11527   asection *o;
11528   bfd_boolean ret = FALSE;
11529   unsigned char *tdata;
11530   size_t i, skip;
11531
11532   o = bfd_get_section_by_name (abfd, ".pdr");
11533   if (! o)
11534     return FALSE;
11535   if (o->size == 0)
11536     return FALSE;
11537   if (o->size % PDR_SIZE != 0)
11538     return FALSE;
11539   if (o->output_section != NULL
11540       && bfd_is_abs_section (o->output_section))
11541     return FALSE;
11542
11543   tdata = bfd_zmalloc (o->size / PDR_SIZE);
11544   if (! tdata)
11545     return FALSE;
11546
11547   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
11548                                             info->keep_memory);
11549   if (!cookie->rels)
11550     {
11551       free (tdata);
11552       return FALSE;
11553     }
11554
11555   cookie->rel = cookie->rels;
11556   cookie->relend = cookie->rels + o->reloc_count;
11557
11558   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
11559     {
11560       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
11561         {
11562           tdata[i] = 1;
11563           skip ++;
11564         }
11565     }
11566
11567   if (skip != 0)
11568     {
11569       mips_elf_section_data (o)->u.tdata = tdata;
11570       o->size -= skip * PDR_SIZE;
11571       ret = TRUE;
11572     }
11573   else
11574     free (tdata);
11575
11576   if (! info->keep_memory)
11577     free (cookie->rels);
11578
11579   return ret;
11580 }
11581
11582 bfd_boolean
11583 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
11584 {
11585   if (strcmp (sec->name, ".pdr") == 0)
11586     return TRUE;
11587   return FALSE;
11588 }
11589
11590 bfd_boolean
11591 _bfd_mips_elf_write_section (bfd *output_bfd,
11592                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
11593                              asection *sec, bfd_byte *contents)
11594 {
11595   bfd_byte *to, *from, *end;
11596   int i;
11597
11598   if (strcmp (sec->name, ".pdr") != 0)
11599     return FALSE;
11600
11601   if (mips_elf_section_data (sec)->u.tdata == NULL)
11602     return FALSE;
11603
11604   to = contents;
11605   end = contents + sec->size;
11606   for (from = contents, i = 0;
11607        from < end;
11608        from += PDR_SIZE, i++)
11609     {
11610       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
11611         continue;
11612       if (to != from)
11613         memcpy (to, from, PDR_SIZE);
11614       to += PDR_SIZE;
11615     }
11616   bfd_set_section_contents (output_bfd, sec->output_section, contents,
11617                             sec->output_offset, sec->size);
11618   return TRUE;
11619 }
11620 \f
11621 /* microMIPS code retains local labels for linker relaxation.  Omit them
11622    from output by default for clarity.  */
11623
11624 bfd_boolean
11625 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
11626 {
11627   return _bfd_elf_is_local_label_name (abfd, sym->name);
11628 }
11629
11630 /* MIPS ELF uses a special find_nearest_line routine in order the
11631    handle the ECOFF debugging information.  */
11632
11633 struct mips_elf_find_line
11634 {
11635   struct ecoff_debug_info d;
11636   struct ecoff_find_line i;
11637 };
11638
11639 bfd_boolean
11640 _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section,
11641                                  asymbol **symbols, bfd_vma offset,
11642                                  const char **filename_ptr,
11643                                  const char **functionname_ptr,
11644                                  unsigned int *line_ptr)
11645 {
11646   asection *msec;
11647
11648   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
11649                                      filename_ptr, functionname_ptr,
11650                                      line_ptr))
11651     return TRUE;
11652
11653   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
11654                                      section, symbols, offset,
11655                                      filename_ptr, functionname_ptr,
11656                                      line_ptr, NULL, ABI_64_P (abfd) ? 8 : 0,
11657                                      &elf_tdata (abfd)->dwarf2_find_line_info))
11658     return TRUE;
11659
11660   msec = bfd_get_section_by_name (abfd, ".mdebug");
11661   if (msec != NULL)
11662     {
11663       flagword origflags;
11664       struct mips_elf_find_line *fi;
11665       const struct ecoff_debug_swap * const swap =
11666         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
11667
11668       /* If we are called during a link, mips_elf_final_link may have
11669          cleared the SEC_HAS_CONTENTS field.  We force it back on here
11670          if appropriate (which it normally will be).  */
11671       origflags = msec->flags;
11672       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
11673         msec->flags |= SEC_HAS_CONTENTS;
11674
11675       fi = elf_tdata (abfd)->find_line_info;
11676       if (fi == NULL)
11677         {
11678           bfd_size_type external_fdr_size;
11679           char *fraw_src;
11680           char *fraw_end;
11681           struct fdr *fdr_ptr;
11682           bfd_size_type amt = sizeof (struct mips_elf_find_line);
11683
11684           fi = bfd_zalloc (abfd, amt);
11685           if (fi == NULL)
11686             {
11687               msec->flags = origflags;
11688               return FALSE;
11689             }
11690
11691           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
11692             {
11693               msec->flags = origflags;
11694               return FALSE;
11695             }
11696
11697           /* Swap in the FDR information.  */
11698           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
11699           fi->d.fdr = bfd_alloc (abfd, amt);
11700           if (fi->d.fdr == NULL)
11701             {
11702               msec->flags = origflags;
11703               return FALSE;
11704             }
11705           external_fdr_size = swap->external_fdr_size;
11706           fdr_ptr = fi->d.fdr;
11707           fraw_src = (char *) fi->d.external_fdr;
11708           fraw_end = (fraw_src
11709                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
11710           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
11711             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
11712
11713           elf_tdata (abfd)->find_line_info = fi;
11714
11715           /* Note that we don't bother to ever free this information.
11716              find_nearest_line is either called all the time, as in
11717              objdump -l, so the information should be saved, or it is
11718              rarely called, as in ld error messages, so the memory
11719              wasted is unimportant.  Still, it would probably be a
11720              good idea for free_cached_info to throw it away.  */
11721         }
11722
11723       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
11724                                   &fi->i, filename_ptr, functionname_ptr,
11725                                   line_ptr))
11726         {
11727           msec->flags = origflags;
11728           return TRUE;
11729         }
11730
11731       msec->flags = origflags;
11732     }
11733
11734   /* Fall back on the generic ELF find_nearest_line routine.  */
11735
11736   return _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
11737                                      filename_ptr, functionname_ptr,
11738                                      line_ptr);
11739 }
11740
11741 bfd_boolean
11742 _bfd_mips_elf_find_inliner_info (bfd *abfd,
11743                                  const char **filename_ptr,
11744                                  const char **functionname_ptr,
11745                                  unsigned int *line_ptr)
11746 {
11747   bfd_boolean found;
11748   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
11749                                          functionname_ptr, line_ptr,
11750                                          & elf_tdata (abfd)->dwarf2_find_line_info);
11751   return found;
11752 }
11753
11754 \f
11755 /* When are writing out the .options or .MIPS.options section,
11756    remember the bytes we are writing out, so that we can install the
11757    GP value in the section_processing routine.  */
11758
11759 bfd_boolean
11760 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
11761                                     const void *location,
11762                                     file_ptr offset, bfd_size_type count)
11763 {
11764   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
11765     {
11766       bfd_byte *c;
11767
11768       if (elf_section_data (section) == NULL)
11769         {
11770           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
11771           section->used_by_bfd = bfd_zalloc (abfd, amt);
11772           if (elf_section_data (section) == NULL)
11773             return FALSE;
11774         }
11775       c = mips_elf_section_data (section)->u.tdata;
11776       if (c == NULL)
11777         {
11778           c = bfd_zalloc (abfd, section->size);
11779           if (c == NULL)
11780             return FALSE;
11781           mips_elf_section_data (section)->u.tdata = c;
11782         }
11783
11784       memcpy (c + offset, location, count);
11785     }
11786
11787   return _bfd_elf_set_section_contents (abfd, section, location, offset,
11788                                         count);
11789 }
11790
11791 /* This is almost identical to bfd_generic_get_... except that some
11792    MIPS relocations need to be handled specially.  Sigh.  */
11793
11794 bfd_byte *
11795 _bfd_elf_mips_get_relocated_section_contents
11796   (bfd *abfd,
11797    struct bfd_link_info *link_info,
11798    struct bfd_link_order *link_order,
11799    bfd_byte *data,
11800    bfd_boolean relocatable,
11801    asymbol **symbols)
11802 {
11803   /* Get enough memory to hold the stuff */
11804   bfd *input_bfd = link_order->u.indirect.section->owner;
11805   asection *input_section = link_order->u.indirect.section;
11806   bfd_size_type sz;
11807
11808   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
11809   arelent **reloc_vector = NULL;
11810   long reloc_count;
11811
11812   if (reloc_size < 0)
11813     goto error_return;
11814
11815   reloc_vector = bfd_malloc (reloc_size);
11816   if (reloc_vector == NULL && reloc_size != 0)
11817     goto error_return;
11818
11819   /* read in the section */
11820   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
11821   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
11822     goto error_return;
11823
11824   reloc_count = bfd_canonicalize_reloc (input_bfd,
11825                                         input_section,
11826                                         reloc_vector,
11827                                         symbols);
11828   if (reloc_count < 0)
11829     goto error_return;
11830
11831   if (reloc_count > 0)
11832     {
11833       arelent **parent;
11834       /* for mips */
11835       int gp_found;
11836       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
11837
11838       {
11839         struct bfd_hash_entry *h;
11840         struct bfd_link_hash_entry *lh;
11841         /* Skip all this stuff if we aren't mixing formats.  */
11842         if (abfd && input_bfd
11843             && abfd->xvec == input_bfd->xvec)
11844           lh = 0;
11845         else
11846           {
11847             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
11848             lh = (struct bfd_link_hash_entry *) h;
11849           }
11850       lookup:
11851         if (lh)
11852           {
11853             switch (lh->type)
11854               {
11855               case bfd_link_hash_undefined:
11856               case bfd_link_hash_undefweak:
11857               case bfd_link_hash_common:
11858                 gp_found = 0;
11859                 break;
11860               case bfd_link_hash_defined:
11861               case bfd_link_hash_defweak:
11862                 gp_found = 1;
11863                 gp = lh->u.def.value;
11864                 break;
11865               case bfd_link_hash_indirect:
11866               case bfd_link_hash_warning:
11867                 lh = lh->u.i.link;
11868                 /* @@FIXME  ignoring warning for now */
11869                 goto lookup;
11870               case bfd_link_hash_new:
11871               default:
11872                 abort ();
11873               }
11874           }
11875         else
11876           gp_found = 0;
11877       }
11878       /* end mips */
11879       for (parent = reloc_vector; *parent != NULL; parent++)
11880         {
11881           char *error_message = NULL;
11882           bfd_reloc_status_type r;
11883
11884           /* Specific to MIPS: Deal with relocation types that require
11885              knowing the gp of the output bfd.  */
11886           asymbol *sym = *(*parent)->sym_ptr_ptr;
11887
11888           /* If we've managed to find the gp and have a special
11889              function for the relocation then go ahead, else default
11890              to the generic handling.  */
11891           if (gp_found
11892               && (*parent)->howto->special_function
11893               == _bfd_mips_elf32_gprel16_reloc)
11894             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
11895                                                input_section, relocatable,
11896                                                data, gp);
11897           else
11898             r = bfd_perform_relocation (input_bfd, *parent, data,
11899                                         input_section,
11900                                         relocatable ? abfd : NULL,
11901                                         &error_message);
11902
11903           if (relocatable)
11904             {
11905               asection *os = input_section->output_section;
11906
11907               /* A partial link, so keep the relocs */
11908               os->orelocation[os->reloc_count] = *parent;
11909               os->reloc_count++;
11910             }
11911
11912           if (r != bfd_reloc_ok)
11913             {
11914               switch (r)
11915                 {
11916                 case bfd_reloc_undefined:
11917                   if (!((*link_info->callbacks->undefined_symbol)
11918                         (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11919                          input_bfd, input_section, (*parent)->address, TRUE)))
11920                     goto error_return;
11921                   break;
11922                 case bfd_reloc_dangerous:
11923                   BFD_ASSERT (error_message != NULL);
11924                   if (!((*link_info->callbacks->reloc_dangerous)
11925                         (link_info, error_message, input_bfd, input_section,
11926                          (*parent)->address)))
11927                     goto error_return;
11928                   break;
11929                 case bfd_reloc_overflow:
11930                   if (!((*link_info->callbacks->reloc_overflow)
11931                         (link_info, NULL,
11932                          bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11933                          (*parent)->howto->name, (*parent)->addend,
11934                          input_bfd, input_section, (*parent)->address)))
11935                     goto error_return;
11936                   break;
11937                 case bfd_reloc_outofrange:
11938                 default:
11939                   abort ();
11940                   break;
11941                 }
11942
11943             }
11944         }
11945     }
11946   if (reloc_vector != NULL)
11947     free (reloc_vector);
11948   return data;
11949
11950 error_return:
11951   if (reloc_vector != NULL)
11952     free (reloc_vector);
11953   return NULL;
11954 }
11955 \f
11956 static bfd_boolean
11957 mips_elf_relax_delete_bytes (bfd *abfd,
11958                              asection *sec, bfd_vma addr, int count)
11959 {
11960   Elf_Internal_Shdr *symtab_hdr;
11961   unsigned int sec_shndx;
11962   bfd_byte *contents;
11963   Elf_Internal_Rela *irel, *irelend;
11964   Elf_Internal_Sym *isym;
11965   Elf_Internal_Sym *isymend;
11966   struct elf_link_hash_entry **sym_hashes;
11967   struct elf_link_hash_entry **end_hashes;
11968   struct elf_link_hash_entry **start_hashes;
11969   unsigned int symcount;
11970
11971   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
11972   contents = elf_section_data (sec)->this_hdr.contents;
11973
11974   irel = elf_section_data (sec)->relocs;
11975   irelend = irel + sec->reloc_count;
11976
11977   /* Actually delete the bytes.  */
11978   memmove (contents + addr, contents + addr + count,
11979            (size_t) (sec->size - addr - count));
11980   sec->size -= count;
11981
11982   /* Adjust all the relocs.  */
11983   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
11984     {
11985       /* Get the new reloc address.  */
11986       if (irel->r_offset > addr)
11987         irel->r_offset -= count;
11988     }
11989
11990   BFD_ASSERT (addr % 2 == 0);
11991   BFD_ASSERT (count % 2 == 0);
11992
11993   /* Adjust the local symbols defined in this section.  */
11994   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11995   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
11996   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
11997     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
11998       isym->st_value -= count;
11999
12000   /* Now adjust the global symbols defined in this section.  */
12001   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
12002               - symtab_hdr->sh_info);
12003   sym_hashes = start_hashes = elf_sym_hashes (abfd);
12004   end_hashes = sym_hashes + symcount;
12005
12006   for (; sym_hashes < end_hashes; sym_hashes++)
12007     {
12008       struct elf_link_hash_entry *sym_hash = *sym_hashes;
12009
12010       if ((sym_hash->root.type == bfd_link_hash_defined
12011            || sym_hash->root.type == bfd_link_hash_defweak)
12012           && sym_hash->root.u.def.section == sec)
12013         {
12014           bfd_vma value = sym_hash->root.u.def.value;
12015
12016           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
12017             value &= MINUS_TWO;
12018           if (value > addr)
12019             sym_hash->root.u.def.value -= count;
12020         }
12021     }
12022
12023   return TRUE;
12024 }
12025
12026
12027 /* Opcodes needed for microMIPS relaxation as found in
12028    opcodes/micromips-opc.c.  */
12029
12030 struct opcode_descriptor {
12031   unsigned long match;
12032   unsigned long mask;
12033 };
12034
12035 /* The $ra register aka $31.  */
12036
12037 #define RA 31
12038
12039 /* 32-bit instruction format register fields.  */
12040
12041 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
12042 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
12043
12044 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
12045
12046 #define OP16_VALID_REG(r) \
12047   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
12048
12049
12050 /* 32-bit and 16-bit branches.  */
12051
12052 static const struct opcode_descriptor b_insns_32[] = {
12053   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
12054   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
12055   { 0, 0 }  /* End marker for find_match().  */
12056 };
12057
12058 static const struct opcode_descriptor bc_insn_32 =
12059   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
12060
12061 static const struct opcode_descriptor bz_insn_32 =
12062   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
12063
12064 static const struct opcode_descriptor bzal_insn_32 =
12065   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
12066
12067 static const struct opcode_descriptor beq_insn_32 =
12068   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
12069
12070 static const struct opcode_descriptor b_insn_16 =
12071   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
12072
12073 static const struct opcode_descriptor bz_insn_16 =
12074   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
12075
12076
12077 /* 32-bit and 16-bit branch EQ and NE zero.  */
12078
12079 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
12080    eq and second the ne.  This convention is used when replacing a
12081    32-bit BEQ/BNE with the 16-bit version.  */
12082
12083 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
12084
12085 static const struct opcode_descriptor bz_rs_insns_32[] = {
12086   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
12087   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
12088   { 0, 0 }  /* End marker for find_match().  */
12089 };
12090
12091 static const struct opcode_descriptor bz_rt_insns_32[] = {
12092   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
12093   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
12094   { 0, 0 }  /* End marker for find_match().  */
12095 };
12096
12097 static const struct opcode_descriptor bzc_insns_32[] = {
12098   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
12099   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
12100   { 0, 0 }  /* End marker for find_match().  */
12101 };
12102
12103 static const struct opcode_descriptor bz_insns_16[] = {
12104   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
12105   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
12106   { 0, 0 }  /* End marker for find_match().  */
12107 };
12108
12109 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
12110
12111 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0x17) + 2)
12112 #define BZ16_REG_FIELD(r) \
12113   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 7)
12114
12115
12116 /* 32-bit instructions with a delay slot.  */
12117
12118 static const struct opcode_descriptor jal_insn_32_bd16 =
12119   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
12120
12121 static const struct opcode_descriptor jal_insn_32_bd32 =
12122   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
12123
12124 static const struct opcode_descriptor jal_x_insn_32_bd32 =
12125   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
12126
12127 static const struct opcode_descriptor j_insn_32 =
12128   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
12129
12130 static const struct opcode_descriptor jalr_insn_32 =
12131   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
12132
12133 /* This table can be compacted, because no opcode replacement is made.  */
12134
12135 static const struct opcode_descriptor ds_insns_32_bd16[] = {
12136   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
12137
12138   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
12139   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
12140
12141   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
12142   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
12143   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
12144   { 0, 0 }  /* End marker for find_match().  */
12145 };
12146
12147 /* This table can be compacted, because no opcode replacement is made.  */
12148
12149 static const struct opcode_descriptor ds_insns_32_bd32[] = {
12150   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
12151
12152   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
12153   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
12154   { 0, 0 }  /* End marker for find_match().  */
12155 };
12156
12157
12158 /* 16-bit instructions with a delay slot.  */
12159
12160 static const struct opcode_descriptor jalr_insn_16_bd16 =
12161   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
12162
12163 static const struct opcode_descriptor jalr_insn_16_bd32 =
12164   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
12165
12166 static const struct opcode_descriptor jr_insn_16 =
12167   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
12168
12169 #define JR16_REG(opcode) ((opcode) & 0x1f)
12170
12171 /* This table can be compacted, because no opcode replacement is made.  */
12172
12173 static const struct opcode_descriptor ds_insns_16_bd16[] = {
12174   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
12175
12176   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
12177   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
12178   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
12179   { 0, 0 }  /* End marker for find_match().  */
12180 };
12181
12182
12183 /* LUI instruction.  */
12184
12185 static const struct opcode_descriptor lui_insn =
12186  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
12187
12188
12189 /* ADDIU instruction.  */
12190
12191 static const struct opcode_descriptor addiu_insn =
12192   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
12193
12194 static const struct opcode_descriptor addiupc_insn =
12195   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
12196
12197 #define ADDIUPC_REG_FIELD(r) \
12198   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
12199
12200
12201 /* Relaxable instructions in a JAL delay slot: MOVE.  */
12202
12203 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
12204    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
12205 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
12206 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
12207
12208 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
12209 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
12210
12211 static const struct opcode_descriptor move_insns_32[] = {
12212   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
12213   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
12214   { 0, 0 }  /* End marker for find_match().  */
12215 };
12216
12217 static const struct opcode_descriptor move_insn_16 =
12218   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
12219
12220
12221 /* NOP instructions.  */
12222
12223 static const struct opcode_descriptor nop_insn_32 =
12224   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
12225
12226 static const struct opcode_descriptor nop_insn_16 =
12227   { /* "nop",   "",             */ 0x0c00,     0xffff };
12228
12229
12230 /* Instruction match support.  */
12231
12232 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
12233
12234 static int
12235 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
12236 {
12237   unsigned long indx;
12238
12239   for (indx = 0; insn[indx].mask != 0; indx++)
12240     if (MATCH (opcode, insn[indx]))
12241       return indx;
12242
12243   return -1;
12244 }
12245
12246
12247 /* Branch and delay slot decoding support.  */
12248
12249 /* If PTR points to what *might* be a 16-bit branch or jump, then
12250    return the minimum length of its delay slot, otherwise return 0.
12251    Non-zero results are not definitive as we might be checking against
12252    the second half of another instruction.  */
12253
12254 static int
12255 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
12256 {
12257   unsigned long opcode;
12258   int bdsize;
12259
12260   opcode = bfd_get_16 (abfd, ptr);
12261   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
12262     /* 16-bit branch/jump with a 32-bit delay slot.  */
12263     bdsize = 4;
12264   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
12265            || find_match (opcode, ds_insns_16_bd16) >= 0)
12266     /* 16-bit branch/jump with a 16-bit delay slot.  */
12267     bdsize = 2;
12268   else
12269     /* No delay slot.  */
12270     bdsize = 0;
12271
12272   return bdsize;
12273 }
12274
12275 /* If PTR points to what *might* be a 32-bit branch or jump, then
12276    return the minimum length of its delay slot, otherwise return 0.
12277    Non-zero results are not definitive as we might be checking against
12278    the second half of another instruction.  */
12279
12280 static int
12281 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
12282 {
12283   unsigned long opcode;
12284   int bdsize;
12285
12286   opcode = bfd_get_micromips_32 (abfd, ptr);
12287   if (find_match (opcode, ds_insns_32_bd32) >= 0)
12288     /* 32-bit branch/jump with a 32-bit delay slot.  */
12289     bdsize = 4;
12290   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
12291     /* 32-bit branch/jump with a 16-bit delay slot.  */
12292     bdsize = 2;
12293   else
12294     /* No delay slot.  */
12295     bdsize = 0;
12296
12297   return bdsize;
12298 }
12299
12300 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
12301    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
12302
12303 static bfd_boolean
12304 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12305 {
12306   unsigned long opcode;
12307
12308   opcode = bfd_get_16 (abfd, ptr);
12309   if (MATCH (opcode, b_insn_16)
12310                                                 /* B16  */
12311       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
12312                                                 /* JR16  */
12313       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
12314                                                 /* BEQZ16, BNEZ16  */
12315       || (MATCH (opcode, jalr_insn_16_bd32)
12316                                                 /* JALR16  */
12317           && reg != JR16_REG (opcode) && reg != RA))
12318     return TRUE;
12319
12320   return FALSE;
12321 }
12322
12323 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
12324    then return TRUE, otherwise FALSE.  */
12325
12326 static bfd_boolean
12327 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12328 {
12329   unsigned long opcode;
12330
12331   opcode = bfd_get_micromips_32 (abfd, ptr);
12332   if (MATCH (opcode, j_insn_32)
12333                                                 /* J  */
12334       || MATCH (opcode, bc_insn_32)
12335                                                 /* BC1F, BC1T, BC2F, BC2T  */
12336       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
12337                                                 /* JAL, JALX  */
12338       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
12339                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
12340       || (MATCH (opcode, bzal_insn_32)
12341                                                 /* BGEZAL, BLTZAL  */
12342           && reg != OP32_SREG (opcode) && reg != RA)
12343       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
12344                                                 /* JALR, JALR.HB, BEQ, BNE  */
12345           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
12346     return TRUE;
12347
12348   return FALSE;
12349 }
12350
12351 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
12352    IRELEND) at OFFSET indicate that there must be a compact branch there,
12353    then return TRUE, otherwise FALSE.  */
12354
12355 static bfd_boolean
12356 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
12357                      const Elf_Internal_Rela *internal_relocs,
12358                      const Elf_Internal_Rela *irelend)
12359 {
12360   const Elf_Internal_Rela *irel;
12361   unsigned long opcode;
12362
12363   opcode = bfd_get_micromips_32 (abfd, ptr);
12364   if (find_match (opcode, bzc_insns_32) < 0)
12365     return FALSE;
12366
12367   for (irel = internal_relocs; irel < irelend; irel++)
12368     if (irel->r_offset == offset
12369         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
12370       return TRUE;
12371
12372   return FALSE;
12373 }
12374
12375 /* Bitsize checking.  */
12376 #define IS_BITSIZE(val, N)                                              \
12377   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
12378     - (1ULL << ((N) - 1))) == (val))
12379
12380 \f
12381 bfd_boolean
12382 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
12383                              struct bfd_link_info *link_info,
12384                              bfd_boolean *again)
12385 {
12386   Elf_Internal_Shdr *symtab_hdr;
12387   Elf_Internal_Rela *internal_relocs;
12388   Elf_Internal_Rela *irel, *irelend;
12389   bfd_byte *contents = NULL;
12390   Elf_Internal_Sym *isymbuf = NULL;
12391
12392   /* Assume nothing changes.  */
12393   *again = FALSE;
12394
12395   /* We don't have to do anything for a relocatable link, if
12396      this section does not have relocs, or if this is not a
12397      code section.  */
12398
12399   if (link_info->relocatable
12400       || (sec->flags & SEC_RELOC) == 0
12401       || sec->reloc_count == 0
12402       || (sec->flags & SEC_CODE) == 0)
12403     return TRUE;
12404
12405   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12406
12407   /* Get a copy of the native relocations.  */
12408   internal_relocs = (_bfd_elf_link_read_relocs
12409                      (abfd, sec, NULL, (Elf_Internal_Rela *) NULL,
12410                       link_info->keep_memory));
12411   if (internal_relocs == NULL)
12412     goto error_return;
12413
12414   /* Walk through them looking for relaxing opportunities.  */
12415   irelend = internal_relocs + sec->reloc_count;
12416   for (irel = internal_relocs; irel < irelend; irel++)
12417     {
12418       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
12419       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
12420       bfd_boolean target_is_micromips_code_p;
12421       unsigned long opcode;
12422       bfd_vma symval;
12423       bfd_vma pcrval;
12424       bfd_byte *ptr;
12425       int fndopc;
12426
12427       /* The number of bytes to delete for relaxation and from where
12428          to delete these bytes starting at irel->r_offset.  */
12429       int delcnt = 0;
12430       int deloff = 0;
12431
12432       /* If this isn't something that can be relaxed, then ignore
12433          this reloc.  */
12434       if (r_type != R_MICROMIPS_HI16
12435           && r_type != R_MICROMIPS_PC16_S1
12436           && r_type != R_MICROMIPS_26_S1)
12437         continue;
12438
12439       /* Get the section contents if we haven't done so already.  */
12440       if (contents == NULL)
12441         {
12442           /* Get cached copy if it exists.  */
12443           if (elf_section_data (sec)->this_hdr.contents != NULL)
12444             contents = elf_section_data (sec)->this_hdr.contents;
12445           /* Go get them off disk.  */
12446           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
12447             goto error_return;
12448         }
12449       ptr = contents + irel->r_offset;
12450
12451       /* Read this BFD's local symbols if we haven't done so already.  */
12452       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
12453         {
12454           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
12455           if (isymbuf == NULL)
12456             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12457                                             symtab_hdr->sh_info, 0,
12458                                             NULL, NULL, NULL);
12459           if (isymbuf == NULL)
12460             goto error_return;
12461         }
12462
12463       /* Get the value of the symbol referred to by the reloc.  */
12464       if (r_symndx < symtab_hdr->sh_info)
12465         {
12466           /* A local symbol.  */
12467           Elf_Internal_Sym *isym;
12468           asection *sym_sec;
12469
12470           isym = isymbuf + r_symndx;
12471           if (isym->st_shndx == SHN_UNDEF)
12472             sym_sec = bfd_und_section_ptr;
12473           else if (isym->st_shndx == SHN_ABS)
12474             sym_sec = bfd_abs_section_ptr;
12475           else if (isym->st_shndx == SHN_COMMON)
12476             sym_sec = bfd_com_section_ptr;
12477           else
12478             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
12479           symval = (isym->st_value
12480                     + sym_sec->output_section->vma
12481                     + sym_sec->output_offset);
12482           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
12483         }
12484       else
12485         {
12486           unsigned long indx;
12487           struct elf_link_hash_entry *h;
12488
12489           /* An external symbol.  */
12490           indx = r_symndx - symtab_hdr->sh_info;
12491           h = elf_sym_hashes (abfd)[indx];
12492           BFD_ASSERT (h != NULL);
12493
12494           if (h->root.type != bfd_link_hash_defined
12495               && h->root.type != bfd_link_hash_defweak)
12496             /* This appears to be a reference to an undefined
12497                symbol.  Just ignore it -- it will be caught by the
12498                regular reloc processing.  */
12499             continue;
12500
12501           symval = (h->root.u.def.value
12502                     + h->root.u.def.section->output_section->vma
12503                     + h->root.u.def.section->output_offset);
12504           target_is_micromips_code_p = (!h->needs_plt
12505                                         && ELF_ST_IS_MICROMIPS (h->other));
12506         }
12507
12508
12509       /* For simplicity of coding, we are going to modify the
12510          section contents, the section relocs, and the BFD symbol
12511          table.  We must tell the rest of the code not to free up this
12512          information.  It would be possible to instead create a table
12513          of changes which have to be made, as is done in coff-mips.c;
12514          that would be more work, but would require less memory when
12515          the linker is run.  */
12516
12517       /* Only 32-bit instructions relaxed.  */
12518       if (irel->r_offset + 4 > sec->size)
12519         continue;
12520
12521       opcode = bfd_get_micromips_32 (abfd, ptr);
12522
12523       /* This is the pc-relative distance from the instruction the
12524          relocation is applied to, to the symbol referred.  */
12525       pcrval = (symval
12526                 - (sec->output_section->vma + sec->output_offset)
12527                 - irel->r_offset);
12528
12529       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
12530          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
12531          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
12532
12533            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
12534
12535          where pcrval has first to be adjusted to apply against the LO16
12536          location (we make the adjustment later on, when we have figured
12537          out the offset).  */
12538       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
12539         {
12540           bfd_boolean bzc = FALSE;
12541           unsigned long nextopc;
12542           unsigned long reg;
12543           bfd_vma offset;
12544
12545           /* Give up if the previous reloc was a HI16 against this symbol
12546              too.  */
12547           if (irel > internal_relocs
12548               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
12549               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
12550             continue;
12551
12552           /* Or if the next reloc is not a LO16 against this symbol.  */
12553           if (irel + 1 >= irelend
12554               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
12555               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
12556             continue;
12557
12558           /* Or if the second next reloc is a LO16 against this symbol too.  */
12559           if (irel + 2 >= irelend
12560               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
12561               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
12562             continue;
12563
12564           /* See if the LUI instruction *might* be in a branch delay slot.
12565              We check whether what looks like a 16-bit branch or jump is
12566              actually an immediate argument to a compact branch, and let
12567              it through if so.  */
12568           if (irel->r_offset >= 2
12569               && check_br16_dslot (abfd, ptr - 2)
12570               && !(irel->r_offset >= 4
12571                    && (bzc = check_relocated_bzc (abfd,
12572                                                   ptr - 4, irel->r_offset - 4,
12573                                                   internal_relocs, irelend))))
12574             continue;
12575           if (irel->r_offset >= 4
12576               && !bzc
12577               && check_br32_dslot (abfd, ptr - 4))
12578             continue;
12579
12580           reg = OP32_SREG (opcode);
12581
12582           /* We only relax adjacent instructions or ones separated with
12583              a branch or jump that has a delay slot.  The branch or jump
12584              must not fiddle with the register used to hold the address.
12585              Subtract 4 for the LUI itself.  */
12586           offset = irel[1].r_offset - irel[0].r_offset;
12587           switch (offset - 4)
12588             {
12589             case 0:
12590               break;
12591             case 2:
12592               if (check_br16 (abfd, ptr + 4, reg))
12593                 break;
12594               continue;
12595             case 4:
12596               if (check_br32 (abfd, ptr + 4, reg))
12597                 break;
12598               continue;
12599             default:
12600               continue;
12601             }
12602
12603           nextopc = bfd_get_micromips_32 (abfd, contents + irel[1].r_offset);
12604
12605           /* Give up unless the same register is used with both
12606              relocations.  */
12607           if (OP32_SREG (nextopc) != reg)
12608             continue;
12609
12610           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
12611              and rounding up to take masking of the two LSBs into account.  */
12612           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
12613
12614           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
12615           if (IS_BITSIZE (symval, 16))
12616             {
12617               /* Fix the relocation's type.  */
12618               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
12619
12620               /* Instructions using R_MICROMIPS_LO16 have the base or
12621                  source register in bits 20:16.  This register becomes $0
12622                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
12623               nextopc &= ~0x001f0000;
12624               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
12625                           contents + irel[1].r_offset);
12626             }
12627
12628           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
12629              We add 4 to take LUI deletion into account while checking
12630              the PC-relative distance.  */
12631           else if (symval % 4 == 0
12632                    && IS_BITSIZE (pcrval + 4, 25)
12633                    && MATCH (nextopc, addiu_insn)
12634                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
12635                    && OP16_VALID_REG (OP32_TREG (nextopc)))
12636             {
12637               /* Fix the relocation's type.  */
12638               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
12639
12640               /* Replace ADDIU with the ADDIUPC version.  */
12641               nextopc = (addiupc_insn.match
12642                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
12643
12644               bfd_put_micromips_32 (abfd, nextopc,
12645                                     contents + irel[1].r_offset);
12646             }
12647
12648           /* Can't do anything, give up, sigh...  */
12649           else
12650             continue;
12651
12652           /* Fix the relocation's type.  */
12653           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
12654
12655           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
12656           delcnt = 4;
12657           deloff = 0;
12658         }
12659
12660       /* Compact branch relaxation -- due to the multitude of macros
12661          employed by the compiler/assembler, compact branches are not
12662          always generated.  Obviously, this can/will be fixed elsewhere,
12663          but there is no drawback in double checking it here.  */
12664       else if (r_type == R_MICROMIPS_PC16_S1
12665                && irel->r_offset + 5 < sec->size
12666                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12667                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
12668                && MATCH (bfd_get_16 (abfd, ptr + 4), nop_insn_16))
12669         {
12670           unsigned long reg;
12671
12672           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12673
12674           /* Replace BEQZ/BNEZ with the compact version.  */
12675           opcode = (bzc_insns_32[fndopc].match
12676                     | BZC32_REG_FIELD (reg)
12677                     | (opcode & 0xffff));               /* Addend value.  */
12678
12679           bfd_put_micromips_32 (abfd, opcode, ptr);
12680
12681           /* Delete the 16-bit delay slot NOP: two bytes from
12682              irel->offset + 4.  */
12683           delcnt = 2;
12684           deloff = 4;
12685         }
12686
12687       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
12688          to check the distance from the next instruction, so subtract 2.  */
12689       else if (r_type == R_MICROMIPS_PC16_S1
12690                && IS_BITSIZE (pcrval - 2, 11)
12691                && find_match (opcode, b_insns_32) >= 0)
12692         {
12693           /* Fix the relocation's type.  */
12694           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
12695
12696           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12697           bfd_put_16 (abfd,
12698                       (b_insn_16.match
12699                        | (opcode & 0x3ff)),             /* Addend value.  */
12700                       ptr);
12701
12702           /* Delete 2 bytes from irel->r_offset + 2.  */
12703           delcnt = 2;
12704           deloff = 2;
12705         }
12706
12707       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
12708          to check the distance from the next instruction, so subtract 2.  */
12709       else if (r_type == R_MICROMIPS_PC16_S1
12710                && IS_BITSIZE (pcrval - 2, 8)
12711                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12712                     && OP16_VALID_REG (OP32_SREG (opcode)))
12713                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
12714                        && OP16_VALID_REG (OP32_TREG (opcode)))))
12715         {
12716           unsigned long reg;
12717
12718           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12719
12720           /* Fix the relocation's type.  */
12721           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
12722
12723           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12724           bfd_put_16 (abfd,
12725                       (bz_insns_16[fndopc].match
12726                        | BZ16_REG_FIELD (reg)
12727                        | (opcode & 0x7f)),              /* Addend value.  */
12728                       ptr);
12729
12730           /* Delete 2 bytes from irel->r_offset + 2.  */
12731           delcnt = 2;
12732           deloff = 2;
12733         }
12734
12735       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
12736       else if (r_type == R_MICROMIPS_26_S1
12737                && target_is_micromips_code_p
12738                && irel->r_offset + 7 < sec->size
12739                && MATCH (opcode, jal_insn_32_bd32))
12740         {
12741           unsigned long n32opc;
12742           bfd_boolean relaxed = FALSE;
12743
12744           n32opc = bfd_get_micromips_32 (abfd, ptr + 4);
12745
12746           if (MATCH (n32opc, nop_insn_32))
12747             {
12748               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
12749               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
12750
12751               relaxed = TRUE;
12752             }
12753           else if (find_match (n32opc, move_insns_32) >= 0)
12754             {
12755               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
12756               bfd_put_16 (abfd,
12757                           (move_insn_16.match
12758                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
12759                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
12760                           ptr + 4);
12761
12762               relaxed = TRUE;
12763             }
12764           /* Other 32-bit instructions relaxable to 16-bit
12765              instructions will be handled here later.  */
12766
12767           if (relaxed)
12768             {
12769               /* JAL with 32-bit delay slot that is changed to a JALS
12770                  with 16-bit delay slot.  */
12771               bfd_put_micromips_32 (abfd, jal_insn_32_bd16.match, ptr);
12772
12773               /* Delete 2 bytes from irel->r_offset + 6.  */
12774               delcnt = 2;
12775               deloff = 6;
12776             }
12777         }
12778
12779       if (delcnt != 0)
12780         {
12781           /* Note that we've changed the relocs, section contents, etc.  */
12782           elf_section_data (sec)->relocs = internal_relocs;
12783           elf_section_data (sec)->this_hdr.contents = contents;
12784           symtab_hdr->contents = (unsigned char *) isymbuf;
12785
12786           /* Delete bytes depending on the delcnt and deloff.  */
12787           if (!mips_elf_relax_delete_bytes (abfd, sec,
12788                                             irel->r_offset + deloff, delcnt))
12789             goto error_return;
12790
12791           /* That will change things, so we should relax again.
12792              Note that this is not required, and it may be slow.  */
12793           *again = TRUE;
12794         }
12795     }
12796
12797   if (isymbuf != NULL
12798       && symtab_hdr->contents != (unsigned char *) isymbuf)
12799     {
12800       if (! link_info->keep_memory)
12801         free (isymbuf);
12802       else
12803         {
12804           /* Cache the symbols for elf_link_input_bfd.  */
12805           symtab_hdr->contents = (unsigned char *) isymbuf;
12806         }
12807     }
12808
12809   if (contents != NULL
12810       && elf_section_data (sec)->this_hdr.contents != contents)
12811     {
12812       if (! link_info->keep_memory)
12813         free (contents);
12814       else
12815         {
12816           /* Cache the section contents for elf_link_input_bfd.  */
12817           elf_section_data (sec)->this_hdr.contents = contents;
12818         }
12819     }
12820
12821   if (internal_relocs != NULL
12822       && elf_section_data (sec)->relocs != internal_relocs)
12823     free (internal_relocs);
12824
12825   return TRUE;
12826
12827  error_return:
12828   if (isymbuf != NULL
12829       && symtab_hdr->contents != (unsigned char *) isymbuf)
12830     free (isymbuf);
12831   if (contents != NULL
12832       && elf_section_data (sec)->this_hdr.contents != contents)
12833     free (contents);
12834   if (internal_relocs != NULL
12835       && elf_section_data (sec)->relocs != internal_relocs)
12836     free (internal_relocs);
12837
12838   return FALSE;
12839 }
12840 \f
12841 /* Create a MIPS ELF linker hash table.  */
12842
12843 struct bfd_link_hash_table *
12844 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
12845 {
12846   struct mips_elf_link_hash_table *ret;
12847   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
12848
12849   ret = bfd_zmalloc (amt);
12850   if (ret == NULL)
12851     return NULL;
12852
12853   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
12854                                       mips_elf_link_hash_newfunc,
12855                                       sizeof (struct mips_elf_link_hash_entry),
12856                                       MIPS_ELF_DATA))
12857     {
12858       free (ret);
12859       return NULL;
12860     }
12861
12862   return &ret->root.root;
12863 }
12864
12865 /* Likewise, but indicate that the target is VxWorks.  */
12866
12867 struct bfd_link_hash_table *
12868 _bfd_mips_vxworks_link_hash_table_create (bfd *abfd)
12869 {
12870   struct bfd_link_hash_table *ret;
12871
12872   ret = _bfd_mips_elf_link_hash_table_create (abfd);
12873   if (ret)
12874     {
12875       struct mips_elf_link_hash_table *htab;
12876
12877       htab = (struct mips_elf_link_hash_table *) ret;
12878       htab->use_plts_and_copy_relocs = TRUE;
12879       htab->is_vxworks = TRUE;
12880     }
12881   return ret;
12882 }
12883
12884 /* A function that the linker calls if we are allowed to use PLTs
12885    and copy relocs.  */
12886
12887 void
12888 _bfd_mips_elf_use_plts_and_copy_relocs (struct bfd_link_info *info)
12889 {
12890   mips_elf_hash_table (info)->use_plts_and_copy_relocs = TRUE;
12891 }
12892 \f
12893 /* We need to use a special link routine to handle the .reginfo and
12894    the .mdebug sections.  We need to merge all instances of these
12895    sections together, not write them all out sequentially.  */
12896
12897 bfd_boolean
12898 _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info)
12899 {
12900   asection *o;
12901   struct bfd_link_order *p;
12902   asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec;
12903   asection *rtproc_sec;
12904   Elf32_RegInfo reginfo;
12905   struct ecoff_debug_info debug;
12906   struct mips_htab_traverse_info hti;
12907   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12908   const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap;
12909   HDRR *symhdr = &debug.symbolic_header;
12910   void *mdebug_handle = NULL;
12911   asection *s;
12912   EXTR esym;
12913   unsigned int i;
12914   bfd_size_type amt;
12915   struct mips_elf_link_hash_table *htab;
12916
12917   static const char * const secname[] =
12918   {
12919     ".text", ".init", ".fini", ".data",
12920     ".rodata", ".sdata", ".sbss", ".bss"
12921   };
12922   static const int sc[] =
12923   {
12924     scText, scInit, scFini, scData,
12925     scRData, scSData, scSBss, scBss
12926   };
12927
12928   /* Sort the dynamic symbols so that those with GOT entries come after
12929      those without.  */
12930   htab = mips_elf_hash_table (info);
12931   BFD_ASSERT (htab != NULL);
12932
12933   if (!mips_elf_sort_hash_table (abfd, info))
12934     return FALSE;
12935
12936   /* Create any scheduled LA25 stubs.  */
12937   hti.info = info;
12938   hti.output_bfd = abfd;
12939   hti.error = FALSE;
12940   htab_traverse (htab->la25_stubs, mips_elf_create_la25_stub, &hti);
12941   if (hti.error)
12942     return FALSE;
12943
12944   /* Get a value for the GP register.  */
12945   if (elf_gp (abfd) == 0)
12946     {
12947       struct bfd_link_hash_entry *h;
12948
12949       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
12950       if (h != NULL && h->type == bfd_link_hash_defined)
12951         elf_gp (abfd) = (h->u.def.value
12952                          + h->u.def.section->output_section->vma
12953                          + h->u.def.section->output_offset);
12954       else if (htab->is_vxworks
12955                && (h = bfd_link_hash_lookup (info->hash,
12956                                              "_GLOBAL_OFFSET_TABLE_",
12957                                              FALSE, FALSE, TRUE))
12958                && h->type == bfd_link_hash_defined)
12959         elf_gp (abfd) = (h->u.def.section->output_section->vma
12960                          + h->u.def.section->output_offset
12961                          + h->u.def.value);
12962       else if (info->relocatable)
12963         {
12964           bfd_vma lo = MINUS_ONE;
12965
12966           /* Find the GP-relative section with the lowest offset.  */
12967           for (o = abfd->sections; o != NULL; o = o->next)
12968             if (o->vma < lo
12969                 && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL))
12970               lo = o->vma;
12971
12972           /* And calculate GP relative to that.  */
12973           elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (info);
12974         }
12975       else
12976         {
12977           /* If the relocate_section function needs to do a reloc
12978              involving the GP value, it should make a reloc_dangerous
12979              callback to warn that GP is not defined.  */
12980         }
12981     }
12982
12983   /* Go through the sections and collect the .reginfo and .mdebug
12984      information.  */
12985   reginfo_sec = NULL;
12986   mdebug_sec = NULL;
12987   gptab_data_sec = NULL;
12988   gptab_bss_sec = NULL;
12989   for (o = abfd->sections; o != NULL; o = o->next)
12990     {
12991       if (strcmp (o->name, ".reginfo") == 0)
12992         {
12993           memset (&reginfo, 0, sizeof reginfo);
12994
12995           /* We have found the .reginfo section in the output file.
12996              Look through all the link_orders comprising it and merge
12997              the information together.  */
12998           for (p = o->map_head.link_order; p != NULL; p = p->next)
12999             {
13000               asection *input_section;
13001               bfd *input_bfd;
13002               Elf32_External_RegInfo ext;
13003               Elf32_RegInfo sub;
13004
13005               if (p->type != bfd_indirect_link_order)
13006                 {
13007                   if (p->type == bfd_data_link_order)
13008                     continue;
13009                   abort ();
13010                 }
13011
13012               input_section = p->u.indirect.section;
13013               input_bfd = input_section->owner;
13014
13015               if (! bfd_get_section_contents (input_bfd, input_section,
13016                                               &ext, 0, sizeof ext))
13017                 return FALSE;
13018
13019               bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub);
13020
13021               reginfo.ri_gprmask |= sub.ri_gprmask;
13022               reginfo.ri_cprmask[0] |= sub.ri_cprmask[0];
13023               reginfo.ri_cprmask[1] |= sub.ri_cprmask[1];
13024               reginfo.ri_cprmask[2] |= sub.ri_cprmask[2];
13025               reginfo.ri_cprmask[3] |= sub.ri_cprmask[3];
13026
13027               /* ri_gp_value is set by the function
13028                  mips_elf32_section_processing when the section is
13029                  finally written out.  */
13030
13031               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13032                  elf_link_input_bfd ignores this section.  */
13033               input_section->flags &= ~SEC_HAS_CONTENTS;
13034             }
13035
13036           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
13037           BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo));
13038
13039           /* Skip this section later on (I don't think this currently
13040              matters, but someday it might).  */
13041           o->map_head.link_order = NULL;
13042
13043           reginfo_sec = o;
13044         }
13045
13046       if (strcmp (o->name, ".mdebug") == 0)
13047         {
13048           struct extsym_info einfo;
13049           bfd_vma last;
13050
13051           /* We have found the .mdebug section in the output file.
13052              Look through all the link_orders comprising it and merge
13053              the information together.  */
13054           symhdr->magic = swap->sym_magic;
13055           /* FIXME: What should the version stamp be?  */
13056           symhdr->vstamp = 0;
13057           symhdr->ilineMax = 0;
13058           symhdr->cbLine = 0;
13059           symhdr->idnMax = 0;
13060           symhdr->ipdMax = 0;
13061           symhdr->isymMax = 0;
13062           symhdr->ioptMax = 0;
13063           symhdr->iauxMax = 0;
13064           symhdr->issMax = 0;
13065           symhdr->issExtMax = 0;
13066           symhdr->ifdMax = 0;
13067           symhdr->crfd = 0;
13068           symhdr->iextMax = 0;
13069
13070           /* We accumulate the debugging information itself in the
13071              debug_info structure.  */
13072           debug.line = NULL;
13073           debug.external_dnr = NULL;
13074           debug.external_pdr = NULL;
13075           debug.external_sym = NULL;
13076           debug.external_opt = NULL;
13077           debug.external_aux = NULL;
13078           debug.ss = NULL;
13079           debug.ssext = debug.ssext_end = NULL;
13080           debug.external_fdr = NULL;
13081           debug.external_rfd = NULL;
13082           debug.external_ext = debug.external_ext_end = NULL;
13083
13084           mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info);
13085           if (mdebug_handle == NULL)
13086             return FALSE;
13087
13088           esym.jmptbl = 0;
13089           esym.cobol_main = 0;
13090           esym.weakext = 0;
13091           esym.reserved = 0;
13092           esym.ifd = ifdNil;
13093           esym.asym.iss = issNil;
13094           esym.asym.st = stLocal;
13095           esym.asym.reserved = 0;
13096           esym.asym.index = indexNil;
13097           last = 0;
13098           for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++)
13099             {
13100               esym.asym.sc = sc[i];
13101               s = bfd_get_section_by_name (abfd, secname[i]);
13102               if (s != NULL)
13103                 {
13104                   esym.asym.value = s->vma;
13105                   last = s->vma + s->size;
13106                 }
13107               else
13108                 esym.asym.value = last;
13109               if (!bfd_ecoff_debug_one_external (abfd, &debug, swap,
13110                                                  secname[i], &esym))
13111                 return FALSE;
13112             }
13113
13114           for (p = o->map_head.link_order; p != NULL; p = p->next)
13115             {
13116               asection *input_section;
13117               bfd *input_bfd;
13118               const struct ecoff_debug_swap *input_swap;
13119               struct ecoff_debug_info input_debug;
13120               char *eraw_src;
13121               char *eraw_end;
13122
13123               if (p->type != bfd_indirect_link_order)
13124                 {
13125                   if (p->type == bfd_data_link_order)
13126                     continue;
13127                   abort ();
13128                 }
13129
13130               input_section = p->u.indirect.section;
13131               input_bfd = input_section->owner;
13132
13133               if (!is_mips_elf (input_bfd))
13134                 {
13135                   /* I don't know what a non MIPS ELF bfd would be
13136                      doing with a .mdebug section, but I don't really
13137                      want to deal with it.  */
13138                   continue;
13139                 }
13140
13141               input_swap = (get_elf_backend_data (input_bfd)
13142                             ->elf_backend_ecoff_debug_swap);
13143
13144               BFD_ASSERT (p->size == input_section->size);
13145
13146               /* The ECOFF linking code expects that we have already
13147                  read in the debugging information and set up an
13148                  ecoff_debug_info structure, so we do that now.  */
13149               if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section,
13150                                                    &input_debug))
13151                 return FALSE;
13152
13153               if (! (bfd_ecoff_debug_accumulate
13154                      (mdebug_handle, abfd, &debug, swap, input_bfd,
13155                       &input_debug, input_swap, info)))
13156                 return FALSE;
13157
13158               /* Loop through the external symbols.  For each one with
13159                  interesting information, try to find the symbol in
13160                  the linker global hash table and save the information
13161                  for the output external symbols.  */
13162               eraw_src = input_debug.external_ext;
13163               eraw_end = (eraw_src
13164                           + (input_debug.symbolic_header.iextMax
13165                              * input_swap->external_ext_size));
13166               for (;
13167                    eraw_src < eraw_end;
13168                    eraw_src += input_swap->external_ext_size)
13169                 {
13170                   EXTR ext;
13171                   const char *name;
13172                   struct mips_elf_link_hash_entry *h;
13173
13174                   (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext);
13175                   if (ext.asym.sc == scNil
13176                       || ext.asym.sc == scUndefined
13177                       || ext.asym.sc == scSUndefined)
13178                     continue;
13179
13180                   name = input_debug.ssext + ext.asym.iss;
13181                   h = mips_elf_link_hash_lookup (mips_elf_hash_table (info),
13182                                                  name, FALSE, FALSE, TRUE);
13183                   if (h == NULL || h->esym.ifd != -2)
13184                     continue;
13185
13186                   if (ext.ifd != -1)
13187                     {
13188                       BFD_ASSERT (ext.ifd
13189                                   < input_debug.symbolic_header.ifdMax);
13190                       ext.ifd = input_debug.ifdmap[ext.ifd];
13191                     }
13192
13193                   h->esym = ext;
13194                 }
13195
13196               /* Free up the information we just read.  */
13197               free (input_debug.line);
13198               free (input_debug.external_dnr);
13199               free (input_debug.external_pdr);
13200               free (input_debug.external_sym);
13201               free (input_debug.external_opt);
13202               free (input_debug.external_aux);
13203               free (input_debug.ss);
13204               free (input_debug.ssext);
13205               free (input_debug.external_fdr);
13206               free (input_debug.external_rfd);
13207               free (input_debug.external_ext);
13208
13209               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13210                  elf_link_input_bfd ignores this section.  */
13211               input_section->flags &= ~SEC_HAS_CONTENTS;
13212             }
13213
13214           if (SGI_COMPAT (abfd) && info->shared)
13215             {
13216               /* Create .rtproc section.  */
13217               rtproc_sec = bfd_get_linker_section (abfd, ".rtproc");
13218               if (rtproc_sec == NULL)
13219                 {
13220                   flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
13221                                     | SEC_LINKER_CREATED | SEC_READONLY);
13222
13223                   rtproc_sec = bfd_make_section_anyway_with_flags (abfd,
13224                                                                    ".rtproc",
13225                                                                    flags);
13226                   if (rtproc_sec == NULL
13227                       || ! bfd_set_section_alignment (abfd, rtproc_sec, 4))
13228                     return FALSE;
13229                 }
13230
13231               if (! mips_elf_create_procedure_table (mdebug_handle, abfd,
13232                                                      info, rtproc_sec,
13233                                                      &debug))
13234                 return FALSE;
13235             }
13236
13237           /* Build the external symbol information.  */
13238           einfo.abfd = abfd;
13239           einfo.info = info;
13240           einfo.debug = &debug;
13241           einfo.swap = swap;
13242           einfo.failed = FALSE;
13243           mips_elf_link_hash_traverse (mips_elf_hash_table (info),
13244                                        mips_elf_output_extsym, &einfo);
13245           if (einfo.failed)
13246             return FALSE;
13247
13248           /* Set the size of the .mdebug section.  */
13249           o->size = bfd_ecoff_debug_size (abfd, &debug, swap);
13250
13251           /* Skip this section later on (I don't think this currently
13252              matters, but someday it might).  */
13253           o->map_head.link_order = NULL;
13254
13255           mdebug_sec = o;
13256         }
13257
13258       if (CONST_STRNEQ (o->name, ".gptab."))
13259         {
13260           const char *subname;
13261           unsigned int c;
13262           Elf32_gptab *tab;
13263           Elf32_External_gptab *ext_tab;
13264           unsigned int j;
13265
13266           /* The .gptab.sdata and .gptab.sbss sections hold
13267              information describing how the small data area would
13268              change depending upon the -G switch.  These sections
13269              not used in executables files.  */
13270           if (! info->relocatable)
13271             {
13272               for (p = o->map_head.link_order; p != NULL; p = p->next)
13273                 {
13274                   asection *input_section;
13275
13276                   if (p->type != bfd_indirect_link_order)
13277                     {
13278                       if (p->type == bfd_data_link_order)
13279                         continue;
13280                       abort ();
13281                     }
13282
13283                   input_section = p->u.indirect.section;
13284
13285                   /* Hack: reset the SEC_HAS_CONTENTS flag so that
13286                      elf_link_input_bfd ignores this section.  */
13287                   input_section->flags &= ~SEC_HAS_CONTENTS;
13288                 }
13289
13290               /* Skip this section later on (I don't think this
13291                  currently matters, but someday it might).  */
13292               o->map_head.link_order = NULL;
13293
13294               /* Really remove the section.  */
13295               bfd_section_list_remove (abfd, o);
13296               --abfd->section_count;
13297
13298               continue;
13299             }
13300
13301           /* There is one gptab for initialized data, and one for
13302              uninitialized data.  */
13303           if (strcmp (o->name, ".gptab.sdata") == 0)
13304             gptab_data_sec = o;
13305           else if (strcmp (o->name, ".gptab.sbss") == 0)
13306             gptab_bss_sec = o;
13307           else
13308             {
13309               (*_bfd_error_handler)
13310                 (_("%s: illegal section name `%s'"),
13311                  bfd_get_filename (abfd), o->name);
13312               bfd_set_error (bfd_error_nonrepresentable_section);
13313               return FALSE;
13314             }
13315
13316           /* The linker script always combines .gptab.data and
13317              .gptab.sdata into .gptab.sdata, and likewise for
13318              .gptab.bss and .gptab.sbss.  It is possible that there is
13319              no .sdata or .sbss section in the output file, in which
13320              case we must change the name of the output section.  */
13321           subname = o->name + sizeof ".gptab" - 1;
13322           if (bfd_get_section_by_name (abfd, subname) == NULL)
13323             {
13324               if (o == gptab_data_sec)
13325                 o->name = ".gptab.data";
13326               else
13327                 o->name = ".gptab.bss";
13328               subname = o->name + sizeof ".gptab" - 1;
13329               BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL);
13330             }
13331
13332           /* Set up the first entry.  */
13333           c = 1;
13334           amt = c * sizeof (Elf32_gptab);
13335           tab = bfd_malloc (amt);
13336           if (tab == NULL)
13337             return FALSE;
13338           tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd);
13339           tab[0].gt_header.gt_unused = 0;
13340
13341           /* Combine the input sections.  */
13342           for (p = o->map_head.link_order; p != NULL; p = p->next)
13343             {
13344               asection *input_section;
13345               bfd *input_bfd;
13346               bfd_size_type size;
13347               unsigned long last;
13348               bfd_size_type gpentry;
13349
13350               if (p->type != bfd_indirect_link_order)
13351                 {
13352                   if (p->type == bfd_data_link_order)
13353                     continue;
13354                   abort ();
13355                 }
13356
13357               input_section = p->u.indirect.section;
13358               input_bfd = input_section->owner;
13359
13360               /* Combine the gptab entries for this input section one
13361                  by one.  We know that the input gptab entries are
13362                  sorted by ascending -G value.  */
13363               size = input_section->size;
13364               last = 0;
13365               for (gpentry = sizeof (Elf32_External_gptab);
13366                    gpentry < size;
13367                    gpentry += sizeof (Elf32_External_gptab))
13368                 {
13369                   Elf32_External_gptab ext_gptab;
13370                   Elf32_gptab int_gptab;
13371                   unsigned long val;
13372                   unsigned long add;
13373                   bfd_boolean exact;
13374                   unsigned int look;
13375
13376                   if (! (bfd_get_section_contents
13377                          (input_bfd, input_section, &ext_gptab, gpentry,
13378                           sizeof (Elf32_External_gptab))))
13379                     {
13380                       free (tab);
13381                       return FALSE;
13382                     }
13383
13384                   bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab,
13385                                                 &int_gptab);
13386                   val = int_gptab.gt_entry.gt_g_value;
13387                   add = int_gptab.gt_entry.gt_bytes - last;
13388
13389                   exact = FALSE;
13390                   for (look = 1; look < c; look++)
13391                     {
13392                       if (tab[look].gt_entry.gt_g_value >= val)
13393                         tab[look].gt_entry.gt_bytes += add;
13394
13395                       if (tab[look].gt_entry.gt_g_value == val)
13396                         exact = TRUE;
13397                     }
13398
13399                   if (! exact)
13400                     {
13401                       Elf32_gptab *new_tab;
13402                       unsigned int max;
13403
13404                       /* We need a new table entry.  */
13405                       amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab);
13406                       new_tab = bfd_realloc (tab, amt);
13407                       if (new_tab == NULL)
13408                         {
13409                           free (tab);
13410                           return FALSE;
13411                         }
13412                       tab = new_tab;
13413                       tab[c].gt_entry.gt_g_value = val;
13414                       tab[c].gt_entry.gt_bytes = add;
13415
13416                       /* Merge in the size for the next smallest -G
13417                          value, since that will be implied by this new
13418                          value.  */
13419                       max = 0;
13420                       for (look = 1; look < c; look++)
13421                         {
13422                           if (tab[look].gt_entry.gt_g_value < val
13423                               && (max == 0
13424                                   || (tab[look].gt_entry.gt_g_value
13425                                       > tab[max].gt_entry.gt_g_value)))
13426                             max = look;
13427                         }
13428                       if (max != 0)
13429                         tab[c].gt_entry.gt_bytes +=
13430                           tab[max].gt_entry.gt_bytes;
13431
13432                       ++c;
13433                     }
13434
13435                   last = int_gptab.gt_entry.gt_bytes;
13436                 }
13437
13438               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13439                  elf_link_input_bfd ignores this section.  */
13440               input_section->flags &= ~SEC_HAS_CONTENTS;
13441             }
13442
13443           /* The table must be sorted by -G value.  */
13444           if (c > 2)
13445             qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare);
13446
13447           /* Swap out the table.  */
13448           amt = (bfd_size_type) c * sizeof (Elf32_External_gptab);
13449           ext_tab = bfd_alloc (abfd, amt);
13450           if (ext_tab == NULL)
13451             {
13452               free (tab);
13453               return FALSE;
13454             }
13455
13456           for (j = 0; j < c; j++)
13457             bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j);
13458           free (tab);
13459
13460           o->size = c * sizeof (Elf32_External_gptab);
13461           o->contents = (bfd_byte *) ext_tab;
13462
13463           /* Skip this section later on (I don't think this currently
13464              matters, but someday it might).  */
13465           o->map_head.link_order = NULL;
13466         }
13467     }
13468
13469   /* Invoke the regular ELF backend linker to do all the work.  */
13470   if (!bfd_elf_final_link (abfd, info))
13471     return FALSE;
13472
13473   /* Now write out the computed sections.  */
13474
13475   if (reginfo_sec != NULL)
13476     {
13477       Elf32_External_RegInfo ext;
13478
13479       bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext);
13480       if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext))
13481         return FALSE;
13482     }
13483
13484   if (mdebug_sec != NULL)
13485     {
13486       BFD_ASSERT (abfd->output_has_begun);
13487       if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug,
13488                                                swap, info,
13489                                                mdebug_sec->filepos))
13490         return FALSE;
13491
13492       bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info);
13493     }
13494
13495   if (gptab_data_sec != NULL)
13496     {
13497       if (! bfd_set_section_contents (abfd, gptab_data_sec,
13498                                       gptab_data_sec->contents,
13499                                       0, gptab_data_sec->size))
13500         return FALSE;
13501     }
13502
13503   if (gptab_bss_sec != NULL)
13504     {
13505       if (! bfd_set_section_contents (abfd, gptab_bss_sec,
13506                                       gptab_bss_sec->contents,
13507                                       0, gptab_bss_sec->size))
13508         return FALSE;
13509     }
13510
13511   if (SGI_COMPAT (abfd))
13512     {
13513       rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
13514       if (rtproc_sec != NULL)
13515         {
13516           if (! bfd_set_section_contents (abfd, rtproc_sec,
13517                                           rtproc_sec->contents,
13518                                           0, rtproc_sec->size))
13519             return FALSE;
13520         }
13521     }
13522
13523   return TRUE;
13524 }
13525 \f
13526 /* Structure for saying that BFD machine EXTENSION extends BASE.  */
13527
13528 struct mips_mach_extension {
13529   unsigned long extension, base;
13530 };
13531
13532
13533 /* An array describing how BFD machines relate to one another.  The entries
13534    are ordered topologically with MIPS I extensions listed last.  */
13535
13536 static const struct mips_mach_extension mips_mach_extensions[] = {
13537   /* MIPS64r2 extensions.  */
13538   { bfd_mach_mips_octeon2, bfd_mach_mips_octeonp },
13539   { bfd_mach_mips_octeonp, bfd_mach_mips_octeon },
13540   { bfd_mach_mips_octeon, bfd_mach_mipsisa64r2 },
13541
13542   /* MIPS64 extensions.  */
13543   { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 },
13544   { bfd_mach_mips_sb1, bfd_mach_mipsisa64 },
13545   { bfd_mach_mips_xlr, bfd_mach_mipsisa64 },
13546   { bfd_mach_mips_loongson_3a, bfd_mach_mipsisa64 },
13547
13548   /* MIPS V extensions.  */
13549   { bfd_mach_mipsisa64, bfd_mach_mips5 },
13550
13551   /* R10000 extensions.  */
13552   { bfd_mach_mips12000, bfd_mach_mips10000 },
13553   { bfd_mach_mips14000, bfd_mach_mips10000 },
13554   { bfd_mach_mips16000, bfd_mach_mips10000 },
13555
13556   /* R5000 extensions.  Note: the vr5500 ISA is an extension of the core
13557      vr5400 ISA, but doesn't include the multimedia stuff.  It seems
13558      better to allow vr5400 and vr5500 code to be merged anyway, since
13559      many libraries will just use the core ISA.  Perhaps we could add
13560      some sort of ASE flag if this ever proves a problem.  */
13561   { bfd_mach_mips5500, bfd_mach_mips5400 },
13562   { bfd_mach_mips5400, bfd_mach_mips5000 },
13563
13564   /* MIPS IV extensions.  */
13565   { bfd_mach_mips5, bfd_mach_mips8000 },
13566   { bfd_mach_mips10000, bfd_mach_mips8000 },
13567   { bfd_mach_mips5000, bfd_mach_mips8000 },
13568   { bfd_mach_mips7000, bfd_mach_mips8000 },
13569   { bfd_mach_mips9000, bfd_mach_mips8000 },
13570
13571   /* VR4100 extensions.  */
13572   { bfd_mach_mips4120, bfd_mach_mips4100 },
13573   { bfd_mach_mips4111, bfd_mach_mips4100 },
13574
13575   /* MIPS III extensions.  */
13576   { bfd_mach_mips_loongson_2e, bfd_mach_mips4000 },
13577   { bfd_mach_mips_loongson_2f, bfd_mach_mips4000 },
13578   { bfd_mach_mips8000, bfd_mach_mips4000 },
13579   { bfd_mach_mips4650, bfd_mach_mips4000 },
13580   { bfd_mach_mips4600, bfd_mach_mips4000 },
13581   { bfd_mach_mips4400, bfd_mach_mips4000 },
13582   { bfd_mach_mips4300, bfd_mach_mips4000 },
13583   { bfd_mach_mips4100, bfd_mach_mips4000 },
13584   { bfd_mach_mips4010, bfd_mach_mips4000 },
13585   { bfd_mach_mips5900, bfd_mach_mips4000 },
13586
13587   /* MIPS32 extensions.  */
13588   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
13589
13590   /* MIPS II extensions.  */
13591   { bfd_mach_mips4000, bfd_mach_mips6000 },
13592   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
13593
13594   /* MIPS I extensions.  */
13595   { bfd_mach_mips6000, bfd_mach_mips3000 },
13596   { bfd_mach_mips3900, bfd_mach_mips3000 }
13597 };
13598
13599
13600 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
13601
13602 static bfd_boolean
13603 mips_mach_extends_p (unsigned long base, unsigned long extension)
13604 {
13605   size_t i;
13606
13607   if (extension == base)
13608     return TRUE;
13609
13610   if (base == bfd_mach_mipsisa32
13611       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
13612     return TRUE;
13613
13614   if (base == bfd_mach_mipsisa32r2
13615       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
13616     return TRUE;
13617
13618   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
13619     if (extension == mips_mach_extensions[i].extension)
13620       {
13621         extension = mips_mach_extensions[i].base;
13622         if (extension == base)
13623           return TRUE;
13624       }
13625
13626   return FALSE;
13627 }
13628
13629
13630 /* Return true if the given ELF header flags describe a 32-bit binary.  */
13631
13632 static bfd_boolean
13633 mips_32bit_flags_p (flagword flags)
13634 {
13635   return ((flags & EF_MIPS_32BITMODE) != 0
13636           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
13637           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
13638           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
13639           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
13640           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
13641           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2);
13642 }
13643
13644
13645 /* Merge object attributes from IBFD into OBFD.  Raise an error if
13646    there are conflicting attributes.  */
13647 static bfd_boolean
13648 mips_elf_merge_obj_attributes (bfd *ibfd, bfd *obfd)
13649 {
13650   obj_attribute *in_attr;
13651   obj_attribute *out_attr;
13652   bfd *abi_fp_bfd;
13653
13654   abi_fp_bfd = mips_elf_tdata (obfd)->abi_fp_bfd;
13655   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
13656   if (!abi_fp_bfd && in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13657     mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
13658
13659   if (!elf_known_obj_attributes_proc (obfd)[0].i)
13660     {
13661       /* This is the first object.  Copy the attributes.  */
13662       _bfd_elf_copy_obj_attributes (ibfd, obfd);
13663
13664       /* Use the Tag_null value to indicate the attributes have been
13665          initialized.  */
13666       elf_known_obj_attributes_proc (obfd)[0].i = 1;
13667
13668       return TRUE;
13669     }
13670
13671   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
13672      non-conflicting ones.  */
13673   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
13674   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
13675     {
13676       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
13677       if (out_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
13678         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
13679       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13680         switch (out_attr[Tag_GNU_MIPS_ABI_FP].i)
13681           {
13682           case 1:
13683             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13684               {
13685               case 2:
13686                 _bfd_error_handler
13687                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13688                    obfd, abi_fp_bfd, ibfd, "-mdouble-float", "-msingle-float");
13689                 break;
13690
13691               case 3:
13692                 _bfd_error_handler
13693                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13694                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13695                 break;
13696
13697               case 4:
13698                 _bfd_error_handler
13699                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13700                    obfd, abi_fp_bfd, ibfd,
13701                    "-mdouble-float", "-mips32r2 -mfp64");
13702                 break;
13703
13704               default:
13705                 _bfd_error_handler
13706                   (_("Warning: %B uses %s (set by %B), "
13707                      "%B uses unknown floating point ABI %d"),
13708                    obfd, abi_fp_bfd, ibfd,
13709                    "-mdouble-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13710                 break;
13711               }
13712             break;
13713
13714           case 2:
13715             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13716               {
13717               case 1:
13718                 _bfd_error_handler
13719                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13720                    obfd, abi_fp_bfd, ibfd, "-msingle-float", "-mdouble-float");
13721                 break;
13722
13723               case 3:
13724                 _bfd_error_handler
13725                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13726                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13727                 break;
13728
13729               case 4:
13730                 _bfd_error_handler
13731                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13732                    obfd, abi_fp_bfd, ibfd,
13733                    "-msingle-float", "-mips32r2 -mfp64");
13734                 break;
13735
13736               default:
13737                 _bfd_error_handler
13738                   (_("Warning: %B uses %s (set by %B), "
13739                      "%B uses unknown floating point ABI %d"),
13740                    obfd, abi_fp_bfd, ibfd,
13741                    "-msingle-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13742                 break;
13743               }
13744             break;
13745
13746           case 3:
13747             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13748               {
13749               case 1:
13750               case 2:
13751               case 4:
13752                 _bfd_error_handler
13753                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13754                    obfd, abi_fp_bfd, ibfd, "-msoft-float", "-mhard-float");
13755                 break;
13756
13757               default:
13758                 _bfd_error_handler
13759                   (_("Warning: %B uses %s (set by %B), "
13760                      "%B uses unknown floating point ABI %d"),
13761                    obfd, abi_fp_bfd, ibfd,
13762                    "-msoft-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13763                 break;
13764               }
13765             break;
13766
13767           case 4:
13768             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13769               {
13770               case 1:
13771                 _bfd_error_handler
13772                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13773                    obfd, abi_fp_bfd, ibfd,
13774                    "-mips32r2 -mfp64", "-mdouble-float");
13775                 break;
13776
13777               case 2:
13778                 _bfd_error_handler
13779                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13780                    obfd, abi_fp_bfd, ibfd,
13781                    "-mips32r2 -mfp64", "-msingle-float");
13782                 break;
13783
13784               case 3:
13785                 _bfd_error_handler
13786                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13787                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13788                 break;
13789
13790               default:
13791                 _bfd_error_handler
13792                   (_("Warning: %B uses %s (set by %B), "
13793                      "%B uses unknown floating point ABI %d"),
13794                    obfd, abi_fp_bfd, ibfd,
13795                    "-mips32r2 -mfp64", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13796                 break;
13797               }
13798             break;
13799
13800           default:
13801             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13802               {
13803               case 1:
13804                 _bfd_error_handler
13805                   (_("Warning: %B uses unknown floating point ABI %d "
13806                      "(set by %B), %B uses %s"),
13807                    obfd, abi_fp_bfd, ibfd,
13808                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mdouble-float");
13809                 break;
13810
13811               case 2:
13812                 _bfd_error_handler
13813                   (_("Warning: %B uses unknown floating point ABI %d "
13814                      "(set by %B), %B uses %s"),
13815                    obfd, abi_fp_bfd, ibfd,
13816                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msingle-float");
13817                 break;
13818
13819               case 3:
13820                 _bfd_error_handler
13821                   (_("Warning: %B uses unknown floating point ABI %d "
13822                      "(set by %B), %B uses %s"),
13823                    obfd, abi_fp_bfd, ibfd,
13824                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msoft-float");
13825                 break;
13826
13827               case 4:
13828                 _bfd_error_handler
13829                   (_("Warning: %B uses unknown floating point ABI %d "
13830                      "(set by %B), %B uses %s"),
13831                    obfd, abi_fp_bfd, ibfd,
13832                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mips32r2 -mfp64");
13833                 break;
13834
13835               default:
13836                 _bfd_error_handler
13837                   (_("Warning: %B uses unknown floating point ABI %d "
13838                      "(set by %B), %B uses unknown floating point ABI %d"),
13839                    obfd, abi_fp_bfd, ibfd,
13840                    out_attr[Tag_GNU_MIPS_ABI_FP].i,
13841                    in_attr[Tag_GNU_MIPS_ABI_FP].i);
13842                 break;
13843               }
13844             break;
13845           }
13846     }
13847
13848   /* Merge Tag_compatibility attributes and any common GNU ones.  */
13849   _bfd_elf_merge_object_attributes (ibfd, obfd);
13850
13851   return TRUE;
13852 }
13853
13854 /* Merge backend specific data from an object file to the output
13855    object file when linking.  */
13856
13857 bfd_boolean
13858 _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
13859 {
13860   flagword old_flags;
13861   flagword new_flags;
13862   bfd_boolean ok;
13863   bfd_boolean null_input_bfd = TRUE;
13864   asection *sec;
13865
13866   /* Check if we have the same endianness.  */
13867   if (! _bfd_generic_verify_endian_match (ibfd, obfd))
13868     {
13869       (*_bfd_error_handler)
13870         (_("%B: endianness incompatible with that of the selected emulation"),
13871          ibfd);
13872       return FALSE;
13873     }
13874
13875   if (!is_mips_elf (ibfd) || !is_mips_elf (obfd))
13876     return TRUE;
13877
13878   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
13879     {
13880       (*_bfd_error_handler)
13881         (_("%B: ABI is incompatible with that of the selected emulation"),
13882          ibfd);
13883       return FALSE;
13884     }
13885
13886   if (!mips_elf_merge_obj_attributes (ibfd, obfd))
13887     return FALSE;
13888
13889   new_flags = elf_elfheader (ibfd)->e_flags;
13890   elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER;
13891   old_flags = elf_elfheader (obfd)->e_flags;
13892
13893   if (! elf_flags_init (obfd))
13894     {
13895       elf_flags_init (obfd) = TRUE;
13896       elf_elfheader (obfd)->e_flags = new_flags;
13897       elf_elfheader (obfd)->e_ident[EI_CLASS]
13898         = elf_elfheader (ibfd)->e_ident[EI_CLASS];
13899
13900       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
13901           && (bfd_get_arch_info (obfd)->the_default
13902               || mips_mach_extends_p (bfd_get_mach (obfd),
13903                                       bfd_get_mach (ibfd))))
13904         {
13905           if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
13906                                    bfd_get_mach (ibfd)))
13907             return FALSE;
13908         }
13909
13910       return TRUE;
13911     }
13912
13913   /* Check flag compatibility.  */
13914
13915   new_flags &= ~EF_MIPS_NOREORDER;
13916   old_flags &= ~EF_MIPS_NOREORDER;
13917
13918   /* Some IRIX 6 BSD-compatibility objects have this bit set.  It
13919      doesn't seem to matter.  */
13920   new_flags &= ~EF_MIPS_XGOT;
13921   old_flags &= ~EF_MIPS_XGOT;
13922
13923   /* MIPSpro generates ucode info in n64 objects.  Again, we should
13924      just be able to ignore this.  */
13925   new_flags &= ~EF_MIPS_UCODE;
13926   old_flags &= ~EF_MIPS_UCODE;
13927
13928   /* DSOs should only be linked with CPIC code.  */
13929   if ((ibfd->flags & DYNAMIC) != 0)
13930     new_flags |= EF_MIPS_PIC | EF_MIPS_CPIC;
13931
13932   if (new_flags == old_flags)
13933     return TRUE;
13934
13935   /* Check to see if the input BFD actually contains any sections.
13936      If not, its flags may not have been initialised either, but it cannot
13937      actually cause any incompatibility.  */
13938   for (sec = ibfd->sections; sec != NULL; sec = sec->next)
13939     {
13940       /* Ignore synthetic sections and empty .text, .data and .bss sections
13941          which are automatically generated by gas.  Also ignore fake
13942          (s)common sections, since merely defining a common symbol does
13943          not affect compatibility.  */
13944       if ((sec->flags & SEC_IS_COMMON) == 0
13945           && strcmp (sec->name, ".reginfo")
13946           && strcmp (sec->name, ".mdebug")
13947           && (sec->size != 0
13948               || (strcmp (sec->name, ".text")
13949                   && strcmp (sec->name, ".data")
13950                   && strcmp (sec->name, ".bss"))))
13951         {
13952           null_input_bfd = FALSE;
13953           break;
13954         }
13955     }
13956   if (null_input_bfd)
13957     return TRUE;
13958
13959   ok = TRUE;
13960
13961   if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)
13962       != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0))
13963     {
13964       (*_bfd_error_handler)
13965         (_("%B: warning: linking abicalls files with non-abicalls files"),
13966          ibfd);
13967       ok = TRUE;
13968     }
13969
13970   if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC))
13971     elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC;
13972   if (! (new_flags & EF_MIPS_PIC))
13973     elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC;
13974
13975   new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13976   old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13977
13978   /* Compare the ISAs.  */
13979   if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags))
13980     {
13981       (*_bfd_error_handler)
13982         (_("%B: linking 32-bit code with 64-bit code"),
13983          ibfd);
13984       ok = FALSE;
13985     }
13986   else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd)))
13987     {
13988       /* OBFD's ISA isn't the same as, or an extension of, IBFD's.  */
13989       if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd)))
13990         {
13991           /* Copy the architecture info from IBFD to OBFD.  Also copy
13992              the 32-bit flag (if set) so that we continue to recognise
13993              OBFD as a 32-bit binary.  */
13994           bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd));
13995           elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
13996           elf_elfheader (obfd)->e_flags
13997             |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13998
13999           /* Copy across the ABI flags if OBFD doesn't use them
14000              and if that was what caused us to treat IBFD as 32-bit.  */
14001           if ((old_flags & EF_MIPS_ABI) == 0
14002               && mips_32bit_flags_p (new_flags)
14003               && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI))
14004             elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI;
14005         }
14006       else
14007         {
14008           /* The ISAs aren't compatible.  */
14009           (*_bfd_error_handler)
14010             (_("%B: linking %s module with previous %s modules"),
14011              ibfd,
14012              bfd_printable_name (ibfd),
14013              bfd_printable_name (obfd));
14014           ok = FALSE;
14015         }
14016     }
14017
14018   new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14019   old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14020
14021   /* Compare ABIs.  The 64-bit ABI does not use EF_MIPS_ABI.  But, it
14022      does set EI_CLASS differently from any 32-bit ABI.  */
14023   if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI)
14024       || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14025           != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14026     {
14027       /* Only error if both are set (to different values).  */
14028       if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI))
14029           || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14030               != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14031         {
14032           (*_bfd_error_handler)
14033             (_("%B: ABI mismatch: linking %s module with previous %s modules"),
14034              ibfd,
14035              elf_mips_abi_name (ibfd),
14036              elf_mips_abi_name (obfd));
14037           ok = FALSE;
14038         }
14039       new_flags &= ~EF_MIPS_ABI;
14040       old_flags &= ~EF_MIPS_ABI;
14041     }
14042
14043   /* Compare ASEs.  Forbid linking MIPS16 and microMIPS ASE modules together
14044      and allow arbitrary mixing of the remaining ASEs (retain the union).  */
14045   if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE))
14046     {
14047       int old_micro = old_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14048       int new_micro = new_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14049       int old_m16 = old_flags & EF_MIPS_ARCH_ASE_M16;
14050       int new_m16 = new_flags & EF_MIPS_ARCH_ASE_M16;
14051       int micro_mis = old_m16 && new_micro;
14052       int m16_mis = old_micro && new_m16;
14053
14054       if (m16_mis || micro_mis)
14055         {
14056           (*_bfd_error_handler)
14057             (_("%B: ASE mismatch: linking %s module with previous %s modules"),
14058              ibfd,
14059              m16_mis ? "MIPS16" : "microMIPS",
14060              m16_mis ? "microMIPS" : "MIPS16");
14061           ok = FALSE;
14062         }
14063
14064       elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE;
14065
14066       new_flags &= ~ EF_MIPS_ARCH_ASE;
14067       old_flags &= ~ EF_MIPS_ARCH_ASE;
14068     }
14069
14070   /* Warn about any other mismatches */
14071   if (new_flags != old_flags)
14072     {
14073       (*_bfd_error_handler)
14074         (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"),
14075          ibfd, (unsigned long) new_flags,
14076          (unsigned long) old_flags);
14077       ok = FALSE;
14078     }
14079
14080   if (! ok)
14081     {
14082       bfd_set_error (bfd_error_bad_value);
14083       return FALSE;
14084     }
14085
14086   return TRUE;
14087 }
14088
14089 /* Function to keep MIPS specific file flags like as EF_MIPS_PIC.  */
14090
14091 bfd_boolean
14092 _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags)
14093 {
14094   BFD_ASSERT (!elf_flags_init (abfd)
14095               || elf_elfheader (abfd)->e_flags == flags);
14096
14097   elf_elfheader (abfd)->e_flags = flags;
14098   elf_flags_init (abfd) = TRUE;
14099   return TRUE;
14100 }
14101
14102 char *
14103 _bfd_mips_elf_get_target_dtag (bfd_vma dtag)
14104 {
14105   switch (dtag)
14106     {
14107     default: return "";
14108     case DT_MIPS_RLD_VERSION:
14109       return "MIPS_RLD_VERSION";
14110     case DT_MIPS_TIME_STAMP:
14111       return "MIPS_TIME_STAMP";
14112     case DT_MIPS_ICHECKSUM:
14113       return "MIPS_ICHECKSUM";
14114     case DT_MIPS_IVERSION:
14115       return "MIPS_IVERSION";
14116     case DT_MIPS_FLAGS:
14117       return "MIPS_FLAGS";
14118     case DT_MIPS_BASE_ADDRESS:
14119       return "MIPS_BASE_ADDRESS";
14120     case DT_MIPS_MSYM:
14121       return "MIPS_MSYM";
14122     case DT_MIPS_CONFLICT:
14123       return "MIPS_CONFLICT";
14124     case DT_MIPS_LIBLIST:
14125       return "MIPS_LIBLIST";
14126     case DT_MIPS_LOCAL_GOTNO:
14127       return "MIPS_LOCAL_GOTNO";
14128     case DT_MIPS_CONFLICTNO:
14129       return "MIPS_CONFLICTNO";
14130     case DT_MIPS_LIBLISTNO:
14131       return "MIPS_LIBLISTNO";
14132     case DT_MIPS_SYMTABNO:
14133       return "MIPS_SYMTABNO";
14134     case DT_MIPS_UNREFEXTNO:
14135       return "MIPS_UNREFEXTNO";
14136     case DT_MIPS_GOTSYM:
14137       return "MIPS_GOTSYM";
14138     case DT_MIPS_HIPAGENO:
14139       return "MIPS_HIPAGENO";
14140     case DT_MIPS_RLD_MAP:
14141       return "MIPS_RLD_MAP";
14142     case DT_MIPS_DELTA_CLASS:
14143       return "MIPS_DELTA_CLASS";
14144     case DT_MIPS_DELTA_CLASS_NO:
14145       return "MIPS_DELTA_CLASS_NO";
14146     case DT_MIPS_DELTA_INSTANCE:
14147       return "MIPS_DELTA_INSTANCE";
14148     case DT_MIPS_DELTA_INSTANCE_NO:
14149       return "MIPS_DELTA_INSTANCE_NO";
14150     case DT_MIPS_DELTA_RELOC:
14151       return "MIPS_DELTA_RELOC";
14152     case DT_MIPS_DELTA_RELOC_NO:
14153       return "MIPS_DELTA_RELOC_NO";
14154     case DT_MIPS_DELTA_SYM:
14155       return "MIPS_DELTA_SYM";
14156     case DT_MIPS_DELTA_SYM_NO:
14157       return "MIPS_DELTA_SYM_NO";
14158     case DT_MIPS_DELTA_CLASSSYM:
14159       return "MIPS_DELTA_CLASSSYM";
14160     case DT_MIPS_DELTA_CLASSSYM_NO:
14161       return "MIPS_DELTA_CLASSSYM_NO";
14162     case DT_MIPS_CXX_FLAGS:
14163       return "MIPS_CXX_FLAGS";
14164     case DT_MIPS_PIXIE_INIT:
14165       return "MIPS_PIXIE_INIT";
14166     case DT_MIPS_SYMBOL_LIB:
14167       return "MIPS_SYMBOL_LIB";
14168     case DT_MIPS_LOCALPAGE_GOTIDX:
14169       return "MIPS_LOCALPAGE_GOTIDX";
14170     case DT_MIPS_LOCAL_GOTIDX:
14171       return "MIPS_LOCAL_GOTIDX";
14172     case DT_MIPS_HIDDEN_GOTIDX:
14173       return "MIPS_HIDDEN_GOTIDX";
14174     case DT_MIPS_PROTECTED_GOTIDX:
14175       return "MIPS_PROTECTED_GOT_IDX";
14176     case DT_MIPS_OPTIONS:
14177       return "MIPS_OPTIONS";
14178     case DT_MIPS_INTERFACE:
14179       return "MIPS_INTERFACE";
14180     case DT_MIPS_DYNSTR_ALIGN:
14181       return "DT_MIPS_DYNSTR_ALIGN";
14182     case DT_MIPS_INTERFACE_SIZE:
14183       return "DT_MIPS_INTERFACE_SIZE";
14184     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
14185       return "DT_MIPS_RLD_TEXT_RESOLVE_ADDR";
14186     case DT_MIPS_PERF_SUFFIX:
14187       return "DT_MIPS_PERF_SUFFIX";
14188     case DT_MIPS_COMPACT_SIZE:
14189       return "DT_MIPS_COMPACT_SIZE";
14190     case DT_MIPS_GP_VALUE:
14191       return "DT_MIPS_GP_VALUE";
14192     case DT_MIPS_AUX_DYNAMIC:
14193       return "DT_MIPS_AUX_DYNAMIC";
14194     case DT_MIPS_PLTGOT:
14195       return "DT_MIPS_PLTGOT";
14196     case DT_MIPS_RWPLT:
14197       return "DT_MIPS_RWPLT";
14198     }
14199 }
14200
14201 bfd_boolean
14202 _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr)
14203 {
14204   FILE *file = ptr;
14205
14206   BFD_ASSERT (abfd != NULL && ptr != NULL);
14207
14208   /* Print normal ELF private data.  */
14209   _bfd_elf_print_private_bfd_data (abfd, ptr);
14210
14211   /* xgettext:c-format */
14212   fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
14213
14214   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
14215     fprintf (file, _(" [abi=O32]"));
14216   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64)
14217     fprintf (file, _(" [abi=O64]"));
14218   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32)
14219     fprintf (file, _(" [abi=EABI32]"));
14220   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
14221     fprintf (file, _(" [abi=EABI64]"));
14222   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI))
14223     fprintf (file, _(" [abi unknown]"));
14224   else if (ABI_N32_P (abfd))
14225     fprintf (file, _(" [abi=N32]"));
14226   else if (ABI_64_P (abfd))
14227     fprintf (file, _(" [abi=64]"));
14228   else
14229     fprintf (file, _(" [no abi set]"));
14230
14231   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1)
14232     fprintf (file, " [mips1]");
14233   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2)
14234     fprintf (file, " [mips2]");
14235   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3)
14236     fprintf (file, " [mips3]");
14237   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4)
14238     fprintf (file, " [mips4]");
14239   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5)
14240     fprintf (file, " [mips5]");
14241   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32)
14242     fprintf (file, " [mips32]");
14243   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64)
14244     fprintf (file, " [mips64]");
14245   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2)
14246     fprintf (file, " [mips32r2]");
14247   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2)
14248     fprintf (file, " [mips64r2]");
14249   else
14250     fprintf (file, _(" [unknown ISA]"));
14251
14252   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
14253     fprintf (file, " [mdmx]");
14254
14255   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
14256     fprintf (file, " [mips16]");
14257
14258   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
14259     fprintf (file, " [micromips]");
14260
14261   if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE)
14262     fprintf (file, " [32bitmode]");
14263   else
14264     fprintf (file, _(" [not 32bitmode]"));
14265
14266   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NOREORDER)
14267     fprintf (file, " [noreorder]");
14268
14269   if (elf_elfheader (abfd)->e_flags & EF_MIPS_PIC)
14270     fprintf (file, " [PIC]");
14271
14272   if (elf_elfheader (abfd)->e_flags & EF_MIPS_CPIC)
14273     fprintf (file, " [CPIC]");
14274
14275   if (elf_elfheader (abfd)->e_flags & EF_MIPS_XGOT)
14276     fprintf (file, " [XGOT]");
14277
14278   if (elf_elfheader (abfd)->e_flags & EF_MIPS_UCODE)
14279     fprintf (file, " [UCODE]");
14280
14281   fputc ('\n', file);
14282
14283   return TRUE;
14284 }
14285
14286 const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] =
14287 {
14288   { STRING_COMMA_LEN (".lit4"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14289   { STRING_COMMA_LEN (".lit8"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14290   { STRING_COMMA_LEN (".mdebug"), 0, SHT_MIPS_DEBUG, 0 },
14291   { STRING_COMMA_LEN (".sbss"),  -2, SHT_NOBITS,     SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14292   { STRING_COMMA_LEN (".sdata"), -2, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14293   { STRING_COMMA_LEN (".ucode"),  0, SHT_MIPS_UCODE, 0 },
14294   { NULL,                     0,  0, 0,              0 }
14295 };
14296
14297 /* Merge non visibility st_other attributes.  Ensure that the
14298    STO_OPTIONAL flag is copied into h->other, even if this is not a
14299    definiton of the symbol.  */
14300 void
14301 _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
14302                                       const Elf_Internal_Sym *isym,
14303                                       bfd_boolean definition,
14304                                       bfd_boolean dynamic ATTRIBUTE_UNUSED)
14305 {
14306   if ((isym->st_other & ~ELF_ST_VISIBILITY (-1)) != 0)
14307     {
14308       unsigned char other;
14309
14310       other = (definition ? isym->st_other : h->other);
14311       other &= ~ELF_ST_VISIBILITY (-1);
14312       h->other = other | ELF_ST_VISIBILITY (h->other);
14313     }
14314
14315   if (!definition
14316       && ELF_MIPS_IS_OPTIONAL (isym->st_other))
14317     h->other |= STO_OPTIONAL;
14318 }
14319
14320 /* Decide whether an undefined symbol is special and can be ignored.
14321    This is the case for OPTIONAL symbols on IRIX.  */
14322 bfd_boolean
14323 _bfd_mips_elf_ignore_undef_symbol (struct elf_link_hash_entry *h)
14324 {
14325   return ELF_MIPS_IS_OPTIONAL (h->other) ? TRUE : FALSE;
14326 }
14327
14328 bfd_boolean
14329 _bfd_mips_elf_common_definition (Elf_Internal_Sym *sym)
14330 {
14331   return (sym->st_shndx == SHN_COMMON
14332           || sym->st_shndx == SHN_MIPS_ACOMMON
14333           || sym->st_shndx == SHN_MIPS_SCOMMON);
14334 }
14335
14336 /* Return address for Ith PLT stub in section PLT, for relocation REL
14337    or (bfd_vma) -1 if it should not be included.  */
14338
14339 bfd_vma
14340 _bfd_mips_elf_plt_sym_val (bfd_vma i, const asection *plt,
14341                            const arelent *rel ATTRIBUTE_UNUSED)
14342 {
14343   return (plt->vma
14344           + 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry)
14345           + i * 4 * ARRAY_SIZE (mips_exec_plt_entry));
14346 }
14347
14348 void
14349 _bfd_mips_post_process_headers (bfd *abfd, struct bfd_link_info *link_info)
14350 {
14351   struct mips_elf_link_hash_table *htab;
14352   Elf_Internal_Ehdr *i_ehdrp;
14353
14354   i_ehdrp = elf_elfheader (abfd);
14355   if (link_info)
14356     {
14357       htab = mips_elf_hash_table (link_info);
14358       BFD_ASSERT (htab != NULL);
14359
14360       if (htab->use_plts_and_copy_relocs && !htab->is_vxworks)
14361         i_ehdrp->e_ident[EI_ABIVERSION] = 1;
14362     }
14363 }