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 #define GOT_NORMAL      0
93 #define GOT_TLS_GD      1
94 #define GOT_TLS_LDM     2
95 #define GOT_TLS_IE      4
96 #define GOT_TLS_TYPE    7
97 #define GOT_TLS_DONE    0x80
98   unsigned char tls_type;
99
100   /* The offset from the beginning of the .got section to the entry
101      corresponding to this symbol+addend.  If it's a global symbol
102      whose offset is yet to be decided, it's going to be -1.  */
103   long gotidx;
104 };
105
106 /* This structure describes a range of addends: [MIN_ADDEND, MAX_ADDEND].
107    The structures form a non-overlapping list that is sorted by increasing
108    MIN_ADDEND.  */
109 struct mips_got_page_range
110 {
111   struct mips_got_page_range *next;
112   bfd_signed_vma min_addend;
113   bfd_signed_vma max_addend;
114 };
115
116 /* This structure describes the range of addends that are applied to page
117    relocations against a given symbol.  */
118 struct mips_got_page_entry
119 {
120   /* The input bfd in which the symbol is defined.  */
121   bfd *abfd;
122   /* The index of the symbol, as stored in the relocation r_info.  */
123   long symndx;
124   /* The ranges for this page entry.  */
125   struct mips_got_page_range *ranges;
126   /* The maximum number of page entries needed for RANGES.  */
127   bfd_vma num_pages;
128 };
129
130 /* This structure is used to hold .got information when linking.  */
131
132 struct mips_got_info
133 {
134   /* The number of global .got entries.  */
135   unsigned int global_gotno;
136   /* The number of global .got entries that are in the GGA_RELOC_ONLY area.  */
137   unsigned int reloc_only_gotno;
138   /* The number of .got slots used for TLS.  */
139   unsigned int tls_gotno;
140   /* The first unused TLS .got entry.  Used only during
141      mips_elf_initialize_tls_index.  */
142   unsigned int tls_assigned_gotno;
143   /* The number of local .got entries, eventually including page entries.  */
144   unsigned int local_gotno;
145   /* The maximum number of page entries needed.  */
146   unsigned int page_gotno;
147   /* The number of relocations needed for the GOT entries.  */
148   unsigned int relocs;
149   /* The number of local .got entries we have used.  */
150   unsigned int assigned_gotno;
151   /* A hash table holding members of the got.  */
152   struct htab *got_entries;
153   /* A hash table of mips_got_page_entry structures.  */
154   struct htab *got_page_entries;
155   /* In multi-got links, a pointer to the next got (err, rather, most
156      of the time, it points to the previous got).  */
157   struct mips_got_info *next;
158 };
159
160 /* Structure passed when merging bfds' gots.  */
161
162 struct mips_elf_got_per_bfd_arg
163 {
164   /* The output bfd.  */
165   bfd *obfd;
166   /* The link information.  */
167   struct bfd_link_info *info;
168   /* A pointer to the primary got, i.e., the one that's going to get
169      the implicit relocations from DT_MIPS_LOCAL_GOTNO and
170      DT_MIPS_GOTSYM.  */
171   struct mips_got_info *primary;
172   /* A non-primary got we're trying to merge with other input bfd's
173      gots.  */
174   struct mips_got_info *current;
175   /* The maximum number of got entries that can be addressed with a
176      16-bit offset.  */
177   unsigned int max_count;
178   /* The maximum number of page entries needed by each got.  */
179   unsigned int max_pages;
180   /* The total number of global entries which will live in the
181      primary got and be automatically relocated.  This includes
182      those not referenced by the primary GOT but included in
183      the "master" GOT.  */
184   unsigned int global_count;
185 };
186
187 /* A structure used to pass information to htab_traverse callbacks
188    when laying out the GOT.  */
189
190 struct mips_elf_traverse_got_arg
191 {
192   struct bfd_link_info *info;
193   struct mips_got_info *g;
194   int value;
195 };
196
197 struct _mips_elf_section_data
198 {
199   struct bfd_elf_section_data elf;
200   union
201   {
202     bfd_byte *tdata;
203   } u;
204 };
205
206 #define mips_elf_section_data(sec) \
207   ((struct _mips_elf_section_data *) elf_section_data (sec))
208
209 #define is_mips_elf(bfd)                                \
210   (bfd_get_flavour (bfd) == bfd_target_elf_flavour      \
211    && elf_tdata (bfd) != NULL                           \
212    && elf_object_id (bfd) == MIPS_ELF_DATA)
213
214 /* The ABI says that every symbol used by dynamic relocations must have
215    a global GOT entry.  Among other things, this provides the dynamic
216    linker with a free, directly-indexed cache.  The GOT can therefore
217    contain symbols that are not referenced by GOT relocations themselves
218    (in other words, it may have symbols that are not referenced by things
219    like R_MIPS_GOT16 and R_MIPS_GOT_PAGE).
220
221    GOT relocations are less likely to overflow if we put the associated
222    GOT entries towards the beginning.  We therefore divide the global
223    GOT entries into two areas: "normal" and "reloc-only".  Entries in
224    the first area can be used for both dynamic relocations and GP-relative
225    accesses, while those in the "reloc-only" area are for dynamic
226    relocations only.
227
228    These GGA_* ("Global GOT Area") values are organised so that lower
229    values are more general than higher values.  Also, non-GGA_NONE
230    values are ordered by the position of the area in the GOT.  */
231 #define GGA_NORMAL 0
232 #define GGA_RELOC_ONLY 1
233 #define GGA_NONE 2
234
235 /* Information about a non-PIC interface to a PIC function.  There are
236    two ways of creating these interfaces.  The first is to add:
237
238         lui     $25,%hi(func)
239         addiu   $25,$25,%lo(func)
240
241    immediately before a PIC function "func".  The second is to add:
242
243         lui     $25,%hi(func)
244         j       func
245         addiu   $25,$25,%lo(func)
246
247    to a separate trampoline section.
248
249    Stubs of the first kind go in a new section immediately before the
250    target function.  Stubs of the second kind go in a single section
251    pointed to by the hash table's "strampoline" field.  */
252 struct mips_elf_la25_stub {
253   /* The generated section that contains this stub.  */
254   asection *stub_section;
255
256   /* The offset of the stub from the start of STUB_SECTION.  */
257   bfd_vma offset;
258
259   /* One symbol for the original function.  Its location is available
260      in H->root.root.u.def.  */
261   struct mips_elf_link_hash_entry *h;
262 };
263
264 /* Macros for populating a mips_elf_la25_stub.  */
265
266 #define LA25_LUI(VAL) (0x3c190000 | (VAL))      /* lui t9,VAL */
267 #define LA25_J(VAL) (0x08000000 | (((VAL) >> 2) & 0x3ffffff)) /* j VAL */
268 #define LA25_ADDIU(VAL) (0x27390000 | (VAL))    /* addiu t9,t9,VAL */
269 #define LA25_LUI_MICROMIPS(VAL)                                         \
270   (0x41b90000 | (VAL))                          /* lui t9,VAL */
271 #define LA25_J_MICROMIPS(VAL)                                           \
272   (0xd4000000 | (((VAL) >> 1) & 0x3ffffff))     /* j VAL */
273 #define LA25_ADDIU_MICROMIPS(VAL)                                       \
274   (0x33390000 | (VAL))                          /* addiu t9,t9,VAL */
275
276 /* This structure is passed to mips_elf_sort_hash_table_f when sorting
277    the dynamic symbols.  */
278
279 struct mips_elf_hash_sort_data
280 {
281   /* The symbol in the global GOT with the lowest dynamic symbol table
282      index.  */
283   struct elf_link_hash_entry *low;
284   /* The least dynamic symbol table index corresponding to a non-TLS
285      symbol with a GOT entry.  */
286   long min_got_dynindx;
287   /* The greatest dynamic symbol table index corresponding to a symbol
288      with a GOT entry that is not referenced (e.g., a dynamic symbol
289      with dynamic relocations pointing to it from non-primary GOTs).  */
290   long max_unref_got_dynindx;
291   /* The greatest dynamic symbol table index not corresponding to a
292      symbol without a GOT entry.  */
293   long max_non_got_dynindx;
294 };
295
296 /* The MIPS ELF linker needs additional information for each symbol in
297    the global hash table.  */
298
299 struct mips_elf_link_hash_entry
300 {
301   struct elf_link_hash_entry root;
302
303   /* External symbol information.  */
304   EXTR esym;
305
306   /* The la25 stub we have created for ths symbol, if any.  */
307   struct mips_elf_la25_stub *la25_stub;
308
309   /* Number of R_MIPS_32, R_MIPS_REL32, or R_MIPS_64 relocs against
310      this symbol.  */
311   unsigned int possibly_dynamic_relocs;
312
313   /* If there is a stub that 32 bit functions should use to call this
314      16 bit function, this points to the section containing the stub.  */
315   asection *fn_stub;
316
317   /* If there is a stub that 16 bit functions should use to call this
318      32 bit function, this points to the section containing the stub.  */
319   asection *call_stub;
320
321   /* This is like the call_stub field, but it is used if the function
322      being called returns a floating point value.  */
323   asection *call_fp_stub;
324
325   /* The highest GGA_* value that satisfies all references to this symbol.  */
326   unsigned int global_got_area : 2;
327
328   /* True if all GOT relocations against this symbol are for calls.  This is
329      a looser condition than no_fn_stub below, because there may be other
330      non-call non-GOT relocations against the symbol.  */
331   unsigned int got_only_for_calls : 1;
332
333   /* True if one of the relocations described by possibly_dynamic_relocs
334      is against a readonly section.  */
335   unsigned int readonly_reloc : 1;
336
337   /* True if there is a relocation against this symbol that must be
338      resolved by the static linker (in other words, if the relocation
339      cannot possibly be made dynamic).  */
340   unsigned int has_static_relocs : 1;
341
342   /* True if we must not create a .MIPS.stubs entry for this symbol.
343      This is set, for example, if there are relocations related to
344      taking the function's address, i.e. any but R_MIPS_CALL*16 ones.
345      See "MIPS ABI Supplement, 3rd Edition", p. 4-20.  */
346   unsigned int no_fn_stub : 1;
347
348   /* Whether we need the fn_stub; this is true if this symbol appears
349      in any relocs other than a 16 bit call.  */
350   unsigned int need_fn_stub : 1;
351
352   /* True if this symbol is referenced by branch relocations from
353      any non-PIC input file.  This is used to determine whether an
354      la25 stub is required.  */
355   unsigned int has_nonpic_branches : 1;
356
357   /* Does this symbol need a traditional MIPS lazy-binding stub
358      (as opposed to a PLT entry)?  */
359   unsigned int needs_lazy_stub : 1;
360 };
361
362 /* MIPS ELF linker hash table.  */
363
364 struct mips_elf_link_hash_table
365 {
366   struct elf_link_hash_table root;
367
368   /* The number of .rtproc entries.  */
369   bfd_size_type procedure_count;
370
371   /* The size of the .compact_rel section (if SGI_COMPAT).  */
372   bfd_size_type compact_rel_size;
373
374   /* This flag indicates that the value of DT_MIPS_RLD_MAP dynamic entry
375      is set to the address of __rld_obj_head as in IRIX5 and IRIX6.  */
376   bfd_boolean use_rld_obj_head;
377
378   /* The  __rld_map or __rld_obj_head symbol. */
379   struct elf_link_hash_entry *rld_symbol;
380
381   /* This is set if we see any mips16 stub sections.  */
382   bfd_boolean mips16_stubs_seen;
383
384   /* True if we can generate copy relocs and PLTs.  */
385   bfd_boolean use_plts_and_copy_relocs;
386
387   /* True if we're generating code for VxWorks.  */
388   bfd_boolean is_vxworks;
389
390   /* True if we already reported the small-data section overflow.  */
391   bfd_boolean small_data_overflow_reported;
392
393   /* Shortcuts to some dynamic sections, or NULL if they are not
394      being used.  */
395   asection *srelbss;
396   asection *sdynbss;
397   asection *srelplt;
398   asection *srelplt2;
399   asection *sgotplt;
400   asection *splt;
401   asection *sstubs;
402   asection *sgot;
403
404   /* The master GOT information.  */
405   struct mips_got_info *got_info;
406
407   /* The global symbol in the GOT with the lowest index in the dynamic
408      symbol table.  */
409   struct elf_link_hash_entry *global_gotsym;
410
411   /* The size of the PLT header in bytes.  */
412   bfd_vma plt_header_size;
413
414   /* The size of a PLT entry in bytes.  */
415   bfd_vma plt_entry_size;
416
417   /* The number of functions that need a lazy-binding stub.  */
418   bfd_vma lazy_stub_count;
419
420   /* The size of a function stub entry in bytes.  */
421   bfd_vma function_stub_size;
422
423   /* The number of reserved entries at the beginning of the GOT.  */
424   unsigned int reserved_gotno;
425
426   /* The section used for mips_elf_la25_stub trampolines.
427      See the comment above that structure for details.  */
428   asection *strampoline;
429
430   /* A table of mips_elf_la25_stubs, indexed by (input_section, offset)
431      pairs.  */
432   htab_t la25_stubs;
433
434   /* A function FN (NAME, IS, OS) that creates a new input section
435      called NAME and links it to output section OS.  If IS is nonnull,
436      the new section should go immediately before it, otherwise it
437      should go at the (current) beginning of OS.
438
439      The function returns the new section on success, otherwise it
440      returns null.  */
441   asection *(*add_stub_section) (const char *, asection *, asection *);
442 };
443
444 /* Get the MIPS ELF linker hash table from a link_info structure.  */
445
446 #define mips_elf_hash_table(p) \
447   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
448   == MIPS_ELF_DATA ? ((struct mips_elf_link_hash_table *) ((p)->hash)) : NULL)
449
450 /* A structure used to communicate with htab_traverse callbacks.  */
451 struct mips_htab_traverse_info
452 {
453   /* The usual link-wide information.  */
454   struct bfd_link_info *info;
455   bfd *output_bfd;
456
457   /* Starts off FALSE and is set to TRUE if the link should be aborted.  */
458   bfd_boolean error;
459 };
460
461 /* MIPS ELF private object data.  */
462
463 struct mips_elf_obj_tdata
464 {
465   /* Generic ELF private object data.  */
466   struct elf_obj_tdata root;
467
468   /* Input BFD providing Tag_GNU_MIPS_ABI_FP attribute for output.  */
469   bfd *abi_fp_bfd;
470
471   /* The GOT requirements of input bfds.  */
472   struct mips_got_info *got;
473 };
474
475 /* Get MIPS ELF private object data from BFD's tdata.  */
476
477 #define mips_elf_tdata(bfd) \
478   ((struct mips_elf_obj_tdata *) (bfd)->tdata.any)
479
480 #define TLS_RELOC_P(r_type) \
481   (r_type == R_MIPS_TLS_DTPMOD32                \
482    || r_type == R_MIPS_TLS_DTPMOD64             \
483    || r_type == R_MIPS_TLS_DTPREL32             \
484    || r_type == R_MIPS_TLS_DTPREL64             \
485    || r_type == R_MIPS_TLS_GD                   \
486    || r_type == R_MIPS_TLS_LDM                  \
487    || r_type == R_MIPS_TLS_DTPREL_HI16          \
488    || r_type == R_MIPS_TLS_DTPREL_LO16          \
489    || r_type == R_MIPS_TLS_GOTTPREL             \
490    || r_type == R_MIPS_TLS_TPREL32              \
491    || r_type == R_MIPS_TLS_TPREL64              \
492    || r_type == R_MIPS_TLS_TPREL_HI16           \
493    || r_type == R_MIPS_TLS_TPREL_LO16           \
494    || r_type == R_MIPS16_TLS_GD                 \
495    || r_type == R_MIPS16_TLS_LDM                \
496    || r_type == R_MIPS16_TLS_DTPREL_HI16        \
497    || r_type == R_MIPS16_TLS_DTPREL_LO16        \
498    || r_type == R_MIPS16_TLS_GOTTPREL           \
499    || r_type == R_MIPS16_TLS_TPREL_HI16         \
500    || r_type == R_MIPS16_TLS_TPREL_LO16         \
501    || r_type == R_MICROMIPS_TLS_GD              \
502    || r_type == R_MICROMIPS_TLS_LDM             \
503    || r_type == R_MICROMIPS_TLS_DTPREL_HI16     \
504    || r_type == R_MICROMIPS_TLS_DTPREL_LO16     \
505    || r_type == R_MICROMIPS_TLS_GOTTPREL        \
506    || r_type == R_MICROMIPS_TLS_TPREL_HI16      \
507    || r_type == R_MICROMIPS_TLS_TPREL_LO16)
508
509 /* Structure used to pass information to mips_elf_output_extsym.  */
510
511 struct extsym_info
512 {
513   bfd *abfd;
514   struct bfd_link_info *info;
515   struct ecoff_debug_info *debug;
516   const struct ecoff_debug_swap *swap;
517   bfd_boolean failed;
518 };
519
520 /* The names of the runtime procedure table symbols used on IRIX5.  */
521
522 static const char * const mips_elf_dynsym_rtproc_names[] =
523 {
524   "_procedure_table",
525   "_procedure_string_table",
526   "_procedure_table_size",
527   NULL
528 };
529
530 /* These structures are used to generate the .compact_rel section on
531    IRIX5.  */
532
533 typedef struct
534 {
535   unsigned long id1;            /* Always one?  */
536   unsigned long num;            /* Number of compact relocation entries.  */
537   unsigned long id2;            /* Always two?  */
538   unsigned long offset;         /* The file offset of the first relocation.  */
539   unsigned long reserved0;      /* Zero?  */
540   unsigned long reserved1;      /* Zero?  */
541 } Elf32_compact_rel;
542
543 typedef struct
544 {
545   bfd_byte id1[4];
546   bfd_byte num[4];
547   bfd_byte id2[4];
548   bfd_byte offset[4];
549   bfd_byte reserved0[4];
550   bfd_byte reserved1[4];
551 } Elf32_External_compact_rel;
552
553 typedef struct
554 {
555   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
556   unsigned int rtype : 4;       /* Relocation types. See below.  */
557   unsigned int dist2to : 8;
558   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
559   unsigned long konst;          /* KONST field. See below.  */
560   unsigned long vaddr;          /* VADDR to be relocated.  */
561 } Elf32_crinfo;
562
563 typedef struct
564 {
565   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
566   unsigned int rtype : 4;       /* Relocation types. See below.  */
567   unsigned int dist2to : 8;
568   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
569   unsigned long konst;          /* KONST field. See below.  */
570 } Elf32_crinfo2;
571
572 typedef struct
573 {
574   bfd_byte info[4];
575   bfd_byte konst[4];
576   bfd_byte vaddr[4];
577 } Elf32_External_crinfo;
578
579 typedef struct
580 {
581   bfd_byte info[4];
582   bfd_byte konst[4];
583 } Elf32_External_crinfo2;
584
585 /* These are the constants used to swap the bitfields in a crinfo.  */
586
587 #define CRINFO_CTYPE (0x1)
588 #define CRINFO_CTYPE_SH (31)
589 #define CRINFO_RTYPE (0xf)
590 #define CRINFO_RTYPE_SH (27)
591 #define CRINFO_DIST2TO (0xff)
592 #define CRINFO_DIST2TO_SH (19)
593 #define CRINFO_RELVADDR (0x7ffff)
594 #define CRINFO_RELVADDR_SH (0)
595
596 /* A compact relocation info has long (3 words) or short (2 words)
597    formats.  A short format doesn't have VADDR field and relvaddr
598    fields contains ((VADDR - vaddr of the previous entry) >> 2).  */
599 #define CRF_MIPS_LONG                   1
600 #define CRF_MIPS_SHORT                  0
601
602 /* There are 4 types of compact relocation at least. The value KONST
603    has different meaning for each type:
604
605    (type)               (konst)
606    CT_MIPS_REL32        Address in data
607    CT_MIPS_WORD         Address in word (XXX)
608    CT_MIPS_GPHI_LO      GP - vaddr
609    CT_MIPS_JMPAD        Address to jump
610    */
611
612 #define CRT_MIPS_REL32                  0xa
613 #define CRT_MIPS_WORD                   0xb
614 #define CRT_MIPS_GPHI_LO                0xc
615 #define CRT_MIPS_JMPAD                  0xd
616
617 #define mips_elf_set_cr_format(x,format)        ((x).ctype = (format))
618 #define mips_elf_set_cr_type(x,type)            ((x).rtype = (type))
619 #define mips_elf_set_cr_dist2to(x,v)            ((x).dist2to = (v))
620 #define mips_elf_set_cr_relvaddr(x,d)           ((x).relvaddr = (d)<<2)
621 \f
622 /* The structure of the runtime procedure descriptor created by the
623    loader for use by the static exception system.  */
624
625 typedef struct runtime_pdr {
626         bfd_vma adr;            /* Memory address of start of procedure.  */
627         long    regmask;        /* Save register mask.  */
628         long    regoffset;      /* Save register offset.  */
629         long    fregmask;       /* Save floating point register mask.  */
630         long    fregoffset;     /* Save floating point register offset.  */
631         long    frameoffset;    /* Frame size.  */
632         short   framereg;       /* Frame pointer register.  */
633         short   pcreg;          /* Offset or reg of return pc.  */
634         long    irpss;          /* Index into the runtime string table.  */
635         long    reserved;
636         struct exception_info *exception_info;/* Pointer to exception array.  */
637 } RPDR, *pRPDR;
638 #define cbRPDR sizeof (RPDR)
639 #define rpdNil ((pRPDR) 0)
640 \f
641 static struct mips_got_entry *mips_elf_create_local_got_entry
642   (bfd *, struct bfd_link_info *, bfd *, bfd_vma, unsigned long,
643    struct mips_elf_link_hash_entry *, int);
644 static bfd_boolean mips_elf_sort_hash_table_f
645   (struct mips_elf_link_hash_entry *, void *);
646 static bfd_vma mips_elf_high
647   (bfd_vma);
648 static bfd_boolean mips_elf_create_dynamic_relocation
649   (bfd *, struct bfd_link_info *, const Elf_Internal_Rela *,
650    struct mips_elf_link_hash_entry *, asection *, bfd_vma,
651    bfd_vma *, asection *);
652 static bfd_vma mips_elf_adjust_gp
653   (bfd *, struct mips_got_info *, bfd *);
654
655 /* This will be used when we sort the dynamic relocation records.  */
656 static bfd *reldyn_sorting_bfd;
657
658 /* True if ABFD is for CPUs with load interlocking that include
659    non-MIPS1 CPUs and R3900.  */
660 #define LOAD_INTERLOCKS_P(abfd) \
661   (   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) != E_MIPS_ARCH_1) \
662    || ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_3900))
663
664 /* True if ABFD is for CPUs that are faster if JAL is converted to BAL.
665    This should be safe for all architectures.  We enable this predicate
666    for RM9000 for now.  */
667 #define JAL_TO_BAL_P(abfd) \
668   ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_9000)
669
670 /* True if ABFD is for CPUs that are faster if JALR is converted to BAL.
671    This should be safe for all architectures.  We enable this predicate for
672    all CPUs.  */
673 #define JALR_TO_BAL_P(abfd) 1
674
675 /* True if ABFD is for CPUs that are faster if JR is converted to B.
676    This should be safe for all architectures.  We enable this predicate for
677    all CPUs.  */
678 #define JR_TO_B_P(abfd) 1
679
680 /* True if ABFD is a PIC object.  */
681 #define PIC_OBJECT_P(abfd) \
682   ((elf_elfheader (abfd)->e_flags & EF_MIPS_PIC) != 0)
683
684 /* Nonzero if ABFD is using the N32 ABI.  */
685 #define ABI_N32_P(abfd) \
686   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI2) != 0)
687
688 /* Nonzero if ABFD is using the N64 ABI.  */
689 #define ABI_64_P(abfd) \
690   (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS64)
691
692 /* Nonzero if ABFD is using NewABI conventions.  */
693 #define NEWABI_P(abfd) (ABI_N32_P (abfd) || ABI_64_P (abfd))
694
695 /* The IRIX compatibility level we are striving for.  */
696 #define IRIX_COMPAT(abfd) \
697   (get_elf_backend_data (abfd)->elf_backend_mips_irix_compat (abfd))
698
699 /* Whether we are trying to be compatible with IRIX at all.  */
700 #define SGI_COMPAT(abfd) \
701   (IRIX_COMPAT (abfd) != ict_none)
702
703 /* The name of the options section.  */
704 #define MIPS_ELF_OPTIONS_SECTION_NAME(abfd) \
705   (NEWABI_P (abfd) ? ".MIPS.options" : ".options")
706
707 /* True if NAME is the recognized name of any SHT_MIPS_OPTIONS section.
708    Some IRIX system files do not use MIPS_ELF_OPTIONS_SECTION_NAME.  */
709 #define MIPS_ELF_OPTIONS_SECTION_NAME_P(NAME) \
710   (strcmp (NAME, ".MIPS.options") == 0 || strcmp (NAME, ".options") == 0)
711
712 /* Whether the section is readonly.  */
713 #define MIPS_ELF_READONLY_SECTION(sec) \
714   ((sec->flags & (SEC_ALLOC | SEC_LOAD | SEC_READONLY))         \
715    == (SEC_ALLOC | SEC_LOAD | SEC_READONLY))
716
717 /* The name of the stub section.  */
718 #define MIPS_ELF_STUB_SECTION_NAME(abfd) ".MIPS.stubs"
719
720 /* The size of an external REL relocation.  */
721 #define MIPS_ELF_REL_SIZE(abfd) \
722   (get_elf_backend_data (abfd)->s->sizeof_rel)
723
724 /* The size of an external RELA relocation.  */
725 #define MIPS_ELF_RELA_SIZE(abfd) \
726   (get_elf_backend_data (abfd)->s->sizeof_rela)
727
728 /* The size of an external dynamic table entry.  */
729 #define MIPS_ELF_DYN_SIZE(abfd) \
730   (get_elf_backend_data (abfd)->s->sizeof_dyn)
731
732 /* The size of a GOT entry.  */
733 #define MIPS_ELF_GOT_SIZE(abfd) \
734   (get_elf_backend_data (abfd)->s->arch_size / 8)
735
736 /* The size of the .rld_map section. */
737 #define MIPS_ELF_RLD_MAP_SIZE(abfd) \
738   (get_elf_backend_data (abfd)->s->arch_size / 8)
739
740 /* The size of a symbol-table entry.  */
741 #define MIPS_ELF_SYM_SIZE(abfd) \
742   (get_elf_backend_data (abfd)->s->sizeof_sym)
743
744 /* The default alignment for sections, as a power of two.  */
745 #define MIPS_ELF_LOG_FILE_ALIGN(abfd)                           \
746   (get_elf_backend_data (abfd)->s->log_file_align)
747
748 /* Get word-sized data.  */
749 #define MIPS_ELF_GET_WORD(abfd, ptr) \
750   (ABI_64_P (abfd) ? bfd_get_64 (abfd, ptr) : bfd_get_32 (abfd, ptr))
751
752 /* Put out word-sized data.  */
753 #define MIPS_ELF_PUT_WORD(abfd, val, ptr)       \
754   (ABI_64_P (abfd)                              \
755    ? bfd_put_64 (abfd, val, ptr)                \
756    : bfd_put_32 (abfd, val, ptr))
757
758 /* The opcode for word-sized loads (LW or LD).  */
759 #define MIPS_ELF_LOAD_WORD(abfd) \
760   (ABI_64_P (abfd) ? 0xdc000000 : 0x8c000000)
761
762 /* Add a dynamic symbol table-entry.  */
763 #define MIPS_ELF_ADD_DYNAMIC_ENTRY(info, tag, val)      \
764   _bfd_elf_add_dynamic_entry (info, tag, val)
765
766 #define MIPS_ELF_RTYPE_TO_HOWTO(abfd, rtype, rela)                      \
767   (get_elf_backend_data (abfd)->elf_backend_mips_rtype_to_howto (rtype, rela))
768
769 /* The name of the dynamic relocation section.  */
770 #define MIPS_ELF_REL_DYN_NAME(INFO) \
771   (mips_elf_hash_table (INFO)->is_vxworks ? ".rela.dyn" : ".rel.dyn")
772
773 /* In case we're on a 32-bit machine, construct a 64-bit "-1" value
774    from smaller values.  Start with zero, widen, *then* decrement.  */
775 #define MINUS_ONE       (((bfd_vma)0) - 1)
776 #define MINUS_TWO       (((bfd_vma)0) - 2)
777
778 /* The value to write into got[1] for SVR4 targets, to identify it is
779    a GNU object.  The dynamic linker can then use got[1] to store the
780    module pointer.  */
781 #define MIPS_ELF_GNU_GOT1_MASK(abfd) \
782   ((bfd_vma) 1 << (ABI_64_P (abfd) ? 63 : 31))
783
784 /* The offset of $gp from the beginning of the .got section.  */
785 #define ELF_MIPS_GP_OFFSET(INFO) \
786   (mips_elf_hash_table (INFO)->is_vxworks ? 0x0 : 0x7ff0)
787
788 /* The maximum size of the GOT for it to be addressable using 16-bit
789    offsets from $gp.  */
790 #define MIPS_ELF_GOT_MAX_SIZE(INFO) (ELF_MIPS_GP_OFFSET (INFO) + 0x7fff)
791
792 /* Instructions which appear in a stub.  */
793 #define STUB_LW(abfd)                                                   \
794   ((ABI_64_P (abfd)                                                     \
795     ? 0xdf998010                                /* ld t9,0x8010(gp) */  \
796     : 0x8f998010))                              /* lw t9,0x8010(gp) */
797 #define STUB_MOVE(abfd)                                                 \
798    ((ABI_64_P (abfd)                                                    \
799      ? 0x03e0782d                               /* daddu t7,ra */       \
800      : 0x03e07821))                             /* addu t7,ra */
801 #define STUB_LUI(VAL) (0x3c180000 + (VAL))      /* lui t8,VAL */
802 #define STUB_JALR 0x0320f809                    /* jalr t9,ra */
803 #define STUB_ORI(VAL) (0x37180000 + (VAL))      /* ori t8,t8,VAL */
804 #define STUB_LI16U(VAL) (0x34180000 + (VAL))    /* ori t8,zero,VAL unsigned */
805 #define STUB_LI16S(abfd, VAL)                                           \
806    ((ABI_64_P (abfd)                                                    \
807     ? (0x64180000 + (VAL))      /* daddiu t8,zero,VAL sign extended */  \
808     : (0x24180000 + (VAL))))    /* addiu t8,zero,VAL sign extended */
809
810 #define MIPS_FUNCTION_STUB_NORMAL_SIZE 16
811 #define MIPS_FUNCTION_STUB_BIG_SIZE 20
812
813 /* The name of the dynamic interpreter.  This is put in the .interp
814    section.  */
815
816 #define ELF_DYNAMIC_INTERPRETER(abfd)           \
817    (ABI_N32_P (abfd) ? "/usr/lib32/libc.so.1"   \
818     : ABI_64_P (abfd) ? "/usr/lib64/libc.so.1"  \
819     : "/usr/lib/libc.so.1")
820
821 #ifdef BFD64
822 #define MNAME(bfd,pre,pos) \
823   (ABI_64_P (bfd) ? CONCAT4 (pre,64,_,pos) : CONCAT4 (pre,32,_,pos))
824 #define ELF_R_SYM(bfd, i)                                       \
825   (ABI_64_P (bfd) ? ELF64_R_SYM (i) : ELF32_R_SYM (i))
826 #define ELF_R_TYPE(bfd, i)                                      \
827   (ABI_64_P (bfd) ? ELF64_MIPS_R_TYPE (i) : ELF32_R_TYPE (i))
828 #define ELF_R_INFO(bfd, s, t)                                   \
829   (ABI_64_P (bfd) ? ELF64_R_INFO (s, t) : ELF32_R_INFO (s, t))
830 #else
831 #define MNAME(bfd,pre,pos) CONCAT4 (pre,32,_,pos)
832 #define ELF_R_SYM(bfd, i)                                       \
833   (ELF32_R_SYM (i))
834 #define ELF_R_TYPE(bfd, i)                                      \
835   (ELF32_R_TYPE (i))
836 #define ELF_R_INFO(bfd, s, t)                                   \
837   (ELF32_R_INFO (s, t))
838 #endif
839 \f
840   /* The mips16 compiler uses a couple of special sections to handle
841      floating point arguments.
842
843      Section names that look like .mips16.fn.FNNAME contain stubs that
844      copy floating point arguments from the fp regs to the gp regs and
845      then jump to FNNAME.  If any 32 bit function calls FNNAME, the
846      call should be redirected to the stub instead.  If no 32 bit
847      function calls FNNAME, the stub should be discarded.  We need to
848      consider any reference to the function, not just a call, because
849      if the address of the function is taken we will need the stub,
850      since the address might be passed to a 32 bit function.
851
852      Section names that look like .mips16.call.FNNAME contain stubs
853      that copy floating point arguments from the gp regs to the fp
854      regs and then jump to FNNAME.  If FNNAME is a 32 bit function,
855      then any 16 bit function that calls FNNAME should be redirected
856      to the stub instead.  If FNNAME is not a 32 bit function, the
857      stub should be discarded.
858
859      .mips16.call.fp.FNNAME sections are similar, but contain stubs
860      which call FNNAME and then copy the return value from the fp regs
861      to the gp regs.  These stubs store the return value in $18 while
862      calling FNNAME; any function which might call one of these stubs
863      must arrange to save $18 around the call.  (This case is not
864      needed for 32 bit functions that call 16 bit functions, because
865      16 bit functions always return floating point values in both
866      $f0/$f1 and $2/$3.)
867
868      Note that in all cases FNNAME might be defined statically.
869      Therefore, FNNAME is not used literally.  Instead, the relocation
870      information will indicate which symbol the section is for.
871
872      We record any stubs that we find in the symbol table.  */
873
874 #define FN_STUB ".mips16.fn."
875 #define CALL_STUB ".mips16.call."
876 #define CALL_FP_STUB ".mips16.call.fp."
877
878 #define FN_STUB_P(name) CONST_STRNEQ (name, FN_STUB)
879 #define CALL_STUB_P(name) CONST_STRNEQ (name, CALL_STUB)
880 #define CALL_FP_STUB_P(name) CONST_STRNEQ (name, CALL_FP_STUB)
881 \f
882 /* The format of the first PLT entry in an O32 executable.  */
883 static const bfd_vma mips_o32_exec_plt0_entry[] =
884 {
885   0x3c1c0000,   /* lui $28, %hi(&GOTPLT[0])                             */
886   0x8f990000,   /* lw $25, %lo(&GOTPLT[0])($28)                         */
887   0x279c0000,   /* addiu $28, $28, %lo(&GOTPLT[0])                      */
888   0x031cc023,   /* subu $24, $24, $28                                   */
889   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
890   0x0018c082,   /* srl $24, $24, 2                                      */
891   0x0320f809,   /* jalr $25                                             */
892   0x2718fffe    /* subu $24, $24, 2                                     */
893 };
894
895 /* The format of the first PLT entry in an N32 executable.  Different
896    because gp ($28) is not available; we use t2 ($14) instead.  */
897 static const bfd_vma mips_n32_exec_plt0_entry[] =
898 {
899   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
900   0x8dd90000,   /* lw $25, %lo(&GOTPLT[0])($14)                         */
901   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
902   0x030ec023,   /* subu $24, $24, $14                                   */
903   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
904   0x0018c082,   /* srl $24, $24, 2                                      */
905   0x0320f809,   /* jalr $25                                             */
906   0x2718fffe    /* subu $24, $24, 2                                     */
907 };
908
909 /* The format of the first PLT entry in an N64 executable.  Different
910    from N32 because of the increased size of GOT entries.  */
911 static const bfd_vma mips_n64_exec_plt0_entry[] =
912 {
913   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
914   0xddd90000,   /* ld $25, %lo(&GOTPLT[0])($14)                         */
915   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
916   0x030ec023,   /* subu $24, $24, $14                                   */
917   0x03e0782d,   /* move $15, $31        # 64-bit move (daddu)           */
918   0x0018c0c2,   /* srl $24, $24, 3                                      */
919   0x0320f809,   /* jalr $25                                             */
920   0x2718fffe    /* subu $24, $24, 2                                     */
921 };
922
923 /* The format of subsequent PLT entries.  */
924 static const bfd_vma mips_exec_plt_entry[] =
925 {
926   0x3c0f0000,   /* lui $15, %hi(.got.plt entry)                 */
927   0x01f90000,   /* l[wd] $25, %lo(.got.plt entry)($15)          */
928   0x25f80000,   /* addiu $24, $15, %lo(.got.plt entry)          */
929   0x03200008    /* jr $25                                       */
930 };
931
932 /* The format of the first PLT entry in a VxWorks executable.  */
933 static const bfd_vma mips_vxworks_exec_plt0_entry[] =
934 {
935   0x3c190000,   /* lui t9, %hi(_GLOBAL_OFFSET_TABLE_)           */
936   0x27390000,   /* addiu t9, t9, %lo(_GLOBAL_OFFSET_TABLE_)     */
937   0x8f390008,   /* lw t9, 8(t9)                                 */
938   0x00000000,   /* nop                                          */
939   0x03200008,   /* jr t9                                        */
940   0x00000000    /* nop                                          */
941 };
942
943 /* The format of subsequent PLT entries.  */
944 static const bfd_vma mips_vxworks_exec_plt_entry[] =
945 {
946   0x10000000,   /* b .PLT_resolver                      */
947   0x24180000,   /* li t8, <pltindex>                    */
948   0x3c190000,   /* lui t9, %hi(<.got.plt slot>)         */
949   0x27390000,   /* addiu t9, t9, %lo(<.got.plt slot>)   */
950   0x8f390000,   /* lw t9, 0(t9)                         */
951   0x00000000,   /* nop                                  */
952   0x03200008,   /* jr t9                                */
953   0x00000000    /* nop                                  */
954 };
955
956 /* The format of the first PLT entry in a VxWorks shared object.  */
957 static const bfd_vma mips_vxworks_shared_plt0_entry[] =
958 {
959   0x8f990008,   /* lw t9, 8(gp)         */
960   0x00000000,   /* nop                  */
961   0x03200008,   /* jr t9                */
962   0x00000000,   /* nop                  */
963   0x00000000,   /* nop                  */
964   0x00000000    /* nop                  */
965 };
966
967 /* The format of subsequent PLT entries.  */
968 static const bfd_vma mips_vxworks_shared_plt_entry[] =
969 {
970   0x10000000,   /* b .PLT_resolver      */
971   0x24180000    /* li t8, <pltindex>    */
972 };
973 \f
974 /* microMIPS 32-bit opcode helper installer.  */
975
976 static void
977 bfd_put_micromips_32 (const bfd *abfd, bfd_vma opcode, bfd_byte *ptr)
978 {
979   bfd_put_16 (abfd, (opcode >> 16) & 0xffff, ptr);
980   bfd_put_16 (abfd,  opcode        & 0xffff, ptr + 2);
981 }
982
983 /* microMIPS 32-bit opcode helper retriever.  */
984
985 static bfd_vma
986 bfd_get_micromips_32 (const bfd *abfd, const bfd_byte *ptr)
987 {
988   return (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
989 }
990 \f
991 /* Look up an entry in a MIPS ELF linker hash table.  */
992
993 #define mips_elf_link_hash_lookup(table, string, create, copy, follow)  \
994   ((struct mips_elf_link_hash_entry *)                                  \
995    elf_link_hash_lookup (&(table)->root, (string), (create),            \
996                          (copy), (follow)))
997
998 /* Traverse a MIPS ELF linker hash table.  */
999
1000 #define mips_elf_link_hash_traverse(table, func, info)                  \
1001   (elf_link_hash_traverse                                               \
1002    (&(table)->root,                                                     \
1003     (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func),    \
1004     (info)))
1005
1006 /* Find the base offsets for thread-local storage in this object,
1007    for GD/LD and IE/LE respectively.  */
1008
1009 #define TP_OFFSET 0x7000
1010 #define DTP_OFFSET 0x8000
1011
1012 static bfd_vma
1013 dtprel_base (struct bfd_link_info *info)
1014 {
1015   /* If tls_sec is NULL, we should have signalled an error already.  */
1016   if (elf_hash_table (info)->tls_sec == NULL)
1017     return 0;
1018   return elf_hash_table (info)->tls_sec->vma + DTP_OFFSET;
1019 }
1020
1021 static bfd_vma
1022 tprel_base (struct bfd_link_info *info)
1023 {
1024   /* If tls_sec is NULL, we should have signalled an error already.  */
1025   if (elf_hash_table (info)->tls_sec == NULL)
1026     return 0;
1027   return elf_hash_table (info)->tls_sec->vma + TP_OFFSET;
1028 }
1029
1030 /* Create an entry in a MIPS ELF linker hash table.  */
1031
1032 static struct bfd_hash_entry *
1033 mips_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
1034                             struct bfd_hash_table *table, const char *string)
1035 {
1036   struct mips_elf_link_hash_entry *ret =
1037     (struct mips_elf_link_hash_entry *) entry;
1038
1039   /* Allocate the structure if it has not already been allocated by a
1040      subclass.  */
1041   if (ret == NULL)
1042     ret = bfd_hash_allocate (table, sizeof (struct mips_elf_link_hash_entry));
1043   if (ret == NULL)
1044     return (struct bfd_hash_entry *) ret;
1045
1046   /* Call the allocation method of the superclass.  */
1047   ret = ((struct mips_elf_link_hash_entry *)
1048          _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret,
1049                                      table, string));
1050   if (ret != NULL)
1051     {
1052       /* Set local fields.  */
1053       memset (&ret->esym, 0, sizeof (EXTR));
1054       /* We use -2 as a marker to indicate that the information has
1055          not been set.  -1 means there is no associated ifd.  */
1056       ret->esym.ifd = -2;
1057       ret->la25_stub = 0;
1058       ret->possibly_dynamic_relocs = 0;
1059       ret->fn_stub = NULL;
1060       ret->call_stub = NULL;
1061       ret->call_fp_stub = NULL;
1062       ret->global_got_area = GGA_NONE;
1063       ret->got_only_for_calls = TRUE;
1064       ret->readonly_reloc = FALSE;
1065       ret->has_static_relocs = FALSE;
1066       ret->no_fn_stub = FALSE;
1067       ret->need_fn_stub = FALSE;
1068       ret->has_nonpic_branches = FALSE;
1069       ret->needs_lazy_stub = FALSE;
1070     }
1071
1072   return (struct bfd_hash_entry *) ret;
1073 }
1074
1075 /* Allocate MIPS ELF private object data.  */
1076
1077 bfd_boolean
1078 _bfd_mips_elf_mkobject (bfd *abfd)
1079 {
1080   return bfd_elf_allocate_object (abfd, sizeof (struct mips_elf_obj_tdata),
1081                                   MIPS_ELF_DATA);
1082 }
1083
1084 bfd_boolean
1085 _bfd_mips_elf_new_section_hook (bfd *abfd, asection *sec)
1086 {
1087   if (!sec->used_by_bfd)
1088     {
1089       struct _mips_elf_section_data *sdata;
1090       bfd_size_type amt = sizeof (*sdata);
1091
1092       sdata = bfd_zalloc (abfd, amt);
1093       if (sdata == NULL)
1094         return FALSE;
1095       sec->used_by_bfd = sdata;
1096     }
1097
1098   return _bfd_elf_new_section_hook (abfd, sec);
1099 }
1100 \f
1101 /* Read ECOFF debugging information from a .mdebug section into a
1102    ecoff_debug_info structure.  */
1103
1104 bfd_boolean
1105 _bfd_mips_elf_read_ecoff_info (bfd *abfd, asection *section,
1106                                struct ecoff_debug_info *debug)
1107 {
1108   HDRR *symhdr;
1109   const struct ecoff_debug_swap *swap;
1110   char *ext_hdr;
1111
1112   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1113   memset (debug, 0, sizeof (*debug));
1114
1115   ext_hdr = bfd_malloc (swap->external_hdr_size);
1116   if (ext_hdr == NULL && swap->external_hdr_size != 0)
1117     goto error_return;
1118
1119   if (! bfd_get_section_contents (abfd, section, ext_hdr, 0,
1120                                   swap->external_hdr_size))
1121     goto error_return;
1122
1123   symhdr = &debug->symbolic_header;
1124   (*swap->swap_hdr_in) (abfd, ext_hdr, symhdr);
1125
1126   /* The symbolic header contains absolute file offsets and sizes to
1127      read.  */
1128 #define READ(ptr, offset, count, size, type)                            \
1129   if (symhdr->count == 0)                                               \
1130     debug->ptr = NULL;                                                  \
1131   else                                                                  \
1132     {                                                                   \
1133       bfd_size_type amt = (bfd_size_type) size * symhdr->count;         \
1134       debug->ptr = bfd_malloc (amt);                                    \
1135       if (debug->ptr == NULL)                                           \
1136         goto error_return;                                              \
1137       if (bfd_seek (abfd, symhdr->offset, SEEK_SET) != 0                \
1138           || bfd_bread (debug->ptr, amt, abfd) != amt)                  \
1139         goto error_return;                                              \
1140     }
1141
1142   READ (line, cbLineOffset, cbLine, sizeof (unsigned char), unsigned char *);
1143   READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *);
1144   READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *);
1145   READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *);
1146   READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *);
1147   READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext),
1148         union aux_ext *);
1149   READ (ss, cbSsOffset, issMax, sizeof (char), char *);
1150   READ (ssext, cbSsExtOffset, issExtMax, sizeof (char), char *);
1151   READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *);
1152   READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *);
1153   READ (external_ext, cbExtOffset, iextMax, swap->external_ext_size, void *);
1154 #undef READ
1155
1156   debug->fdr = NULL;
1157
1158   return TRUE;
1159
1160  error_return:
1161   if (ext_hdr != NULL)
1162     free (ext_hdr);
1163   if (debug->line != NULL)
1164     free (debug->line);
1165   if (debug->external_dnr != NULL)
1166     free (debug->external_dnr);
1167   if (debug->external_pdr != NULL)
1168     free (debug->external_pdr);
1169   if (debug->external_sym != NULL)
1170     free (debug->external_sym);
1171   if (debug->external_opt != NULL)
1172     free (debug->external_opt);
1173   if (debug->external_aux != NULL)
1174     free (debug->external_aux);
1175   if (debug->ss != NULL)
1176     free (debug->ss);
1177   if (debug->ssext != NULL)
1178     free (debug->ssext);
1179   if (debug->external_fdr != NULL)
1180     free (debug->external_fdr);
1181   if (debug->external_rfd != NULL)
1182     free (debug->external_rfd);
1183   if (debug->external_ext != NULL)
1184     free (debug->external_ext);
1185   return FALSE;
1186 }
1187 \f
1188 /* Swap RPDR (runtime procedure table entry) for output.  */
1189
1190 static void
1191 ecoff_swap_rpdr_out (bfd *abfd, const RPDR *in, struct rpdr_ext *ex)
1192 {
1193   H_PUT_S32 (abfd, in->adr, ex->p_adr);
1194   H_PUT_32 (abfd, in->regmask, ex->p_regmask);
1195   H_PUT_32 (abfd, in->regoffset, ex->p_regoffset);
1196   H_PUT_32 (abfd, in->fregmask, ex->p_fregmask);
1197   H_PUT_32 (abfd, in->fregoffset, ex->p_fregoffset);
1198   H_PUT_32 (abfd, in->frameoffset, ex->p_frameoffset);
1199
1200   H_PUT_16 (abfd, in->framereg, ex->p_framereg);
1201   H_PUT_16 (abfd, in->pcreg, ex->p_pcreg);
1202
1203   H_PUT_32 (abfd, in->irpss, ex->p_irpss);
1204 }
1205
1206 /* Create a runtime procedure table from the .mdebug section.  */
1207
1208 static bfd_boolean
1209 mips_elf_create_procedure_table (void *handle, bfd *abfd,
1210                                  struct bfd_link_info *info, asection *s,
1211                                  struct ecoff_debug_info *debug)
1212 {
1213   const struct ecoff_debug_swap *swap;
1214   HDRR *hdr = &debug->symbolic_header;
1215   RPDR *rpdr, *rp;
1216   struct rpdr_ext *erp;
1217   void *rtproc;
1218   struct pdr_ext *epdr;
1219   struct sym_ext *esym;
1220   char *ss, **sv;
1221   char *str;
1222   bfd_size_type size;
1223   bfd_size_type count;
1224   unsigned long sindex;
1225   unsigned long i;
1226   PDR pdr;
1227   SYMR sym;
1228   const char *no_name_func = _("static procedure (no name)");
1229
1230   epdr = NULL;
1231   rpdr = NULL;
1232   esym = NULL;
1233   ss = NULL;
1234   sv = NULL;
1235
1236   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1237
1238   sindex = strlen (no_name_func) + 1;
1239   count = hdr->ipdMax;
1240   if (count > 0)
1241     {
1242       size = swap->external_pdr_size;
1243
1244       epdr = bfd_malloc (size * count);
1245       if (epdr == NULL)
1246         goto error_return;
1247
1248       if (! _bfd_ecoff_get_accumulated_pdr (handle, (bfd_byte *) epdr))
1249         goto error_return;
1250
1251       size = sizeof (RPDR);
1252       rp = rpdr = bfd_malloc (size * count);
1253       if (rpdr == NULL)
1254         goto error_return;
1255
1256       size = sizeof (char *);
1257       sv = bfd_malloc (size * count);
1258       if (sv == NULL)
1259         goto error_return;
1260
1261       count = hdr->isymMax;
1262       size = swap->external_sym_size;
1263       esym = bfd_malloc (size * count);
1264       if (esym == NULL)
1265         goto error_return;
1266
1267       if (! _bfd_ecoff_get_accumulated_sym (handle, (bfd_byte *) esym))
1268         goto error_return;
1269
1270       count = hdr->issMax;
1271       ss = bfd_malloc (count);
1272       if (ss == NULL)
1273         goto error_return;
1274       if (! _bfd_ecoff_get_accumulated_ss (handle, (bfd_byte *) ss))
1275         goto error_return;
1276
1277       count = hdr->ipdMax;
1278       for (i = 0; i < (unsigned long) count; i++, rp++)
1279         {
1280           (*swap->swap_pdr_in) (abfd, epdr + i, &pdr);
1281           (*swap->swap_sym_in) (abfd, &esym[pdr.isym], &sym);
1282           rp->adr = sym.value;
1283           rp->regmask = pdr.regmask;
1284           rp->regoffset = pdr.regoffset;
1285           rp->fregmask = pdr.fregmask;
1286           rp->fregoffset = pdr.fregoffset;
1287           rp->frameoffset = pdr.frameoffset;
1288           rp->framereg = pdr.framereg;
1289           rp->pcreg = pdr.pcreg;
1290           rp->irpss = sindex;
1291           sv[i] = ss + sym.iss;
1292           sindex += strlen (sv[i]) + 1;
1293         }
1294     }
1295
1296   size = sizeof (struct rpdr_ext) * (count + 2) + sindex;
1297   size = BFD_ALIGN (size, 16);
1298   rtproc = bfd_alloc (abfd, size);
1299   if (rtproc == NULL)
1300     {
1301       mips_elf_hash_table (info)->procedure_count = 0;
1302       goto error_return;
1303     }
1304
1305   mips_elf_hash_table (info)->procedure_count = count + 2;
1306
1307   erp = rtproc;
1308   memset (erp, 0, sizeof (struct rpdr_ext));
1309   erp++;
1310   str = (char *) rtproc + sizeof (struct rpdr_ext) * (count + 2);
1311   strcpy (str, no_name_func);
1312   str += strlen (no_name_func) + 1;
1313   for (i = 0; i < count; i++)
1314     {
1315       ecoff_swap_rpdr_out (abfd, rpdr + i, erp + i);
1316       strcpy (str, sv[i]);
1317       str += strlen (sv[i]) + 1;
1318     }
1319   H_PUT_S32 (abfd, -1, (erp + count)->p_adr);
1320
1321   /* Set the size and contents of .rtproc section.  */
1322   s->size = size;
1323   s->contents = rtproc;
1324
1325   /* Skip this section later on (I don't think this currently
1326      matters, but someday it might).  */
1327   s->map_head.link_order = NULL;
1328
1329   if (epdr != NULL)
1330     free (epdr);
1331   if (rpdr != NULL)
1332     free (rpdr);
1333   if (esym != NULL)
1334     free (esym);
1335   if (ss != NULL)
1336     free (ss);
1337   if (sv != NULL)
1338     free (sv);
1339
1340   return TRUE;
1341
1342  error_return:
1343   if (epdr != NULL)
1344     free (epdr);
1345   if (rpdr != NULL)
1346     free (rpdr);
1347   if (esym != NULL)
1348     free (esym);
1349   if (ss != NULL)
1350     free (ss);
1351   if (sv != NULL)
1352     free (sv);
1353   return FALSE;
1354 }
1355 \f
1356 /* We're going to create a stub for H.  Create a symbol for the stub's
1357    value and size, to help make the disassembly easier to read.  */
1358
1359 static bfd_boolean
1360 mips_elf_create_stub_symbol (struct bfd_link_info *info,
1361                              struct mips_elf_link_hash_entry *h,
1362                              const char *prefix, asection *s, bfd_vma value,
1363                              bfd_vma size)
1364 {
1365   struct bfd_link_hash_entry *bh;
1366   struct elf_link_hash_entry *elfh;
1367   const char *name;
1368
1369   if (ELF_ST_IS_MICROMIPS (h->root.other))
1370     value |= 1;
1371
1372   /* Create a new symbol.  */
1373   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1374   bh = NULL;
1375   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1376                                          BSF_LOCAL, s, value, NULL,
1377                                          TRUE, FALSE, &bh))
1378     return FALSE;
1379
1380   /* Make it a local function.  */
1381   elfh = (struct elf_link_hash_entry *) bh;
1382   elfh->type = ELF_ST_INFO (STB_LOCAL, STT_FUNC);
1383   elfh->size = size;
1384   elfh->forced_local = 1;
1385   return TRUE;
1386 }
1387
1388 /* We're about to redefine H.  Create a symbol to represent H's
1389    current value and size, to help make the disassembly easier
1390    to read.  */
1391
1392 static bfd_boolean
1393 mips_elf_create_shadow_symbol (struct bfd_link_info *info,
1394                                struct mips_elf_link_hash_entry *h,
1395                                const char *prefix)
1396 {
1397   struct bfd_link_hash_entry *bh;
1398   struct elf_link_hash_entry *elfh;
1399   const char *name;
1400   asection *s;
1401   bfd_vma value;
1402
1403   /* Read the symbol's value.  */
1404   BFD_ASSERT (h->root.root.type == bfd_link_hash_defined
1405               || h->root.root.type == bfd_link_hash_defweak);
1406   s = h->root.root.u.def.section;
1407   value = h->root.root.u.def.value;
1408
1409   /* Create a new symbol.  */
1410   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1411   bh = NULL;
1412   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1413                                          BSF_LOCAL, s, value, NULL,
1414                                          TRUE, FALSE, &bh))
1415     return FALSE;
1416
1417   /* Make it local and copy the other attributes from H.  */
1418   elfh = (struct elf_link_hash_entry *) bh;
1419   elfh->type = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (h->root.type));
1420   elfh->other = h->root.other;
1421   elfh->size = h->root.size;
1422   elfh->forced_local = 1;
1423   return TRUE;
1424 }
1425
1426 /* Return TRUE if relocations in SECTION can refer directly to a MIPS16
1427    function rather than to a hard-float stub.  */
1428
1429 static bfd_boolean
1430 section_allows_mips16_refs_p (asection *section)
1431 {
1432   const char *name;
1433
1434   name = bfd_get_section_name (section->owner, section);
1435   return (FN_STUB_P (name)
1436           || CALL_STUB_P (name)
1437           || CALL_FP_STUB_P (name)
1438           || strcmp (name, ".pdr") == 0);
1439 }
1440
1441 /* [RELOCS, RELEND) are the relocations against SEC, which is a MIPS16
1442    stub section of some kind.  Return the R_SYMNDX of the target
1443    function, or 0 if we can't decide which function that is.  */
1444
1445 static unsigned long
1446 mips16_stub_symndx (const struct elf_backend_data *bed,
1447                     asection *sec ATTRIBUTE_UNUSED,
1448                     const Elf_Internal_Rela *relocs,
1449                     const Elf_Internal_Rela *relend)
1450 {
1451   int int_rels_per_ext_rel = bed->s->int_rels_per_ext_rel;
1452   const Elf_Internal_Rela *rel;
1453
1454   /* Trust the first R_MIPS_NONE relocation, if any, but not a subsequent
1455      one in a compound relocation.  */
1456   for (rel = relocs; rel < relend; rel += int_rels_per_ext_rel)
1457     if (ELF_R_TYPE (sec->owner, rel->r_info) == R_MIPS_NONE)
1458       return ELF_R_SYM (sec->owner, rel->r_info);
1459
1460   /* Otherwise trust the first relocation, whatever its kind.  This is
1461      the traditional behavior.  */
1462   if (relocs < relend)
1463     return ELF_R_SYM (sec->owner, relocs->r_info);
1464
1465   return 0;
1466 }
1467
1468 /* Check the mips16 stubs for a particular symbol, and see if we can
1469    discard them.  */
1470
1471 static void
1472 mips_elf_check_mips16_stubs (struct bfd_link_info *info,
1473                              struct mips_elf_link_hash_entry *h)
1474 {
1475   /* Dynamic symbols must use the standard call interface, in case other
1476      objects try to call them.  */
1477   if (h->fn_stub != NULL
1478       && h->root.dynindx != -1)
1479     {
1480       mips_elf_create_shadow_symbol (info, h, ".mips16.");
1481       h->need_fn_stub = TRUE;
1482     }
1483
1484   if (h->fn_stub != NULL
1485       && ! h->need_fn_stub)
1486     {
1487       /* We don't need the fn_stub; the only references to this symbol
1488          are 16 bit calls.  Clobber the size to 0 to prevent it from
1489          being included in the link.  */
1490       h->fn_stub->size = 0;
1491       h->fn_stub->flags &= ~SEC_RELOC;
1492       h->fn_stub->reloc_count = 0;
1493       h->fn_stub->flags |= SEC_EXCLUDE;
1494     }
1495
1496   if (h->call_stub != NULL
1497       && ELF_ST_IS_MIPS16 (h->root.other))
1498     {
1499       /* We don't need the call_stub; this is a 16 bit function, so
1500          calls from other 16 bit functions are OK.  Clobber the size
1501          to 0 to prevent it from being included in the link.  */
1502       h->call_stub->size = 0;
1503       h->call_stub->flags &= ~SEC_RELOC;
1504       h->call_stub->reloc_count = 0;
1505       h->call_stub->flags |= SEC_EXCLUDE;
1506     }
1507
1508   if (h->call_fp_stub != NULL
1509       && ELF_ST_IS_MIPS16 (h->root.other))
1510     {
1511       /* We don't need the call_stub; this is a 16 bit function, so
1512          calls from other 16 bit functions are OK.  Clobber the size
1513          to 0 to prevent it from being included in the link.  */
1514       h->call_fp_stub->size = 0;
1515       h->call_fp_stub->flags &= ~SEC_RELOC;
1516       h->call_fp_stub->reloc_count = 0;
1517       h->call_fp_stub->flags |= SEC_EXCLUDE;
1518     }
1519 }
1520
1521 /* Hashtable callbacks for mips_elf_la25_stubs.  */
1522
1523 static hashval_t
1524 mips_elf_la25_stub_hash (const void *entry_)
1525 {
1526   const struct mips_elf_la25_stub *entry;
1527
1528   entry = (struct mips_elf_la25_stub *) entry_;
1529   return entry->h->root.root.u.def.section->id
1530     + entry->h->root.root.u.def.value;
1531 }
1532
1533 static int
1534 mips_elf_la25_stub_eq (const void *entry1_, const void *entry2_)
1535 {
1536   const struct mips_elf_la25_stub *entry1, *entry2;
1537
1538   entry1 = (struct mips_elf_la25_stub *) entry1_;
1539   entry2 = (struct mips_elf_la25_stub *) entry2_;
1540   return ((entry1->h->root.root.u.def.section
1541            == entry2->h->root.root.u.def.section)
1542           && (entry1->h->root.root.u.def.value
1543               == entry2->h->root.root.u.def.value));
1544 }
1545
1546 /* Called by the linker to set up the la25 stub-creation code.  FN is
1547    the linker's implementation of add_stub_function.  Return true on
1548    success.  */
1549
1550 bfd_boolean
1551 _bfd_mips_elf_init_stubs (struct bfd_link_info *info,
1552                           asection *(*fn) (const char *, asection *,
1553                                            asection *))
1554 {
1555   struct mips_elf_link_hash_table *htab;
1556
1557   htab = mips_elf_hash_table (info);
1558   if (htab == NULL)
1559     return FALSE;
1560
1561   htab->add_stub_section = fn;
1562   htab->la25_stubs = htab_try_create (1, mips_elf_la25_stub_hash,
1563                                       mips_elf_la25_stub_eq, NULL);
1564   if (htab->la25_stubs == NULL)
1565     return FALSE;
1566
1567   return TRUE;
1568 }
1569
1570 /* Return true if H is a locally-defined PIC function, in the sense
1571    that it or its fn_stub might need $25 to be valid on entry.
1572    Note that MIPS16 functions set up $gp using PC-relative instructions,
1573    so they themselves never need $25 to be valid.  Only non-MIPS16
1574    entry points are of interest here.  */
1575
1576 static bfd_boolean
1577 mips_elf_local_pic_function_p (struct mips_elf_link_hash_entry *h)
1578 {
1579   return ((h->root.root.type == bfd_link_hash_defined
1580            || h->root.root.type == bfd_link_hash_defweak)
1581           && h->root.def_regular
1582           && !bfd_is_abs_section (h->root.root.u.def.section)
1583           && (!ELF_ST_IS_MIPS16 (h->root.other)
1584               || (h->fn_stub && h->need_fn_stub))
1585           && (PIC_OBJECT_P (h->root.root.u.def.section->owner)
1586               || ELF_ST_IS_MIPS_PIC (h->root.other)));
1587 }
1588
1589 /* Set *SEC to the input section that contains the target of STUB.
1590    Return the offset of the target from the start of that section.  */
1591
1592 static bfd_vma
1593 mips_elf_get_la25_target (struct mips_elf_la25_stub *stub,
1594                           asection **sec)
1595 {
1596   if (ELF_ST_IS_MIPS16 (stub->h->root.other))
1597     {
1598       BFD_ASSERT (stub->h->need_fn_stub);
1599       *sec = stub->h->fn_stub;
1600       return 0;
1601     }
1602   else
1603     {
1604       *sec = stub->h->root.root.u.def.section;
1605       return stub->h->root.root.u.def.value;
1606     }
1607 }
1608
1609 /* STUB describes an la25 stub that we have decided to implement
1610    by inserting an LUI/ADDIU pair before the target function.
1611    Create the section and redirect the function symbol to it.  */
1612
1613 static bfd_boolean
1614 mips_elf_add_la25_intro (struct mips_elf_la25_stub *stub,
1615                          struct bfd_link_info *info)
1616 {
1617   struct mips_elf_link_hash_table *htab;
1618   char *name;
1619   asection *s, *input_section;
1620   unsigned int align;
1621
1622   htab = mips_elf_hash_table (info);
1623   if (htab == NULL)
1624     return FALSE;
1625
1626   /* Create a unique name for the new section.  */
1627   name = bfd_malloc (11 + sizeof (".text.stub."));
1628   if (name == NULL)
1629     return FALSE;
1630   sprintf (name, ".text.stub.%d", (int) htab_elements (htab->la25_stubs));
1631
1632   /* Create the section.  */
1633   mips_elf_get_la25_target (stub, &input_section);
1634   s = htab->add_stub_section (name, input_section,
1635                               input_section->output_section);
1636   if (s == NULL)
1637     return FALSE;
1638
1639   /* Make sure that any padding goes before the stub.  */
1640   align = input_section->alignment_power;
1641   if (!bfd_set_section_alignment (s->owner, s, align))
1642     return FALSE;
1643   if (align > 3)
1644     s->size = (1 << align) - 8;
1645
1646   /* Create a symbol for the stub.  */
1647   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 8);
1648   stub->stub_section = s;
1649   stub->offset = s->size;
1650
1651   /* Allocate room for it.  */
1652   s->size += 8;
1653   return TRUE;
1654 }
1655
1656 /* STUB describes an la25 stub that we have decided to implement
1657    with a separate trampoline.  Allocate room for it and redirect
1658    the function symbol to it.  */
1659
1660 static bfd_boolean
1661 mips_elf_add_la25_trampoline (struct mips_elf_la25_stub *stub,
1662                               struct bfd_link_info *info)
1663 {
1664   struct mips_elf_link_hash_table *htab;
1665   asection *s;
1666
1667   htab = mips_elf_hash_table (info);
1668   if (htab == NULL)
1669     return FALSE;
1670
1671   /* Create a trampoline section, if we haven't already.  */
1672   s = htab->strampoline;
1673   if (s == NULL)
1674     {
1675       asection *input_section = stub->h->root.root.u.def.section;
1676       s = htab->add_stub_section (".text", NULL,
1677                                   input_section->output_section);
1678       if (s == NULL || !bfd_set_section_alignment (s->owner, s, 4))
1679         return FALSE;
1680       htab->strampoline = s;
1681     }
1682
1683   /* Create a symbol for the stub.  */
1684   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 16);
1685   stub->stub_section = s;
1686   stub->offset = s->size;
1687
1688   /* Allocate room for it.  */
1689   s->size += 16;
1690   return TRUE;
1691 }
1692
1693 /* H describes a symbol that needs an la25 stub.  Make sure that an
1694    appropriate stub exists and point H at it.  */
1695
1696 static bfd_boolean
1697 mips_elf_add_la25_stub (struct bfd_link_info *info,
1698                         struct mips_elf_link_hash_entry *h)
1699 {
1700   struct mips_elf_link_hash_table *htab;
1701   struct mips_elf_la25_stub search, *stub;
1702   bfd_boolean use_trampoline_p;
1703   asection *s;
1704   bfd_vma value;
1705   void **slot;
1706
1707   /* Describe the stub we want.  */
1708   search.stub_section = NULL;
1709   search.offset = 0;
1710   search.h = h;
1711
1712   /* See if we've already created an equivalent stub.  */
1713   htab = mips_elf_hash_table (info);
1714   if (htab == NULL)
1715     return FALSE;
1716
1717   slot = htab_find_slot (htab->la25_stubs, &search, INSERT);
1718   if (slot == NULL)
1719     return FALSE;
1720
1721   stub = (struct mips_elf_la25_stub *) *slot;
1722   if (stub != NULL)
1723     {
1724       /* We can reuse the existing stub.  */
1725       h->la25_stub = stub;
1726       return TRUE;
1727     }
1728
1729   /* Create a permanent copy of ENTRY and add it to the hash table.  */
1730   stub = bfd_malloc (sizeof (search));
1731   if (stub == NULL)
1732     return FALSE;
1733   *stub = search;
1734   *slot = stub;
1735
1736   /* Prefer to use LUI/ADDIU stubs if the function is at the beginning
1737      of the section and if we would need no more than 2 nops.  */
1738   value = mips_elf_get_la25_target (stub, &s);
1739   use_trampoline_p = (value != 0 || s->alignment_power > 4);
1740
1741   h->la25_stub = stub;
1742   return (use_trampoline_p
1743           ? mips_elf_add_la25_trampoline (stub, info)
1744           : mips_elf_add_la25_intro (stub, info));
1745 }
1746
1747 /* A mips_elf_link_hash_traverse callback that is called before sizing
1748    sections.  DATA points to a mips_htab_traverse_info structure.  */
1749
1750 static bfd_boolean
1751 mips_elf_check_symbols (struct mips_elf_link_hash_entry *h, void *data)
1752 {
1753   struct mips_htab_traverse_info *hti;
1754
1755   hti = (struct mips_htab_traverse_info *) data;
1756   if (!hti->info->relocatable)
1757     mips_elf_check_mips16_stubs (hti->info, h);
1758
1759   if (mips_elf_local_pic_function_p (h))
1760     {
1761       /* PR 12845: If H is in a section that has been garbage
1762          collected it will have its output section set to *ABS*.  */
1763       if (bfd_is_abs_section (h->root.root.u.def.section->output_section))
1764         return TRUE;
1765
1766       /* H is a function that might need $25 to be valid on entry.
1767          If we're creating a non-PIC relocatable object, mark H as
1768          being PIC.  If we're creating a non-relocatable object with
1769          non-PIC branches and jumps to H, make sure that H has an la25
1770          stub.  */
1771       if (hti->info->relocatable)
1772         {
1773           if (!PIC_OBJECT_P (hti->output_bfd))
1774             h->root.other = ELF_ST_SET_MIPS_PIC (h->root.other);
1775         }
1776       else if (h->has_nonpic_branches && !mips_elf_add_la25_stub (hti->info, h))
1777         {
1778           hti->error = TRUE;
1779           return FALSE;
1780         }
1781     }
1782   return TRUE;
1783 }
1784 \f
1785 /* R_MIPS16_26 is used for the mips16 jal and jalx instructions.
1786    Most mips16 instructions are 16 bits, but these instructions
1787    are 32 bits.
1788
1789    The format of these instructions is:
1790
1791    +--------------+--------------------------------+
1792    |     JALX     | X|   Imm 20:16  |   Imm 25:21  |
1793    +--------------+--------------------------------+
1794    |                Immediate  15:0                |
1795    +-----------------------------------------------+
1796
1797    JALX is the 5-bit value 00011.  X is 0 for jal, 1 for jalx.
1798    Note that the immediate value in the first word is swapped.
1799
1800    When producing a relocatable object file, R_MIPS16_26 is
1801    handled mostly like R_MIPS_26.  In particular, the addend is
1802    stored as a straight 26-bit value in a 32-bit instruction.
1803    (gas makes life simpler for itself by never adjusting a
1804    R_MIPS16_26 reloc to be against a section, so the addend is
1805    always zero).  However, the 32 bit instruction is stored as 2
1806    16-bit values, rather than a single 32-bit value.  In a
1807    big-endian file, the result is the same; in a little-endian
1808    file, the two 16-bit halves of the 32 bit value are swapped.
1809    This is so that a disassembler can recognize the jal
1810    instruction.
1811
1812    When doing a final link, R_MIPS16_26 is treated as a 32 bit
1813    instruction stored as two 16-bit values.  The addend A is the
1814    contents of the targ26 field.  The calculation is the same as
1815    R_MIPS_26.  When storing the calculated value, reorder the
1816    immediate value as shown above, and don't forget to store the
1817    value as two 16-bit values.
1818
1819    To put it in MIPS ABI terms, the relocation field is T-targ26-16,
1820    defined as
1821
1822    big-endian:
1823    +--------+----------------------+
1824    |        |                      |
1825    |        |    targ26-16         |
1826    |31    26|25                   0|
1827    +--------+----------------------+
1828
1829    little-endian:
1830    +----------+------+-------------+
1831    |          |      |             |
1832    |  sub1    |      |     sub2    |
1833    |0        9|10  15|16         31|
1834    +----------+--------------------+
1835    where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is
1836    ((sub1 << 16) | sub2)).
1837
1838    When producing a relocatable object file, the calculation is
1839    (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1840    When producing a fully linked file, the calculation is
1841    let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1842    ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff)
1843
1844    The table below lists the other MIPS16 instruction relocations.
1845    Each one is calculated in the same way as the non-MIPS16 relocation
1846    given on the right, but using the extended MIPS16 layout of 16-bit
1847    immediate fields:
1848
1849         R_MIPS16_GPREL          R_MIPS_GPREL16
1850         R_MIPS16_GOT16          R_MIPS_GOT16
1851         R_MIPS16_CALL16         R_MIPS_CALL16
1852         R_MIPS16_HI16           R_MIPS_HI16
1853         R_MIPS16_LO16           R_MIPS_LO16
1854
1855    A typical instruction will have a format like this:
1856
1857    +--------------+--------------------------------+
1858    |    EXTEND    |     Imm 10:5    |   Imm 15:11  |
1859    +--------------+--------------------------------+
1860    |    Major     |   rx   |   ry   |   Imm  4:0   |
1861    +--------------+--------------------------------+
1862
1863    EXTEND is the five bit value 11110.  Major is the instruction
1864    opcode.
1865
1866    All we need to do here is shuffle the bits appropriately.
1867    As above, the two 16-bit halves must be swapped on a
1868    little-endian system.  */
1869
1870 static inline bfd_boolean
1871 mips16_reloc_p (int r_type)
1872 {
1873   switch (r_type)
1874     {
1875     case R_MIPS16_26:
1876     case R_MIPS16_GPREL:
1877     case R_MIPS16_GOT16:
1878     case R_MIPS16_CALL16:
1879     case R_MIPS16_HI16:
1880     case R_MIPS16_LO16:
1881     case R_MIPS16_TLS_GD:
1882     case R_MIPS16_TLS_LDM:
1883     case R_MIPS16_TLS_DTPREL_HI16:
1884     case R_MIPS16_TLS_DTPREL_LO16:
1885     case R_MIPS16_TLS_GOTTPREL:
1886     case R_MIPS16_TLS_TPREL_HI16:
1887     case R_MIPS16_TLS_TPREL_LO16:
1888       return TRUE;
1889
1890     default:
1891       return FALSE;
1892     }
1893 }
1894
1895 /* Check if a microMIPS reloc.  */
1896
1897 static inline bfd_boolean
1898 micromips_reloc_p (unsigned int r_type)
1899 {
1900   return r_type >= R_MICROMIPS_min && r_type < R_MICROMIPS_max;
1901 }
1902
1903 /* Similar to MIPS16, the two 16-bit halves in microMIPS must be swapped
1904    on a little-endian system.  This does not apply to R_MICROMIPS_PC7_S1
1905    and R_MICROMIPS_PC10_S1 relocs that apply to 16-bit instructions.  */
1906
1907 static inline bfd_boolean
1908 micromips_reloc_shuffle_p (unsigned int r_type)
1909 {
1910   return (micromips_reloc_p (r_type)
1911           && r_type != R_MICROMIPS_PC7_S1
1912           && r_type != R_MICROMIPS_PC10_S1);
1913 }
1914
1915 static inline bfd_boolean
1916 got16_reloc_p (int r_type)
1917 {
1918   return (r_type == R_MIPS_GOT16
1919           || r_type == R_MIPS16_GOT16
1920           || r_type == R_MICROMIPS_GOT16);
1921 }
1922
1923 static inline bfd_boolean
1924 call16_reloc_p (int r_type)
1925 {
1926   return (r_type == R_MIPS_CALL16
1927           || r_type == R_MIPS16_CALL16
1928           || r_type == R_MICROMIPS_CALL16);
1929 }
1930
1931 static inline bfd_boolean
1932 got_disp_reloc_p (unsigned int r_type)
1933 {
1934   return r_type == R_MIPS_GOT_DISP || r_type == R_MICROMIPS_GOT_DISP;
1935 }
1936
1937 static inline bfd_boolean
1938 got_page_reloc_p (unsigned int r_type)
1939 {
1940   return r_type == R_MIPS_GOT_PAGE || r_type == R_MICROMIPS_GOT_PAGE;
1941 }
1942
1943 static inline bfd_boolean
1944 got_ofst_reloc_p (unsigned int r_type)
1945 {
1946   return r_type == R_MIPS_GOT_OFST || r_type == R_MICROMIPS_GOT_OFST;
1947 }
1948
1949 static inline bfd_boolean
1950 got_hi16_reloc_p (unsigned int r_type)
1951 {
1952   return r_type == R_MIPS_GOT_HI16 || r_type == R_MICROMIPS_GOT_HI16;
1953 }
1954
1955 static inline bfd_boolean
1956 got_lo16_reloc_p (unsigned int r_type)
1957 {
1958   return r_type == R_MIPS_GOT_LO16 || r_type == R_MICROMIPS_GOT_LO16;
1959 }
1960
1961 static inline bfd_boolean
1962 call_hi16_reloc_p (unsigned int r_type)
1963 {
1964   return r_type == R_MIPS_CALL_HI16 || r_type == R_MICROMIPS_CALL_HI16;
1965 }
1966
1967 static inline bfd_boolean
1968 call_lo16_reloc_p (unsigned int r_type)
1969 {
1970   return r_type == R_MIPS_CALL_LO16 || r_type == R_MICROMIPS_CALL_LO16;
1971 }
1972
1973 static inline bfd_boolean
1974 hi16_reloc_p (int r_type)
1975 {
1976   return (r_type == R_MIPS_HI16
1977           || r_type == R_MIPS16_HI16
1978           || r_type == R_MICROMIPS_HI16);
1979 }
1980
1981 static inline bfd_boolean
1982 lo16_reloc_p (int r_type)
1983 {
1984   return (r_type == R_MIPS_LO16
1985           || r_type == R_MIPS16_LO16
1986           || r_type == R_MICROMIPS_LO16);
1987 }
1988
1989 static inline bfd_boolean
1990 mips16_call_reloc_p (int r_type)
1991 {
1992   return r_type == R_MIPS16_26 || r_type == R_MIPS16_CALL16;
1993 }
1994
1995 static inline bfd_boolean
1996 jal_reloc_p (int r_type)
1997 {
1998   return (r_type == R_MIPS_26
1999           || r_type == R_MIPS16_26
2000           || r_type == R_MICROMIPS_26_S1);
2001 }
2002
2003 static inline bfd_boolean
2004 micromips_branch_reloc_p (int r_type)
2005 {
2006   return (r_type == R_MICROMIPS_26_S1
2007           || r_type == R_MICROMIPS_PC16_S1
2008           || r_type == R_MICROMIPS_PC10_S1
2009           || r_type == R_MICROMIPS_PC7_S1);
2010 }
2011
2012 static inline bfd_boolean
2013 tls_gd_reloc_p (unsigned int r_type)
2014 {
2015   return (r_type == R_MIPS_TLS_GD
2016           || r_type == R_MIPS16_TLS_GD
2017           || r_type == R_MICROMIPS_TLS_GD);
2018 }
2019
2020 static inline bfd_boolean
2021 tls_ldm_reloc_p (unsigned int r_type)
2022 {
2023   return (r_type == R_MIPS_TLS_LDM
2024           || r_type == R_MIPS16_TLS_LDM
2025           || r_type == R_MICROMIPS_TLS_LDM);
2026 }
2027
2028 static inline bfd_boolean
2029 tls_gottprel_reloc_p (unsigned int r_type)
2030 {
2031   return (r_type == R_MIPS_TLS_GOTTPREL
2032           || r_type == R_MIPS16_TLS_GOTTPREL
2033           || r_type == R_MICROMIPS_TLS_GOTTPREL);
2034 }
2035
2036 void
2037 _bfd_mips_elf_reloc_unshuffle (bfd *abfd, int r_type,
2038                                bfd_boolean jal_shuffle, bfd_byte *data)
2039 {
2040   bfd_vma first, second, val;
2041
2042   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2043     return;
2044
2045   /* Pick up the first and second halfwords of the instruction.  */
2046   first = bfd_get_16 (abfd, data);
2047   second = bfd_get_16 (abfd, data + 2);
2048   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2049     val = first << 16 | second;
2050   else if (r_type != R_MIPS16_26)
2051     val = (((first & 0xf800) << 16) | ((second & 0xffe0) << 11)
2052            | ((first & 0x1f) << 11) | (first & 0x7e0) | (second & 0x1f));
2053   else
2054     val = (((first & 0xfc00) << 16) | ((first & 0x3e0) << 11)
2055            | ((first & 0x1f) << 21) | second);
2056   bfd_put_32 (abfd, val, data);
2057 }
2058
2059 void
2060 _bfd_mips_elf_reloc_shuffle (bfd *abfd, int r_type,
2061                              bfd_boolean jal_shuffle, bfd_byte *data)
2062 {
2063   bfd_vma first, second, val;
2064
2065   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2066     return;
2067
2068   val = bfd_get_32 (abfd, data);
2069   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2070     {
2071       second = val & 0xffff;
2072       first = val >> 16;
2073     }
2074   else if (r_type != R_MIPS16_26)
2075     {
2076       second = ((val >> 11) & 0xffe0) | (val & 0x1f);
2077       first = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0);
2078     }
2079   else
2080     {
2081       second = val & 0xffff;
2082       first = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0)
2083                | ((val >> 21) & 0x1f);
2084     }
2085   bfd_put_16 (abfd, second, data + 2);
2086   bfd_put_16 (abfd, first, data);
2087 }
2088
2089 bfd_reloc_status_type
2090 _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol,
2091                                arelent *reloc_entry, asection *input_section,
2092                                bfd_boolean relocatable, void *data, bfd_vma gp)
2093 {
2094   bfd_vma relocation;
2095   bfd_signed_vma val;
2096   bfd_reloc_status_type status;
2097
2098   if (bfd_is_com_section (symbol->section))
2099     relocation = 0;
2100   else
2101     relocation = symbol->value;
2102
2103   relocation += symbol->section->output_section->vma;
2104   relocation += symbol->section->output_offset;
2105
2106   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2107     return bfd_reloc_outofrange;
2108
2109   /* Set val to the offset into the section or symbol.  */
2110   val = reloc_entry->addend;
2111
2112   _bfd_mips_elf_sign_extend (val, 16);
2113
2114   /* Adjust val for the final section location and GP value.  If we
2115      are producing relocatable output, we don't want to do this for
2116      an external symbol.  */
2117   if (! relocatable
2118       || (symbol->flags & BSF_SECTION_SYM) != 0)
2119     val += relocation - gp;
2120
2121   if (reloc_entry->howto->partial_inplace)
2122     {
2123       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2124                                        (bfd_byte *) data
2125                                        + reloc_entry->address);
2126       if (status != bfd_reloc_ok)
2127         return status;
2128     }
2129   else
2130     reloc_entry->addend = val;
2131
2132   if (relocatable)
2133     reloc_entry->address += input_section->output_offset;
2134
2135   return bfd_reloc_ok;
2136 }
2137
2138 /* Used to store a REL high-part relocation such as R_MIPS_HI16 or
2139    R_MIPS_GOT16.  REL is the relocation, INPUT_SECTION is the section
2140    that contains the relocation field and DATA points to the start of
2141    INPUT_SECTION.  */
2142
2143 struct mips_hi16
2144 {
2145   struct mips_hi16 *next;
2146   bfd_byte *data;
2147   asection *input_section;
2148   arelent rel;
2149 };
2150
2151 /* FIXME: This should not be a static variable.  */
2152
2153 static struct mips_hi16 *mips_hi16_list;
2154
2155 /* A howto special_function for REL *HI16 relocations.  We can only
2156    calculate the correct value once we've seen the partnering
2157    *LO16 relocation, so just save the information for later.
2158
2159    The ABI requires that the *LO16 immediately follow the *HI16.
2160    However, as a GNU extension, we permit an arbitrary number of
2161    *HI16s to be associated with a single *LO16.  This significantly
2162    simplies the relocation handling in gcc.  */
2163
2164 bfd_reloc_status_type
2165 _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2166                           asymbol *symbol ATTRIBUTE_UNUSED, void *data,
2167                           asection *input_section, bfd *output_bfd,
2168                           char **error_message ATTRIBUTE_UNUSED)
2169 {
2170   struct mips_hi16 *n;
2171
2172   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2173     return bfd_reloc_outofrange;
2174
2175   n = bfd_malloc (sizeof *n);
2176   if (n == NULL)
2177     return bfd_reloc_outofrange;
2178
2179   n->next = mips_hi16_list;
2180   n->data = data;
2181   n->input_section = input_section;
2182   n->rel = *reloc_entry;
2183   mips_hi16_list = n;
2184
2185   if (output_bfd != NULL)
2186     reloc_entry->address += input_section->output_offset;
2187
2188   return bfd_reloc_ok;
2189 }
2190
2191 /* A howto special_function for REL R_MIPS*_GOT16 relocations.  This is just
2192    like any other 16-bit relocation when applied to global symbols, but is
2193    treated in the same as R_MIPS_HI16 when applied to local symbols.  */
2194
2195 bfd_reloc_status_type
2196 _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2197                            void *data, asection *input_section,
2198                            bfd *output_bfd, char **error_message)
2199 {
2200   if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2201       || bfd_is_und_section (bfd_get_section (symbol))
2202       || bfd_is_com_section (bfd_get_section (symbol)))
2203     /* The relocation is against a global symbol.  */
2204     return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2205                                         input_section, output_bfd,
2206                                         error_message);
2207
2208   return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
2209                                    input_section, output_bfd, error_message);
2210 }
2211
2212 /* A howto special_function for REL *LO16 relocations.  The *LO16 itself
2213    is a straightforward 16 bit inplace relocation, but we must deal with
2214    any partnering high-part relocations as well.  */
2215
2216 bfd_reloc_status_type
2217 _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2218                           void *data, asection *input_section,
2219                           bfd *output_bfd, char **error_message)
2220 {
2221   bfd_vma vallo;
2222   bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2223
2224   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2225     return bfd_reloc_outofrange;
2226
2227   _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2228                                  location);
2229   vallo = bfd_get_32 (abfd, location);
2230   _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2231                                location);
2232
2233   while (mips_hi16_list != NULL)
2234     {
2235       bfd_reloc_status_type ret;
2236       struct mips_hi16 *hi;
2237
2238       hi = mips_hi16_list;
2239
2240       /* R_MIPS*_GOT16 relocations are something of a special case.  We
2241          want to install the addend in the same way as for a R_MIPS*_HI16
2242          relocation (with a rightshift of 16).  However, since GOT16
2243          relocations can also be used with global symbols, their howto
2244          has a rightshift of 0.  */
2245       if (hi->rel.howto->type == R_MIPS_GOT16)
2246         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE);
2247       else if (hi->rel.howto->type == R_MIPS16_GOT16)
2248         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS16_HI16, FALSE);
2249       else if (hi->rel.howto->type == R_MICROMIPS_GOT16)
2250         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MICROMIPS_HI16, FALSE);
2251
2252       /* VALLO is a signed 16-bit number.  Bias it by 0x8000 so that any
2253          carry or borrow will induce a change of +1 or -1 in the high part.  */
2254       hi->rel.addend += (vallo + 0x8000) & 0xffff;
2255
2256       ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data,
2257                                          hi->input_section, output_bfd,
2258                                          error_message);
2259       if (ret != bfd_reloc_ok)
2260         return ret;
2261
2262       mips_hi16_list = hi->next;
2263       free (hi);
2264     }
2265
2266   return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2267                                       input_section, output_bfd,
2268                                       error_message);
2269 }
2270
2271 /* A generic howto special_function.  This calculates and installs the
2272    relocation itself, thus avoiding the oft-discussed problems in
2273    bfd_perform_relocation and bfd_install_relocation.  */
2274
2275 bfd_reloc_status_type
2276 _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2277                              asymbol *symbol, void *data ATTRIBUTE_UNUSED,
2278                              asection *input_section, bfd *output_bfd,
2279                              char **error_message ATTRIBUTE_UNUSED)
2280 {
2281   bfd_signed_vma val;
2282   bfd_reloc_status_type status;
2283   bfd_boolean relocatable;
2284
2285   relocatable = (output_bfd != NULL);
2286
2287   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2288     return bfd_reloc_outofrange;
2289
2290   /* Build up the field adjustment in VAL.  */
2291   val = 0;
2292   if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)
2293     {
2294       /* Either we're calculating the final field value or we have a
2295          relocation against a section symbol.  Add in the section's
2296          offset or address.  */
2297       val += symbol->section->output_section->vma;
2298       val += symbol->section->output_offset;
2299     }
2300
2301   if (!relocatable)
2302     {
2303       /* We're calculating the final field value.  Add in the symbol's value
2304          and, if pc-relative, subtract the address of the field itself.  */
2305       val += symbol->value;
2306       if (reloc_entry->howto->pc_relative)
2307         {
2308           val -= input_section->output_section->vma;
2309           val -= input_section->output_offset;
2310           val -= reloc_entry->address;
2311         }
2312     }
2313
2314   /* VAL is now the final adjustment.  If we're keeping this relocation
2315      in the output file, and if the relocation uses a separate addend,
2316      we just need to add VAL to that addend.  Otherwise we need to add
2317      VAL to the relocation field itself.  */
2318   if (relocatable && !reloc_entry->howto->partial_inplace)
2319     reloc_entry->addend += val;
2320   else
2321     {
2322       bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2323
2324       /* Add in the separate addend, if any.  */
2325       val += reloc_entry->addend;
2326
2327       /* Add VAL to the relocation field.  */
2328       _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2329                                      location);
2330       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2331                                        location);
2332       _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2333                                    location);
2334
2335       if (status != bfd_reloc_ok)
2336         return status;
2337     }
2338
2339   if (relocatable)
2340     reloc_entry->address += input_section->output_offset;
2341
2342   return bfd_reloc_ok;
2343 }
2344 \f
2345 /* Swap an entry in a .gptab section.  Note that these routines rely
2346    on the equivalence of the two elements of the union.  */
2347
2348 static void
2349 bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex,
2350                               Elf32_gptab *in)
2351 {
2352   in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value);
2353   in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes);
2354 }
2355
2356 static void
2357 bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in,
2358                                Elf32_External_gptab *ex)
2359 {
2360   H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value);
2361   H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes);
2362 }
2363
2364 static void
2365 bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in,
2366                                 Elf32_External_compact_rel *ex)
2367 {
2368   H_PUT_32 (abfd, in->id1, ex->id1);
2369   H_PUT_32 (abfd, in->num, ex->num);
2370   H_PUT_32 (abfd, in->id2, ex->id2);
2371   H_PUT_32 (abfd, in->offset, ex->offset);
2372   H_PUT_32 (abfd, in->reserved0, ex->reserved0);
2373   H_PUT_32 (abfd, in->reserved1, ex->reserved1);
2374 }
2375
2376 static void
2377 bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in,
2378                            Elf32_External_crinfo *ex)
2379 {
2380   unsigned long l;
2381
2382   l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH)
2383        | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH)
2384        | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH)
2385        | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH));
2386   H_PUT_32 (abfd, l, ex->info);
2387   H_PUT_32 (abfd, in->konst, ex->konst);
2388   H_PUT_32 (abfd, in->vaddr, ex->vaddr);
2389 }
2390 \f
2391 /* A .reginfo section holds a single Elf32_RegInfo structure.  These
2392    routines swap this structure in and out.  They are used outside of
2393    BFD, so they are globally visible.  */
2394
2395 void
2396 bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex,
2397                                 Elf32_RegInfo *in)
2398 {
2399   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2400   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2401   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2402   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2403   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2404   in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value);
2405 }
2406
2407 void
2408 bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in,
2409                                  Elf32_External_RegInfo *ex)
2410 {
2411   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2412   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2413   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2414   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2415   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2416   H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value);
2417 }
2418
2419 /* In the 64 bit ABI, the .MIPS.options section holds register
2420    information in an Elf64_Reginfo structure.  These routines swap
2421    them in and out.  They are globally visible because they are used
2422    outside of BFD.  These routines are here so that gas can call them
2423    without worrying about whether the 64 bit ABI has been included.  */
2424
2425 void
2426 bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex,
2427                                 Elf64_Internal_RegInfo *in)
2428 {
2429   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2430   in->ri_pad = H_GET_32 (abfd, ex->ri_pad);
2431   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2432   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2433   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2434   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2435   in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value);
2436 }
2437
2438 void
2439 bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in,
2440                                  Elf64_External_RegInfo *ex)
2441 {
2442   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2443   H_PUT_32 (abfd, in->ri_pad, ex->ri_pad);
2444   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2445   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2446   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2447   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2448   H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value);
2449 }
2450
2451 /* Swap in an options header.  */
2452
2453 void
2454 bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex,
2455                               Elf_Internal_Options *in)
2456 {
2457   in->kind = H_GET_8 (abfd, ex->kind);
2458   in->size = H_GET_8 (abfd, ex->size);
2459   in->section = H_GET_16 (abfd, ex->section);
2460   in->info = H_GET_32 (abfd, ex->info);
2461 }
2462
2463 /* Swap out an options header.  */
2464
2465 void
2466 bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in,
2467                                Elf_External_Options *ex)
2468 {
2469   H_PUT_8 (abfd, in->kind, ex->kind);
2470   H_PUT_8 (abfd, in->size, ex->size);
2471   H_PUT_16 (abfd, in->section, ex->section);
2472   H_PUT_32 (abfd, in->info, ex->info);
2473 }
2474 \f
2475 /* This function is called via qsort() to sort the dynamic relocation
2476    entries by increasing r_symndx value.  */
2477
2478 static int
2479 sort_dynamic_relocs (const void *arg1, const void *arg2)
2480 {
2481   Elf_Internal_Rela int_reloc1;
2482   Elf_Internal_Rela int_reloc2;
2483   int diff;
2484
2485   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
2486   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
2487
2488   diff = ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info);
2489   if (diff != 0)
2490     return diff;
2491
2492   if (int_reloc1.r_offset < int_reloc2.r_offset)
2493     return -1;
2494   if (int_reloc1.r_offset > int_reloc2.r_offset)
2495     return 1;
2496   return 0;
2497 }
2498
2499 /* Like sort_dynamic_relocs, but used for elf64 relocations.  */
2500
2501 static int
2502 sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED,
2503                         const void *arg2 ATTRIBUTE_UNUSED)
2504 {
2505 #ifdef BFD64
2506   Elf_Internal_Rela int_reloc1[3];
2507   Elf_Internal_Rela int_reloc2[3];
2508
2509   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2510     (reldyn_sorting_bfd, arg1, int_reloc1);
2511   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2512     (reldyn_sorting_bfd, arg2, int_reloc2);
2513
2514   if (ELF64_R_SYM (int_reloc1[0].r_info) < ELF64_R_SYM (int_reloc2[0].r_info))
2515     return -1;
2516   if (ELF64_R_SYM (int_reloc1[0].r_info) > ELF64_R_SYM (int_reloc2[0].r_info))
2517     return 1;
2518
2519   if (int_reloc1[0].r_offset < int_reloc2[0].r_offset)
2520     return -1;
2521   if (int_reloc1[0].r_offset > int_reloc2[0].r_offset)
2522     return 1;
2523   return 0;
2524 #else
2525   abort ();
2526 #endif
2527 }
2528
2529
2530 /* This routine is used to write out ECOFF debugging external symbol
2531    information.  It is called via mips_elf_link_hash_traverse.  The
2532    ECOFF external symbol information must match the ELF external
2533    symbol information.  Unfortunately, at this point we don't know
2534    whether a symbol is required by reloc information, so the two
2535    tables may wind up being different.  We must sort out the external
2536    symbol information before we can set the final size of the .mdebug
2537    section, and we must set the size of the .mdebug section before we
2538    can relocate any sections, and we can't know which symbols are
2539    required by relocation until we relocate the sections.
2540    Fortunately, it is relatively unlikely that any symbol will be
2541    stripped but required by a reloc.  In particular, it can not happen
2542    when generating a final executable.  */
2543
2544 static bfd_boolean
2545 mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data)
2546 {
2547   struct extsym_info *einfo = data;
2548   bfd_boolean strip;
2549   asection *sec, *output_section;
2550
2551   if (h->root.indx == -2)
2552     strip = FALSE;
2553   else if ((h->root.def_dynamic
2554             || h->root.ref_dynamic
2555             || h->root.type == bfd_link_hash_new)
2556            && !h->root.def_regular
2557            && !h->root.ref_regular)
2558     strip = TRUE;
2559   else if (einfo->info->strip == strip_all
2560            || (einfo->info->strip == strip_some
2561                && bfd_hash_lookup (einfo->info->keep_hash,
2562                                    h->root.root.root.string,
2563                                    FALSE, FALSE) == NULL))
2564     strip = TRUE;
2565   else
2566     strip = FALSE;
2567
2568   if (strip)
2569     return TRUE;
2570
2571   if (h->esym.ifd == -2)
2572     {
2573       h->esym.jmptbl = 0;
2574       h->esym.cobol_main = 0;
2575       h->esym.weakext = 0;
2576       h->esym.reserved = 0;
2577       h->esym.ifd = ifdNil;
2578       h->esym.asym.value = 0;
2579       h->esym.asym.st = stGlobal;
2580
2581       if (h->root.root.type == bfd_link_hash_undefined
2582           || h->root.root.type == bfd_link_hash_undefweak)
2583         {
2584           const char *name;
2585
2586           /* Use undefined class.  Also, set class and type for some
2587              special symbols.  */
2588           name = h->root.root.root.string;
2589           if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
2590               || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
2591             {
2592               h->esym.asym.sc = scData;
2593               h->esym.asym.st = stLabel;
2594               h->esym.asym.value = 0;
2595             }
2596           else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
2597             {
2598               h->esym.asym.sc = scAbs;
2599               h->esym.asym.st = stLabel;
2600               h->esym.asym.value =
2601                 mips_elf_hash_table (einfo->info)->procedure_count;
2602             }
2603           else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd))
2604             {
2605               h->esym.asym.sc = scAbs;
2606               h->esym.asym.st = stLabel;
2607               h->esym.asym.value = elf_gp (einfo->abfd);
2608             }
2609           else
2610             h->esym.asym.sc = scUndefined;
2611         }
2612       else if (h->root.root.type != bfd_link_hash_defined
2613           && h->root.root.type != bfd_link_hash_defweak)
2614         h->esym.asym.sc = scAbs;
2615       else
2616         {
2617           const char *name;
2618
2619           sec = h->root.root.u.def.section;
2620           output_section = sec->output_section;
2621
2622           /* When making a shared library and symbol h is the one from
2623              the another shared library, OUTPUT_SECTION may be null.  */
2624           if (output_section == NULL)
2625             h->esym.asym.sc = scUndefined;
2626           else
2627             {
2628               name = bfd_section_name (output_section->owner, output_section);
2629
2630               if (strcmp (name, ".text") == 0)
2631                 h->esym.asym.sc = scText;
2632               else if (strcmp (name, ".data") == 0)
2633                 h->esym.asym.sc = scData;
2634               else if (strcmp (name, ".sdata") == 0)
2635                 h->esym.asym.sc = scSData;
2636               else if (strcmp (name, ".rodata") == 0
2637                        || strcmp (name, ".rdata") == 0)
2638                 h->esym.asym.sc = scRData;
2639               else if (strcmp (name, ".bss") == 0)
2640                 h->esym.asym.sc = scBss;
2641               else if (strcmp (name, ".sbss") == 0)
2642                 h->esym.asym.sc = scSBss;
2643               else if (strcmp (name, ".init") == 0)
2644                 h->esym.asym.sc = scInit;
2645               else if (strcmp (name, ".fini") == 0)
2646                 h->esym.asym.sc = scFini;
2647               else
2648                 h->esym.asym.sc = scAbs;
2649             }
2650         }
2651
2652       h->esym.asym.reserved = 0;
2653       h->esym.asym.index = indexNil;
2654     }
2655
2656   if (h->root.root.type == bfd_link_hash_common)
2657     h->esym.asym.value = h->root.root.u.c.size;
2658   else if (h->root.root.type == bfd_link_hash_defined
2659            || h->root.root.type == bfd_link_hash_defweak)
2660     {
2661       if (h->esym.asym.sc == scCommon)
2662         h->esym.asym.sc = scBss;
2663       else if (h->esym.asym.sc == scSCommon)
2664         h->esym.asym.sc = scSBss;
2665
2666       sec = h->root.root.u.def.section;
2667       output_section = sec->output_section;
2668       if (output_section != NULL)
2669         h->esym.asym.value = (h->root.root.u.def.value
2670                               + sec->output_offset
2671                               + output_section->vma);
2672       else
2673         h->esym.asym.value = 0;
2674     }
2675   else
2676     {
2677       struct mips_elf_link_hash_entry *hd = h;
2678
2679       while (hd->root.root.type == bfd_link_hash_indirect)
2680         hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link;
2681
2682       if (hd->needs_lazy_stub)
2683         {
2684           /* Set type and value for a symbol with a function stub.  */
2685           h->esym.asym.st = stProc;
2686           sec = hd->root.root.u.def.section;
2687           if (sec == NULL)
2688             h->esym.asym.value = 0;
2689           else
2690             {
2691               output_section = sec->output_section;
2692               if (output_section != NULL)
2693                 h->esym.asym.value = (hd->root.plt.offset
2694                                       + sec->output_offset
2695                                       + output_section->vma);
2696               else
2697                 h->esym.asym.value = 0;
2698             }
2699         }
2700     }
2701
2702   if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap,
2703                                       h->root.root.root.string,
2704                                       &h->esym))
2705     {
2706       einfo->failed = TRUE;
2707       return FALSE;
2708     }
2709
2710   return TRUE;
2711 }
2712
2713 /* A comparison routine used to sort .gptab entries.  */
2714
2715 static int
2716 gptab_compare (const void *p1, const void *p2)
2717 {
2718   const Elf32_gptab *a1 = p1;
2719   const Elf32_gptab *a2 = p2;
2720
2721   return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value;
2722 }
2723 \f
2724 /* Functions to manage the got entry hash table.  */
2725
2726 /* Use all 64 bits of a bfd_vma for the computation of a 32-bit
2727    hash number.  */
2728
2729 static INLINE hashval_t
2730 mips_elf_hash_bfd_vma (bfd_vma addr)
2731 {
2732 #ifdef BFD64
2733   return addr + (addr >> 32);
2734 #else
2735   return addr;
2736 #endif
2737 }
2738
2739 static hashval_t
2740 mips_elf_got_entry_hash (const void *entry_)
2741 {
2742   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2743
2744   return (entry->symndx
2745           + (((entry->tls_type & GOT_TLS_TYPE) == GOT_TLS_LDM) << 18)
2746           + ((entry->tls_type & GOT_TLS_TYPE) == GOT_TLS_LDM ? 0
2747              : !entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address)
2748              : entry->symndx >= 0 ? (entry->abfd->id
2749                                      + mips_elf_hash_bfd_vma (entry->d.addend))
2750              : entry->d.h->root.root.root.hash));
2751 }
2752
2753 static int
2754 mips_elf_got_entry_eq (const void *entry1, const void *entry2)
2755 {
2756   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2757   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2758
2759   return (e1->symndx == e2->symndx
2760           && (e1->tls_type & GOT_TLS_TYPE) == (e2->tls_type & GOT_TLS_TYPE)
2761           && ((e1->tls_type & GOT_TLS_TYPE) == GOT_TLS_LDM ? TRUE
2762               : !e1->abfd ? !e2->abfd && e1->d.address == e2->d.address
2763               : e1->symndx >= 0 ? (e1->abfd == e2->abfd
2764                                    && e1->d.addend == e2->d.addend)
2765               : e2->abfd && e1->d.h == e2->d.h));
2766 }
2767
2768 static hashval_t
2769 mips_got_page_entry_hash (const void *entry_)
2770 {
2771   const struct mips_got_page_entry *entry;
2772
2773   entry = (const struct mips_got_page_entry *) entry_;
2774   return entry->abfd->id + entry->symndx;
2775 }
2776
2777 static int
2778 mips_got_page_entry_eq (const void *entry1_, const void *entry2_)
2779 {
2780   const struct mips_got_page_entry *entry1, *entry2;
2781
2782   entry1 = (const struct mips_got_page_entry *) entry1_;
2783   entry2 = (const struct mips_got_page_entry *) entry2_;
2784   return entry1->abfd == entry2->abfd && entry1->symndx == entry2->symndx;
2785 }
2786 \f
2787 /* Create and return a new mips_got_info structure.  */
2788
2789 static struct mips_got_info *
2790 mips_elf_create_got_info (bfd *abfd)
2791 {
2792   struct mips_got_info *g;
2793
2794   g = bfd_zalloc (abfd, sizeof (struct mips_got_info));
2795   if (g == NULL)
2796     return NULL;
2797
2798   g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
2799                                     mips_elf_got_entry_eq, NULL);
2800   if (g->got_entries == NULL)
2801     return NULL;
2802
2803   g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
2804                                          mips_got_page_entry_eq, NULL);
2805   if (g->got_page_entries == NULL)
2806     return NULL;
2807
2808   return g;
2809 }
2810
2811 /* Return the GOT info for input bfd ABFD, trying to create a new one if
2812    CREATE_P and if ABFD doesn't already have a GOT.  */
2813
2814 static struct mips_got_info *
2815 mips_elf_bfd_got (bfd *abfd, bfd_boolean create_p)
2816 {
2817   struct mips_elf_obj_tdata *tdata;
2818
2819   if (!is_mips_elf (abfd))
2820     return NULL;
2821
2822   tdata = mips_elf_tdata (abfd);
2823   if (!tdata->got && create_p)
2824     tdata->got = mips_elf_create_got_info (abfd);
2825   return tdata->got;
2826 }
2827
2828 /* Record that ABFD should use output GOT G.  */
2829
2830 static void
2831 mips_elf_replace_bfd_got (bfd *abfd, struct mips_got_info *g)
2832 {
2833   struct mips_elf_obj_tdata *tdata;
2834
2835   BFD_ASSERT (is_mips_elf (abfd));
2836   tdata = mips_elf_tdata (abfd);
2837   if (tdata->got)
2838     {
2839       /* The GOT structure itself and the hash table entries are
2840          allocated to a bfd, but the hash tables aren't.  */
2841       htab_delete (tdata->got->got_entries);
2842       htab_delete (tdata->got->got_page_entries);
2843     }
2844   tdata->got = g;
2845 }
2846
2847 /* Return the dynamic relocation section.  If it doesn't exist, try to
2848    create a new it if CREATE_P, otherwise return NULL.  Also return NULL
2849    if creation fails.  */
2850
2851 static asection *
2852 mips_elf_rel_dyn_section (struct bfd_link_info *info, bfd_boolean create_p)
2853 {
2854   const char *dname;
2855   asection *sreloc;
2856   bfd *dynobj;
2857
2858   dname = MIPS_ELF_REL_DYN_NAME (info);
2859   dynobj = elf_hash_table (info)->dynobj;
2860   sreloc = bfd_get_linker_section (dynobj, dname);
2861   if (sreloc == NULL && create_p)
2862     {
2863       sreloc = bfd_make_section_anyway_with_flags (dynobj, dname,
2864                                                    (SEC_ALLOC
2865                                                     | SEC_LOAD
2866                                                     | SEC_HAS_CONTENTS
2867                                                     | SEC_IN_MEMORY
2868                                                     | SEC_LINKER_CREATED
2869                                                     | SEC_READONLY));
2870       if (sreloc == NULL
2871           || ! bfd_set_section_alignment (dynobj, sreloc,
2872                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
2873         return NULL;
2874     }
2875   return sreloc;
2876 }
2877
2878 /* Return the GOT_TLS_* type required by relocation type R_TYPE.  */
2879
2880 static int
2881 mips_elf_reloc_tls_type (unsigned int r_type)
2882 {
2883   if (tls_gd_reloc_p (r_type))
2884     return GOT_TLS_GD;
2885
2886   if (tls_ldm_reloc_p (r_type))
2887     return GOT_TLS_LDM;
2888
2889   if (tls_gottprel_reloc_p (r_type))
2890     return GOT_TLS_IE;
2891
2892   return GOT_NORMAL;
2893 }
2894
2895 /* Return the number of GOT slots needed for GOT TLS type TYPE.  */
2896
2897 static int
2898 mips_tls_got_entries (unsigned int type)
2899 {
2900   switch (type)
2901     {
2902     case GOT_TLS_GD:
2903     case GOT_TLS_LDM:
2904       return 2;
2905
2906     case GOT_TLS_IE:
2907       return 1;
2908
2909     case GOT_NORMAL:
2910       return 0;
2911     }
2912   abort ();
2913 }
2914
2915 /* Count the number of relocations needed for a TLS GOT entry, with
2916    access types from TLS_TYPE, and symbol H (or a local symbol if H
2917    is NULL).  */
2918
2919 static int
2920 mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type,
2921                      struct elf_link_hash_entry *h)
2922 {
2923   int indx = 0;
2924   bfd_boolean need_relocs = FALSE;
2925   bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
2926
2927   if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, h)
2928       && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, h)))
2929     indx = h->dynindx;
2930
2931   if ((info->shared || indx != 0)
2932       && (h == NULL
2933           || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2934           || h->root.type != bfd_link_hash_undefweak))
2935     need_relocs = TRUE;
2936
2937   if (!need_relocs)
2938     return 0;
2939
2940   switch (tls_type & GOT_TLS_TYPE)
2941     {
2942     case GOT_TLS_GD:
2943       return indx != 0 ? 2 : 1;
2944
2945     case GOT_TLS_IE:
2946       return 1;
2947
2948     case GOT_TLS_LDM:
2949       return info->shared ? 1 : 0;
2950
2951     default:
2952       return 0;
2953     }
2954 }
2955
2956 /* Add the number of GOT entries and TLS relocations required by ENTRY
2957    to G.  */
2958
2959 static void
2960 mips_elf_count_got_entry (struct bfd_link_info *info,
2961                           struct mips_got_info *g,
2962                           struct mips_got_entry *entry)
2963 {
2964   unsigned char tls_type;
2965
2966   tls_type = entry->tls_type & GOT_TLS_TYPE;
2967   if (tls_type)
2968     {
2969       g->tls_gotno += mips_tls_got_entries (tls_type);
2970       g->relocs += mips_tls_got_relocs (info, tls_type,
2971                                         entry->symndx < 0
2972                                         ? &entry->d.h->root : NULL);
2973     }
2974   else if (entry->symndx >= 0 || entry->d.h->global_got_area == GGA_NONE)
2975     g->local_gotno += 1;
2976   else
2977     g->global_gotno += 1;
2978 }
2979
2980 /* A htab_traverse callback.  Count the number of GOT entries and
2981    TLS relocations required for the GOT entry in *ENTRYP.  DATA points
2982    to a mips_elf_traverse_got_arg structure.  */
2983
2984 static int
2985 mips_elf_count_got_entries (void **entryp, void *data)
2986 {
2987   struct mips_got_entry *entry;
2988   struct mips_elf_traverse_got_arg *arg;
2989
2990   entry = (struct mips_got_entry *) *entryp;
2991   arg = (struct mips_elf_traverse_got_arg *) data;
2992   mips_elf_count_got_entry (arg->info, arg->g, entry);
2993
2994   return 1;
2995 }
2996
2997 /* Output a simple dynamic relocation into SRELOC.  */
2998
2999 static void
3000 mips_elf_output_dynamic_relocation (bfd *output_bfd,
3001                                     asection *sreloc,
3002                                     unsigned long reloc_index,
3003                                     unsigned long indx,
3004                                     int r_type,
3005                                     bfd_vma offset)
3006 {
3007   Elf_Internal_Rela rel[3];
3008
3009   memset (rel, 0, sizeof (rel));
3010
3011   rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type);
3012   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
3013
3014   if (ABI_64_P (output_bfd))
3015     {
3016       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
3017         (output_bfd, &rel[0],
3018          (sreloc->contents
3019           + reloc_index * sizeof (Elf64_Mips_External_Rel)));
3020     }
3021   else
3022     bfd_elf32_swap_reloc_out
3023       (output_bfd, &rel[0],
3024        (sreloc->contents
3025         + reloc_index * sizeof (Elf32_External_Rel)));
3026 }
3027
3028 /* Initialize a set of TLS GOT entries for one symbol.  */
3029
3030 static void
3031 mips_elf_initialize_tls_slots (bfd *abfd, bfd_vma got_offset,
3032                                unsigned char *tls_type_p,
3033                                struct bfd_link_info *info,
3034                                struct mips_elf_link_hash_entry *h,
3035                                bfd_vma value)
3036 {
3037   struct mips_elf_link_hash_table *htab;
3038   int indx;
3039   asection *sreloc, *sgot;
3040   bfd_vma got_offset2;
3041   bfd_boolean need_relocs = FALSE;
3042
3043   htab = mips_elf_hash_table (info);
3044   if (htab == NULL)
3045     return;
3046
3047   sgot = htab->sgot;
3048
3049   indx = 0;
3050   if (h != NULL)
3051     {
3052       bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3053
3054       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, &h->root)
3055           && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3056         indx = h->root.dynindx;
3057     }
3058
3059   if (*tls_type_p & GOT_TLS_DONE)
3060     return;
3061
3062   if ((info->shared || indx != 0)
3063       && (h == NULL
3064           || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT
3065           || h->root.type != bfd_link_hash_undefweak))
3066     need_relocs = TRUE;
3067
3068   /* MINUS_ONE means the symbol is not defined in this object.  It may not
3069      be defined at all; assume that the value doesn't matter in that
3070      case.  Otherwise complain if we would use the value.  */
3071   BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs)
3072               || h->root.root.type == bfd_link_hash_undefweak);
3073
3074   /* Emit necessary relocations.  */
3075   sreloc = mips_elf_rel_dyn_section (info, FALSE);
3076
3077   switch (*tls_type_p & GOT_TLS_TYPE)
3078     {
3079     case GOT_TLS_GD:
3080       /* General Dynamic.  */
3081       got_offset2 = got_offset + MIPS_ELF_GOT_SIZE (abfd);
3082
3083       if (need_relocs)
3084         {
3085           mips_elf_output_dynamic_relocation
3086             (abfd, sreloc, sreloc->reloc_count++, indx,
3087              ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3088              sgot->output_offset + sgot->output_section->vma + got_offset);
3089
3090           if (indx)
3091             mips_elf_output_dynamic_relocation
3092               (abfd, sreloc, sreloc->reloc_count++, indx,
3093                ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32,
3094                sgot->output_offset + sgot->output_section->vma + got_offset2);
3095           else
3096             MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3097                                sgot->contents + got_offset2);
3098         }
3099       else
3100         {
3101           MIPS_ELF_PUT_WORD (abfd, 1,
3102                              sgot->contents + got_offset);
3103           MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3104                              sgot->contents + got_offset2);
3105         }
3106       break;
3107
3108     case GOT_TLS_IE:
3109       /* Initial Exec model.  */
3110       if (need_relocs)
3111         {
3112           if (indx == 0)
3113             MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma,
3114                                sgot->contents + got_offset);
3115           else
3116             MIPS_ELF_PUT_WORD (abfd, 0,
3117                                sgot->contents + got_offset);
3118
3119           mips_elf_output_dynamic_relocation
3120             (abfd, sreloc, sreloc->reloc_count++, indx,
3121              ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32,
3122              sgot->output_offset + sgot->output_section->vma + got_offset);
3123         }
3124       else
3125         MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info),
3126                            sgot->contents + got_offset);
3127       break;
3128
3129     case GOT_TLS_LDM:
3130       /* The initial offset is zero, and the LD offsets will include the
3131          bias by DTP_OFFSET.  */
3132       MIPS_ELF_PUT_WORD (abfd, 0,
3133                          sgot->contents + got_offset
3134                          + MIPS_ELF_GOT_SIZE (abfd));
3135
3136       if (!info->shared)
3137         MIPS_ELF_PUT_WORD (abfd, 1,
3138                            sgot->contents + got_offset);
3139       else
3140         mips_elf_output_dynamic_relocation
3141           (abfd, sreloc, sreloc->reloc_count++, indx,
3142            ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3143            sgot->output_offset + sgot->output_section->vma + got_offset);
3144       break;
3145
3146     default:
3147       abort ();
3148     }
3149
3150   *tls_type_p |= GOT_TLS_DONE;
3151 }
3152
3153 /* Return the GOT index to use for a relocation against H using the
3154    TLS model in *TLS_TYPE.  The GOT entries for this symbol/model
3155    combination start at GOT_INDEX into ABFD's GOT.  This function
3156    initializes the GOT entries and corresponding relocations.  */
3157
3158 static bfd_vma
3159 mips_tls_got_index (bfd *abfd, bfd_vma got_index, unsigned char *tls_type,
3160                     struct bfd_link_info *info,
3161                     struct mips_elf_link_hash_entry *h, bfd_vma symbol)
3162 {
3163   mips_elf_initialize_tls_slots (abfd, got_index, tls_type, info, h, symbol);
3164   return got_index;
3165 }
3166
3167 /* Return the offset from _GLOBAL_OFFSET_TABLE_ of the .got.plt entry
3168    for global symbol H.  .got.plt comes before the GOT, so the offset
3169    will be negative.  */
3170
3171 static bfd_vma
3172 mips_elf_gotplt_index (struct bfd_link_info *info,
3173                        struct elf_link_hash_entry *h)
3174 {
3175   bfd_vma plt_index, got_address, got_value;
3176   struct mips_elf_link_hash_table *htab;
3177
3178   htab = mips_elf_hash_table (info);
3179   BFD_ASSERT (htab != NULL);
3180
3181   BFD_ASSERT (h->plt.offset != (bfd_vma) -1);
3182
3183   /* This function only works for VxWorks, because a non-VxWorks .got.plt
3184      section starts with reserved entries.  */
3185   BFD_ASSERT (htab->is_vxworks);
3186
3187   /* Calculate the index of the symbol's PLT entry.  */
3188   plt_index = (h->plt.offset - htab->plt_header_size) / htab->plt_entry_size;
3189
3190   /* Calculate the address of the associated .got.plt entry.  */
3191   got_address = (htab->sgotplt->output_section->vma
3192                  + htab->sgotplt->output_offset
3193                  + plt_index * 4);
3194
3195   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
3196   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
3197                + htab->root.hgot->root.u.def.section->output_offset
3198                + htab->root.hgot->root.u.def.value);
3199
3200   return got_address - got_value;
3201 }
3202
3203 /* Return the GOT offset for address VALUE.   If there is not yet a GOT
3204    entry for this value, create one.  If R_SYMNDX refers to a TLS symbol,
3205    create a TLS GOT entry instead.  Return -1 if no satisfactory GOT
3206    offset can be found.  */
3207
3208 static bfd_vma
3209 mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3210                           bfd_vma value, unsigned long r_symndx,
3211                           struct mips_elf_link_hash_entry *h, int r_type)
3212 {
3213   struct mips_elf_link_hash_table *htab;
3214   struct mips_got_entry *entry;
3215
3216   htab = mips_elf_hash_table (info);
3217   BFD_ASSERT (htab != NULL);
3218
3219   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value,
3220                                            r_symndx, h, r_type);
3221   if (!entry)
3222     return MINUS_ONE;
3223
3224   if (entry->tls_type)
3225     return mips_tls_got_index (abfd, entry->gotidx, &entry->tls_type,
3226                                info, h, value);
3227   else
3228     return entry->gotidx;
3229 }
3230
3231 /* Return the GOT index of global symbol H in the primary GOT.  */
3232
3233 static bfd_vma
3234 mips_elf_primary_global_got_index (bfd *obfd, struct bfd_link_info *info,
3235                                    struct elf_link_hash_entry *h)
3236 {
3237   struct mips_elf_link_hash_table *htab;
3238   long global_got_dynindx;
3239   struct mips_got_info *g;
3240   bfd_vma got_index;
3241
3242   htab = mips_elf_hash_table (info);
3243   BFD_ASSERT (htab != NULL);
3244
3245   global_got_dynindx = 0;
3246   if (htab->global_gotsym != NULL)
3247     global_got_dynindx = htab->global_gotsym->dynindx;
3248
3249   /* Once we determine the global GOT entry with the lowest dynamic
3250      symbol table index, we must put all dynamic symbols with greater
3251      indices into the primary GOT.  That makes it easy to calculate the
3252      GOT offset.  */
3253   BFD_ASSERT (h->dynindx >= global_got_dynindx);
3254   g = mips_elf_bfd_got (obfd, FALSE);
3255   got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3256                * MIPS_ELF_GOT_SIZE (obfd));
3257   BFD_ASSERT (got_index < htab->sgot->size);
3258
3259   return got_index;
3260 }
3261
3262 /* Return the GOT index for the global symbol indicated by H, which is
3263    referenced by a relocation of type R_TYPE in IBFD.  */
3264
3265 static bfd_vma
3266 mips_elf_global_got_index (bfd *obfd, struct bfd_link_info *info, bfd *ibfd,
3267                            struct elf_link_hash_entry *h, int r_type)
3268 {
3269   struct mips_elf_link_hash_table *htab;
3270   struct mips_got_info *g;
3271   struct mips_got_entry lookup, *entry;
3272   bfd_vma gotidx;
3273
3274   htab = mips_elf_hash_table (info);
3275   BFD_ASSERT (htab != NULL);
3276
3277   g = mips_elf_bfd_got (ibfd, FALSE);
3278   BFD_ASSERT (g);
3279
3280   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3281   if (!lookup.tls_type && g == mips_elf_bfd_got (obfd, FALSE))
3282     return mips_elf_primary_global_got_index (obfd, info, h);
3283
3284   lookup.abfd = ibfd;
3285   lookup.symndx = -1;
3286   lookup.d.h = (struct mips_elf_link_hash_entry *) h;
3287   entry = htab_find (g->got_entries, &lookup);
3288   BFD_ASSERT (entry);
3289
3290   gotidx = entry->gotidx;
3291   BFD_ASSERT (gotidx > 0 && gotidx < htab->sgot->size);
3292
3293   if (lookup.tls_type)
3294     {
3295       bfd_vma value = MINUS_ONE;
3296
3297       if ((h->root.type == bfd_link_hash_defined
3298            || h->root.type == bfd_link_hash_defweak)
3299           && h->root.u.def.section->output_section)
3300         value = (h->root.u.def.value
3301                  + h->root.u.def.section->output_offset
3302                  + h->root.u.def.section->output_section->vma);
3303
3304       return mips_tls_got_index (obfd, gotidx, &entry->tls_type,
3305                                  info, lookup.d.h, value);
3306     }
3307   return gotidx;
3308 }
3309
3310 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3311    entries are supposed to be placed at small offsets in the GOT, i.e.,
3312    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3313    entry could be created.  If OFFSETP is nonnull, use it to return the
3314    offset of the GOT entry from VALUE.  */
3315
3316 static bfd_vma
3317 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3318                    bfd_vma value, bfd_vma *offsetp)
3319 {
3320   bfd_vma page, got_index;
3321   struct mips_got_entry *entry;
3322
3323   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3324   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3325                                            NULL, R_MIPS_GOT_PAGE);
3326
3327   if (!entry)
3328     return MINUS_ONE;
3329
3330   got_index = entry->gotidx;
3331
3332   if (offsetp)
3333     *offsetp = value - entry->d.address;
3334
3335   return got_index;
3336 }
3337
3338 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3339    EXTERNAL is true if the relocation was originally against a global
3340    symbol that binds locally.  */
3341
3342 static bfd_vma
3343 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3344                       bfd_vma value, bfd_boolean external)
3345 {
3346   struct mips_got_entry *entry;
3347
3348   /* GOT16 relocations against local symbols are followed by a LO16
3349      relocation; those against global symbols are not.  Thus if the
3350      symbol was originally local, the GOT16 relocation should load the
3351      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3352   if (! external)
3353     value = mips_elf_high (value) << 16;
3354
3355   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3356      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3357      same in all cases.  */
3358   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3359                                            NULL, R_MIPS_GOT16);
3360   if (entry)
3361     return entry->gotidx;
3362   else
3363     return MINUS_ONE;
3364 }
3365
3366 /* Returns the offset for the entry at the INDEXth position
3367    in the GOT.  */
3368
3369 static bfd_vma
3370 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3371                                 bfd *input_bfd, bfd_vma got_index)
3372 {
3373   struct mips_elf_link_hash_table *htab;
3374   asection *sgot;
3375   bfd_vma gp;
3376
3377   htab = mips_elf_hash_table (info);
3378   BFD_ASSERT (htab != NULL);
3379
3380   sgot = htab->sgot;
3381   gp = _bfd_get_gp_value (output_bfd)
3382     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3383
3384   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3385 }
3386
3387 /* Create and return a local GOT entry for VALUE, which was calculated
3388    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3389    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3390    instead.  */
3391
3392 static struct mips_got_entry *
3393 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3394                                  bfd *ibfd, bfd_vma value,
3395                                  unsigned long r_symndx,
3396                                  struct mips_elf_link_hash_entry *h,
3397                                  int r_type)
3398 {
3399   struct mips_got_entry lookup, *entry;
3400   void **loc;
3401   struct mips_got_info *g;
3402   struct mips_elf_link_hash_table *htab;
3403   bfd_vma gotidx;
3404
3405   htab = mips_elf_hash_table (info);
3406   BFD_ASSERT (htab != NULL);
3407
3408   g = mips_elf_bfd_got (ibfd, FALSE);
3409   if (g == NULL)
3410     {
3411       g = mips_elf_bfd_got (abfd, FALSE);
3412       BFD_ASSERT (g != NULL);
3413     }
3414
3415   /* This function shouldn't be called for symbols that live in the global
3416      area of the GOT.  */
3417   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3418
3419   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3420   if (lookup.tls_type)
3421     {
3422       lookup.abfd = ibfd;
3423       if (tls_ldm_reloc_p (r_type))
3424         {
3425           lookup.symndx = 0;
3426           lookup.d.addend = 0;
3427         }
3428       else if (h == NULL)
3429         {
3430           lookup.symndx = r_symndx;
3431           lookup.d.addend = 0;
3432         }
3433       else
3434         {
3435           lookup.symndx = -1;
3436           lookup.d.h = h;
3437         }
3438
3439       entry = (struct mips_got_entry *) htab_find (g->got_entries, &lookup);
3440       BFD_ASSERT (entry);
3441
3442       gotidx = entry->gotidx;
3443       BFD_ASSERT (gotidx > 0 && gotidx < htab->sgot->size);
3444
3445       return entry;
3446     }
3447
3448   lookup.abfd = NULL;
3449   lookup.symndx = -1;
3450   lookup.d.address = value;
3451   loc = htab_find_slot (g->got_entries, &lookup, INSERT);
3452   if (!loc)
3453     return NULL;
3454
3455   entry = (struct mips_got_entry *) *loc;
3456   if (entry)
3457     return entry;
3458
3459   if (g->assigned_gotno >= g->local_gotno)
3460     {
3461       /* We didn't allocate enough space in the GOT.  */
3462       (*_bfd_error_handler)
3463         (_("not enough GOT space for local GOT entries"));
3464       bfd_set_error (bfd_error_bad_value);
3465       return NULL;
3466     }
3467
3468   entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3469   if (!entry)
3470     return NULL;
3471
3472   lookup.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_gotno++;
3473   *entry = lookup;
3474   *loc = entry;
3475
3476   MIPS_ELF_PUT_WORD (abfd, value, htab->sgot->contents + entry->gotidx);
3477
3478   /* These GOT entries need a dynamic relocation on VxWorks.  */
3479   if (htab->is_vxworks)
3480     {
3481       Elf_Internal_Rela outrel;
3482       asection *s;
3483       bfd_byte *rloc;
3484       bfd_vma got_address;
3485
3486       s = mips_elf_rel_dyn_section (info, FALSE);
3487       got_address = (htab->sgot->output_section->vma
3488                      + htab->sgot->output_offset
3489                      + entry->gotidx);
3490
3491       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3492       outrel.r_offset = got_address;
3493       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3494       outrel.r_addend = value;
3495       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3496     }
3497
3498   return entry;
3499 }
3500
3501 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3502    The number might be exact or a worst-case estimate, depending on how
3503    much information is available to elf_backend_omit_section_dynsym at
3504    the current linking stage.  */
3505
3506 static bfd_size_type
3507 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3508 {
3509   bfd_size_type count;
3510
3511   count = 0;
3512   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
3513     {
3514       asection *p;
3515       const struct elf_backend_data *bed;
3516
3517       bed = get_elf_backend_data (output_bfd);
3518       for (p = output_bfd->sections; p ; p = p->next)
3519         if ((p->flags & SEC_EXCLUDE) == 0
3520             && (p->flags & SEC_ALLOC) != 0
3521             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3522           ++count;
3523     }
3524   return count;
3525 }
3526
3527 /* Sort the dynamic symbol table so that symbols that need GOT entries
3528    appear towards the end.  */
3529
3530 static bfd_boolean
3531 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3532 {
3533   struct mips_elf_link_hash_table *htab;
3534   struct mips_elf_hash_sort_data hsd;
3535   struct mips_got_info *g;
3536
3537   if (elf_hash_table (info)->dynsymcount == 0)
3538     return TRUE;
3539
3540   htab = mips_elf_hash_table (info);
3541   BFD_ASSERT (htab != NULL);
3542
3543   g = htab->got_info;
3544   if (g == NULL)
3545     return TRUE;
3546
3547   hsd.low = NULL;
3548   hsd.max_unref_got_dynindx
3549     = hsd.min_got_dynindx
3550     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3551   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3552   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3553                                 elf_hash_table (info)),
3554                                mips_elf_sort_hash_table_f,
3555                                &hsd);
3556
3557   /* There should have been enough room in the symbol table to
3558      accommodate both the GOT and non-GOT symbols.  */
3559   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3560   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3561               == elf_hash_table (info)->dynsymcount);
3562   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3563               == g->global_gotno);
3564
3565   /* Now we know which dynamic symbol has the lowest dynamic symbol
3566      table index in the GOT.  */
3567   htab->global_gotsym = hsd.low;
3568
3569   return TRUE;
3570 }
3571
3572 /* If H needs a GOT entry, assign it the highest available dynamic
3573    index.  Otherwise, assign it the lowest available dynamic
3574    index.  */
3575
3576 static bfd_boolean
3577 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3578 {
3579   struct mips_elf_hash_sort_data *hsd = data;
3580
3581   /* Symbols without dynamic symbol table entries aren't interesting
3582      at all.  */
3583   if (h->root.dynindx == -1)
3584     return TRUE;
3585
3586   switch (h->global_got_area)
3587     {
3588     case GGA_NONE:
3589       h->root.dynindx = hsd->max_non_got_dynindx++;
3590       break;
3591
3592     case GGA_NORMAL:
3593       h->root.dynindx = --hsd->min_got_dynindx;
3594       hsd->low = (struct elf_link_hash_entry *) h;
3595       break;
3596
3597     case GGA_RELOC_ONLY:
3598       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3599         hsd->low = (struct elf_link_hash_entry *) h;
3600       h->root.dynindx = hsd->max_unref_got_dynindx++;
3601       break;
3602     }
3603
3604   return TRUE;
3605 }
3606
3607 /* Record that input bfd ABFD requires a GOT entry like *LOOKUP
3608    (which is owned by the caller and shouldn't be added to the
3609    hash table directly).  */
3610
3611 static bfd_boolean
3612 mips_elf_record_got_entry (struct bfd_link_info *info, bfd *abfd,
3613                            struct mips_got_entry *lookup)
3614 {
3615   struct mips_elf_link_hash_table *htab;
3616   struct mips_got_entry *entry;
3617   struct mips_got_info *g;
3618   void **loc, **bfd_loc;
3619
3620   /* Make sure there's a slot for this entry in the master GOT.  */
3621   htab = mips_elf_hash_table (info);
3622   g = htab->got_info;
3623   loc = htab_find_slot (g->got_entries, lookup, INSERT);
3624   if (!loc)
3625     return FALSE;
3626
3627   /* Populate the entry if it isn't already.  */
3628   entry = (struct mips_got_entry *) *loc;
3629   if (!entry)
3630     {
3631       entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3632       if (!entry)
3633         return FALSE;
3634
3635       lookup->gotidx = -1;
3636       *entry = *lookup;
3637       *loc = entry;
3638     }
3639
3640   /* Reuse the same GOT entry for the BFD's GOT.  */
3641   g = mips_elf_bfd_got (abfd, TRUE);
3642   if (!g)
3643     return FALSE;
3644
3645   bfd_loc = htab_find_slot (g->got_entries, lookup, INSERT);
3646   if (!bfd_loc)
3647     return FALSE;
3648
3649   if (!*bfd_loc)
3650     *bfd_loc = entry;
3651   return TRUE;
3652 }
3653
3654 /* ABFD has a GOT relocation of type R_TYPE against H.  Reserve a GOT
3655    entry for it.  FOR_CALL is true if the caller is only interested in
3656    using the GOT entry for calls.  */
3657
3658 static bfd_boolean
3659 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3660                                    bfd *abfd, struct bfd_link_info *info,
3661                                    bfd_boolean for_call, int r_type)
3662 {
3663   struct mips_elf_link_hash_table *htab;
3664   struct mips_elf_link_hash_entry *hmips;
3665   struct mips_got_entry entry;
3666   unsigned char tls_type;
3667
3668   htab = mips_elf_hash_table (info);
3669   BFD_ASSERT (htab != NULL);
3670
3671   hmips = (struct mips_elf_link_hash_entry *) h;
3672   if (!for_call)
3673     hmips->got_only_for_calls = FALSE;
3674
3675   /* A global symbol in the GOT must also be in the dynamic symbol
3676      table.  */
3677   if (h->dynindx == -1)
3678     {
3679       switch (ELF_ST_VISIBILITY (h->other))
3680         {
3681         case STV_INTERNAL:
3682         case STV_HIDDEN:
3683           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3684           break;
3685         }
3686       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3687         return FALSE;
3688     }
3689
3690   tls_type = mips_elf_reloc_tls_type (r_type);
3691   if (tls_type == GOT_NORMAL && hmips->global_got_area > GGA_NORMAL)
3692     hmips->global_got_area = GGA_NORMAL;
3693
3694   entry.abfd = abfd;
3695   entry.symndx = -1;
3696   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3697   entry.tls_type = tls_type;
3698   return mips_elf_record_got_entry (info, abfd, &entry);
3699 }
3700
3701 /* ABFD has a GOT relocation of type R_TYPE against symbol SYMNDX + ADDEND,
3702    where SYMNDX is a local symbol.  Reserve a GOT entry for it.  */
3703
3704 static bfd_boolean
3705 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
3706                                   struct bfd_link_info *info, int r_type)
3707 {
3708   struct mips_elf_link_hash_table *htab;
3709   struct mips_got_info *g;
3710   struct mips_got_entry entry;
3711
3712   htab = mips_elf_hash_table (info);
3713   BFD_ASSERT (htab != NULL);
3714
3715   g = htab->got_info;
3716   BFD_ASSERT (g != NULL);
3717
3718   entry.abfd = abfd;
3719   entry.symndx = symndx;
3720   entry.d.addend = addend;
3721   entry.tls_type = mips_elf_reloc_tls_type (r_type);
3722   return mips_elf_record_got_entry (info, abfd, &entry);
3723 }
3724
3725 /* Return the maximum number of GOT page entries required for RANGE.  */
3726
3727 static bfd_vma
3728 mips_elf_pages_for_range (const struct mips_got_page_range *range)
3729 {
3730   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
3731 }
3732
3733 /* Record that ABFD has a page relocation against symbol SYMNDX and
3734    that ADDEND is the addend for that relocation.
3735
3736    This function creates an upper bound on the number of GOT slots
3737    required; no attempt is made to combine references to non-overridable
3738    global symbols across multiple input files.  */
3739
3740 static bfd_boolean
3741 mips_elf_record_got_page_entry (struct bfd_link_info *info, bfd *abfd,
3742                                 long symndx, bfd_signed_vma addend)
3743 {
3744   struct mips_elf_link_hash_table *htab;
3745   struct mips_got_info *g1, *g2;
3746   struct mips_got_page_entry lookup, *entry;
3747   struct mips_got_page_range **range_ptr, *range;
3748   bfd_vma old_pages, new_pages;
3749   void **loc, **bfd_loc;
3750
3751   htab = mips_elf_hash_table (info);
3752   BFD_ASSERT (htab != NULL);
3753
3754   g1 = htab->got_info;
3755   BFD_ASSERT (g1 != NULL);
3756
3757   /* Find the mips_got_page_entry hash table entry for this symbol.  */
3758   lookup.abfd = abfd;
3759   lookup.symndx = symndx;
3760   loc = htab_find_slot (g1->got_page_entries, &lookup, INSERT);
3761   if (loc == NULL)
3762     return FALSE;
3763
3764   /* Create a mips_got_page_entry if this is the first time we've
3765      seen the symbol.  */
3766   entry = (struct mips_got_page_entry *) *loc;
3767   if (!entry)
3768     {
3769       entry = bfd_alloc (abfd, sizeof (*entry));
3770       if (!entry)
3771         return FALSE;
3772
3773       entry->abfd = abfd;
3774       entry->symndx = symndx;
3775       entry->ranges = NULL;
3776       entry->num_pages = 0;
3777       *loc = entry;
3778     }
3779
3780   /* Add the same entry to the BFD's GOT.  */
3781   g2 = mips_elf_bfd_got (abfd, TRUE);
3782   if (!g2)
3783     return FALSE;
3784
3785   bfd_loc = htab_find_slot (g2->got_page_entries, &lookup, INSERT);
3786   if (!bfd_loc)
3787     return FALSE;
3788
3789   if (!*bfd_loc)
3790     *bfd_loc = entry;
3791
3792   /* Skip over ranges whose maximum extent cannot share a page entry
3793      with ADDEND.  */
3794   range_ptr = &entry->ranges;
3795   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
3796     range_ptr = &(*range_ptr)->next;
3797
3798   /* If we scanned to the end of the list, or found a range whose
3799      minimum extent cannot share a page entry with ADDEND, create
3800      a new singleton range.  */
3801   range = *range_ptr;
3802   if (!range || addend < range->min_addend - 0xffff)
3803     {
3804       range = bfd_alloc (abfd, sizeof (*range));
3805       if (!range)
3806         return FALSE;
3807
3808       range->next = *range_ptr;
3809       range->min_addend = addend;
3810       range->max_addend = addend;
3811
3812       *range_ptr = range;
3813       entry->num_pages++;
3814       g1->page_gotno++;
3815       g2->page_gotno++;
3816       return TRUE;
3817     }
3818
3819   /* Remember how many pages the old range contributed.  */
3820   old_pages = mips_elf_pages_for_range (range);
3821
3822   /* Update the ranges.  */
3823   if (addend < range->min_addend)
3824     range->min_addend = addend;
3825   else if (addend > range->max_addend)
3826     {
3827       if (range->next && addend >= range->next->min_addend - 0xffff)
3828         {
3829           old_pages += mips_elf_pages_for_range (range->next);
3830           range->max_addend = range->next->max_addend;
3831           range->next = range->next->next;
3832         }
3833       else
3834         range->max_addend = addend;
3835     }
3836
3837   /* Record any change in the total estimate.  */
3838   new_pages = mips_elf_pages_for_range (range);
3839   if (old_pages != new_pages)
3840     {
3841       entry->num_pages += new_pages - old_pages;
3842       g1->page_gotno += new_pages - old_pages;
3843       g2->page_gotno += new_pages - old_pages;
3844     }
3845
3846   return TRUE;
3847 }
3848
3849 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
3850
3851 static void
3852 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
3853                                        unsigned int n)
3854 {
3855   asection *s;
3856   struct mips_elf_link_hash_table *htab;
3857
3858   htab = mips_elf_hash_table (info);
3859   BFD_ASSERT (htab != NULL);
3860
3861   s = mips_elf_rel_dyn_section (info, FALSE);
3862   BFD_ASSERT (s != NULL);
3863
3864   if (htab->is_vxworks)
3865     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
3866   else
3867     {
3868       if (s->size == 0)
3869         {
3870           /* Make room for a null element.  */
3871           s->size += MIPS_ELF_REL_SIZE (abfd);
3872           ++s->reloc_count;
3873         }
3874       s->size += n * MIPS_ELF_REL_SIZE (abfd);
3875     }
3876 }
3877 \f
3878 /* A htab_traverse callback for GOT entries.  Set boolean *DATA to true
3879    if the GOT entry is for an indirect or warning symbol.  */
3880
3881 static int
3882 mips_elf_check_recreate_got (void **entryp, void *data)
3883 {
3884   struct mips_got_entry *entry;
3885   bfd_boolean *must_recreate;
3886
3887   entry = (struct mips_got_entry *) *entryp;
3888   must_recreate = (bfd_boolean *) data;
3889   if (entry->abfd != NULL && entry->symndx == -1)
3890     {
3891       struct mips_elf_link_hash_entry *h;
3892
3893       h = entry->d.h;
3894       if (h->root.root.type == bfd_link_hash_indirect
3895           || h->root.root.type == bfd_link_hash_warning)
3896         {
3897           *must_recreate = TRUE;
3898           return 0;
3899         }
3900     }
3901   return 1;
3902 }
3903
3904 /* A htab_traverse callback for GOT entries.  Add all entries to
3905    hash table *DATA, converting entries for indirect and warning
3906    symbols into entries for the target symbol.  Set *DATA to null
3907    on error.  */
3908
3909 static int
3910 mips_elf_recreate_got (void **entryp, void *data)
3911 {
3912   htab_t *new_got;
3913   struct mips_got_entry new_entry, *entry;
3914   void **slot;
3915
3916   new_got = (htab_t *) data;
3917   entry = (struct mips_got_entry *) *entryp;
3918   if (entry->abfd != NULL
3919       && entry->symndx == -1
3920       && (entry->d.h->root.root.type == bfd_link_hash_indirect
3921           || entry->d.h->root.root.type == bfd_link_hash_warning))
3922     {
3923       struct mips_elf_link_hash_entry *h;
3924
3925       new_entry = *entry;
3926       entry = &new_entry;
3927       h = entry->d.h;
3928       do
3929         {
3930           BFD_ASSERT (h->global_got_area == GGA_NONE);
3931           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
3932         }
3933       while (h->root.root.type == bfd_link_hash_indirect
3934              || h->root.root.type == bfd_link_hash_warning);
3935       entry->d.h = h;
3936     }
3937   slot = htab_find_slot (*new_got, entry, INSERT);
3938   if (slot == NULL)
3939     {
3940       *new_got = NULL;
3941       return 0;
3942     }
3943   if (*slot == NULL)
3944     {
3945       if (entry == &new_entry)
3946         {
3947           entry = bfd_alloc (entry->abfd, sizeof (*entry));
3948           if (!entry)
3949             {
3950               *new_got = NULL;
3951               return 0;
3952             }
3953           *entry = new_entry;
3954         }
3955       *slot = entry;
3956     }
3957   return 1;
3958 }
3959
3960 /* If any entries in G->got_entries are for indirect or warning symbols,
3961    replace them with entries for the target symbol.  */
3962
3963 static bfd_boolean
3964 mips_elf_resolve_final_got_entries (struct mips_got_info *g)
3965 {
3966   bfd_boolean must_recreate;
3967   htab_t new_got;
3968
3969   must_recreate = FALSE;
3970   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &must_recreate);
3971   if (must_recreate)
3972     {
3973       new_got = htab_create (htab_size (g->got_entries),
3974                              mips_elf_got_entry_hash,
3975                              mips_elf_got_entry_eq, NULL);
3976       htab_traverse (g->got_entries, mips_elf_recreate_got, &new_got);
3977       if (new_got == NULL)
3978         return FALSE;
3979
3980       htab_delete (g->got_entries);
3981       g->got_entries = new_got;
3982     }
3983   return TRUE;
3984 }
3985
3986 /* A mips_elf_link_hash_traverse callback for which DATA points to the
3987    link_info structure.  Decide whether the hash entry needs an entry in
3988    the global part of the primary GOT, setting global_got_area accordingly.
3989    Count the number of global symbols that are in the primary GOT only
3990    because they have relocations against them (reloc_only_gotno).  */
3991
3992 static int
3993 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
3994 {
3995   struct bfd_link_info *info;
3996   struct mips_elf_link_hash_table *htab;
3997   struct mips_got_info *g;
3998
3999   info = (struct bfd_link_info *) data;
4000   htab = mips_elf_hash_table (info);
4001   g = htab->got_info;
4002   if (h->global_got_area != GGA_NONE)
4003     {
4004       /* Make a final decision about whether the symbol belongs in the
4005          local or global GOT.  Symbols that bind locally can (and in the
4006          case of forced-local symbols, must) live in the local GOT.
4007          Those that are aren't in the dynamic symbol table must also
4008          live in the local GOT.
4009
4010          Note that the former condition does not always imply the
4011          latter: symbols do not bind locally if they are completely
4012          undefined.  We'll report undefined symbols later if appropriate.  */
4013       if (h->root.dynindx == -1
4014           || (h->got_only_for_calls
4015               ? SYMBOL_CALLS_LOCAL (info, &h->root)
4016               : SYMBOL_REFERENCES_LOCAL (info, &h->root)))
4017         /* The symbol belongs in the local GOT.  We no longer need this
4018            entry if it was only used for relocations; those relocations
4019            will be against the null or section symbol instead of H.  */
4020         h->global_got_area = GGA_NONE;
4021       else if (htab->is_vxworks
4022                && h->got_only_for_calls
4023                && h->root.plt.offset != MINUS_ONE)
4024         /* On VxWorks, calls can refer directly to the .got.plt entry;
4025            they don't need entries in the regular GOT.  .got.plt entries
4026            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4027         h->global_got_area = GGA_NONE;
4028       else if (h->global_got_area == GGA_RELOC_ONLY)
4029         {
4030           g->reloc_only_gotno++;
4031           g->global_gotno++;
4032         }
4033     }
4034   return 1;
4035 }
4036 \f
4037 /* A htab_traverse callback for GOT entries.  Add each one to the GOT
4038    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4039
4040 static int
4041 mips_elf_add_got_entry (void **entryp, void *data)
4042 {
4043   struct mips_got_entry *entry;
4044   struct mips_elf_traverse_got_arg *arg;
4045   void **slot;
4046
4047   entry = (struct mips_got_entry *) *entryp;
4048   arg = (struct mips_elf_traverse_got_arg *) data;
4049   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
4050   if (!slot)
4051     {
4052       arg->g = NULL;
4053       return 0;
4054     }
4055   if (!*slot)
4056     {
4057       *slot = entry;
4058       mips_elf_count_got_entry (arg->info, arg->g, entry);
4059     }
4060   return 1;
4061 }
4062
4063 /* A htab_traverse callback for GOT page entries.  Add each one to the GOT
4064    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4065
4066 static int
4067 mips_elf_add_got_page_entry (void **entryp, void *data)
4068 {
4069   struct mips_got_page_entry *entry;
4070   struct mips_elf_traverse_got_arg *arg;
4071   void **slot;
4072
4073   entry = (struct mips_got_page_entry *) *entryp;
4074   arg = (struct mips_elf_traverse_got_arg *) data;
4075   slot = htab_find_slot (arg->g->got_page_entries, entry, INSERT);
4076   if (!slot)
4077     {
4078       arg->g = NULL;
4079       return 0;
4080     }
4081   if (!*slot)
4082     {
4083       *slot = entry;
4084       arg->g->page_gotno += entry->num_pages;
4085     }
4086   return 1;
4087 }
4088
4089 /* Consider merging FROM, which is ABFD's GOT, into TO.  Return -1 if
4090    this would lead to overflow, 1 if they were merged successfully,
4091    and 0 if a merge failed due to lack of memory.  (These values are chosen
4092    so that nonnegative return values can be returned by a htab_traverse
4093    callback.)  */
4094
4095 static int
4096 mips_elf_merge_got_with (bfd *abfd, struct mips_got_info *from,
4097                          struct mips_got_info *to,
4098                          struct mips_elf_got_per_bfd_arg *arg)
4099 {
4100   struct mips_elf_traverse_got_arg tga;
4101   unsigned int estimate;
4102
4103   /* Work out how many page entries we would need for the combined GOT.  */
4104   estimate = arg->max_pages;
4105   if (estimate >= from->page_gotno + to->page_gotno)
4106     estimate = from->page_gotno + to->page_gotno;
4107
4108   /* And conservatively estimate how many local and TLS entries
4109      would be needed.  */
4110   estimate += from->local_gotno + to->local_gotno;
4111   estimate += from->tls_gotno + to->tls_gotno;
4112
4113   /* If we're merging with the primary got, any TLS relocations will
4114      come after the full set of global entries.  Otherwise estimate those
4115      conservatively as well.  */
4116   if (to == arg->primary && from->tls_gotno + to->tls_gotno)
4117     estimate += arg->global_count;
4118   else
4119     estimate += from->global_gotno + to->global_gotno;
4120
4121   /* Bail out if the combined GOT might be too big.  */
4122   if (estimate > arg->max_count)
4123     return -1;
4124
4125   /* Transfer the bfd's got information from FROM to TO.  */
4126   tga.info = arg->info;
4127   tga.g = to;
4128   htab_traverse (from->got_entries, mips_elf_add_got_entry, &tga);
4129   if (!tga.g)
4130     return 0;
4131
4132   htab_traverse (from->got_page_entries, mips_elf_add_got_page_entry, &tga);
4133   if (!tga.g)
4134     return 0;
4135
4136   mips_elf_replace_bfd_got (abfd, to);
4137   return 1;
4138 }
4139
4140 /* Attempt to merge GOT G, which belongs to ABFD.  Try to use as much
4141    as possible of the primary got, since it doesn't require explicit
4142    dynamic relocations, but don't use bfds that would reference global
4143    symbols out of the addressable range.  Failing the primary got,
4144    attempt to merge with the current got, or finish the current got
4145    and then make make the new got current.  */
4146
4147 static bfd_boolean
4148 mips_elf_merge_got (bfd *abfd, struct mips_got_info *g,
4149                     struct mips_elf_got_per_bfd_arg *arg)
4150 {
4151   struct mips_elf_traverse_got_arg tga;
4152   unsigned int estimate;
4153   int result;
4154
4155   if (!mips_elf_resolve_final_got_entries (g))
4156     return FALSE;
4157
4158   tga.info = arg->info;
4159   tga.g = g;
4160   htab_traverse (g->got_entries, mips_elf_count_got_entries, &tga);
4161
4162   /* Work out the number of page, local and TLS entries.  */
4163   estimate = arg->max_pages;
4164   if (estimate > g->page_gotno)
4165     estimate = g->page_gotno;
4166   estimate += g->local_gotno + g->tls_gotno;
4167
4168   /* We place TLS GOT entries after both locals and globals.  The globals
4169      for the primary GOT may overflow the normal GOT size limit, so be
4170      sure not to merge a GOT which requires TLS with the primary GOT in that
4171      case.  This doesn't affect non-primary GOTs.  */
4172   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4173
4174   if (estimate <= arg->max_count)
4175     {
4176       /* If we don't have a primary GOT, use it as
4177          a starting point for the primary GOT.  */
4178       if (!arg->primary)
4179         {
4180           arg->primary = g;
4181           return TRUE;
4182         }
4183
4184       /* Try merging with the primary GOT.  */
4185       result = mips_elf_merge_got_with (abfd, g, arg->primary, arg);
4186       if (result >= 0)
4187         return result;
4188     }
4189
4190   /* If we can merge with the last-created got, do it.  */
4191   if (arg->current)
4192     {
4193       result = mips_elf_merge_got_with (abfd, g, arg->current, arg);
4194       if (result >= 0)
4195         return result;
4196     }
4197
4198   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4199      fits; if it turns out that it doesn't, we'll get relocation
4200      overflows anyway.  */
4201   g->next = arg->current;
4202   arg->current = g;
4203
4204   return TRUE;
4205 }
4206
4207 /* ENTRYP is a hash table entry for a mips_got_entry.  Set its gotidx
4208    to GOTIDX, duplicating the entry if it has already been assigned
4209    an index in a different GOT.  */
4210
4211 static bfd_boolean
4212 mips_elf_set_gotidx (void **entryp, long gotidx)
4213 {
4214   struct mips_got_entry *entry;
4215
4216   entry = (struct mips_got_entry *) *entryp;
4217   if (entry->gotidx > 0)
4218     {
4219       struct mips_got_entry *new_entry;
4220
4221       new_entry = bfd_alloc (entry->abfd, sizeof (*entry));
4222       if (!new_entry)
4223         return FALSE;
4224
4225       *new_entry = *entry;
4226       *entryp = new_entry;
4227       entry = new_entry;
4228     }
4229   entry->gotidx = gotidx;
4230   return TRUE;
4231 }
4232
4233 /* Set the TLS GOT index for the GOT entry in ENTRYP.  DATA points to a
4234    mips_elf_traverse_got_arg in which DATA->value is the size of one
4235    GOT entry.  Set DATA->g to null on failure.  */
4236
4237 static int
4238 mips_elf_initialize_tls_index (void **entryp, void *data)
4239 {
4240   struct mips_got_entry *entry;
4241   struct mips_elf_traverse_got_arg *arg;
4242   unsigned char tls_type;
4243
4244   /* We're only interested in TLS symbols.  */
4245   entry = (struct mips_got_entry *) *entryp;
4246   tls_type = (entry->tls_type & GOT_TLS_TYPE);
4247   if (tls_type == 0)
4248     return 1;
4249
4250   arg = (struct mips_elf_traverse_got_arg *) data;
4251   if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->tls_assigned_gotno))
4252     {
4253       arg->g = NULL;
4254       return 0;
4255     }
4256
4257   /* Account for the entries we've just allocated.  */
4258   arg->g->tls_assigned_gotno += mips_tls_got_entries (tls_type);
4259   return 1;
4260 }
4261
4262 /* A htab_traverse callback for GOT entries, where DATA points to a
4263    mips_elf_traverse_got_arg.  Set the global_got_area of each global
4264    symbol to DATA->value.  */
4265
4266 static int
4267 mips_elf_set_global_got_area (void **entryp, void *data)
4268 {
4269   struct mips_got_entry *entry;
4270   struct mips_elf_traverse_got_arg *arg;
4271
4272   entry = (struct mips_got_entry *) *entryp;
4273   arg = (struct mips_elf_traverse_got_arg *) data;
4274   if (entry->abfd != NULL
4275       && entry->symndx == -1
4276       && entry->d.h->global_got_area != GGA_NONE)
4277     entry->d.h->global_got_area = arg->value;
4278   return 1;
4279 }
4280
4281 /* A htab_traverse callback for secondary GOT entries, where DATA points
4282    to a mips_elf_traverse_got_arg.  Assign GOT indices to global entries
4283    and record the number of relocations they require.  DATA->value is
4284    the size of one GOT entry.  Set DATA->g to null on failure.  */
4285
4286 static int
4287 mips_elf_set_global_gotidx (void **entryp, void *data)
4288 {
4289   struct mips_got_entry *entry;
4290   struct mips_elf_traverse_got_arg *arg;
4291
4292   entry = (struct mips_got_entry *) *entryp;
4293   arg = (struct mips_elf_traverse_got_arg *) data;
4294   if (entry->abfd != NULL
4295       && entry->symndx == -1
4296       && entry->d.h->global_got_area != GGA_NONE)
4297     {
4298       if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->assigned_gotno))
4299         {
4300           arg->g = NULL;
4301           return 0;
4302         }
4303       arg->g->assigned_gotno += 1;
4304
4305       if (arg->info->shared
4306           || (elf_hash_table (arg->info)->dynamic_sections_created
4307               && entry->d.h->root.def_dynamic
4308               && !entry->d.h->root.def_regular))
4309         arg->g->relocs += 1;
4310     }
4311
4312   return 1;
4313 }
4314
4315 /* A htab_traverse callback for GOT entries for which DATA is the
4316    bfd_link_info.  Forbid any global symbols from having traditional
4317    lazy-binding stubs.  */
4318
4319 static int
4320 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4321 {
4322   struct bfd_link_info *info;
4323   struct mips_elf_link_hash_table *htab;
4324   struct mips_got_entry *entry;
4325
4326   entry = (struct mips_got_entry *) *entryp;
4327   info = (struct bfd_link_info *) data;
4328   htab = mips_elf_hash_table (info);
4329   BFD_ASSERT (htab != NULL);
4330
4331   if (entry->abfd != NULL
4332       && entry->symndx == -1
4333       && entry->d.h->needs_lazy_stub)
4334     {
4335       entry->d.h->needs_lazy_stub = FALSE;
4336       htab->lazy_stub_count--;
4337     }
4338
4339   return 1;
4340 }
4341
4342 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4343    the primary GOT.  */
4344 static bfd_vma
4345 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4346 {
4347   if (!g->next)
4348     return 0;
4349
4350   g = mips_elf_bfd_got (ibfd, FALSE);
4351   if (! g)
4352     return 0;
4353
4354   BFD_ASSERT (g->next);
4355
4356   g = g->next;
4357
4358   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4359     * MIPS_ELF_GOT_SIZE (abfd);
4360 }
4361
4362 /* Turn a single GOT that is too big for 16-bit addressing into
4363    a sequence of GOTs, each one 16-bit addressable.  */
4364
4365 static bfd_boolean
4366 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4367                     asection *got, bfd_size_type pages)
4368 {
4369   struct mips_elf_link_hash_table *htab;
4370   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4371   struct mips_elf_traverse_got_arg tga;
4372   struct mips_got_info *g, *gg;
4373   unsigned int assign, needed_relocs;
4374   bfd *dynobj, *ibfd;
4375
4376   dynobj = elf_hash_table (info)->dynobj;
4377   htab = mips_elf_hash_table (info);
4378   BFD_ASSERT (htab != NULL);
4379
4380   g = htab->got_info;
4381
4382   got_per_bfd_arg.obfd = abfd;
4383   got_per_bfd_arg.info = info;
4384   got_per_bfd_arg.current = NULL;
4385   got_per_bfd_arg.primary = NULL;
4386   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4387                                 / MIPS_ELF_GOT_SIZE (abfd))
4388                                - htab->reserved_gotno);
4389   got_per_bfd_arg.max_pages = pages;
4390   /* The number of globals that will be included in the primary GOT.
4391      See the calls to mips_elf_set_global_got_area below for more
4392      information.  */
4393   got_per_bfd_arg.global_count = g->global_gotno;
4394
4395   /* Try to merge the GOTs of input bfds together, as long as they
4396      don't seem to exceed the maximum GOT size, choosing one of them
4397      to be the primary GOT.  */
4398   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
4399     {
4400       gg = mips_elf_bfd_got (ibfd, FALSE);
4401       if (gg && !mips_elf_merge_got (ibfd, gg, &got_per_bfd_arg))
4402         return FALSE;
4403     }
4404
4405   /* If we do not find any suitable primary GOT, create an empty one.  */
4406   if (got_per_bfd_arg.primary == NULL)
4407     g->next = mips_elf_create_got_info (abfd);
4408   else
4409     g->next = got_per_bfd_arg.primary;
4410   g->next->next = got_per_bfd_arg.current;
4411
4412   /* GG is now the master GOT, and G is the primary GOT.  */
4413   gg = g;
4414   g = g->next;
4415
4416   /* Map the output bfd to the primary got.  That's what we're going
4417      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4418      didn't mark in check_relocs, and we want a quick way to find it.
4419      We can't just use gg->next because we're going to reverse the
4420      list.  */
4421   mips_elf_replace_bfd_got (abfd, g);
4422
4423   /* Every symbol that is referenced in a dynamic relocation must be
4424      present in the primary GOT, so arrange for them to appear after
4425      those that are actually referenced.  */
4426   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4427   g->global_gotno = gg->global_gotno;
4428
4429   tga.info = info;
4430   tga.value = GGA_RELOC_ONLY;
4431   htab_traverse (gg->got_entries, mips_elf_set_global_got_area, &tga);
4432   tga.value = GGA_NORMAL;
4433   htab_traverse (g->got_entries, mips_elf_set_global_got_area, &tga);
4434
4435   /* Now go through the GOTs assigning them offset ranges.
4436      [assigned_gotno, local_gotno[ will be set to the range of local
4437      entries in each GOT.  We can then compute the end of a GOT by
4438      adding local_gotno to global_gotno.  We reverse the list and make
4439      it circular since then we'll be able to quickly compute the
4440      beginning of a GOT, by computing the end of its predecessor.  To
4441      avoid special cases for the primary GOT, while still preserving
4442      assertions that are valid for both single- and multi-got links,
4443      we arrange for the main got struct to have the right number of
4444      global entries, but set its local_gotno such that the initial
4445      offset of the primary GOT is zero.  Remember that the primary GOT
4446      will become the last item in the circular linked list, so it
4447      points back to the master GOT.  */
4448   gg->local_gotno = -g->global_gotno;
4449   gg->global_gotno = g->global_gotno;
4450   gg->tls_gotno = 0;
4451   assign = 0;
4452   gg->next = gg;
4453
4454   do
4455     {
4456       struct mips_got_info *gn;
4457
4458       assign += htab->reserved_gotno;
4459       g->assigned_gotno = assign;
4460       g->local_gotno += assign;
4461       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4462       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4463
4464       /* Take g out of the direct list, and push it onto the reversed
4465          list that gg points to.  g->next is guaranteed to be nonnull after
4466          this operation, as required by mips_elf_initialize_tls_index. */
4467       gn = g->next;
4468       g->next = gg->next;
4469       gg->next = g;
4470
4471       /* Set up any TLS entries.  We always place the TLS entries after
4472          all non-TLS entries.  */
4473       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4474       tga.g = g;
4475       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4476       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
4477       if (!tga.g)
4478         return FALSE;
4479       BFD_ASSERT (g->tls_assigned_gotno == assign);
4480
4481       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4482       g = gn;
4483
4484       /* Forbid global symbols in every non-primary GOT from having
4485          lazy-binding stubs.  */
4486       if (g)
4487         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4488     }
4489   while (g);
4490
4491   got->size = assign * MIPS_ELF_GOT_SIZE (abfd);
4492
4493   needed_relocs = 0;
4494   for (g = gg->next; g && g->next != gg; g = g->next)
4495     {
4496       unsigned int save_assign;
4497
4498       /* Assign offsets to global GOT entries and count how many
4499          relocations they need.  */
4500       save_assign = g->assigned_gotno;
4501       g->assigned_gotno = g->local_gotno;
4502       tga.info = info;
4503       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4504       tga.g = g;
4505       htab_traverse (g->got_entries, mips_elf_set_global_gotidx, &tga);
4506       if (!tga.g)
4507         return FALSE;
4508       BFD_ASSERT (g->assigned_gotno == g->local_gotno + g->global_gotno);
4509       g->assigned_gotno = save_assign;
4510
4511       if (info->shared)
4512         {
4513           g->relocs += g->local_gotno - g->assigned_gotno;
4514           BFD_ASSERT (g->assigned_gotno == g->next->local_gotno
4515                       + g->next->global_gotno
4516                       + g->next->tls_gotno
4517                       + htab->reserved_gotno);
4518         }
4519       needed_relocs += g->relocs;
4520     }
4521   needed_relocs += g->relocs;
4522
4523   if (needed_relocs)
4524     mips_elf_allocate_dynamic_relocations (dynobj, info,
4525                                            needed_relocs);
4526
4527   return TRUE;
4528 }
4529
4530 \f
4531 /* Returns the first relocation of type r_type found, beginning with
4532    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4533
4534 static const Elf_Internal_Rela *
4535 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4536                           const Elf_Internal_Rela *relocation,
4537                           const Elf_Internal_Rela *relend)
4538 {
4539   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4540
4541   while (relocation < relend)
4542     {
4543       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4544           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4545         return relocation;
4546
4547       ++relocation;
4548     }
4549
4550   /* We didn't find it.  */
4551   return NULL;
4552 }
4553
4554 /* Return whether an input relocation is against a local symbol.  */
4555
4556 static bfd_boolean
4557 mips_elf_local_relocation_p (bfd *input_bfd,
4558                              const Elf_Internal_Rela *relocation,
4559                              asection **local_sections)
4560 {
4561   unsigned long r_symndx;
4562   Elf_Internal_Shdr *symtab_hdr;
4563   size_t extsymoff;
4564
4565   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4566   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4567   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
4568
4569   if (r_symndx < extsymoff)
4570     return TRUE;
4571   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
4572     return TRUE;
4573
4574   return FALSE;
4575 }
4576 \f
4577 /* Sign-extend VALUE, which has the indicated number of BITS.  */
4578
4579 bfd_vma
4580 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
4581 {
4582   if (value & ((bfd_vma) 1 << (bits - 1)))
4583     /* VALUE is negative.  */
4584     value |= ((bfd_vma) - 1) << bits;
4585
4586   return value;
4587 }
4588
4589 /* Return non-zero if the indicated VALUE has overflowed the maximum
4590    range expressible by a signed number with the indicated number of
4591    BITS.  */
4592
4593 static bfd_boolean
4594 mips_elf_overflow_p (bfd_vma value, int bits)
4595 {
4596   bfd_signed_vma svalue = (bfd_signed_vma) value;
4597
4598   if (svalue > (1 << (bits - 1)) - 1)
4599     /* The value is too big.  */
4600     return TRUE;
4601   else if (svalue < -(1 << (bits - 1)))
4602     /* The value is too small.  */
4603     return TRUE;
4604
4605   /* All is well.  */
4606   return FALSE;
4607 }
4608
4609 /* Calculate the %high function.  */
4610
4611 static bfd_vma
4612 mips_elf_high (bfd_vma value)
4613 {
4614   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
4615 }
4616
4617 /* Calculate the %higher function.  */
4618
4619 static bfd_vma
4620 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
4621 {
4622 #ifdef BFD64
4623   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
4624 #else
4625   abort ();
4626   return MINUS_ONE;
4627 #endif
4628 }
4629
4630 /* Calculate the %highest function.  */
4631
4632 static bfd_vma
4633 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
4634 {
4635 #ifdef BFD64
4636   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
4637 #else
4638   abort ();
4639   return MINUS_ONE;
4640 #endif
4641 }
4642 \f
4643 /* Create the .compact_rel section.  */
4644
4645 static bfd_boolean
4646 mips_elf_create_compact_rel_section
4647   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
4648 {
4649   flagword flags;
4650   register asection *s;
4651
4652   if (bfd_get_linker_section (abfd, ".compact_rel") == NULL)
4653     {
4654       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
4655                | SEC_READONLY);
4656
4657       s = bfd_make_section_anyway_with_flags (abfd, ".compact_rel", flags);
4658       if (s == NULL
4659           || ! bfd_set_section_alignment (abfd, s,
4660                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
4661         return FALSE;
4662
4663       s->size = sizeof (Elf32_External_compact_rel);
4664     }
4665
4666   return TRUE;
4667 }
4668
4669 /* Create the .got section to hold the global offset table.  */
4670
4671 static bfd_boolean
4672 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
4673 {
4674   flagword flags;
4675   register asection *s;
4676   struct elf_link_hash_entry *h;
4677   struct bfd_link_hash_entry *bh;
4678   struct mips_elf_link_hash_table *htab;
4679
4680   htab = mips_elf_hash_table (info);
4681   BFD_ASSERT (htab != NULL);
4682
4683   /* This function may be called more than once.  */
4684   if (htab->sgot)
4685     return TRUE;
4686
4687   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
4688            | SEC_LINKER_CREATED);
4689
4690   /* We have to use an alignment of 2**4 here because this is hardcoded
4691      in the function stub generation and in the linker script.  */
4692   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
4693   if (s == NULL
4694       || ! bfd_set_section_alignment (abfd, s, 4))
4695     return FALSE;
4696   htab->sgot = s;
4697
4698   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
4699      linker script because we don't want to define the symbol if we
4700      are not creating a global offset table.  */
4701   bh = NULL;
4702   if (! (_bfd_generic_link_add_one_symbol
4703          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
4704           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
4705     return FALSE;
4706
4707   h = (struct elf_link_hash_entry *) bh;
4708   h->non_elf = 0;
4709   h->def_regular = 1;
4710   h->type = STT_OBJECT;
4711   elf_hash_table (info)->hgot = h;
4712
4713   if (info->shared
4714       && ! bfd_elf_link_record_dynamic_symbol (info, h))
4715     return FALSE;
4716
4717   htab->got_info = mips_elf_create_got_info (abfd);
4718   mips_elf_section_data (s)->elf.this_hdr.sh_flags
4719     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
4720
4721   /* We also need a .got.plt section when generating PLTs.  */
4722   s = bfd_make_section_anyway_with_flags (abfd, ".got.plt",
4723                                           SEC_ALLOC | SEC_LOAD
4724                                           | SEC_HAS_CONTENTS
4725                                           | SEC_IN_MEMORY
4726                                           | SEC_LINKER_CREATED);
4727   if (s == NULL)
4728     return FALSE;
4729   htab->sgotplt = s;
4730
4731   return TRUE;
4732 }
4733 \f
4734 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
4735    __GOTT_INDEX__ symbols.  These symbols are only special for
4736    shared objects; they are not used in executables.  */
4737
4738 static bfd_boolean
4739 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
4740 {
4741   return (mips_elf_hash_table (info)->is_vxworks
4742           && info->shared
4743           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
4744               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
4745 }
4746
4747 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
4748    require an la25 stub.  See also mips_elf_local_pic_function_p,
4749    which determines whether the destination function ever requires a
4750    stub.  */
4751
4752 static bfd_boolean
4753 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type,
4754                                      bfd_boolean target_is_16_bit_code_p)
4755 {
4756   /* We specifically ignore branches and jumps from EF_PIC objects,
4757      where the onus is on the compiler or programmer to perform any
4758      necessary initialization of $25.  Sometimes such initialization
4759      is unnecessary; for example, -mno-shared functions do not use
4760      the incoming value of $25, and may therefore be called directly.  */
4761   if (PIC_OBJECT_P (input_bfd))
4762     return FALSE;
4763
4764   switch (r_type)
4765     {
4766     case R_MIPS_26:
4767     case R_MIPS_PC16:
4768     case R_MICROMIPS_26_S1:
4769     case R_MICROMIPS_PC7_S1:
4770     case R_MICROMIPS_PC10_S1:
4771     case R_MICROMIPS_PC16_S1:
4772     case R_MICROMIPS_PC23_S2:
4773       return TRUE;
4774
4775     case R_MIPS16_26:
4776       return !target_is_16_bit_code_p;
4777
4778     default:
4779       return FALSE;
4780     }
4781 }
4782 \f
4783 /* Calculate the value produced by the RELOCATION (which comes from
4784    the INPUT_BFD).  The ADDEND is the addend to use for this
4785    RELOCATION; RELOCATION->R_ADDEND is ignored.
4786
4787    The result of the relocation calculation is stored in VALUEP.
4788    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
4789    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
4790
4791    This function returns bfd_reloc_continue if the caller need take no
4792    further action regarding this relocation, bfd_reloc_notsupported if
4793    something goes dramatically wrong, bfd_reloc_overflow if an
4794    overflow occurs, and bfd_reloc_ok to indicate success.  */
4795
4796 static bfd_reloc_status_type
4797 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
4798                                asection *input_section,
4799                                struct bfd_link_info *info,
4800                                const Elf_Internal_Rela *relocation,
4801                                bfd_vma addend, reloc_howto_type *howto,
4802                                Elf_Internal_Sym *local_syms,
4803                                asection **local_sections, bfd_vma *valuep,
4804                                const char **namep,
4805                                bfd_boolean *cross_mode_jump_p,
4806                                bfd_boolean save_addend)
4807 {
4808   /* The eventual value we will return.  */
4809   bfd_vma value;
4810   /* The address of the symbol against which the relocation is
4811      occurring.  */
4812   bfd_vma symbol = 0;
4813   /* The final GP value to be used for the relocatable, executable, or
4814      shared object file being produced.  */
4815   bfd_vma gp;
4816   /* The place (section offset or address) of the storage unit being
4817      relocated.  */
4818   bfd_vma p;
4819   /* The value of GP used to create the relocatable object.  */
4820   bfd_vma gp0;
4821   /* The offset into the global offset table at which the address of
4822      the relocation entry symbol, adjusted by the addend, resides
4823      during execution.  */
4824   bfd_vma g = MINUS_ONE;
4825   /* The section in which the symbol referenced by the relocation is
4826      located.  */
4827   asection *sec = NULL;
4828   struct mips_elf_link_hash_entry *h = NULL;
4829   /* TRUE if the symbol referred to by this relocation is a local
4830      symbol.  */
4831   bfd_boolean local_p, was_local_p;
4832   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
4833   bfd_boolean gp_disp_p = FALSE;
4834   /* TRUE if the symbol referred to by this relocation is
4835      "__gnu_local_gp".  */
4836   bfd_boolean gnu_local_gp_p = FALSE;
4837   Elf_Internal_Shdr *symtab_hdr;
4838   size_t extsymoff;
4839   unsigned long r_symndx;
4840   int r_type;
4841   /* TRUE if overflow occurred during the calculation of the
4842      relocation value.  */
4843   bfd_boolean overflowed_p;
4844   /* TRUE if this relocation refers to a MIPS16 function.  */
4845   bfd_boolean target_is_16_bit_code_p = FALSE;
4846   bfd_boolean target_is_micromips_code_p = FALSE;
4847   struct mips_elf_link_hash_table *htab;
4848   bfd *dynobj;
4849
4850   dynobj = elf_hash_table (info)->dynobj;
4851   htab = mips_elf_hash_table (info);
4852   BFD_ASSERT (htab != NULL);
4853
4854   /* Parse the relocation.  */
4855   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4856   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
4857   p = (input_section->output_section->vma
4858        + input_section->output_offset
4859        + relocation->r_offset);
4860
4861   /* Assume that there will be no overflow.  */
4862   overflowed_p = FALSE;
4863
4864   /* Figure out whether or not the symbol is local, and get the offset
4865      used in the array of hash table entries.  */
4866   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4867   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
4868                                          local_sections);
4869   was_local_p = local_p;
4870   if (! elf_bad_symtab (input_bfd))
4871     extsymoff = symtab_hdr->sh_info;
4872   else
4873     {
4874       /* The symbol table does not follow the rule that local symbols
4875          must come before globals.  */
4876       extsymoff = 0;
4877     }
4878
4879   /* Figure out the value of the symbol.  */
4880   if (local_p)
4881     {
4882       Elf_Internal_Sym *sym;
4883
4884       sym = local_syms + r_symndx;
4885       sec = local_sections[r_symndx];
4886
4887       symbol = sec->output_section->vma + sec->output_offset;
4888       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION
4889           || (sec->flags & SEC_MERGE))
4890         symbol += sym->st_value;
4891       if ((sec->flags & SEC_MERGE)
4892           && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
4893         {
4894           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
4895           addend -= symbol;
4896           addend += sec->output_section->vma + sec->output_offset;
4897         }
4898
4899       /* MIPS16/microMIPS text labels should be treated as odd.  */
4900       if (ELF_ST_IS_COMPRESSED (sym->st_other))
4901         ++symbol;
4902
4903       /* Record the name of this symbol, for our caller.  */
4904       *namep = bfd_elf_string_from_elf_section (input_bfd,
4905                                                 symtab_hdr->sh_link,
4906                                                 sym->st_name);
4907       if (*namep == '\0')
4908         *namep = bfd_section_name (input_bfd, sec);
4909
4910       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
4911       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
4912     }
4913   else
4914     {
4915       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
4916
4917       /* For global symbols we look up the symbol in the hash-table.  */
4918       h = ((struct mips_elf_link_hash_entry *)
4919            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
4920       /* Find the real hash-table entry for this symbol.  */
4921       while (h->root.root.type == bfd_link_hash_indirect
4922              || h->root.root.type == bfd_link_hash_warning)
4923         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
4924
4925       /* Record the name of this symbol, for our caller.  */
4926       *namep = h->root.root.root.string;
4927
4928       /* See if this is the special _gp_disp symbol.  Note that such a
4929          symbol must always be a global symbol.  */
4930       if (strcmp (*namep, "_gp_disp") == 0
4931           && ! NEWABI_P (input_bfd))
4932         {
4933           /* Relocations against _gp_disp are permitted only with
4934              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
4935           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
4936             return bfd_reloc_notsupported;
4937
4938           gp_disp_p = TRUE;
4939         }
4940       /* See if this is the special _gp symbol.  Note that such a
4941          symbol must always be a global symbol.  */
4942       else if (strcmp (*namep, "__gnu_local_gp") == 0)
4943         gnu_local_gp_p = TRUE;
4944
4945
4946       /* If this symbol is defined, calculate its address.  Note that
4947          _gp_disp is a magic symbol, always implicitly defined by the
4948          linker, so it's inappropriate to check to see whether or not
4949          its defined.  */
4950       else if ((h->root.root.type == bfd_link_hash_defined
4951                 || h->root.root.type == bfd_link_hash_defweak)
4952                && h->root.root.u.def.section)
4953         {
4954           sec = h->root.root.u.def.section;
4955           if (sec->output_section)
4956             symbol = (h->root.root.u.def.value
4957                       + sec->output_section->vma
4958                       + sec->output_offset);
4959           else
4960             symbol = h->root.root.u.def.value;
4961         }
4962       else if (h->root.root.type == bfd_link_hash_undefweak)
4963         /* We allow relocations against undefined weak symbols, giving
4964            it the value zero, so that you can undefined weak functions
4965            and check to see if they exist by looking at their
4966            addresses.  */
4967         symbol = 0;
4968       else if (info->unresolved_syms_in_objects == RM_IGNORE
4969                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
4970         symbol = 0;
4971       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
4972                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
4973         {
4974           /* If this is a dynamic link, we should have created a
4975              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
4976              in in _bfd_mips_elf_create_dynamic_sections.
4977              Otherwise, we should define the symbol with a value of 0.
4978              FIXME: It should probably get into the symbol table
4979              somehow as well.  */
4980           BFD_ASSERT (! info->shared);
4981           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
4982           symbol = 0;
4983         }
4984       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
4985         {
4986           /* This is an optional symbol - an Irix specific extension to the
4987              ELF spec.  Ignore it for now.
4988              XXX - FIXME - there is more to the spec for OPTIONAL symbols
4989              than simply ignoring them, but we do not handle this for now.
4990              For information see the "64-bit ELF Object File Specification"
4991              which is available from here:
4992              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
4993           symbol = 0;
4994         }
4995       else if ((*info->callbacks->undefined_symbol)
4996                (info, h->root.root.root.string, input_bfd,
4997                 input_section, relocation->r_offset,
4998                 (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
4999                  || ELF_ST_VISIBILITY (h->root.other)))
5000         {
5001           return bfd_reloc_undefined;
5002         }
5003       else
5004         {
5005           return bfd_reloc_notsupported;
5006         }
5007
5008       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
5009       /* If the output section is the PLT section,
5010          then the target is not microMIPS.  */
5011       target_is_micromips_code_p = (htab->splt != sec
5012                                     && ELF_ST_IS_MICROMIPS (h->root.other));
5013     }
5014
5015   /* If this is a reference to a 16-bit function with a stub, we need
5016      to redirect the relocation to the stub unless:
5017
5018      (a) the relocation is for a MIPS16 JAL;
5019
5020      (b) the relocation is for a MIPS16 PIC call, and there are no
5021          non-MIPS16 uses of the GOT slot; or
5022
5023      (c) the section allows direct references to MIPS16 functions.  */
5024   if (r_type != R_MIPS16_26
5025       && !info->relocatable
5026       && ((h != NULL
5027            && h->fn_stub != NULL
5028            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5029           || (local_p
5030               && elf_tdata (input_bfd)->local_stubs != NULL
5031               && elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5032       && !section_allows_mips16_refs_p (input_section))
5033     {
5034       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5035          have already noticed that we were going to need the
5036          stub.  */
5037       if (local_p)
5038         {
5039           sec = elf_tdata (input_bfd)->local_stubs[r_symndx];
5040           value = 0;
5041         }
5042       else
5043         {
5044           BFD_ASSERT (h->need_fn_stub);
5045           if (h->la25_stub)
5046             {
5047               /* If a LA25 header for the stub itself exists, point to the
5048                  prepended LUI/ADDIU sequence.  */
5049               sec = h->la25_stub->stub_section;
5050               value = h->la25_stub->offset;
5051             }
5052           else
5053             {
5054               sec = h->fn_stub;
5055               value = 0;
5056             }
5057         }
5058
5059       symbol = sec->output_section->vma + sec->output_offset + value;
5060       /* The target is 16-bit, but the stub isn't.  */
5061       target_is_16_bit_code_p = FALSE;
5062     }
5063   /* If this is a 16-bit call to a 32- or 64-bit function with a stub, we
5064      need to redirect the call to the stub.  Note that we specifically
5065      exclude R_MIPS16_CALL16 from this behavior; indirect calls should
5066      use an indirect stub instead.  */
5067   else if (r_type == R_MIPS16_26 && !info->relocatable
5068            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5069                || (local_p
5070                    && elf_tdata (input_bfd)->local_call_stubs != NULL
5071                    && elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5072            && !target_is_16_bit_code_p)
5073     {
5074       if (local_p)
5075         sec = elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5076       else
5077         {
5078           /* If both call_stub and call_fp_stub are defined, we can figure
5079              out which one to use by checking which one appears in the input
5080              file.  */
5081           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5082             {
5083               asection *o;
5084
5085               sec = NULL;
5086               for (o = input_bfd->sections; o != NULL; o = o->next)
5087                 {
5088                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5089                     {
5090                       sec = h->call_fp_stub;
5091                       break;
5092                     }
5093                 }
5094               if (sec == NULL)
5095                 sec = h->call_stub;
5096             }
5097           else if (h->call_stub != NULL)
5098             sec = h->call_stub;
5099           else
5100             sec = h->call_fp_stub;
5101         }
5102
5103       BFD_ASSERT (sec->size > 0);
5104       symbol = sec->output_section->vma + sec->output_offset;
5105     }
5106   /* If this is a direct call to a PIC function, redirect to the
5107      non-PIC stub.  */
5108   else if (h != NULL && h->la25_stub
5109            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type,
5110                                                    target_is_16_bit_code_p))
5111     symbol = (h->la25_stub->stub_section->output_section->vma
5112               + h->la25_stub->stub_section->output_offset
5113               + h->la25_stub->offset);
5114
5115   /* Make sure MIPS16 and microMIPS are not used together.  */
5116   if ((r_type == R_MIPS16_26 && target_is_micromips_code_p)
5117       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5118    {
5119       (*_bfd_error_handler)
5120         (_("MIPS16 and microMIPS functions cannot call each other"));
5121       return bfd_reloc_notsupported;
5122    }
5123
5124   /* Calls from 16-bit code to 32-bit code and vice versa require the
5125      mode change.  However, we can ignore calls to undefined weak symbols,
5126      which should never be executed at runtime.  This exception is important
5127      because the assembly writer may have "known" that any definition of the
5128      symbol would be 16-bit code, and that direct jumps were therefore
5129      acceptable.  */
5130   *cross_mode_jump_p = (!info->relocatable
5131                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5132                         && ((r_type == R_MIPS16_26 && !target_is_16_bit_code_p)
5133                             || (r_type == R_MICROMIPS_26_S1
5134                                 && !target_is_micromips_code_p)
5135                             || ((r_type == R_MIPS_26 || r_type == R_MIPS_JALR)
5136                                 && (target_is_16_bit_code_p
5137                                     || target_is_micromips_code_p))));
5138
5139   local_p = (h == NULL
5140              || (h->got_only_for_calls
5141                  ? SYMBOL_CALLS_LOCAL (info, &h->root)
5142                  : SYMBOL_REFERENCES_LOCAL (info, &h->root)));
5143
5144   gp0 = _bfd_get_gp_value (input_bfd);
5145   gp = _bfd_get_gp_value (abfd);
5146   if (htab->got_info)
5147     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5148
5149   if (gnu_local_gp_p)
5150     symbol = gp;
5151
5152   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5153      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5154      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5155   if (got_page_reloc_p (r_type) && !local_p)
5156     {
5157       r_type = (micromips_reloc_p (r_type)
5158                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5159       addend = 0;
5160     }
5161
5162   /* If we haven't already determined the GOT offset, and we're going
5163      to need it, get it now.  */
5164   switch (r_type)
5165     {
5166     case R_MIPS16_CALL16:
5167     case R_MIPS16_GOT16:
5168     case R_MIPS_CALL16:
5169     case R_MIPS_GOT16:
5170     case R_MIPS_GOT_DISP:
5171     case R_MIPS_GOT_HI16:
5172     case R_MIPS_CALL_HI16:
5173     case R_MIPS_GOT_LO16:
5174     case R_MIPS_CALL_LO16:
5175     case R_MICROMIPS_CALL16:
5176     case R_MICROMIPS_GOT16:
5177     case R_MICROMIPS_GOT_DISP:
5178     case R_MICROMIPS_GOT_HI16:
5179     case R_MICROMIPS_CALL_HI16:
5180     case R_MICROMIPS_GOT_LO16:
5181     case R_MICROMIPS_CALL_LO16:
5182     case R_MIPS_TLS_GD:
5183     case R_MIPS_TLS_GOTTPREL:
5184     case R_MIPS_TLS_LDM:
5185     case R_MIPS16_TLS_GD:
5186     case R_MIPS16_TLS_GOTTPREL:
5187     case R_MIPS16_TLS_LDM:
5188     case R_MICROMIPS_TLS_GD:
5189     case R_MICROMIPS_TLS_GOTTPREL:
5190     case R_MICROMIPS_TLS_LDM:
5191       /* Find the index into the GOT where this value is located.  */
5192       if (tls_ldm_reloc_p (r_type))
5193         {
5194           g = mips_elf_local_got_index (abfd, input_bfd, info,
5195                                         0, 0, NULL, r_type);
5196           if (g == MINUS_ONE)
5197             return bfd_reloc_outofrange;
5198         }
5199       else if (!local_p)
5200         {
5201           /* On VxWorks, CALL relocations should refer to the .got.plt
5202              entry, which is initialized to point at the PLT stub.  */
5203           if (htab->is_vxworks
5204               && (call_hi16_reloc_p (r_type)
5205                   || call_lo16_reloc_p (r_type)
5206                   || call16_reloc_p (r_type)))
5207             {
5208               BFD_ASSERT (addend == 0);
5209               BFD_ASSERT (h->root.needs_plt);
5210               g = mips_elf_gotplt_index (info, &h->root);
5211             }
5212           else
5213             {
5214               BFD_ASSERT (addend == 0);
5215               g = mips_elf_global_got_index (abfd, info, input_bfd,
5216                                              &h->root, r_type);
5217               if (!TLS_RELOC_P (r_type)
5218                   && !elf_hash_table (info)->dynamic_sections_created)
5219                 /* This is a static link.  We must initialize the GOT entry.  */
5220                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->sgot->contents + g);
5221             }
5222         }
5223       else if (!htab->is_vxworks
5224                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5225         /* The calculation below does not involve "g".  */
5226         break;
5227       else
5228         {
5229           g = mips_elf_local_got_index (abfd, input_bfd, info,
5230                                         symbol + addend, r_symndx, h, r_type);
5231           if (g == MINUS_ONE)
5232             return bfd_reloc_outofrange;
5233         }
5234
5235       /* Convert GOT indices to actual offsets.  */
5236       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5237       break;
5238     }
5239
5240   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5241      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5242   if (h != NULL && is_gott_symbol (info, &h->root))
5243     {
5244       Elf_Internal_Rela outrel;
5245       bfd_byte *loc;
5246       asection *s;
5247
5248       s = mips_elf_rel_dyn_section (info, FALSE);
5249       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5250
5251       outrel.r_offset = (input_section->output_section->vma
5252                          + input_section->output_offset
5253                          + relocation->r_offset);
5254       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5255       outrel.r_addend = addend;
5256       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5257
5258       /* If we've written this relocation for a readonly section,
5259          we need to set DF_TEXTREL again, so that we do not delete the
5260          DT_TEXTREL tag.  */
5261       if (MIPS_ELF_READONLY_SECTION (input_section))
5262         info->flags |= DF_TEXTREL;
5263
5264       *valuep = 0;
5265       return bfd_reloc_ok;
5266     }
5267
5268   /* Figure out what kind of relocation is being performed.  */
5269   switch (r_type)
5270     {
5271     case R_MIPS_NONE:
5272       return bfd_reloc_continue;
5273
5274     case R_MIPS_16:
5275       value = symbol + _bfd_mips_elf_sign_extend (addend, 16);
5276       overflowed_p = mips_elf_overflow_p (value, 16);
5277       break;
5278
5279     case R_MIPS_32:
5280     case R_MIPS_REL32:
5281     case R_MIPS_64:
5282       if ((info->shared
5283            || (htab->root.dynamic_sections_created
5284                && h != NULL
5285                && h->root.def_dynamic
5286                && !h->root.def_regular
5287                && !h->has_static_relocs))
5288           && r_symndx != STN_UNDEF
5289           && (h == NULL
5290               || h->root.root.type != bfd_link_hash_undefweak
5291               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5292           && (input_section->flags & SEC_ALLOC) != 0)
5293         {
5294           /* If we're creating a shared library, then we can't know
5295              where the symbol will end up.  So, we create a relocation
5296              record in the output, and leave the job up to the dynamic
5297              linker.  We must do the same for executable references to
5298              shared library symbols, unless we've decided to use copy
5299              relocs or PLTs instead.  */
5300           value = addend;
5301           if (!mips_elf_create_dynamic_relocation (abfd,
5302                                                    info,
5303                                                    relocation,
5304                                                    h,
5305                                                    sec,
5306                                                    symbol,
5307                                                    &value,
5308                                                    input_section))
5309             return bfd_reloc_undefined;
5310         }
5311       else
5312         {
5313           if (r_type != R_MIPS_REL32)
5314             value = symbol + addend;
5315           else
5316             value = addend;
5317         }
5318       value &= howto->dst_mask;
5319       break;
5320
5321     case R_MIPS_PC32:
5322       value = symbol + addend - p;
5323       value &= howto->dst_mask;
5324       break;
5325
5326     case R_MIPS16_26:
5327       /* The calculation for R_MIPS16_26 is just the same as for an
5328          R_MIPS_26.  It's only the storage of the relocated field into
5329          the output file that's different.  That's handled in
5330          mips_elf_perform_relocation.  So, we just fall through to the
5331          R_MIPS_26 case here.  */
5332     case R_MIPS_26:
5333     case R_MICROMIPS_26_S1:
5334       {
5335         unsigned int shift;
5336
5337         /* Make sure the target of JALX is word-aligned.  Bit 0 must be
5338            the correct ISA mode selector and bit 1 must be 0.  */
5339         if (*cross_mode_jump_p && (symbol & 3) != (r_type == R_MIPS_26))
5340           return bfd_reloc_outofrange;
5341
5342         /* Shift is 2, unusually, for microMIPS JALX.  */
5343         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5344
5345         if (was_local_p)
5346           value = addend | ((p + 4) & (0xfc000000 << shift));
5347         else
5348           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5349         value = (value + symbol) >> shift;
5350         if (!was_local_p && h->root.root.type != bfd_link_hash_undefweak)
5351           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5352         value &= howto->dst_mask;
5353       }
5354       break;
5355
5356     case R_MIPS_TLS_DTPREL_HI16:
5357     case R_MIPS16_TLS_DTPREL_HI16:
5358     case R_MICROMIPS_TLS_DTPREL_HI16:
5359       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5360                & howto->dst_mask);
5361       break;
5362
5363     case R_MIPS_TLS_DTPREL_LO16:
5364     case R_MIPS_TLS_DTPREL32:
5365     case R_MIPS_TLS_DTPREL64:
5366     case R_MIPS16_TLS_DTPREL_LO16:
5367     case R_MICROMIPS_TLS_DTPREL_LO16:
5368       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5369       break;
5370
5371     case R_MIPS_TLS_TPREL_HI16:
5372     case R_MIPS16_TLS_TPREL_HI16:
5373     case R_MICROMIPS_TLS_TPREL_HI16:
5374       value = (mips_elf_high (addend + symbol - tprel_base (info))
5375                & howto->dst_mask);
5376       break;
5377
5378     case R_MIPS_TLS_TPREL_LO16:
5379     case R_MIPS_TLS_TPREL32:
5380     case R_MIPS_TLS_TPREL64:
5381     case R_MIPS16_TLS_TPREL_LO16:
5382     case R_MICROMIPS_TLS_TPREL_LO16:
5383       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5384       break;
5385
5386     case R_MIPS_HI16:
5387     case R_MIPS16_HI16:
5388     case R_MICROMIPS_HI16:
5389       if (!gp_disp_p)
5390         {
5391           value = mips_elf_high (addend + symbol);
5392           value &= howto->dst_mask;
5393         }
5394       else
5395         {
5396           /* For MIPS16 ABI code we generate this sequence
5397                 0: li      $v0,%hi(_gp_disp)
5398                 4: addiupc $v1,%lo(_gp_disp)
5399                 8: sll     $v0,16
5400                12: addu    $v0,$v1
5401                14: move    $gp,$v0
5402              So the offsets of hi and lo relocs are the same, but the
5403              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5404              ADDIUPC clears the low two bits of the instruction address,
5405              so the base is ($t9 + 4) & ~3.  */
5406           if (r_type == R_MIPS16_HI16)
5407             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5408           /* The microMIPS .cpload sequence uses the same assembly
5409              instructions as the traditional psABI version, but the
5410              incoming $t9 has the low bit set.  */
5411           else if (r_type == R_MICROMIPS_HI16)
5412             value = mips_elf_high (addend + gp - p - 1);
5413           else
5414             value = mips_elf_high (addend + gp - p);
5415           overflowed_p = mips_elf_overflow_p (value, 16);
5416         }
5417       break;
5418
5419     case R_MIPS_LO16:
5420     case R_MIPS16_LO16:
5421     case R_MICROMIPS_LO16:
5422     case R_MICROMIPS_HI0_LO16:
5423       if (!gp_disp_p)
5424         value = (symbol + addend) & howto->dst_mask;
5425       else
5426         {
5427           /* See the comment for R_MIPS16_HI16 above for the reason
5428              for this conditional.  */
5429           if (r_type == R_MIPS16_LO16)
5430             value = addend + gp - (p & ~(bfd_vma) 0x3);
5431           else if (r_type == R_MICROMIPS_LO16
5432                    || r_type == R_MICROMIPS_HI0_LO16)
5433             value = addend + gp - p + 3;
5434           else
5435             value = addend + gp - p + 4;
5436           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5437              for overflow.  But, on, say, IRIX5, relocations against
5438              _gp_disp are normally generated from the .cpload
5439              pseudo-op.  It generates code that normally looks like
5440              this:
5441
5442                lui    $gp,%hi(_gp_disp)
5443                addiu  $gp,$gp,%lo(_gp_disp)
5444                addu   $gp,$gp,$t9
5445
5446              Here $t9 holds the address of the function being called,
5447              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5448              relocation can easily overflow in this situation, but the
5449              R_MIPS_HI16 relocation will handle the overflow.
5450              Therefore, we consider this a bug in the MIPS ABI, and do
5451              not check for overflow here.  */
5452         }
5453       break;
5454
5455     case R_MIPS_LITERAL:
5456     case R_MICROMIPS_LITERAL:
5457       /* Because we don't merge literal sections, we can handle this
5458          just like R_MIPS_GPREL16.  In the long run, we should merge
5459          shared literals, and then we will need to additional work
5460          here.  */
5461
5462       /* Fall through.  */
5463
5464     case R_MIPS16_GPREL:
5465       /* The R_MIPS16_GPREL performs the same calculation as
5466          R_MIPS_GPREL16, but stores the relocated bits in a different
5467          order.  We don't need to do anything special here; the
5468          differences are handled in mips_elf_perform_relocation.  */
5469     case R_MIPS_GPREL16:
5470     case R_MICROMIPS_GPREL7_S2:
5471     case R_MICROMIPS_GPREL16:
5472       /* Only sign-extend the addend if it was extracted from the
5473          instruction.  If the addend was separate, leave it alone,
5474          otherwise we may lose significant bits.  */
5475       if (howto->partial_inplace)
5476         addend = _bfd_mips_elf_sign_extend (addend, 16);
5477       value = symbol + addend - gp;
5478       /* If the symbol was local, any earlier relocatable links will
5479          have adjusted its addend with the gp offset, so compensate
5480          for that now.  Don't do it for symbols forced local in this
5481          link, though, since they won't have had the gp offset applied
5482          to them before.  */
5483       if (was_local_p)
5484         value += gp0;
5485       overflowed_p = mips_elf_overflow_p (value, 16);
5486       break;
5487
5488     case R_MIPS16_GOT16:
5489     case R_MIPS16_CALL16:
5490     case R_MIPS_GOT16:
5491     case R_MIPS_CALL16:
5492     case R_MICROMIPS_GOT16:
5493     case R_MICROMIPS_CALL16:
5494       /* VxWorks does not have separate local and global semantics for
5495          R_MIPS*_GOT16; every relocation evaluates to "G".  */
5496       if (!htab->is_vxworks && local_p)
5497         {
5498           value = mips_elf_got16_entry (abfd, input_bfd, info,
5499                                         symbol + addend, !was_local_p);
5500           if (value == MINUS_ONE)
5501             return bfd_reloc_outofrange;
5502           value
5503             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5504           overflowed_p = mips_elf_overflow_p (value, 16);
5505           break;
5506         }
5507
5508       /* Fall through.  */
5509
5510     case R_MIPS_TLS_GD:
5511     case R_MIPS_TLS_GOTTPREL:
5512     case R_MIPS_TLS_LDM:
5513     case R_MIPS_GOT_DISP:
5514     case R_MIPS16_TLS_GD:
5515     case R_MIPS16_TLS_GOTTPREL:
5516     case R_MIPS16_TLS_LDM:
5517     case R_MICROMIPS_TLS_GD:
5518     case R_MICROMIPS_TLS_GOTTPREL:
5519     case R_MICROMIPS_TLS_LDM:
5520     case R_MICROMIPS_GOT_DISP:
5521       value = g;
5522       overflowed_p = mips_elf_overflow_p (value, 16);
5523       break;
5524
5525     case R_MIPS_GPREL32:
5526       value = (addend + symbol + gp0 - gp);
5527       if (!save_addend)
5528         value &= howto->dst_mask;
5529       break;
5530
5531     case R_MIPS_PC16:
5532     case R_MIPS_GNU_REL16_S2:
5533       value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p;
5534       overflowed_p = mips_elf_overflow_p (value, 18);
5535       value >>= howto->rightshift;
5536       value &= howto->dst_mask;
5537       break;
5538
5539     case R_MICROMIPS_PC7_S1:
5540       value = symbol + _bfd_mips_elf_sign_extend (addend, 8) - p;
5541       overflowed_p = mips_elf_overflow_p (value, 8);
5542       value >>= howto->rightshift;
5543       value &= howto->dst_mask;
5544       break;
5545
5546     case R_MICROMIPS_PC10_S1:
5547       value = symbol + _bfd_mips_elf_sign_extend (addend, 11) - p;
5548       overflowed_p = mips_elf_overflow_p (value, 11);
5549       value >>= howto->rightshift;
5550       value &= howto->dst_mask;
5551       break;
5552
5553     case R_MICROMIPS_PC16_S1:
5554       value = symbol + _bfd_mips_elf_sign_extend (addend, 17) - p;
5555       overflowed_p = mips_elf_overflow_p (value, 17);
5556       value >>= howto->rightshift;
5557       value &= howto->dst_mask;
5558       break;
5559
5560     case R_MICROMIPS_PC23_S2:
5561       value = symbol + _bfd_mips_elf_sign_extend (addend, 25) - ((p | 3) ^ 3);
5562       overflowed_p = mips_elf_overflow_p (value, 25);
5563       value >>= howto->rightshift;
5564       value &= howto->dst_mask;
5565       break;
5566
5567     case R_MIPS_GOT_HI16:
5568     case R_MIPS_CALL_HI16:
5569     case R_MICROMIPS_GOT_HI16:
5570     case R_MICROMIPS_CALL_HI16:
5571       /* We're allowed to handle these two relocations identically.
5572          The dynamic linker is allowed to handle the CALL relocations
5573          differently by creating a lazy evaluation stub.  */
5574       value = g;
5575       value = mips_elf_high (value);
5576       value &= howto->dst_mask;
5577       break;
5578
5579     case R_MIPS_GOT_LO16:
5580     case R_MIPS_CALL_LO16:
5581     case R_MICROMIPS_GOT_LO16:
5582     case R_MICROMIPS_CALL_LO16:
5583       value = g & howto->dst_mask;
5584       break;
5585
5586     case R_MIPS_GOT_PAGE:
5587     case R_MICROMIPS_GOT_PAGE:
5588       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
5589       if (value == MINUS_ONE)
5590         return bfd_reloc_outofrange;
5591       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5592       overflowed_p = mips_elf_overflow_p (value, 16);
5593       break;
5594
5595     case R_MIPS_GOT_OFST:
5596     case R_MICROMIPS_GOT_OFST:
5597       if (local_p)
5598         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
5599       else
5600         value = addend;
5601       overflowed_p = mips_elf_overflow_p (value, 16);
5602       break;
5603
5604     case R_MIPS_SUB:
5605     case R_MICROMIPS_SUB:
5606       value = symbol - addend;
5607       value &= howto->dst_mask;
5608       break;
5609
5610     case R_MIPS_HIGHER:
5611     case R_MICROMIPS_HIGHER:
5612       value = mips_elf_higher (addend + symbol);
5613       value &= howto->dst_mask;
5614       break;
5615
5616     case R_MIPS_HIGHEST:
5617     case R_MICROMIPS_HIGHEST:
5618       value = mips_elf_highest (addend + symbol);
5619       value &= howto->dst_mask;
5620       break;
5621
5622     case R_MIPS_SCN_DISP:
5623     case R_MICROMIPS_SCN_DISP:
5624       value = symbol + addend - sec->output_offset;
5625       value &= howto->dst_mask;
5626       break;
5627
5628     case R_MIPS_JALR:
5629     case R_MICROMIPS_JALR:
5630       /* This relocation is only a hint.  In some cases, we optimize
5631          it into a bal instruction.  But we don't try to optimize
5632          when the symbol does not resolve locally.  */
5633       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
5634         return bfd_reloc_continue;
5635       value = symbol + addend;
5636       break;
5637
5638     case R_MIPS_PJUMP:
5639     case R_MIPS_GNU_VTINHERIT:
5640     case R_MIPS_GNU_VTENTRY:
5641       /* We don't do anything with these at present.  */
5642       return bfd_reloc_continue;
5643
5644     default:
5645       /* An unrecognized relocation type.  */
5646       return bfd_reloc_notsupported;
5647     }
5648
5649   /* Store the VALUE for our caller.  */
5650   *valuep = value;
5651   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
5652 }
5653
5654 /* Obtain the field relocated by RELOCATION.  */
5655
5656 static bfd_vma
5657 mips_elf_obtain_contents (reloc_howto_type *howto,
5658                           const Elf_Internal_Rela *relocation,
5659                           bfd *input_bfd, bfd_byte *contents)
5660 {
5661   bfd_vma x;
5662   bfd_byte *location = contents + relocation->r_offset;
5663
5664   /* Obtain the bytes.  */
5665   x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location);
5666
5667   return x;
5668 }
5669
5670 /* It has been determined that the result of the RELOCATION is the
5671    VALUE.  Use HOWTO to place VALUE into the output file at the
5672    appropriate position.  The SECTION is the section to which the
5673    relocation applies.
5674    CROSS_MODE_JUMP_P is true if the relocation field
5675    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5676
5677    Returns FALSE if anything goes wrong.  */
5678
5679 static bfd_boolean
5680 mips_elf_perform_relocation (struct bfd_link_info *info,
5681                              reloc_howto_type *howto,
5682                              const Elf_Internal_Rela *relocation,
5683                              bfd_vma value, bfd *input_bfd,
5684                              asection *input_section, bfd_byte *contents,
5685                              bfd_boolean cross_mode_jump_p)
5686 {
5687   bfd_vma x;
5688   bfd_byte *location;
5689   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5690
5691   /* Figure out where the relocation is occurring.  */
5692   location = contents + relocation->r_offset;
5693
5694   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
5695
5696   /* Obtain the current value.  */
5697   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
5698
5699   /* Clear the field we are setting.  */
5700   x &= ~howto->dst_mask;
5701
5702   /* Set the field.  */
5703   x |= (value & howto->dst_mask);
5704
5705   /* If required, turn JAL into JALX.  */
5706   if (cross_mode_jump_p && jal_reloc_p (r_type))
5707     {
5708       bfd_boolean ok;
5709       bfd_vma opcode = x >> 26;
5710       bfd_vma jalx_opcode;
5711
5712       /* Check to see if the opcode is already JAL or JALX.  */
5713       if (r_type == R_MIPS16_26)
5714         {
5715           ok = ((opcode == 0x6) || (opcode == 0x7));
5716           jalx_opcode = 0x7;
5717         }
5718       else if (r_type == R_MICROMIPS_26_S1)
5719         {
5720           ok = ((opcode == 0x3d) || (opcode == 0x3c));
5721           jalx_opcode = 0x3c;
5722         }
5723       else
5724         {
5725           ok = ((opcode == 0x3) || (opcode == 0x1d));
5726           jalx_opcode = 0x1d;
5727         }
5728
5729       /* If the opcode is not JAL or JALX, there's a problem.  We cannot
5730          convert J or JALS to JALX.  */
5731       if (!ok)
5732         {
5733           (*_bfd_error_handler)
5734             (_("%B: %A+0x%lx: Unsupported jump between ISA modes; consider recompiling with interlinking enabled."),
5735              input_bfd,
5736              input_section,
5737              (unsigned long) relocation->r_offset);
5738           bfd_set_error (bfd_error_bad_value);
5739           return FALSE;
5740         }
5741
5742       /* Make this the JALX opcode.  */
5743       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
5744     }
5745
5746   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
5747      range.  */
5748   if (!info->relocatable
5749       && !cross_mode_jump_p
5750       && ((JAL_TO_BAL_P (input_bfd)
5751            && r_type == R_MIPS_26
5752            && (x >> 26) == 0x3)         /* jal addr */
5753           || (JALR_TO_BAL_P (input_bfd)
5754               && r_type == R_MIPS_JALR
5755               && x == 0x0320f809)       /* jalr t9 */
5756           || (JR_TO_B_P (input_bfd)
5757               && r_type == R_MIPS_JALR
5758               && x == 0x03200008)))     /* jr t9 */
5759     {
5760       bfd_vma addr;
5761       bfd_vma dest;
5762       bfd_signed_vma off;
5763
5764       addr = (input_section->output_section->vma
5765               + input_section->output_offset
5766               + relocation->r_offset
5767               + 4);
5768       if (r_type == R_MIPS_26)
5769         dest = (value << 2) | ((addr >> 28) << 28);
5770       else
5771         dest = value;
5772       off = dest - addr;
5773       if (off <= 0x1ffff && off >= -0x20000)
5774         {
5775           if (x == 0x03200008)  /* jr t9 */
5776             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
5777           else
5778             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
5779         }
5780     }
5781
5782   /* Put the value into the output.  */
5783   bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location);
5784
5785   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !info->relocatable,
5786                                location);
5787
5788   return TRUE;
5789 }
5790 \f
5791 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
5792    is the original relocation, which is now being transformed into a
5793    dynamic relocation.  The ADDENDP is adjusted if necessary; the
5794    caller should store the result in place of the original addend.  */
5795
5796 static bfd_boolean
5797 mips_elf_create_dynamic_relocation (bfd *output_bfd,
5798                                     struct bfd_link_info *info,
5799                                     const Elf_Internal_Rela *rel,
5800                                     struct mips_elf_link_hash_entry *h,
5801                                     asection *sec, bfd_vma symbol,
5802                                     bfd_vma *addendp, asection *input_section)
5803 {
5804   Elf_Internal_Rela outrel[3];
5805   asection *sreloc;
5806   bfd *dynobj;
5807   int r_type;
5808   long indx;
5809   bfd_boolean defined_p;
5810   struct mips_elf_link_hash_table *htab;
5811
5812   htab = mips_elf_hash_table (info);
5813   BFD_ASSERT (htab != NULL);
5814
5815   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
5816   dynobj = elf_hash_table (info)->dynobj;
5817   sreloc = mips_elf_rel_dyn_section (info, FALSE);
5818   BFD_ASSERT (sreloc != NULL);
5819   BFD_ASSERT (sreloc->contents != NULL);
5820   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
5821               < sreloc->size);
5822
5823   outrel[0].r_offset =
5824     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
5825   if (ABI_64_P (output_bfd))
5826     {
5827       outrel[1].r_offset =
5828         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
5829       outrel[2].r_offset =
5830         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
5831     }
5832
5833   if (outrel[0].r_offset == MINUS_ONE)
5834     /* The relocation field has been deleted.  */
5835     return TRUE;
5836
5837   if (outrel[0].r_offset == MINUS_TWO)
5838     {
5839       /* The relocation field has been converted into a relative value of
5840          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
5841          the field to be fully relocated, so add in the symbol's value.  */
5842       *addendp += symbol;
5843       return TRUE;
5844     }
5845
5846   /* We must now calculate the dynamic symbol table index to use
5847      in the relocation.  */
5848   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
5849     {
5850       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
5851       indx = h->root.dynindx;
5852       if (SGI_COMPAT (output_bfd))
5853         defined_p = h->root.def_regular;
5854       else
5855         /* ??? glibc's ld.so just adds the final GOT entry to the
5856            relocation field.  It therefore treats relocs against
5857            defined symbols in the same way as relocs against
5858            undefined symbols.  */
5859         defined_p = FALSE;
5860     }
5861   else
5862     {
5863       if (sec != NULL && bfd_is_abs_section (sec))
5864         indx = 0;
5865       else if (sec == NULL || sec->owner == NULL)
5866         {
5867           bfd_set_error (bfd_error_bad_value);
5868           return FALSE;
5869         }
5870       else
5871         {
5872           indx = elf_section_data (sec->output_section)->dynindx;
5873           if (indx == 0)
5874             {
5875               asection *osec = htab->root.text_index_section;
5876               indx = elf_section_data (osec)->dynindx;
5877             }
5878           if (indx == 0)
5879             abort ();
5880         }
5881
5882       /* Instead of generating a relocation using the section
5883          symbol, we may as well make it a fully relative
5884          relocation.  We want to avoid generating relocations to
5885          local symbols because we used to generate them
5886          incorrectly, without adding the original symbol value,
5887          which is mandated by the ABI for section symbols.  In
5888          order to give dynamic loaders and applications time to
5889          phase out the incorrect use, we refrain from emitting
5890          section-relative relocations.  It's not like they're
5891          useful, after all.  This should be a bit more efficient
5892          as well.  */
5893       /* ??? Although this behavior is compatible with glibc's ld.so,
5894          the ABI says that relocations against STN_UNDEF should have
5895          a symbol value of 0.  Irix rld honors this, so relocations
5896          against STN_UNDEF have no effect.  */
5897       if (!SGI_COMPAT (output_bfd))
5898         indx = 0;
5899       defined_p = TRUE;
5900     }
5901
5902   /* If the relocation was previously an absolute relocation and
5903      this symbol will not be referred to by the relocation, we must
5904      adjust it by the value we give it in the dynamic symbol table.
5905      Otherwise leave the job up to the dynamic linker.  */
5906   if (defined_p && r_type != R_MIPS_REL32)
5907     *addendp += symbol;
5908
5909   if (htab->is_vxworks)
5910     /* VxWorks uses non-relative relocations for this.  */
5911     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
5912   else
5913     /* The relocation is always an REL32 relocation because we don't
5914        know where the shared library will wind up at load-time.  */
5915     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
5916                                    R_MIPS_REL32);
5917
5918   /* For strict adherence to the ABI specification, we should
5919      generate a R_MIPS_64 relocation record by itself before the
5920      _REL32/_64 record as well, such that the addend is read in as
5921      a 64-bit value (REL32 is a 32-bit relocation, after all).
5922      However, since none of the existing ELF64 MIPS dynamic
5923      loaders seems to care, we don't waste space with these
5924      artificial relocations.  If this turns out to not be true,
5925      mips_elf_allocate_dynamic_relocation() should be tweaked so
5926      as to make room for a pair of dynamic relocations per
5927      invocation if ABI_64_P, and here we should generate an
5928      additional relocation record with R_MIPS_64 by itself for a
5929      NULL symbol before this relocation record.  */
5930   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
5931                                  ABI_64_P (output_bfd)
5932                                  ? R_MIPS_64
5933                                  : R_MIPS_NONE);
5934   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
5935
5936   /* Adjust the output offset of the relocation to reference the
5937      correct location in the output file.  */
5938   outrel[0].r_offset += (input_section->output_section->vma
5939                          + input_section->output_offset);
5940   outrel[1].r_offset += (input_section->output_section->vma
5941                          + input_section->output_offset);
5942   outrel[2].r_offset += (input_section->output_section->vma
5943                          + input_section->output_offset);
5944
5945   /* Put the relocation back out.  We have to use the special
5946      relocation outputter in the 64-bit case since the 64-bit
5947      relocation format is non-standard.  */
5948   if (ABI_64_P (output_bfd))
5949     {
5950       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
5951         (output_bfd, &outrel[0],
5952          (sreloc->contents
5953           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
5954     }
5955   else if (htab->is_vxworks)
5956     {
5957       /* VxWorks uses RELA rather than REL dynamic relocations.  */
5958       outrel[0].r_addend = *addendp;
5959       bfd_elf32_swap_reloca_out
5960         (output_bfd, &outrel[0],
5961          (sreloc->contents
5962           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
5963     }
5964   else
5965     bfd_elf32_swap_reloc_out
5966       (output_bfd, &outrel[0],
5967        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
5968
5969   /* We've now added another relocation.  */
5970   ++sreloc->reloc_count;
5971
5972   /* Make sure the output section is writable.  The dynamic linker
5973      will be writing to it.  */
5974   elf_section_data (input_section->output_section)->this_hdr.sh_flags
5975     |= SHF_WRITE;
5976
5977   /* On IRIX5, make an entry of compact relocation info.  */
5978   if (IRIX_COMPAT (output_bfd) == ict_irix5)
5979     {
5980       asection *scpt = bfd_get_linker_section (dynobj, ".compact_rel");
5981       bfd_byte *cr;
5982
5983       if (scpt)
5984         {
5985           Elf32_crinfo cptrel;
5986
5987           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
5988           cptrel.vaddr = (rel->r_offset
5989                           + input_section->output_section->vma
5990                           + input_section->output_offset);
5991           if (r_type == R_MIPS_REL32)
5992             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
5993           else
5994             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
5995           mips_elf_set_cr_dist2to (cptrel, 0);
5996           cptrel.konst = *addendp;
5997
5998           cr = (scpt->contents
5999                 + sizeof (Elf32_External_compact_rel));
6000           mips_elf_set_cr_relvaddr (cptrel, 0);
6001           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
6002                                      ((Elf32_External_crinfo *) cr
6003                                       + scpt->reloc_count));
6004           ++scpt->reloc_count;
6005         }
6006     }
6007
6008   /* If we've written this relocation for a readonly section,
6009      we need to set DF_TEXTREL again, so that we do not delete the
6010      DT_TEXTREL tag.  */
6011   if (MIPS_ELF_READONLY_SECTION (input_section))
6012     info->flags |= DF_TEXTREL;
6013
6014   return TRUE;
6015 }
6016 \f
6017 /* Return the MACH for a MIPS e_flags value.  */
6018
6019 unsigned long
6020 _bfd_elf_mips_mach (flagword flags)
6021 {
6022   switch (flags & EF_MIPS_MACH)
6023     {
6024     case E_MIPS_MACH_3900:
6025       return bfd_mach_mips3900;
6026
6027     case E_MIPS_MACH_4010:
6028       return bfd_mach_mips4010;
6029
6030     case E_MIPS_MACH_4100:
6031       return bfd_mach_mips4100;
6032
6033     case E_MIPS_MACH_4111:
6034       return bfd_mach_mips4111;
6035
6036     case E_MIPS_MACH_4120:
6037       return bfd_mach_mips4120;
6038
6039     case E_MIPS_MACH_4650:
6040       return bfd_mach_mips4650;
6041
6042     case E_MIPS_MACH_5400:
6043       return bfd_mach_mips5400;
6044
6045     case E_MIPS_MACH_5500:
6046       return bfd_mach_mips5500;
6047
6048     case E_MIPS_MACH_5900:
6049       return bfd_mach_mips5900;
6050
6051     case E_MIPS_MACH_9000:
6052       return bfd_mach_mips9000;
6053
6054     case E_MIPS_MACH_SB1:
6055       return bfd_mach_mips_sb1;
6056
6057     case E_MIPS_MACH_LS2E:
6058       return bfd_mach_mips_loongson_2e;
6059
6060     case E_MIPS_MACH_LS2F:
6061       return bfd_mach_mips_loongson_2f;
6062
6063     case E_MIPS_MACH_LS3A:
6064       return bfd_mach_mips_loongson_3a;
6065
6066     case E_MIPS_MACH_OCTEON2:
6067       return bfd_mach_mips_octeon2;
6068
6069     case E_MIPS_MACH_OCTEON:
6070       return bfd_mach_mips_octeon;
6071
6072     case E_MIPS_MACH_XLR:
6073       return bfd_mach_mips_xlr;
6074
6075     default:
6076       switch (flags & EF_MIPS_ARCH)
6077         {
6078         default:
6079         case E_MIPS_ARCH_1:
6080           return bfd_mach_mips3000;
6081
6082         case E_MIPS_ARCH_2:
6083           return bfd_mach_mips6000;
6084
6085         case E_MIPS_ARCH_3:
6086           return bfd_mach_mips4000;
6087
6088         case E_MIPS_ARCH_4:
6089           return bfd_mach_mips8000;
6090
6091         case E_MIPS_ARCH_5:
6092           return bfd_mach_mips5;
6093
6094         case E_MIPS_ARCH_32:
6095           return bfd_mach_mipsisa32;
6096
6097         case E_MIPS_ARCH_64:
6098           return bfd_mach_mipsisa64;
6099
6100         case E_MIPS_ARCH_32R2:
6101           return bfd_mach_mipsisa32r2;
6102
6103         case E_MIPS_ARCH_64R2:
6104           return bfd_mach_mipsisa64r2;
6105         }
6106     }
6107
6108   return 0;
6109 }
6110
6111 /* Return printable name for ABI.  */
6112
6113 static INLINE char *
6114 elf_mips_abi_name (bfd *abfd)
6115 {
6116   flagword flags;
6117
6118   flags = elf_elfheader (abfd)->e_flags;
6119   switch (flags & EF_MIPS_ABI)
6120     {
6121     case 0:
6122       if (ABI_N32_P (abfd))
6123         return "N32";
6124       else if (ABI_64_P (abfd))
6125         return "64";
6126       else
6127         return "none";
6128     case E_MIPS_ABI_O32:
6129       return "O32";
6130     case E_MIPS_ABI_O64:
6131       return "O64";
6132     case E_MIPS_ABI_EABI32:
6133       return "EABI32";
6134     case E_MIPS_ABI_EABI64:
6135       return "EABI64";
6136     default:
6137       return "unknown abi";
6138     }
6139 }
6140 \f
6141 /* MIPS ELF uses two common sections.  One is the usual one, and the
6142    other is for small objects.  All the small objects are kept
6143    together, and then referenced via the gp pointer, which yields
6144    faster assembler code.  This is what we use for the small common
6145    section.  This approach is copied from ecoff.c.  */
6146 static asection mips_elf_scom_section;
6147 static asymbol mips_elf_scom_symbol;
6148 static asymbol *mips_elf_scom_symbol_ptr;
6149
6150 /* MIPS ELF also uses an acommon section, which represents an
6151    allocated common symbol which may be overridden by a
6152    definition in a shared library.  */
6153 static asection mips_elf_acom_section;
6154 static asymbol mips_elf_acom_symbol;
6155 static asymbol *mips_elf_acom_symbol_ptr;
6156
6157 /* This is used for both the 32-bit and the 64-bit ABI.  */
6158
6159 void
6160 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6161 {
6162   elf_symbol_type *elfsym;
6163
6164   /* Handle the special MIPS section numbers that a symbol may use.  */
6165   elfsym = (elf_symbol_type *) asym;
6166   switch (elfsym->internal_elf_sym.st_shndx)
6167     {
6168     case SHN_MIPS_ACOMMON:
6169       /* This section is used in a dynamically linked executable file.
6170          It is an allocated common section.  The dynamic linker can
6171          either resolve these symbols to something in a shared
6172          library, or it can just leave them here.  For our purposes,
6173          we can consider these symbols to be in a new section.  */
6174       if (mips_elf_acom_section.name == NULL)
6175         {
6176           /* Initialize the acommon section.  */
6177           mips_elf_acom_section.name = ".acommon";
6178           mips_elf_acom_section.flags = SEC_ALLOC;
6179           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6180           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6181           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6182           mips_elf_acom_symbol.name = ".acommon";
6183           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6184           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6185           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6186         }
6187       asym->section = &mips_elf_acom_section;
6188       break;
6189
6190     case SHN_COMMON:
6191       /* Common symbols less than the GP size are automatically
6192          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6193       if (asym->value > elf_gp_size (abfd)
6194           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6195           || IRIX_COMPAT (abfd) == ict_irix6)
6196         break;
6197       /* Fall through.  */
6198     case SHN_MIPS_SCOMMON:
6199       if (mips_elf_scom_section.name == NULL)
6200         {
6201           /* Initialize the small common section.  */
6202           mips_elf_scom_section.name = ".scommon";
6203           mips_elf_scom_section.flags = SEC_IS_COMMON;
6204           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6205           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6206           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6207           mips_elf_scom_symbol.name = ".scommon";
6208           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6209           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6210           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6211         }
6212       asym->section = &mips_elf_scom_section;
6213       asym->value = elfsym->internal_elf_sym.st_size;
6214       break;
6215
6216     case SHN_MIPS_SUNDEFINED:
6217       asym->section = bfd_und_section_ptr;
6218       break;
6219
6220     case SHN_MIPS_TEXT:
6221       {
6222         asection *section = bfd_get_section_by_name (abfd, ".text");
6223
6224         if (section != NULL)
6225           {
6226             asym->section = section;
6227             /* MIPS_TEXT is a bit special, the address is not an offset
6228                to the base of the .text section.  So substract the section
6229                base address to make it an offset.  */
6230             asym->value -= section->vma;
6231           }
6232       }
6233       break;
6234
6235     case SHN_MIPS_DATA:
6236       {
6237         asection *section = bfd_get_section_by_name (abfd, ".data");
6238
6239         if (section != NULL)
6240           {
6241             asym->section = section;
6242             /* MIPS_DATA is a bit special, the address is not an offset
6243                to the base of the .data section.  So substract the section
6244                base address to make it an offset.  */
6245             asym->value -= section->vma;
6246           }
6247       }
6248       break;
6249     }
6250
6251   /* If this is an odd-valued function symbol, assume it's a MIPS16
6252      or microMIPS one.  */
6253   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6254       && (asym->value & 1) != 0)
6255     {
6256       asym->value--;
6257       if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
6258         elfsym->internal_elf_sym.st_other
6259           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6260       else
6261         elfsym->internal_elf_sym.st_other
6262           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6263     }
6264 }
6265 \f
6266 /* Implement elf_backend_eh_frame_address_size.  This differs from
6267    the default in the way it handles EABI64.
6268
6269    EABI64 was originally specified as an LP64 ABI, and that is what
6270    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6271    historically accepted the combination of -mabi=eabi and -mlong32,
6272    and this ILP32 variation has become semi-official over time.
6273    Both forms use elf32 and have pointer-sized FDE addresses.
6274
6275    If an EABI object was generated by GCC 4.0 or above, it will have
6276    an empty .gcc_compiled_longXX section, where XX is the size of longs
6277    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6278    have no special marking to distinguish them from LP64 objects.
6279
6280    We don't want users of the official LP64 ABI to be punished for the
6281    existence of the ILP32 variant, but at the same time, we don't want
6282    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6283    We therefore take the following approach:
6284
6285       - If ABFD contains a .gcc_compiled_longXX section, use it to
6286         determine the pointer size.
6287
6288       - Otherwise check the type of the first relocation.  Assume that
6289         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
6290
6291       - Otherwise punt.
6292
6293    The second check is enough to detect LP64 objects generated by pre-4.0
6294    compilers because, in the kind of output generated by those compilers,
6295    the first relocation will be associated with either a CIE personality
6296    routine or an FDE start address.  Furthermore, the compilers never
6297    used a special (non-pointer) encoding for this ABI.
6298
6299    Checking the relocation type should also be safe because there is no
6300    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
6301    did so.  */
6302
6303 unsigned int
6304 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
6305 {
6306   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
6307     return 8;
6308   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
6309     {
6310       bfd_boolean long32_p, long64_p;
6311
6312       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
6313       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
6314       if (long32_p && long64_p)
6315         return 0;
6316       if (long32_p)
6317         return 4;
6318       if (long64_p)
6319         return 8;
6320
6321       if (sec->reloc_count > 0
6322           && elf_section_data (sec)->relocs != NULL
6323           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
6324               == R_MIPS_64))
6325         return 8;
6326
6327       return 0;
6328     }
6329   return 4;
6330 }
6331 \f
6332 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
6333    relocations against two unnamed section symbols to resolve to the
6334    same address.  For example, if we have code like:
6335
6336         lw      $4,%got_disp(.data)($gp)
6337         lw      $25,%got_disp(.text)($gp)
6338         jalr    $25
6339
6340    then the linker will resolve both relocations to .data and the program
6341    will jump there rather than to .text.
6342
6343    We can work around this problem by giving names to local section symbols.
6344    This is also what the MIPSpro tools do.  */
6345
6346 bfd_boolean
6347 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
6348 {
6349   return SGI_COMPAT (abfd);
6350 }
6351 \f
6352 /* Work over a section just before writing it out.  This routine is
6353    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
6354    sections that need the SHF_MIPS_GPREL flag by name; there has to be
6355    a better way.  */
6356
6357 bfd_boolean
6358 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
6359 {
6360   if (hdr->sh_type == SHT_MIPS_REGINFO
6361       && hdr->sh_size > 0)
6362     {
6363       bfd_byte buf[4];
6364
6365       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
6366       BFD_ASSERT (hdr->contents == NULL);
6367
6368       if (bfd_seek (abfd,
6369                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
6370                     SEEK_SET) != 0)
6371         return FALSE;
6372       H_PUT_32 (abfd, elf_gp (abfd), buf);
6373       if (bfd_bwrite (buf, 4, abfd) != 4)
6374         return FALSE;
6375     }
6376
6377   if (hdr->sh_type == SHT_MIPS_OPTIONS
6378       && hdr->bfd_section != NULL
6379       && mips_elf_section_data (hdr->bfd_section) != NULL
6380       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
6381     {
6382       bfd_byte *contents, *l, *lend;
6383
6384       /* We stored the section contents in the tdata field in the
6385          set_section_contents routine.  We save the section contents
6386          so that we don't have to read them again.
6387          At this point we know that elf_gp is set, so we can look
6388          through the section contents to see if there is an
6389          ODK_REGINFO structure.  */
6390
6391       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
6392       l = contents;
6393       lend = contents + hdr->sh_size;
6394       while (l + sizeof (Elf_External_Options) <= lend)
6395         {
6396           Elf_Internal_Options intopt;
6397
6398           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6399                                         &intopt);
6400           if (intopt.size < sizeof (Elf_External_Options))
6401             {
6402               (*_bfd_error_handler)
6403                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6404                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6405               break;
6406             }
6407           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6408             {
6409               bfd_byte buf[8];
6410
6411               if (bfd_seek (abfd,
6412                             (hdr->sh_offset
6413                              + (l - contents)
6414                              + sizeof (Elf_External_Options)
6415                              + (sizeof (Elf64_External_RegInfo) - 8)),
6416                              SEEK_SET) != 0)
6417                 return FALSE;
6418               H_PUT_64 (abfd, elf_gp (abfd), buf);
6419               if (bfd_bwrite (buf, 8, abfd) != 8)
6420                 return FALSE;
6421             }
6422           else if (intopt.kind == ODK_REGINFO)
6423             {
6424               bfd_byte buf[4];
6425
6426               if (bfd_seek (abfd,
6427                             (hdr->sh_offset
6428                              + (l - contents)
6429                              + sizeof (Elf_External_Options)
6430                              + (sizeof (Elf32_External_RegInfo) - 4)),
6431                             SEEK_SET) != 0)
6432                 return FALSE;
6433               H_PUT_32 (abfd, elf_gp (abfd), buf);
6434               if (bfd_bwrite (buf, 4, abfd) != 4)
6435                 return FALSE;
6436             }
6437           l += intopt.size;
6438         }
6439     }
6440
6441   if (hdr->bfd_section != NULL)
6442     {
6443       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
6444
6445       /* .sbss is not handled specially here because the GNU/Linux
6446          prelinker can convert .sbss from NOBITS to PROGBITS and
6447          changing it back to NOBITS breaks the binary.  The entry in
6448          _bfd_mips_elf_special_sections will ensure the correct flags
6449          are set on .sbss if BFD creates it without reading it from an
6450          input file, and without special handling here the flags set
6451          on it in an input file will be followed.  */
6452       if (strcmp (name, ".sdata") == 0
6453           || strcmp (name, ".lit8") == 0
6454           || strcmp (name, ".lit4") == 0)
6455         {
6456           hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
6457           hdr->sh_type = SHT_PROGBITS;
6458         }
6459       else if (strcmp (name, ".srdata") == 0)
6460         {
6461           hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
6462           hdr->sh_type = SHT_PROGBITS;
6463         }
6464       else if (strcmp (name, ".compact_rel") == 0)
6465         {
6466           hdr->sh_flags = 0;
6467           hdr->sh_type = SHT_PROGBITS;
6468         }
6469       else if (strcmp (name, ".rtproc") == 0)
6470         {
6471           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
6472             {
6473               unsigned int adjust;
6474
6475               adjust = hdr->sh_size % hdr->sh_addralign;
6476               if (adjust != 0)
6477                 hdr->sh_size += hdr->sh_addralign - adjust;
6478             }
6479         }
6480     }
6481
6482   return TRUE;
6483 }
6484
6485 /* Handle a MIPS specific section when reading an object file.  This
6486    is called when elfcode.h finds a section with an unknown type.
6487    This routine supports both the 32-bit and 64-bit ELF ABI.
6488
6489    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
6490    how to.  */
6491
6492 bfd_boolean
6493 _bfd_mips_elf_section_from_shdr (bfd *abfd,
6494                                  Elf_Internal_Shdr *hdr,
6495                                  const char *name,
6496                                  int shindex)
6497 {
6498   flagword flags = 0;
6499
6500   /* There ought to be a place to keep ELF backend specific flags, but
6501      at the moment there isn't one.  We just keep track of the
6502      sections by their name, instead.  Fortunately, the ABI gives
6503      suggested names for all the MIPS specific sections, so we will
6504      probably get away with this.  */
6505   switch (hdr->sh_type)
6506     {
6507     case SHT_MIPS_LIBLIST:
6508       if (strcmp (name, ".liblist") != 0)
6509         return FALSE;
6510       break;
6511     case SHT_MIPS_MSYM:
6512       if (strcmp (name, ".msym") != 0)
6513         return FALSE;
6514       break;
6515     case SHT_MIPS_CONFLICT:
6516       if (strcmp (name, ".conflict") != 0)
6517         return FALSE;
6518       break;
6519     case SHT_MIPS_GPTAB:
6520       if (! CONST_STRNEQ (name, ".gptab."))
6521         return FALSE;
6522       break;
6523     case SHT_MIPS_UCODE:
6524       if (strcmp (name, ".ucode") != 0)
6525         return FALSE;
6526       break;
6527     case SHT_MIPS_DEBUG:
6528       if (strcmp (name, ".mdebug") != 0)
6529         return FALSE;
6530       flags = SEC_DEBUGGING;
6531       break;
6532     case SHT_MIPS_REGINFO:
6533       if (strcmp (name, ".reginfo") != 0
6534           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
6535         return FALSE;
6536       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6537       break;
6538     case SHT_MIPS_IFACE:
6539       if (strcmp (name, ".MIPS.interfaces") != 0)
6540         return FALSE;
6541       break;
6542     case SHT_MIPS_CONTENT:
6543       if (! CONST_STRNEQ (name, ".MIPS.content"))
6544         return FALSE;
6545       break;
6546     case SHT_MIPS_OPTIONS:
6547       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6548         return FALSE;
6549       break;
6550     case SHT_MIPS_DWARF:
6551       if (! CONST_STRNEQ (name, ".debug_")
6552           && ! CONST_STRNEQ (name, ".zdebug_"))
6553         return FALSE;
6554       break;
6555     case SHT_MIPS_SYMBOL_LIB:
6556       if (strcmp (name, ".MIPS.symlib") != 0)
6557         return FALSE;
6558       break;
6559     case SHT_MIPS_EVENTS:
6560       if (! CONST_STRNEQ (name, ".MIPS.events")
6561           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
6562         return FALSE;
6563       break;
6564     default:
6565       break;
6566     }
6567
6568   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
6569     return FALSE;
6570
6571   if (flags)
6572     {
6573       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
6574                                    (bfd_get_section_flags (abfd,
6575                                                            hdr->bfd_section)
6576                                     | flags)))
6577         return FALSE;
6578     }
6579
6580   /* FIXME: We should record sh_info for a .gptab section.  */
6581
6582   /* For a .reginfo section, set the gp value in the tdata information
6583      from the contents of this section.  We need the gp value while
6584      processing relocs, so we just get it now.  The .reginfo section
6585      is not used in the 64-bit MIPS ELF ABI.  */
6586   if (hdr->sh_type == SHT_MIPS_REGINFO)
6587     {
6588       Elf32_External_RegInfo ext;
6589       Elf32_RegInfo s;
6590
6591       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
6592                                       &ext, 0, sizeof ext))
6593         return FALSE;
6594       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
6595       elf_gp (abfd) = s.ri_gp_value;
6596     }
6597
6598   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
6599      set the gp value based on what we find.  We may see both
6600      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
6601      they should agree.  */
6602   if (hdr->sh_type == SHT_MIPS_OPTIONS)
6603     {
6604       bfd_byte *contents, *l, *lend;
6605
6606       contents = bfd_malloc (hdr->sh_size);
6607       if (contents == NULL)
6608         return FALSE;
6609       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
6610                                       0, hdr->sh_size))
6611         {
6612           free (contents);
6613           return FALSE;
6614         }
6615       l = contents;
6616       lend = contents + hdr->sh_size;
6617       while (l + sizeof (Elf_External_Options) <= lend)
6618         {
6619           Elf_Internal_Options intopt;
6620
6621           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6622                                         &intopt);
6623           if (intopt.size < sizeof (Elf_External_Options))
6624             {
6625               (*_bfd_error_handler)
6626                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6627                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6628               break;
6629             }
6630           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6631             {
6632               Elf64_Internal_RegInfo intreg;
6633
6634               bfd_mips_elf64_swap_reginfo_in
6635                 (abfd,
6636                  ((Elf64_External_RegInfo *)
6637                   (l + sizeof (Elf_External_Options))),
6638                  &intreg);
6639               elf_gp (abfd) = intreg.ri_gp_value;
6640             }
6641           else if (intopt.kind == ODK_REGINFO)
6642             {
6643               Elf32_RegInfo intreg;
6644
6645               bfd_mips_elf32_swap_reginfo_in
6646                 (abfd,
6647                  ((Elf32_External_RegInfo *)
6648                   (l + sizeof (Elf_External_Options))),
6649                  &intreg);
6650               elf_gp (abfd) = intreg.ri_gp_value;
6651             }
6652           l += intopt.size;
6653         }
6654       free (contents);
6655     }
6656
6657   return TRUE;
6658 }
6659
6660 /* Set the correct type for a MIPS ELF section.  We do this by the
6661    section name, which is a hack, but ought to work.  This routine is
6662    used by both the 32-bit and the 64-bit ABI.  */
6663
6664 bfd_boolean
6665 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
6666 {
6667   const char *name = bfd_get_section_name (abfd, sec);
6668
6669   if (strcmp (name, ".liblist") == 0)
6670     {
6671       hdr->sh_type = SHT_MIPS_LIBLIST;
6672       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
6673       /* The sh_link field is set in final_write_processing.  */
6674     }
6675   else if (strcmp (name, ".conflict") == 0)
6676     hdr->sh_type = SHT_MIPS_CONFLICT;
6677   else if (CONST_STRNEQ (name, ".gptab."))
6678     {
6679       hdr->sh_type = SHT_MIPS_GPTAB;
6680       hdr->sh_entsize = sizeof (Elf32_External_gptab);
6681       /* The sh_info field is set in final_write_processing.  */
6682     }
6683   else if (strcmp (name, ".ucode") == 0)
6684     hdr->sh_type = SHT_MIPS_UCODE;
6685   else if (strcmp (name, ".mdebug") == 0)
6686     {
6687       hdr->sh_type = SHT_MIPS_DEBUG;
6688       /* In a shared object on IRIX 5.3, the .mdebug section has an
6689          entsize of 0.  FIXME: Does this matter?  */
6690       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
6691         hdr->sh_entsize = 0;
6692       else
6693         hdr->sh_entsize = 1;
6694     }
6695   else if (strcmp (name, ".reginfo") == 0)
6696     {
6697       hdr->sh_type = SHT_MIPS_REGINFO;
6698       /* In a shared object on IRIX 5.3, the .reginfo section has an
6699          entsize of 0x18.  FIXME: Does this matter?  */
6700       if (SGI_COMPAT (abfd))
6701         {
6702           if ((abfd->flags & DYNAMIC) != 0)
6703             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6704           else
6705             hdr->sh_entsize = 1;
6706         }
6707       else
6708         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6709     }
6710   else if (SGI_COMPAT (abfd)
6711            && (strcmp (name, ".hash") == 0
6712                || strcmp (name, ".dynamic") == 0
6713                || strcmp (name, ".dynstr") == 0))
6714     {
6715       if (SGI_COMPAT (abfd))
6716         hdr->sh_entsize = 0;
6717 #if 0
6718       /* This isn't how the IRIX6 linker behaves.  */
6719       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
6720 #endif
6721     }
6722   else if (strcmp (name, ".got") == 0
6723            || strcmp (name, ".srdata") == 0
6724            || strcmp (name, ".sdata") == 0
6725            || strcmp (name, ".sbss") == 0
6726            || strcmp (name, ".lit4") == 0
6727            || strcmp (name, ".lit8") == 0)
6728     hdr->sh_flags |= SHF_MIPS_GPREL;
6729   else if (strcmp (name, ".MIPS.interfaces") == 0)
6730     {
6731       hdr->sh_type = SHT_MIPS_IFACE;
6732       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6733     }
6734   else if (CONST_STRNEQ (name, ".MIPS.content"))
6735     {
6736       hdr->sh_type = SHT_MIPS_CONTENT;
6737       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6738       /* The sh_info field is set in final_write_processing.  */
6739     }
6740   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6741     {
6742       hdr->sh_type = SHT_MIPS_OPTIONS;
6743       hdr->sh_entsize = 1;
6744       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6745     }
6746   else if (CONST_STRNEQ (name, ".debug_")
6747            || CONST_STRNEQ (name, ".zdebug_"))
6748     {
6749       hdr->sh_type = SHT_MIPS_DWARF;
6750
6751       /* Irix facilities such as libexc expect a single .debug_frame
6752          per executable, the system ones have NOSTRIP set and the linker
6753          doesn't merge sections with different flags so ...  */
6754       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
6755         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6756     }
6757   else if (strcmp (name, ".MIPS.symlib") == 0)
6758     {
6759       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
6760       /* The sh_link and sh_info fields are set in
6761          final_write_processing.  */
6762     }
6763   else if (CONST_STRNEQ (name, ".MIPS.events")
6764            || CONST_STRNEQ (name, ".MIPS.post_rel"))
6765     {
6766       hdr->sh_type = SHT_MIPS_EVENTS;
6767       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6768       /* The sh_link field is set in final_write_processing.  */
6769     }
6770   else if (strcmp (name, ".msym") == 0)
6771     {
6772       hdr->sh_type = SHT_MIPS_MSYM;
6773       hdr->sh_flags |= SHF_ALLOC;
6774       hdr->sh_entsize = 8;
6775     }
6776
6777   /* The generic elf_fake_sections will set up REL_HDR using the default
6778    kind of relocations.  We used to set up a second header for the
6779    non-default kind of relocations here, but only NewABI would use
6780    these, and the IRIX ld doesn't like resulting empty RELA sections.
6781    Thus we create those header only on demand now.  */
6782
6783   return TRUE;
6784 }
6785
6786 /* Given a BFD section, try to locate the corresponding ELF section
6787    index.  This is used by both the 32-bit and the 64-bit ABI.
6788    Actually, it's not clear to me that the 64-bit ABI supports these,
6789    but for non-PIC objects we will certainly want support for at least
6790    the .scommon section.  */
6791
6792 bfd_boolean
6793 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
6794                                         asection *sec, int *retval)
6795 {
6796   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
6797     {
6798       *retval = SHN_MIPS_SCOMMON;
6799       return TRUE;
6800     }
6801   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
6802     {
6803       *retval = SHN_MIPS_ACOMMON;
6804       return TRUE;
6805     }
6806   return FALSE;
6807 }
6808 \f
6809 /* Hook called by the linker routine which adds symbols from an object
6810    file.  We must handle the special MIPS section numbers here.  */
6811
6812 bfd_boolean
6813 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
6814                                Elf_Internal_Sym *sym, const char **namep,
6815                                flagword *flagsp ATTRIBUTE_UNUSED,
6816                                asection **secp, bfd_vma *valp)
6817 {
6818   if (SGI_COMPAT (abfd)
6819       && (abfd->flags & DYNAMIC) != 0
6820       && strcmp (*namep, "_rld_new_interface") == 0)
6821     {
6822       /* Skip IRIX5 rld entry name.  */
6823       *namep = NULL;
6824       return TRUE;
6825     }
6826
6827   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
6828      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
6829      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
6830      a magic symbol resolved by the linker, we ignore this bogus definition
6831      of _gp_disp.  New ABI objects do not suffer from this problem so this
6832      is not done for them. */
6833   if (!NEWABI_P(abfd)
6834       && (sym->st_shndx == SHN_ABS)
6835       && (strcmp (*namep, "_gp_disp") == 0))
6836     {
6837       *namep = NULL;
6838       return TRUE;
6839     }
6840
6841   switch (sym->st_shndx)
6842     {
6843     case SHN_COMMON:
6844       /* Common symbols less than the GP size are automatically
6845          treated as SHN_MIPS_SCOMMON symbols.  */
6846       if (sym->st_size > elf_gp_size (abfd)
6847           || ELF_ST_TYPE (sym->st_info) == STT_TLS
6848           || IRIX_COMPAT (abfd) == ict_irix6)
6849         break;
6850       /* Fall through.  */
6851     case SHN_MIPS_SCOMMON:
6852       *secp = bfd_make_section_old_way (abfd, ".scommon");
6853       (*secp)->flags |= SEC_IS_COMMON;
6854       *valp = sym->st_size;
6855       break;
6856
6857     case SHN_MIPS_TEXT:
6858       /* This section is used in a shared object.  */
6859       if (elf_tdata (abfd)->elf_text_section == NULL)
6860         {
6861           asymbol *elf_text_symbol;
6862           asection *elf_text_section;
6863           bfd_size_type amt = sizeof (asection);
6864
6865           elf_text_section = bfd_zalloc (abfd, amt);
6866           if (elf_text_section == NULL)
6867             return FALSE;
6868
6869           amt = sizeof (asymbol);
6870           elf_text_symbol = bfd_zalloc (abfd, amt);
6871           if (elf_text_symbol == NULL)
6872             return FALSE;
6873
6874           /* Initialize the section.  */
6875
6876           elf_tdata (abfd)->elf_text_section = elf_text_section;
6877           elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
6878
6879           elf_text_section->symbol = elf_text_symbol;
6880           elf_text_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_text_symbol;
6881
6882           elf_text_section->name = ".text";
6883           elf_text_section->flags = SEC_NO_FLAGS;
6884           elf_text_section->output_section = NULL;
6885           elf_text_section->owner = abfd;
6886           elf_text_symbol->name = ".text";
6887           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
6888           elf_text_symbol->section = elf_text_section;
6889         }
6890       /* This code used to do *secp = bfd_und_section_ptr if
6891          info->shared.  I don't know why, and that doesn't make sense,
6892          so I took it out.  */
6893       *secp = elf_tdata (abfd)->elf_text_section;
6894       break;
6895
6896     case SHN_MIPS_ACOMMON:
6897       /* Fall through. XXX Can we treat this as allocated data?  */
6898     case SHN_MIPS_DATA:
6899       /* This section is used in a shared object.  */
6900       if (elf_tdata (abfd)->elf_data_section == NULL)
6901         {
6902           asymbol *elf_data_symbol;
6903           asection *elf_data_section;
6904           bfd_size_type amt = sizeof (asection);
6905
6906           elf_data_section = bfd_zalloc (abfd, amt);
6907           if (elf_data_section == NULL)
6908             return FALSE;
6909
6910           amt = sizeof (asymbol);
6911           elf_data_symbol = bfd_zalloc (abfd, amt);
6912           if (elf_data_symbol == NULL)
6913             return FALSE;
6914
6915           /* Initialize the section.  */
6916
6917           elf_tdata (abfd)->elf_data_section = elf_data_section;
6918           elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
6919
6920           elf_data_section->symbol = elf_data_symbol;
6921           elf_data_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_data_symbol;
6922
6923           elf_data_section->name = ".data";
6924           elf_data_section->flags = SEC_NO_FLAGS;
6925           elf_data_section->output_section = NULL;
6926           elf_data_section->owner = abfd;
6927           elf_data_symbol->name = ".data";
6928           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
6929           elf_data_symbol->section = elf_data_section;
6930         }
6931       /* This code used to do *secp = bfd_und_section_ptr if
6932          info->shared.  I don't know why, and that doesn't make sense,
6933          so I took it out.  */
6934       *secp = elf_tdata (abfd)->elf_data_section;
6935       break;
6936
6937     case SHN_MIPS_SUNDEFINED:
6938       *secp = bfd_und_section_ptr;
6939       break;
6940     }
6941
6942   if (SGI_COMPAT (abfd)
6943       && ! info->shared
6944       && info->output_bfd->xvec == abfd->xvec
6945       && strcmp (*namep, "__rld_obj_head") == 0)
6946     {
6947       struct elf_link_hash_entry *h;
6948       struct bfd_link_hash_entry *bh;
6949
6950       /* Mark __rld_obj_head as dynamic.  */
6951       bh = NULL;
6952       if (! (_bfd_generic_link_add_one_symbol
6953              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
6954               get_elf_backend_data (abfd)->collect, &bh)))
6955         return FALSE;
6956
6957       h = (struct elf_link_hash_entry *) bh;
6958       h->non_elf = 0;
6959       h->def_regular = 1;
6960       h->type = STT_OBJECT;
6961
6962       if (! bfd_elf_link_record_dynamic_symbol (info, h))
6963         return FALSE;
6964
6965       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
6966       mips_elf_hash_table (info)->rld_symbol = h;
6967     }
6968
6969   /* If this is a mips16 text symbol, add 1 to the value to make it
6970      odd.  This will cause something like .word SYM to come up with
6971      the right value when it is loaded into the PC.  */
6972   if (ELF_ST_IS_COMPRESSED (sym->st_other))
6973     ++*valp;
6974
6975   return TRUE;
6976 }
6977
6978 /* This hook function is called before the linker writes out a global
6979    symbol.  We mark symbols as small common if appropriate.  This is
6980    also where we undo the increment of the value for a mips16 symbol.  */
6981
6982 int
6983 _bfd_mips_elf_link_output_symbol_hook
6984   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
6985    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
6986    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
6987 {
6988   /* If we see a common symbol, which implies a relocatable link, then
6989      if a symbol was small common in an input file, mark it as small
6990      common in the output file.  */
6991   if (sym->st_shndx == SHN_COMMON
6992       && strcmp (input_sec->name, ".scommon") == 0)
6993     sym->st_shndx = SHN_MIPS_SCOMMON;
6994
6995   if (ELF_ST_IS_COMPRESSED (sym->st_other))
6996     sym->st_value &= ~1;
6997
6998   return 1;
6999 }
7000 \f
7001 /* Functions for the dynamic linker.  */
7002
7003 /* Create dynamic sections when linking against a dynamic object.  */
7004
7005 bfd_boolean
7006 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
7007 {
7008   struct elf_link_hash_entry *h;
7009   struct bfd_link_hash_entry *bh;
7010   flagword flags;
7011   register asection *s;
7012   const char * const *namep;
7013   struct mips_elf_link_hash_table *htab;
7014
7015   htab = mips_elf_hash_table (info);
7016   BFD_ASSERT (htab != NULL);
7017
7018   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
7019            | SEC_LINKER_CREATED | SEC_READONLY);
7020
7021   /* The psABI requires a read-only .dynamic section, but the VxWorks
7022      EABI doesn't.  */
7023   if (!htab->is_vxworks)
7024     {
7025       s = bfd_get_linker_section (abfd, ".dynamic");
7026       if (s != NULL)
7027         {
7028           if (! bfd_set_section_flags (abfd, s, flags))
7029             return FALSE;
7030         }
7031     }
7032
7033   /* We need to create .got section.  */
7034   if (!mips_elf_create_got_section (abfd, info))
7035     return FALSE;
7036
7037   if (! mips_elf_rel_dyn_section (info, TRUE))
7038     return FALSE;
7039
7040   /* Create .stub section.  */
7041   s = bfd_make_section_anyway_with_flags (abfd,
7042                                           MIPS_ELF_STUB_SECTION_NAME (abfd),
7043                                           flags | SEC_CODE);
7044   if (s == NULL
7045       || ! bfd_set_section_alignment (abfd, s,
7046                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7047     return FALSE;
7048   htab->sstubs = s;
7049
7050   if (!mips_elf_hash_table (info)->use_rld_obj_head
7051       && !info->shared
7052       && bfd_get_linker_section (abfd, ".rld_map") == NULL)
7053     {
7054       s = bfd_make_section_anyway_with_flags (abfd, ".rld_map",
7055                                               flags &~ (flagword) SEC_READONLY);
7056       if (s == NULL
7057           || ! bfd_set_section_alignment (abfd, s,
7058                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7059         return FALSE;
7060     }
7061
7062   /* On IRIX5, we adjust add some additional symbols and change the
7063      alignments of several sections.  There is no ABI documentation
7064      indicating that this is necessary on IRIX6, nor any evidence that
7065      the linker takes such action.  */
7066   if (IRIX_COMPAT (abfd) == ict_irix5)
7067     {
7068       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7069         {
7070           bh = NULL;
7071           if (! (_bfd_generic_link_add_one_symbol
7072                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7073                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7074             return FALSE;
7075
7076           h = (struct elf_link_hash_entry *) bh;
7077           h->non_elf = 0;
7078           h->def_regular = 1;
7079           h->type = STT_SECTION;
7080
7081           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7082             return FALSE;
7083         }
7084
7085       /* We need to create a .compact_rel section.  */
7086       if (SGI_COMPAT (abfd))
7087         {
7088           if (!mips_elf_create_compact_rel_section (abfd, info))
7089             return FALSE;
7090         }
7091
7092       /* Change alignments of some sections.  */
7093       s = bfd_get_linker_section (abfd, ".hash");
7094       if (s != NULL)
7095         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7096       s = bfd_get_linker_section (abfd, ".dynsym");
7097       if (s != NULL)
7098         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7099       s = bfd_get_linker_section (abfd, ".dynstr");
7100       if (s != NULL)
7101         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7102       /* ??? */
7103       s = bfd_get_section_by_name (abfd, ".reginfo");
7104       if (s != NULL)
7105         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7106       s = bfd_get_linker_section (abfd, ".dynamic");
7107       if (s != NULL)
7108         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7109     }
7110
7111   if (!info->shared)
7112     {
7113       const char *name;
7114
7115       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7116       bh = NULL;
7117       if (!(_bfd_generic_link_add_one_symbol
7118             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7119              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7120         return FALSE;
7121
7122       h = (struct elf_link_hash_entry *) bh;
7123       h->non_elf = 0;
7124       h->def_regular = 1;
7125       h->type = STT_SECTION;
7126
7127       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7128         return FALSE;
7129
7130       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7131         {
7132           /* __rld_map is a four byte word located in the .data section
7133              and is filled in by the rtld to contain a pointer to
7134              the _r_debug structure. Its symbol value will be set in
7135              _bfd_mips_elf_finish_dynamic_symbol.  */
7136           s = bfd_get_linker_section (abfd, ".rld_map");
7137           BFD_ASSERT (s != NULL);
7138
7139           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7140           bh = NULL;
7141           if (!(_bfd_generic_link_add_one_symbol
7142                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7143                  get_elf_backend_data (abfd)->collect, &bh)))
7144             return FALSE;
7145
7146           h = (struct elf_link_hash_entry *) bh;
7147           h->non_elf = 0;
7148           h->def_regular = 1;
7149           h->type = STT_OBJECT;
7150
7151           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7152             return FALSE;
7153           mips_elf_hash_table (info)->rld_symbol = h;
7154         }
7155     }
7156
7157   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7158      Also create the _PROCEDURE_LINKAGE_TABLE symbol.  */
7159   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7160     return FALSE;
7161
7162   /* Cache the sections created above.  */
7163   htab->splt = bfd_get_linker_section (abfd, ".plt");
7164   htab->sdynbss = bfd_get_linker_section (abfd, ".dynbss");
7165   if (htab->is_vxworks)
7166     {
7167       htab->srelbss = bfd_get_linker_section (abfd, ".rela.bss");
7168       htab->srelplt = bfd_get_linker_section (abfd, ".rela.plt");
7169     }
7170   else
7171     htab->srelplt = bfd_get_linker_section (abfd, ".rel.plt");
7172   if (!htab->sdynbss
7173       || (htab->is_vxworks && !htab->srelbss && !info->shared)
7174       || !htab->srelplt
7175       || !htab->splt)
7176     abort ();
7177
7178   if (htab->is_vxworks)
7179     {
7180       /* Do the usual VxWorks handling.  */
7181       if (!elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7182         return FALSE;
7183
7184       /* Work out the PLT sizes.  */
7185       if (info->shared)
7186         {
7187           htab->plt_header_size
7188             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
7189           htab->plt_entry_size
7190             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
7191         }
7192       else
7193         {
7194           htab->plt_header_size
7195             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
7196           htab->plt_entry_size
7197             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
7198         }
7199     }
7200   else if (!info->shared)
7201     {
7202       /* All variants of the plt0 entry are the same size.  */
7203       htab->plt_header_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
7204       htab->plt_entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
7205     }
7206
7207   return TRUE;
7208 }
7209 \f
7210 /* Return true if relocation REL against section SEC is a REL rather than
7211    RELA relocation.  RELOCS is the first relocation in the section and
7212    ABFD is the bfd that contains SEC.  */
7213
7214 static bfd_boolean
7215 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7216                            const Elf_Internal_Rela *relocs,
7217                            const Elf_Internal_Rela *rel)
7218 {
7219   Elf_Internal_Shdr *rel_hdr;
7220   const struct elf_backend_data *bed;
7221
7222   /* To determine which flavor of relocation this is, we depend on the
7223      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7224   rel_hdr = elf_section_data (sec)->rel.hdr;
7225   if (rel_hdr == NULL)
7226     return FALSE;
7227   bed = get_elf_backend_data (abfd);
7228   return ((size_t) (rel - relocs)
7229           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7230 }
7231
7232 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7233    HOWTO is the relocation's howto and CONTENTS points to the contents
7234    of the section that REL is against.  */
7235
7236 static bfd_vma
7237 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7238                           reloc_howto_type *howto, bfd_byte *contents)
7239 {
7240   bfd_byte *location;
7241   unsigned int r_type;
7242   bfd_vma addend;
7243
7244   r_type = ELF_R_TYPE (abfd, rel->r_info);
7245   location = contents + rel->r_offset;
7246
7247   /* Get the addend, which is stored in the input file.  */
7248   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7249   addend = mips_elf_obtain_contents (howto, rel, abfd, contents);
7250   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7251
7252   return addend & howto->src_mask;
7253 }
7254
7255 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7256    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7257    and update *ADDEND with the final addend.  Return true on success
7258    or false if the LO16 could not be found.  RELEND is the exclusive
7259    upper bound on the relocations for REL's section.  */
7260
7261 static bfd_boolean
7262 mips_elf_add_lo16_rel_addend (bfd *abfd,
7263                               const Elf_Internal_Rela *rel,
7264                               const Elf_Internal_Rela *relend,
7265                               bfd_byte *contents, bfd_vma *addend)
7266 {
7267   unsigned int r_type, lo16_type;
7268   const Elf_Internal_Rela *lo16_relocation;
7269   reloc_howto_type *lo16_howto;
7270   bfd_vma l;
7271
7272   r_type = ELF_R_TYPE (abfd, rel->r_info);
7273   if (mips16_reloc_p (r_type))
7274     lo16_type = R_MIPS16_LO16;
7275   else if (micromips_reloc_p (r_type))
7276     lo16_type = R_MICROMIPS_LO16;
7277   else
7278     lo16_type = R_MIPS_LO16;
7279
7280   /* The combined value is the sum of the HI16 addend, left-shifted by
7281      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7282      code does a `lui' of the HI16 value, and then an `addiu' of the
7283      LO16 value.)
7284
7285      Scan ahead to find a matching LO16 relocation.
7286
7287      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7288      be immediately following.  However, for the IRIX6 ABI, the next
7289      relocation may be a composed relocation consisting of several
7290      relocations for the same address.  In that case, the R_MIPS_LO16
7291      relocation may occur as one of these.  We permit a similar
7292      extension in general, as that is useful for GCC.
7293
7294      In some cases GCC dead code elimination removes the LO16 but keeps
7295      the corresponding HI16.  This is strictly speaking a violation of
7296      the ABI but not immediately harmful.  */
7297   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
7298   if (lo16_relocation == NULL)
7299     return FALSE;
7300
7301   /* Obtain the addend kept there.  */
7302   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
7303   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
7304
7305   l <<= lo16_howto->rightshift;
7306   l = _bfd_mips_elf_sign_extend (l, 16);
7307
7308   *addend <<= 16;
7309   *addend += l;
7310   return TRUE;
7311 }
7312
7313 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
7314    store the contents in *CONTENTS on success.  Assume that *CONTENTS
7315    already holds the contents if it is nonull on entry.  */
7316
7317 static bfd_boolean
7318 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
7319 {
7320   if (*contents)
7321     return TRUE;
7322
7323   /* Get cached copy if it exists.  */
7324   if (elf_section_data (sec)->this_hdr.contents != NULL)
7325     {
7326       *contents = elf_section_data (sec)->this_hdr.contents;
7327       return TRUE;
7328     }
7329
7330   return bfd_malloc_and_get_section (abfd, sec, contents);
7331 }
7332
7333 /* Look through the relocs for a section during the first phase, and
7334    allocate space in the global offset table.  */
7335
7336 bfd_boolean
7337 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
7338                             asection *sec, const Elf_Internal_Rela *relocs)
7339 {
7340   const char *name;
7341   bfd *dynobj;
7342   Elf_Internal_Shdr *symtab_hdr;
7343   struct elf_link_hash_entry **sym_hashes;
7344   size_t extsymoff;
7345   const Elf_Internal_Rela *rel;
7346   const Elf_Internal_Rela *rel_end;
7347   asection *sreloc;
7348   const struct elf_backend_data *bed;
7349   struct mips_elf_link_hash_table *htab;
7350   bfd_byte *contents;
7351   bfd_vma addend;
7352   reloc_howto_type *howto;
7353
7354   if (info->relocatable)
7355     return TRUE;
7356
7357   htab = mips_elf_hash_table (info);
7358   BFD_ASSERT (htab != NULL);
7359
7360   dynobj = elf_hash_table (info)->dynobj;
7361   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7362   sym_hashes = elf_sym_hashes (abfd);
7363   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
7364
7365   bed = get_elf_backend_data (abfd);
7366   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
7367
7368   /* Check for the mips16 stub sections.  */
7369
7370   name = bfd_get_section_name (abfd, sec);
7371   if (FN_STUB_P (name))
7372     {
7373       unsigned long r_symndx;
7374
7375       /* Look at the relocation information to figure out which symbol
7376          this is for.  */
7377
7378       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7379       if (r_symndx == 0)
7380         {
7381           (*_bfd_error_handler)
7382             (_("%B: Warning: cannot determine the target function for"
7383                " stub section `%s'"),
7384              abfd, name);
7385           bfd_set_error (bfd_error_bad_value);
7386           return FALSE;
7387         }
7388
7389       if (r_symndx < extsymoff
7390           || sym_hashes[r_symndx - extsymoff] == NULL)
7391         {
7392           asection *o;
7393
7394           /* This stub is for a local symbol.  This stub will only be
7395              needed if there is some relocation in this BFD, other
7396              than a 16 bit function call, which refers to this symbol.  */
7397           for (o = abfd->sections; o != NULL; o = o->next)
7398             {
7399               Elf_Internal_Rela *sec_relocs;
7400               const Elf_Internal_Rela *r, *rend;
7401
7402               /* We can ignore stub sections when looking for relocs.  */
7403               if ((o->flags & SEC_RELOC) == 0
7404                   || o->reloc_count == 0
7405                   || section_allows_mips16_refs_p (o))
7406                 continue;
7407
7408               sec_relocs
7409                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7410                                              info->keep_memory);
7411               if (sec_relocs == NULL)
7412                 return FALSE;
7413
7414               rend = sec_relocs + o->reloc_count;
7415               for (r = sec_relocs; r < rend; r++)
7416                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7417                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
7418                   break;
7419
7420               if (elf_section_data (o)->relocs != sec_relocs)
7421                 free (sec_relocs);
7422
7423               if (r < rend)
7424                 break;
7425             }
7426
7427           if (o == NULL)
7428             {
7429               /* There is no non-call reloc for this stub, so we do
7430                  not need it.  Since this function is called before
7431                  the linker maps input sections to output sections, we
7432                  can easily discard it by setting the SEC_EXCLUDE
7433                  flag.  */
7434               sec->flags |= SEC_EXCLUDE;
7435               return TRUE;
7436             }
7437
7438           /* Record this stub in an array of local symbol stubs for
7439              this BFD.  */
7440           if (elf_tdata (abfd)->local_stubs == NULL)
7441             {
7442               unsigned long symcount;
7443               asection **n;
7444               bfd_size_type amt;
7445
7446               if (elf_bad_symtab (abfd))
7447                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7448               else
7449                 symcount = symtab_hdr->sh_info;
7450               amt = symcount * sizeof (asection *);
7451               n = bfd_zalloc (abfd, amt);
7452               if (n == NULL)
7453                 return FALSE;
7454               elf_tdata (abfd)->local_stubs = n;
7455             }
7456
7457           sec->flags |= SEC_KEEP;
7458           elf_tdata (abfd)->local_stubs[r_symndx] = sec;
7459
7460           /* We don't need to set mips16_stubs_seen in this case.
7461              That flag is used to see whether we need to look through
7462              the global symbol table for stubs.  We don't need to set
7463              it here, because we just have a local stub.  */
7464         }
7465       else
7466         {
7467           struct mips_elf_link_hash_entry *h;
7468
7469           h = ((struct mips_elf_link_hash_entry *)
7470                sym_hashes[r_symndx - extsymoff]);
7471
7472           while (h->root.root.type == bfd_link_hash_indirect
7473                  || h->root.root.type == bfd_link_hash_warning)
7474             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
7475
7476           /* H is the symbol this stub is for.  */
7477
7478           /* If we already have an appropriate stub for this function, we
7479              don't need another one, so we can discard this one.  Since
7480              this function is called before the linker maps input sections
7481              to output sections, we can easily discard it by setting the
7482              SEC_EXCLUDE flag.  */
7483           if (h->fn_stub != NULL)
7484             {
7485               sec->flags |= SEC_EXCLUDE;
7486               return TRUE;
7487             }
7488
7489           sec->flags |= SEC_KEEP;
7490           h->fn_stub = sec;
7491           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7492         }
7493     }
7494   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
7495     {
7496       unsigned long r_symndx;
7497       struct mips_elf_link_hash_entry *h;
7498       asection **loc;
7499
7500       /* Look at the relocation information to figure out which symbol
7501          this is for.  */
7502
7503       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7504       if (r_symndx == 0)
7505         {
7506           (*_bfd_error_handler)
7507             (_("%B: Warning: cannot determine the target function for"
7508                " stub section `%s'"),
7509              abfd, name);
7510           bfd_set_error (bfd_error_bad_value);
7511           return FALSE;
7512         }
7513
7514       if (r_symndx < extsymoff
7515           || sym_hashes[r_symndx - extsymoff] == NULL)
7516         {
7517           asection *o;
7518
7519           /* This stub is for a local symbol.  This stub will only be
7520              needed if there is some relocation (R_MIPS16_26) in this BFD
7521              that refers to this symbol.  */
7522           for (o = abfd->sections; o != NULL; o = o->next)
7523             {
7524               Elf_Internal_Rela *sec_relocs;
7525               const Elf_Internal_Rela *r, *rend;
7526
7527               /* We can ignore stub sections when looking for relocs.  */
7528               if ((o->flags & SEC_RELOC) == 0
7529                   || o->reloc_count == 0
7530                   || section_allows_mips16_refs_p (o))
7531                 continue;
7532
7533               sec_relocs
7534                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7535                                              info->keep_memory);
7536               if (sec_relocs == NULL)
7537                 return FALSE;
7538
7539               rend = sec_relocs + o->reloc_count;
7540               for (r = sec_relocs; r < rend; r++)
7541                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7542                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
7543                     break;
7544
7545               if (elf_section_data (o)->relocs != sec_relocs)
7546                 free (sec_relocs);
7547
7548               if (r < rend)
7549                 break;
7550             }
7551
7552           if (o == NULL)
7553             {
7554               /* There is no non-call reloc for this stub, so we do
7555                  not need it.  Since this function is called before
7556                  the linker maps input sections to output sections, we
7557                  can easily discard it by setting the SEC_EXCLUDE
7558                  flag.  */
7559               sec->flags |= SEC_EXCLUDE;
7560               return TRUE;
7561             }
7562
7563           /* Record this stub in an array of local symbol call_stubs for
7564              this BFD.  */
7565           if (elf_tdata (abfd)->local_call_stubs == NULL)
7566             {
7567               unsigned long symcount;
7568               asection **n;
7569               bfd_size_type amt;
7570
7571               if (elf_bad_symtab (abfd))
7572                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7573               else
7574                 symcount = symtab_hdr->sh_info;
7575               amt = symcount * sizeof (asection *);
7576               n = bfd_zalloc (abfd, amt);
7577               if (n == NULL)
7578                 return FALSE;
7579               elf_tdata (abfd)->local_call_stubs = n;
7580             }
7581
7582           sec->flags |= SEC_KEEP;
7583           elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
7584
7585           /* We don't need to set mips16_stubs_seen in this case.
7586              That flag is used to see whether we need to look through
7587              the global symbol table for stubs.  We don't need to set
7588              it here, because we just have a local stub.  */
7589         }
7590       else
7591         {
7592           h = ((struct mips_elf_link_hash_entry *)
7593                sym_hashes[r_symndx - extsymoff]);
7594
7595           /* H is the symbol this stub is for.  */
7596
7597           if (CALL_FP_STUB_P (name))
7598             loc = &h->call_fp_stub;
7599           else
7600             loc = &h->call_stub;
7601
7602           /* If we already have an appropriate stub for this function, we
7603              don't need another one, so we can discard this one.  Since
7604              this function is called before the linker maps input sections
7605              to output sections, we can easily discard it by setting the
7606              SEC_EXCLUDE flag.  */
7607           if (*loc != NULL)
7608             {
7609               sec->flags |= SEC_EXCLUDE;
7610               return TRUE;
7611             }
7612
7613           sec->flags |= SEC_KEEP;
7614           *loc = sec;
7615           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7616         }
7617     }
7618
7619   sreloc = NULL;
7620   contents = NULL;
7621   for (rel = relocs; rel < rel_end; ++rel)
7622     {
7623       unsigned long r_symndx;
7624       unsigned int r_type;
7625       struct elf_link_hash_entry *h;
7626       bfd_boolean can_make_dynamic_p;
7627
7628       r_symndx = ELF_R_SYM (abfd, rel->r_info);
7629       r_type = ELF_R_TYPE (abfd, rel->r_info);
7630
7631       if (r_symndx < extsymoff)
7632         h = NULL;
7633       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
7634         {
7635           (*_bfd_error_handler)
7636             (_("%B: Malformed reloc detected for section %s"),
7637              abfd, name);
7638           bfd_set_error (bfd_error_bad_value);
7639           return FALSE;
7640         }
7641       else
7642         {
7643           h = sym_hashes[r_symndx - extsymoff];
7644           while (h != NULL
7645                  && (h->root.type == bfd_link_hash_indirect
7646                      || h->root.type == bfd_link_hash_warning))
7647             h = (struct elf_link_hash_entry *) h->root.u.i.link;
7648         }
7649
7650       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
7651          relocation into a dynamic one.  */
7652       can_make_dynamic_p = FALSE;
7653       switch (r_type)
7654         {
7655         case R_MIPS_GOT16:
7656         case R_MIPS_CALL16:
7657         case R_MIPS_CALL_HI16:
7658         case R_MIPS_CALL_LO16:
7659         case R_MIPS_GOT_HI16:
7660         case R_MIPS_GOT_LO16:
7661         case R_MIPS_GOT_PAGE:
7662         case R_MIPS_GOT_OFST:
7663         case R_MIPS_GOT_DISP:
7664         case R_MIPS_TLS_GOTTPREL:
7665         case R_MIPS_TLS_GD:
7666         case R_MIPS_TLS_LDM:
7667         case R_MIPS16_GOT16:
7668         case R_MIPS16_CALL16:
7669         case R_MIPS16_TLS_GOTTPREL:
7670         case R_MIPS16_TLS_GD:
7671         case R_MIPS16_TLS_LDM:
7672         case R_MICROMIPS_GOT16:
7673         case R_MICROMIPS_CALL16:
7674         case R_MICROMIPS_CALL_HI16:
7675         case R_MICROMIPS_CALL_LO16:
7676         case R_MICROMIPS_GOT_HI16:
7677         case R_MICROMIPS_GOT_LO16:
7678         case R_MICROMIPS_GOT_PAGE:
7679         case R_MICROMIPS_GOT_OFST:
7680         case R_MICROMIPS_GOT_DISP:
7681         case R_MICROMIPS_TLS_GOTTPREL:
7682         case R_MICROMIPS_TLS_GD:
7683         case R_MICROMIPS_TLS_LDM:
7684           if (dynobj == NULL)
7685             elf_hash_table (info)->dynobj = dynobj = abfd;
7686           if (!mips_elf_create_got_section (dynobj, info))
7687             return FALSE;
7688           if (htab->is_vxworks && !info->shared)
7689             {
7690               (*_bfd_error_handler)
7691                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
7692                  abfd, (unsigned long) rel->r_offset);
7693               bfd_set_error (bfd_error_bad_value);
7694               return FALSE;
7695             }
7696           break;
7697
7698           /* This is just a hint; it can safely be ignored.  Don't set
7699              has_static_relocs for the corresponding symbol.  */
7700         case R_MIPS_JALR:
7701         case R_MICROMIPS_JALR:
7702           break;
7703
7704         case R_MIPS_32:
7705         case R_MIPS_REL32:
7706         case R_MIPS_64:
7707           /* In VxWorks executables, references to external symbols
7708              must be handled using copy relocs or PLT entries; it is not
7709              possible to convert this relocation into a dynamic one.
7710
7711              For executables that use PLTs and copy-relocs, we have a
7712              choice between converting the relocation into a dynamic
7713              one or using copy relocations or PLT entries.  It is
7714              usually better to do the former, unless the relocation is
7715              against a read-only section.  */
7716           if ((info->shared
7717                || (h != NULL
7718                    && !htab->is_vxworks
7719                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
7720                    && !(!info->nocopyreloc
7721                         && !PIC_OBJECT_P (abfd)
7722                         && MIPS_ELF_READONLY_SECTION (sec))))
7723               && (sec->flags & SEC_ALLOC) != 0)
7724             {
7725               can_make_dynamic_p = TRUE;
7726               if (dynobj == NULL)
7727                 elf_hash_table (info)->dynobj = dynobj = abfd;
7728               break;
7729             }
7730           /* For sections that are not SEC_ALLOC a copy reloc would be
7731              output if possible (implying questionable semantics for
7732              read-only data objects) or otherwise the final link would
7733              fail as ld.so will not process them and could not therefore
7734              handle any outstanding dynamic relocations.
7735
7736              For such sections that are also SEC_DEBUGGING, we can avoid
7737              these problems by simply ignoring any relocs as these
7738              sections have a predefined use and we know it is safe to do
7739              so.
7740
7741              This is needed in cases such as a global symbol definition
7742              in a shared library causing a common symbol from an object
7743              file to be converted to an undefined reference.  If that
7744              happens, then all the relocations against this symbol from
7745              SEC_DEBUGGING sections in the object file will resolve to
7746              nil.  */
7747           if ((sec->flags & SEC_DEBUGGING) != 0)
7748             break;
7749           /* Fall through.  */
7750
7751         default:
7752           /* Most static relocations require pointer equality, except
7753              for branches.  */
7754           if (h)
7755             h->pointer_equality_needed = TRUE;
7756           /* Fall through.  */
7757
7758         case R_MIPS_26:
7759         case R_MIPS_PC16:
7760         case R_MIPS16_26:
7761         case R_MICROMIPS_26_S1:
7762         case R_MICROMIPS_PC7_S1:
7763         case R_MICROMIPS_PC10_S1:
7764         case R_MICROMIPS_PC16_S1:
7765         case R_MICROMIPS_PC23_S2:
7766           if (h)
7767             ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = TRUE;
7768           break;
7769         }
7770
7771       if (h)
7772         {
7773           /* Relocations against the special VxWorks __GOTT_BASE__ and
7774              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
7775              room for them in .rela.dyn.  */
7776           if (is_gott_symbol (info, h))
7777             {
7778               if (sreloc == NULL)
7779                 {
7780                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
7781                   if (sreloc == NULL)
7782                     return FALSE;
7783                 }
7784               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
7785               if (MIPS_ELF_READONLY_SECTION (sec))
7786                 /* We tell the dynamic linker that there are
7787                    relocations against the text segment.  */
7788                 info->flags |= DF_TEXTREL;
7789             }
7790         }
7791       else if (call_lo16_reloc_p (r_type)
7792                || got_lo16_reloc_p (r_type)
7793                || got_disp_reloc_p (r_type)
7794                || (got16_reloc_p (r_type) && htab->is_vxworks))
7795         {
7796           /* We may need a local GOT entry for this relocation.  We
7797              don't count R_MIPS_GOT_PAGE because we can estimate the
7798              maximum number of pages needed by looking at the size of
7799              the segment.  Similar comments apply to R_MIPS*_GOT16 and
7800              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
7801              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
7802              R_MIPS_CALL_HI16 because these are always followed by an
7803              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
7804           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
7805                                                  rel->r_addend, info, r_type))
7806             return FALSE;
7807         }
7808
7809       if (h != NULL
7810           && mips_elf_relocation_needs_la25_stub (abfd, r_type,
7811                                                   ELF_ST_IS_MIPS16 (h->other)))
7812         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
7813
7814       switch (r_type)
7815         {
7816         case R_MIPS_CALL16:
7817         case R_MIPS16_CALL16:
7818         case R_MICROMIPS_CALL16:
7819           if (h == NULL)
7820             {
7821               (*_bfd_error_handler)
7822                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
7823                  abfd, (unsigned long) rel->r_offset);
7824               bfd_set_error (bfd_error_bad_value);
7825               return FALSE;
7826             }
7827           /* Fall through.  */
7828
7829         case R_MIPS_CALL_HI16:
7830         case R_MIPS_CALL_LO16:
7831         case R_MICROMIPS_CALL_HI16:
7832         case R_MICROMIPS_CALL_LO16:
7833           if (h != NULL)
7834             {
7835               /* Make sure there is room in the regular GOT to hold the
7836                  function's address.  We may eliminate it in favour of
7837                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
7838               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE,
7839                                                       r_type))
7840                 return FALSE;
7841
7842               /* We need a stub, not a plt entry for the undefined
7843                  function.  But we record it as if it needs plt.  See
7844                  _bfd_elf_adjust_dynamic_symbol.  */
7845               h->needs_plt = 1;
7846               h->type = STT_FUNC;
7847             }
7848           break;
7849
7850         case R_MIPS_GOT_PAGE:
7851         case R_MICROMIPS_GOT_PAGE:
7852           /* If this is a global, overridable symbol, GOT_PAGE will
7853              decay to GOT_DISP, so we'll need a GOT entry for it.  */
7854           if (h)
7855             {
7856               struct mips_elf_link_hash_entry *hmips =
7857                 (struct mips_elf_link_hash_entry *) h;
7858
7859               /* This symbol is definitely not overridable.  */
7860               if (hmips->root.def_regular
7861                   && ! (info->shared && ! info->symbolic
7862                         && ! hmips->root.forced_local))
7863                 h = NULL;
7864             }
7865           /* Fall through.  */
7866
7867         case R_MIPS16_GOT16:
7868         case R_MIPS_GOT16:
7869         case R_MIPS_GOT_HI16:
7870         case R_MIPS_GOT_LO16:
7871         case R_MICROMIPS_GOT16:
7872         case R_MICROMIPS_GOT_HI16:
7873         case R_MICROMIPS_GOT_LO16:
7874           if (!h || got_page_reloc_p (r_type))
7875             {
7876               /* This relocation needs (or may need, if h != NULL) a
7877                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
7878                  know for sure until we know whether the symbol is
7879                  preemptible.  */
7880               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
7881                 {
7882                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
7883                     return FALSE;
7884                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
7885                   addend = mips_elf_read_rel_addend (abfd, rel,
7886                                                      howto, contents);
7887                   if (got16_reloc_p (r_type))
7888                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
7889                                                   contents, &addend);
7890                   else
7891                     addend <<= howto->rightshift;
7892                 }
7893               else
7894                 addend = rel->r_addend;
7895               if (!mips_elf_record_got_page_entry (info, abfd, r_symndx,
7896                                                    addend))
7897                 return FALSE;
7898             }
7899           /* Fall through.  */
7900
7901         case R_MIPS_GOT_DISP:
7902         case R_MICROMIPS_GOT_DISP:
7903           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
7904                                                        FALSE, r_type))
7905             return FALSE;
7906           break;
7907
7908         case R_MIPS_TLS_GOTTPREL:
7909         case R_MIPS16_TLS_GOTTPREL:
7910         case R_MICROMIPS_TLS_GOTTPREL:
7911           if (info->shared)
7912             info->flags |= DF_STATIC_TLS;
7913           /* Fall through */
7914
7915         case R_MIPS_TLS_LDM:
7916         case R_MIPS16_TLS_LDM:
7917         case R_MICROMIPS_TLS_LDM:
7918           if (tls_ldm_reloc_p (r_type))
7919             {
7920               r_symndx = STN_UNDEF;
7921               h = NULL;
7922             }
7923           /* Fall through */
7924
7925         case R_MIPS_TLS_GD:
7926         case R_MIPS16_TLS_GD:
7927         case R_MICROMIPS_TLS_GD:
7928           /* This symbol requires a global offset table entry, or two
7929              for TLS GD relocations.  */
7930           if (h != NULL)
7931             {
7932               if (!mips_elf_record_global_got_symbol (h, abfd, info,
7933                                                       FALSE, r_type))
7934                 return FALSE;
7935             }
7936           else
7937             {
7938               if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
7939                                                      rel->r_addend,
7940                                                      info, r_type))
7941                 return FALSE;
7942             }
7943           break;
7944
7945         case R_MIPS_32:
7946         case R_MIPS_REL32:
7947         case R_MIPS_64:
7948           /* In VxWorks executables, references to external symbols
7949              are handled using copy relocs or PLT stubs, so there's
7950              no need to add a .rela.dyn entry for this relocation.  */
7951           if (can_make_dynamic_p)
7952             {
7953               if (sreloc == NULL)
7954                 {
7955                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
7956                   if (sreloc == NULL)
7957                     return FALSE;
7958                 }
7959               if (info->shared && h == NULL)
7960                 {
7961                   /* When creating a shared object, we must copy these
7962                      reloc types into the output file as R_MIPS_REL32
7963                      relocs.  Make room for this reloc in .rel(a).dyn.  */
7964                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
7965                   if (MIPS_ELF_READONLY_SECTION (sec))
7966                     /* We tell the dynamic linker that there are
7967                        relocations against the text segment.  */
7968                     info->flags |= DF_TEXTREL;
7969                 }
7970               else
7971                 {
7972                   struct mips_elf_link_hash_entry *hmips;
7973
7974                   /* For a shared object, we must copy this relocation
7975                      unless the symbol turns out to be undefined and
7976                      weak with non-default visibility, in which case
7977                      it will be left as zero.
7978
7979                      We could elide R_MIPS_REL32 for locally binding symbols
7980                      in shared libraries, but do not yet do so.
7981
7982                      For an executable, we only need to copy this
7983                      reloc if the symbol is defined in a dynamic
7984                      object.  */
7985                   hmips = (struct mips_elf_link_hash_entry *) h;
7986                   ++hmips->possibly_dynamic_relocs;
7987                   if (MIPS_ELF_READONLY_SECTION (sec))
7988                     /* We need it to tell the dynamic linker if there
7989                        are relocations against the text segment.  */
7990                     hmips->readonly_reloc = TRUE;
7991                 }
7992             }
7993
7994           if (SGI_COMPAT (abfd))
7995             mips_elf_hash_table (info)->compact_rel_size +=
7996               sizeof (Elf32_External_crinfo);
7997           break;
7998
7999         case R_MIPS_26:
8000         case R_MIPS_GPREL16:
8001         case R_MIPS_LITERAL:
8002         case R_MIPS_GPREL32:
8003         case R_MICROMIPS_26_S1:
8004         case R_MICROMIPS_GPREL16:
8005         case R_MICROMIPS_LITERAL:
8006         case R_MICROMIPS_GPREL7_S2:
8007           if (SGI_COMPAT (abfd))
8008             mips_elf_hash_table (info)->compact_rel_size +=
8009               sizeof (Elf32_External_crinfo);
8010           break;
8011
8012           /* This relocation describes the C++ object vtable hierarchy.
8013              Reconstruct it for later use during GC.  */
8014         case R_MIPS_GNU_VTINHERIT:
8015           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
8016             return FALSE;
8017           break;
8018
8019           /* This relocation describes which C++ vtable entries are actually
8020              used.  Record for later use during GC.  */
8021         case R_MIPS_GNU_VTENTRY:
8022           BFD_ASSERT (h != NULL);
8023           if (h != NULL
8024               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
8025             return FALSE;
8026           break;
8027
8028         default:
8029           break;
8030         }
8031
8032       /* We must not create a stub for a symbol that has relocations
8033          related to taking the function's address.  This doesn't apply to
8034          VxWorks, where CALL relocs refer to a .got.plt entry instead of
8035          a normal .got entry.  */
8036       if (!htab->is_vxworks && h != NULL)
8037         switch (r_type)
8038           {
8039           default:
8040             ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8041             break;
8042           case R_MIPS16_CALL16:
8043           case R_MIPS_CALL16:
8044           case R_MIPS_CALL_HI16:
8045           case R_MIPS_CALL_LO16:
8046           case R_MIPS_JALR:
8047           case R_MICROMIPS_CALL16:
8048           case R_MICROMIPS_CALL_HI16:
8049           case R_MICROMIPS_CALL_LO16:
8050           case R_MICROMIPS_JALR:
8051             break;
8052           }
8053
8054       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8055          if there is one.  We only need to handle global symbols here;
8056          we decide whether to keep or delete stubs for local symbols
8057          when processing the stub's relocations.  */
8058       if (h != NULL
8059           && !mips16_call_reloc_p (r_type)
8060           && !section_allows_mips16_refs_p (sec))
8061         {
8062           struct mips_elf_link_hash_entry *mh;
8063
8064           mh = (struct mips_elf_link_hash_entry *) h;
8065           mh->need_fn_stub = TRUE;
8066         }
8067
8068       /* Refuse some position-dependent relocations when creating a
8069          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8070          not PIC, but we can create dynamic relocations and the result
8071          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8072          combined with R_MIPS_GOT16.  */
8073       if (info->shared)
8074         {
8075           switch (r_type)
8076             {
8077             case R_MIPS16_HI16:
8078             case R_MIPS_HI16:
8079             case R_MIPS_HIGHER:
8080             case R_MIPS_HIGHEST:
8081             case R_MICROMIPS_HI16:
8082             case R_MICROMIPS_HIGHER:
8083             case R_MICROMIPS_HIGHEST:
8084               /* Don't refuse a high part relocation if it's against
8085                  no symbol (e.g. part of a compound relocation).  */
8086               if (r_symndx == STN_UNDEF)
8087                 break;
8088
8089               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8090                  and has a special meaning.  */
8091               if (!NEWABI_P (abfd) && h != NULL
8092                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8093                 break;
8094
8095               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8096               if (is_gott_symbol (info, h))
8097                 break;
8098
8099               /* FALLTHROUGH */
8100
8101             case R_MIPS16_26:
8102             case R_MIPS_26:
8103             case R_MICROMIPS_26_S1:
8104               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8105               (*_bfd_error_handler)
8106                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8107                  abfd, howto->name,
8108                  (h) ? h->root.root.string : "a local symbol");
8109               bfd_set_error (bfd_error_bad_value);
8110               return FALSE;
8111             default:
8112               break;
8113             }
8114         }
8115     }
8116
8117   return TRUE;
8118 }
8119 \f
8120 bfd_boolean
8121 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8122                          struct bfd_link_info *link_info,
8123                          bfd_boolean *again)
8124 {
8125   Elf_Internal_Rela *internal_relocs;
8126   Elf_Internal_Rela *irel, *irelend;
8127   Elf_Internal_Shdr *symtab_hdr;
8128   bfd_byte *contents = NULL;
8129   size_t extsymoff;
8130   bfd_boolean changed_contents = FALSE;
8131   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8132   Elf_Internal_Sym *isymbuf = NULL;
8133
8134   /* We are not currently changing any sizes, so only one pass.  */
8135   *again = FALSE;
8136
8137   if (link_info->relocatable)
8138     return TRUE;
8139
8140   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8141                                                link_info->keep_memory);
8142   if (internal_relocs == NULL)
8143     return TRUE;
8144
8145   irelend = internal_relocs + sec->reloc_count
8146     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8147   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8148   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8149
8150   for (irel = internal_relocs; irel < irelend; irel++)
8151     {
8152       bfd_vma symval;
8153       bfd_signed_vma sym_offset;
8154       unsigned int r_type;
8155       unsigned long r_symndx;
8156       asection *sym_sec;
8157       unsigned long instruction;
8158
8159       /* Turn jalr into bgezal, and jr into beq, if they're marked
8160          with a JALR relocation, that indicate where they jump to.
8161          This saves some pipeline bubbles.  */
8162       r_type = ELF_R_TYPE (abfd, irel->r_info);
8163       if (r_type != R_MIPS_JALR)
8164         continue;
8165
8166       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8167       /* Compute the address of the jump target.  */
8168       if (r_symndx >= extsymoff)
8169         {
8170           struct mips_elf_link_hash_entry *h
8171             = ((struct mips_elf_link_hash_entry *)
8172                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8173
8174           while (h->root.root.type == bfd_link_hash_indirect
8175                  || h->root.root.type == bfd_link_hash_warning)
8176             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8177
8178           /* If a symbol is undefined, or if it may be overridden,
8179              skip it.  */
8180           if (! ((h->root.root.type == bfd_link_hash_defined
8181                   || h->root.root.type == bfd_link_hash_defweak)
8182                  && h->root.root.u.def.section)
8183               || (link_info->shared && ! link_info->symbolic
8184                   && !h->root.forced_local))
8185             continue;
8186
8187           sym_sec = h->root.root.u.def.section;
8188           if (sym_sec->output_section)
8189             symval = (h->root.root.u.def.value
8190                       + sym_sec->output_section->vma
8191                       + sym_sec->output_offset);
8192           else
8193             symval = h->root.root.u.def.value;
8194         }
8195       else
8196         {
8197           Elf_Internal_Sym *isym;
8198
8199           /* Read this BFD's symbols if we haven't done so already.  */
8200           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8201             {
8202               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8203               if (isymbuf == NULL)
8204                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8205                                                 symtab_hdr->sh_info, 0,
8206                                                 NULL, NULL, NULL);
8207               if (isymbuf == NULL)
8208                 goto relax_return;
8209             }
8210
8211           isym = isymbuf + r_symndx;
8212           if (isym->st_shndx == SHN_UNDEF)
8213             continue;
8214           else if (isym->st_shndx == SHN_ABS)
8215             sym_sec = bfd_abs_section_ptr;
8216           else if (isym->st_shndx == SHN_COMMON)
8217             sym_sec = bfd_com_section_ptr;
8218           else
8219             sym_sec
8220               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8221           symval = isym->st_value
8222             + sym_sec->output_section->vma
8223             + sym_sec->output_offset;
8224         }
8225
8226       /* Compute branch offset, from delay slot of the jump to the
8227          branch target.  */
8228       sym_offset = (symval + irel->r_addend)
8229         - (sec_start + irel->r_offset + 4);
8230
8231       /* Branch offset must be properly aligned.  */
8232       if ((sym_offset & 3) != 0)
8233         continue;
8234
8235       sym_offset >>= 2;
8236
8237       /* Check that it's in range.  */
8238       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
8239         continue;
8240
8241       /* Get the section contents if we haven't done so already.  */
8242       if (!mips_elf_get_section_contents (abfd, sec, &contents))
8243         goto relax_return;
8244
8245       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
8246
8247       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
8248       if ((instruction & 0xfc1fffff) == 0x0000f809)
8249         instruction = 0x04110000;
8250       /* If it was jr <reg>, turn it into b <target>.  */
8251       else if ((instruction & 0xfc1fffff) == 0x00000008)
8252         instruction = 0x10000000;
8253       else
8254         continue;
8255
8256       instruction |= (sym_offset & 0xffff);
8257       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
8258       changed_contents = TRUE;
8259     }
8260
8261   if (contents != NULL
8262       && elf_section_data (sec)->this_hdr.contents != contents)
8263     {
8264       if (!changed_contents && !link_info->keep_memory)
8265         free (contents);
8266       else
8267         {
8268           /* Cache the section contents for elf_link_input_bfd.  */
8269           elf_section_data (sec)->this_hdr.contents = contents;
8270         }
8271     }
8272   return TRUE;
8273
8274  relax_return:
8275   if (contents != NULL
8276       && elf_section_data (sec)->this_hdr.contents != contents)
8277     free (contents);
8278   return FALSE;
8279 }
8280 \f
8281 /* Allocate space for global sym dynamic relocs.  */
8282
8283 static bfd_boolean
8284 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
8285 {
8286   struct bfd_link_info *info = inf;
8287   bfd *dynobj;
8288   struct mips_elf_link_hash_entry *hmips;
8289   struct mips_elf_link_hash_table *htab;
8290
8291   htab = mips_elf_hash_table (info);
8292   BFD_ASSERT (htab != NULL);
8293
8294   dynobj = elf_hash_table (info)->dynobj;
8295   hmips = (struct mips_elf_link_hash_entry *) h;
8296
8297   /* VxWorks executables are handled elsewhere; we only need to
8298      allocate relocations in shared objects.  */
8299   if (htab->is_vxworks && !info->shared)
8300     return TRUE;
8301
8302   /* Ignore indirect symbols.  All relocations against such symbols
8303      will be redirected to the target symbol.  */
8304   if (h->root.type == bfd_link_hash_indirect)
8305     return TRUE;
8306
8307   /* If this symbol is defined in a dynamic object, or we are creating
8308      a shared library, we will need to copy any R_MIPS_32 or
8309      R_MIPS_REL32 relocs against it into the output file.  */
8310   if (! info->relocatable
8311       && hmips->possibly_dynamic_relocs != 0
8312       && (h->root.type == bfd_link_hash_defweak
8313           || (!h->def_regular && !ELF_COMMON_DEF_P (h))
8314           || info->shared))
8315     {
8316       bfd_boolean do_copy = TRUE;
8317
8318       if (h->root.type == bfd_link_hash_undefweak)
8319         {
8320           /* Do not copy relocations for undefined weak symbols with
8321              non-default visibility.  */
8322           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
8323             do_copy = FALSE;
8324
8325           /* Make sure undefined weak symbols are output as a dynamic
8326              symbol in PIEs.  */
8327           else if (h->dynindx == -1 && !h->forced_local)
8328             {
8329               if (! bfd_elf_link_record_dynamic_symbol (info, h))
8330                 return FALSE;
8331             }
8332         }
8333
8334       if (do_copy)
8335         {
8336           /* Even though we don't directly need a GOT entry for this symbol,
8337              the SVR4 psABI requires it to have a dynamic symbol table
8338              index greater that DT_MIPS_GOTSYM if there are dynamic
8339              relocations against it.
8340
8341              VxWorks does not enforce the same mapping between the GOT
8342              and the symbol table, so the same requirement does not
8343              apply there.  */
8344           if (!htab->is_vxworks)
8345             {
8346               if (hmips->global_got_area > GGA_RELOC_ONLY)
8347                 hmips->global_got_area = GGA_RELOC_ONLY;
8348               hmips->got_only_for_calls = FALSE;
8349             }
8350
8351           mips_elf_allocate_dynamic_relocations
8352             (dynobj, info, hmips->possibly_dynamic_relocs);
8353           if (hmips->readonly_reloc)
8354             /* We tell the dynamic linker that there are relocations
8355                against the text segment.  */
8356             info->flags |= DF_TEXTREL;
8357         }
8358     }
8359
8360   return TRUE;
8361 }
8362
8363 /* Adjust a symbol defined by a dynamic object and referenced by a
8364    regular object.  The current definition is in some section of the
8365    dynamic object, but we're not including those sections.  We have to
8366    change the definition to something the rest of the link can
8367    understand.  */
8368
8369 bfd_boolean
8370 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
8371                                      struct elf_link_hash_entry *h)
8372 {
8373   bfd *dynobj;
8374   struct mips_elf_link_hash_entry *hmips;
8375   struct mips_elf_link_hash_table *htab;
8376
8377   htab = mips_elf_hash_table (info);
8378   BFD_ASSERT (htab != NULL);
8379
8380   dynobj = elf_hash_table (info)->dynobj;
8381   hmips = (struct mips_elf_link_hash_entry *) h;
8382
8383   /* Make sure we know what is going on here.  */
8384   BFD_ASSERT (dynobj != NULL
8385               && (h->needs_plt
8386                   || h->u.weakdef != NULL
8387                   || (h->def_dynamic
8388                       && h->ref_regular
8389                       && !h->def_regular)));
8390
8391   hmips = (struct mips_elf_link_hash_entry *) h;
8392
8393   /* If there are call relocations against an externally-defined symbol,
8394      see whether we can create a MIPS lazy-binding stub for it.  We can
8395      only do this if all references to the function are through call
8396      relocations, and in that case, the traditional lazy-binding stubs
8397      are much more efficient than PLT entries.
8398
8399      Traditional stubs are only available on SVR4 psABI-based systems;
8400      VxWorks always uses PLTs instead.  */
8401   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
8402     {
8403       if (! elf_hash_table (info)->dynamic_sections_created)
8404         return TRUE;
8405
8406       /* If this symbol is not defined in a regular file, then set
8407          the symbol to the stub location.  This is required to make
8408          function pointers compare as equal between the normal
8409          executable and the shared library.  */
8410       if (!h->def_regular)
8411         {
8412           hmips->needs_lazy_stub = TRUE;
8413           htab->lazy_stub_count++;
8414           return TRUE;
8415         }
8416     }
8417   /* As above, VxWorks requires PLT entries for externally-defined
8418      functions that are only accessed through call relocations.
8419
8420      Both VxWorks and non-VxWorks targets also need PLT entries if there
8421      are static-only relocations against an externally-defined function.
8422      This can technically occur for shared libraries if there are
8423      branches to the symbol, although it is unlikely that this will be
8424      used in practice due to the short ranges involved.  It can occur
8425      for any relative or absolute relocation in executables; in that
8426      case, the PLT entry becomes the function's canonical address.  */
8427   else if (((h->needs_plt && !hmips->no_fn_stub)
8428             || (h->type == STT_FUNC && hmips->has_static_relocs))
8429            && htab->use_plts_and_copy_relocs
8430            && !SYMBOL_CALLS_LOCAL (info, h)
8431            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
8432                 && h->root.type == bfd_link_hash_undefweak))
8433     {
8434       /* If this is the first symbol to need a PLT entry, allocate room
8435          for the header.  */
8436       if (htab->splt->size == 0)
8437         {
8438           BFD_ASSERT (htab->sgotplt->size == 0);
8439
8440           /* If we're using the PLT additions to the psABI, each PLT
8441              entry is 16 bytes and the PLT0 entry is 32 bytes.
8442              Encourage better cache usage by aligning.  We do this
8443              lazily to avoid pessimizing traditional objects.  */
8444           if (!htab->is_vxworks
8445               && !bfd_set_section_alignment (dynobj, htab->splt, 5))
8446             return FALSE;
8447
8448           /* Make sure that .got.plt is word-aligned.  We do this lazily
8449              for the same reason as above.  */
8450           if (!bfd_set_section_alignment (dynobj, htab->sgotplt,
8451                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
8452             return FALSE;
8453
8454           htab->splt->size += htab->plt_header_size;
8455
8456           /* On non-VxWorks targets, the first two entries in .got.plt
8457              are reserved.  */
8458           if (!htab->is_vxworks)
8459             htab->sgotplt->size
8460               += get_elf_backend_data (dynobj)->got_header_size;
8461
8462           /* On VxWorks, also allocate room for the header's
8463              .rela.plt.unloaded entries.  */
8464           if (htab->is_vxworks && !info->shared)
8465             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
8466         }
8467
8468       /* Assign the next .plt entry to this symbol.  */
8469       h->plt.offset = htab->splt->size;
8470       htab->splt->size += htab->plt_entry_size;
8471
8472       /* If the output file has no definition of the symbol, set the
8473          symbol's value to the address of the stub.  */
8474       if (!info->shared && !h->def_regular)
8475         {
8476           h->root.u.def.section = htab->splt;
8477           h->root.u.def.value = h->plt.offset;
8478           /* For VxWorks, point at the PLT load stub rather than the
8479              lazy resolution stub; this stub will become the canonical
8480              function address.  */
8481           if (htab->is_vxworks)
8482             h->root.u.def.value += 8;
8483         }
8484
8485       /* Make room for the .got.plt entry and the R_MIPS_JUMP_SLOT
8486          relocation.  */
8487       htab->sgotplt->size += MIPS_ELF_GOT_SIZE (dynobj);
8488       htab->srelplt->size += (htab->is_vxworks
8489                               ? MIPS_ELF_RELA_SIZE (dynobj)
8490                               : MIPS_ELF_REL_SIZE (dynobj));
8491
8492       /* Make room for the .rela.plt.unloaded relocations.  */
8493       if (htab->is_vxworks && !info->shared)
8494         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
8495
8496       /* All relocations against this symbol that could have been made
8497          dynamic will now refer to the PLT entry instead.  */
8498       hmips->possibly_dynamic_relocs = 0;
8499
8500       return TRUE;
8501     }
8502
8503   /* If this is a weak symbol, and there is a real definition, the
8504      processor independent code will have arranged for us to see the
8505      real definition first, and we can just use the same value.  */
8506   if (h->u.weakdef != NULL)
8507     {
8508       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
8509                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
8510       h->root.u.def.section = h->u.weakdef->root.u.def.section;
8511       h->root.u.def.value = h->u.weakdef->root.u.def.value;
8512       return TRUE;
8513     }
8514
8515   /* Otherwise, there is nothing further to do for symbols defined
8516      in regular objects.  */
8517   if (h->def_regular)
8518     return TRUE;
8519
8520   /* There's also nothing more to do if we'll convert all relocations
8521      against this symbol into dynamic relocations.  */
8522   if (!hmips->has_static_relocs)
8523     return TRUE;
8524
8525   /* We're now relying on copy relocations.  Complain if we have
8526      some that we can't convert.  */
8527   if (!htab->use_plts_and_copy_relocs || info->shared)
8528     {
8529       (*_bfd_error_handler) (_("non-dynamic relocations refer to "
8530                                "dynamic symbol %s"),
8531                              h->root.root.string);
8532       bfd_set_error (bfd_error_bad_value);
8533       return FALSE;
8534     }
8535
8536   /* We must allocate the symbol in our .dynbss section, which will
8537      become part of the .bss section of the executable.  There will be
8538      an entry for this symbol in the .dynsym section.  The dynamic
8539      object will contain position independent code, so all references
8540      from the dynamic object to this symbol will go through the global
8541      offset table.  The dynamic linker will use the .dynsym entry to
8542      determine the address it must put in the global offset table, so
8543      both the dynamic object and the regular object will refer to the
8544      same memory location for the variable.  */
8545
8546   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
8547     {
8548       if (htab->is_vxworks)
8549         htab->srelbss->size += sizeof (Elf32_External_Rela);
8550       else
8551         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8552       h->needs_copy = 1;
8553     }
8554
8555   /* All relocations against this symbol that could have been made
8556      dynamic will now refer to the local copy instead.  */
8557   hmips->possibly_dynamic_relocs = 0;
8558
8559   return _bfd_elf_adjust_dynamic_copy (h, htab->sdynbss);
8560 }
8561 \f
8562 /* This function is called after all the input files have been read,
8563    and the input sections have been assigned to output sections.  We
8564    check for any mips16 stub sections that we can discard.  */
8565
8566 bfd_boolean
8567 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
8568                                     struct bfd_link_info *info)
8569 {
8570   asection *ri;
8571   struct mips_elf_link_hash_table *htab;
8572   struct mips_htab_traverse_info hti;
8573
8574   htab = mips_elf_hash_table (info);
8575   BFD_ASSERT (htab != NULL);
8576
8577   /* The .reginfo section has a fixed size.  */
8578   ri = bfd_get_section_by_name (output_bfd, ".reginfo");
8579   if (ri != NULL)
8580     bfd_set_section_size (output_bfd, ri, sizeof (Elf32_External_RegInfo));
8581
8582   hti.info = info;
8583   hti.output_bfd = output_bfd;
8584   hti.error = FALSE;
8585   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
8586                                mips_elf_check_symbols, &hti);
8587   if (hti.error)
8588     return FALSE;
8589
8590   return TRUE;
8591 }
8592
8593 /* If the link uses a GOT, lay it out and work out its size.  */
8594
8595 static bfd_boolean
8596 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
8597 {
8598   bfd *dynobj;
8599   asection *s;
8600   struct mips_got_info *g;
8601   bfd_size_type loadable_size = 0;
8602   bfd_size_type page_gotno;
8603   bfd *ibfd;
8604   struct mips_elf_traverse_got_arg tga;
8605   struct mips_elf_link_hash_table *htab;
8606
8607   htab = mips_elf_hash_table (info);
8608   BFD_ASSERT (htab != NULL);
8609
8610   s = htab->sgot;
8611   if (s == NULL)
8612     return TRUE;
8613
8614   dynobj = elf_hash_table (info)->dynobj;
8615   g = htab->got_info;
8616
8617   /* Allocate room for the reserved entries.  VxWorks always reserves
8618      3 entries; other objects only reserve 2 entries.  */
8619   BFD_ASSERT (g->assigned_gotno == 0);
8620   if (htab->is_vxworks)
8621     htab->reserved_gotno = 3;
8622   else
8623     htab->reserved_gotno = 2;
8624   g->local_gotno += htab->reserved_gotno;
8625   g->assigned_gotno = htab->reserved_gotno;
8626
8627   /* Replace entries for indirect and warning symbols with entries for
8628      the target symbol.  */
8629   if (!mips_elf_resolve_final_got_entries (g))
8630     return FALSE;
8631
8632   /* Decide which symbols need to go in the global part of the GOT and
8633      count the number of reloc-only GOT symbols.  */
8634   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
8635
8636   /* Calculate the total loadable size of the output.  That
8637      will give us the maximum number of GOT_PAGE entries
8638      required.  */
8639   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
8640     {
8641       asection *subsection;
8642
8643       for (subsection = ibfd->sections;
8644            subsection;
8645            subsection = subsection->next)
8646         {
8647           if ((subsection->flags & SEC_ALLOC) == 0)
8648             continue;
8649           loadable_size += ((subsection->size + 0xf)
8650                             &~ (bfd_size_type) 0xf);
8651         }
8652     }
8653
8654   if (htab->is_vxworks)
8655     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
8656        relocations against local symbols evaluate to "G", and the EABI does
8657        not include R_MIPS_GOT_PAGE.  */
8658     page_gotno = 0;
8659   else
8660     /* Assume there are two loadable segments consisting of contiguous
8661        sections.  Is 5 enough?  */
8662     page_gotno = (loadable_size >> 16) + 5;
8663
8664   /* Choose the smaller of the two estimates; both are intended to be
8665      conservative.  */
8666   if (page_gotno > g->page_gotno)
8667     page_gotno = g->page_gotno;
8668
8669   g->local_gotno += page_gotno;
8670
8671   /* Count the number of GOT entries and TLS relocs.  */
8672   tga.info = info;
8673   tga.g = g;
8674   htab_traverse (g->got_entries, mips_elf_count_got_entries, &tga);
8675
8676   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8677   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8678   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8679
8680   /* VxWorks does not support multiple GOTs.  It initializes $gp to
8681      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
8682      dynamic loader.  */
8683   if (htab->is_vxworks)
8684     {
8685       /* VxWorks executables do not need a GOT.  */
8686       if (info->shared)
8687         {
8688           /* Each VxWorks GOT entry needs an explicit relocation.  */
8689           unsigned int count;
8690
8691           count = g->global_gotno + g->local_gotno - htab->reserved_gotno;
8692           if (count)
8693             mips_elf_allocate_dynamic_relocations (dynobj, info, count);
8694         }
8695     }
8696   else if (s->size > MIPS_ELF_GOT_MAX_SIZE (info))
8697     {
8698       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
8699         return FALSE;
8700     }
8701   else
8702     {
8703       /* Record that all bfds use G.  This also has the effect of freeing
8704          the per-bfd GOTs, which we no longer need.  */
8705       for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
8706         if (mips_elf_bfd_got (ibfd, FALSE))
8707           mips_elf_replace_bfd_got (ibfd, g);
8708       mips_elf_replace_bfd_got (output_bfd, g);
8709
8710       /* Set up TLS entries.  */
8711       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
8712       tga.info = info;
8713       tga.g = g;
8714       tga.value = MIPS_ELF_GOT_SIZE (output_bfd);
8715       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
8716       if (!tga.g)
8717         return FALSE;
8718       BFD_ASSERT (g->tls_assigned_gotno
8719                   == g->global_gotno + g->local_gotno + g->tls_gotno);
8720
8721       /* Allocate room for the TLS relocations.  */
8722       if (g->relocs)
8723         mips_elf_allocate_dynamic_relocations (dynobj, info, g->relocs);
8724     }
8725
8726   return TRUE;
8727 }
8728
8729 /* Estimate the size of the .MIPS.stubs section.  */
8730
8731 static void
8732 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
8733 {
8734   struct mips_elf_link_hash_table *htab;
8735   bfd_size_type dynsymcount;
8736
8737   htab = mips_elf_hash_table (info);
8738   BFD_ASSERT (htab != NULL);
8739
8740   if (htab->lazy_stub_count == 0)
8741     return;
8742
8743   /* IRIX rld assumes that a function stub isn't at the end of the .text
8744      section, so add a dummy entry to the end.  */
8745   htab->lazy_stub_count++;
8746
8747   /* Get a worst-case estimate of the number of dynamic symbols needed.
8748      At this point, dynsymcount does not account for section symbols
8749      and count_section_dynsyms may overestimate the number that will
8750      be needed.  */
8751   dynsymcount = (elf_hash_table (info)->dynsymcount
8752                  + count_section_dynsyms (output_bfd, info));
8753
8754   /* Determine the size of one stub entry.  */
8755   htab->function_stub_size = (dynsymcount > 0x10000
8756                               ? MIPS_FUNCTION_STUB_BIG_SIZE
8757                               : MIPS_FUNCTION_STUB_NORMAL_SIZE);
8758
8759   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
8760 }
8761
8762 /* A mips_elf_link_hash_traverse callback for which DATA points to the
8763    MIPS hash table.  If H needs a traditional MIPS lazy-binding stub,
8764    allocate an entry in the stubs section.  */
8765
8766 static bfd_boolean
8767 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void **data)
8768 {
8769   struct mips_elf_link_hash_table *htab;
8770
8771   htab = (struct mips_elf_link_hash_table *) data;
8772   if (h->needs_lazy_stub)
8773     {
8774       h->root.root.u.def.section = htab->sstubs;
8775       h->root.root.u.def.value = htab->sstubs->size;
8776       h->root.plt.offset = htab->sstubs->size;
8777       htab->sstubs->size += htab->function_stub_size;
8778     }
8779   return TRUE;
8780 }
8781
8782 /* Allocate offsets in the stubs section to each symbol that needs one.
8783    Set the final size of the .MIPS.stub section.  */
8784
8785 static void
8786 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
8787 {
8788   struct mips_elf_link_hash_table *htab;
8789
8790   htab = mips_elf_hash_table (info);
8791   BFD_ASSERT (htab != NULL);
8792
8793   if (htab->lazy_stub_count == 0)
8794     return;
8795
8796   htab->sstubs->size = 0;
8797   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, htab);
8798   htab->sstubs->size += htab->function_stub_size;
8799   BFD_ASSERT (htab->sstubs->size
8800               == htab->lazy_stub_count * htab->function_stub_size);
8801 }
8802
8803 /* Set the sizes of the dynamic sections.  */
8804
8805 bfd_boolean
8806 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
8807                                      struct bfd_link_info *info)
8808 {
8809   bfd *dynobj;
8810   asection *s, *sreldyn;
8811   bfd_boolean reltext;
8812   struct mips_elf_link_hash_table *htab;
8813
8814   htab = mips_elf_hash_table (info);
8815   BFD_ASSERT (htab != NULL);
8816   dynobj = elf_hash_table (info)->dynobj;
8817   BFD_ASSERT (dynobj != NULL);
8818
8819   if (elf_hash_table (info)->dynamic_sections_created)
8820     {
8821       /* Set the contents of the .interp section to the interpreter.  */
8822       if (info->executable)
8823         {
8824           s = bfd_get_linker_section (dynobj, ".interp");
8825           BFD_ASSERT (s != NULL);
8826           s->size
8827             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
8828           s->contents
8829             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
8830         }
8831
8832       /* Create a symbol for the PLT, if we know that we are using it.  */
8833       if (htab->splt && htab->splt->size > 0 && htab->root.hplt == NULL)
8834         {
8835           struct elf_link_hash_entry *h;
8836
8837           BFD_ASSERT (htab->use_plts_and_copy_relocs);
8838
8839           h = _bfd_elf_define_linkage_sym (dynobj, info, htab->splt,
8840                                            "_PROCEDURE_LINKAGE_TABLE_");
8841           htab->root.hplt = h;
8842           if (h == NULL)
8843             return FALSE;
8844           h->type = STT_FUNC;
8845         }
8846     }
8847
8848   /* Allocate space for global sym dynamic relocs.  */
8849   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, info);
8850
8851   mips_elf_estimate_stub_size (output_bfd, info);
8852
8853   if (!mips_elf_lay_out_got (output_bfd, info))
8854     return FALSE;
8855
8856   mips_elf_lay_out_lazy_stubs (info);
8857
8858   /* The check_relocs and adjust_dynamic_symbol entry points have
8859      determined the sizes of the various dynamic sections.  Allocate
8860      memory for them.  */
8861   reltext = FALSE;
8862   for (s = dynobj->sections; s != NULL; s = s->next)
8863     {
8864       const char *name;
8865
8866       /* It's OK to base decisions on the section name, because none
8867          of the dynobj section names depend upon the input files.  */
8868       name = bfd_get_section_name (dynobj, s);
8869
8870       if ((s->flags & SEC_LINKER_CREATED) == 0)
8871         continue;
8872
8873       if (CONST_STRNEQ (name, ".rel"))
8874         {
8875           if (s->size != 0)
8876             {
8877               const char *outname;
8878               asection *target;
8879
8880               /* If this relocation section applies to a read only
8881                  section, then we probably need a DT_TEXTREL entry.
8882                  If the relocation section is .rel(a).dyn, we always
8883                  assert a DT_TEXTREL entry rather than testing whether
8884                  there exists a relocation to a read only section or
8885                  not.  */
8886               outname = bfd_get_section_name (output_bfd,
8887                                               s->output_section);
8888               target = bfd_get_section_by_name (output_bfd, outname + 4);
8889               if ((target != NULL
8890                    && (target->flags & SEC_READONLY) != 0
8891                    && (target->flags & SEC_ALLOC) != 0)
8892                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
8893                 reltext = TRUE;
8894
8895               /* We use the reloc_count field as a counter if we need
8896                  to copy relocs into the output file.  */
8897               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
8898                 s->reloc_count = 0;
8899
8900               /* If combreloc is enabled, elf_link_sort_relocs() will
8901                  sort relocations, but in a different way than we do,
8902                  and before we're done creating relocations.  Also, it
8903                  will move them around between input sections'
8904                  relocation's contents, so our sorting would be
8905                  broken, so don't let it run.  */
8906               info->combreloc = 0;
8907             }
8908         }
8909       else if (! info->shared
8910                && ! mips_elf_hash_table (info)->use_rld_obj_head
8911                && CONST_STRNEQ (name, ".rld_map"))
8912         {
8913           /* We add a room for __rld_map.  It will be filled in by the
8914              rtld to contain a pointer to the _r_debug structure.  */
8915           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
8916         }
8917       else if (SGI_COMPAT (output_bfd)
8918                && CONST_STRNEQ (name, ".compact_rel"))
8919         s->size += mips_elf_hash_table (info)->compact_rel_size;
8920       else if (s == htab->splt)
8921         {
8922           /* If the last PLT entry has a branch delay slot, allocate
8923              room for an extra nop to fill the delay slot.  This is
8924              for CPUs without load interlocking.  */
8925           if (! LOAD_INTERLOCKS_P (output_bfd)
8926               && ! htab->is_vxworks && s->size > 0)
8927             s->size += 4;
8928         }
8929       else if (! CONST_STRNEQ (name, ".init")
8930                && s != htab->sgot
8931                && s != htab->sgotplt
8932                && s != htab->sstubs
8933                && s != htab->sdynbss)
8934         {
8935           /* It's not one of our sections, so don't allocate space.  */
8936           continue;
8937         }
8938
8939       if (s->size == 0)
8940         {
8941           s->flags |= SEC_EXCLUDE;
8942           continue;
8943         }
8944
8945       if ((s->flags & SEC_HAS_CONTENTS) == 0)
8946         continue;
8947
8948       /* Allocate memory for the section contents.  */
8949       s->contents = bfd_zalloc (dynobj, s->size);
8950       if (s->contents == NULL)
8951         {
8952           bfd_set_error (bfd_error_no_memory);
8953           return FALSE;
8954         }
8955     }
8956
8957   if (elf_hash_table (info)->dynamic_sections_created)
8958     {
8959       /* Add some entries to the .dynamic section.  We fill in the
8960          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
8961          must add the entries now so that we get the correct size for
8962          the .dynamic section.  */
8963
8964       /* SGI object has the equivalence of DT_DEBUG in the
8965          DT_MIPS_RLD_MAP entry.  This must come first because glibc
8966          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and some tools
8967          may only look at the first one they see.  */
8968       if (!info->shared
8969           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
8970         return FALSE;
8971
8972       /* The DT_DEBUG entry may be filled in by the dynamic linker and
8973          used by the debugger.  */
8974       if (info->executable
8975           && !SGI_COMPAT (output_bfd)
8976           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
8977         return FALSE;
8978
8979       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
8980         info->flags |= DF_TEXTREL;
8981
8982       if ((info->flags & DF_TEXTREL) != 0)
8983         {
8984           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
8985             return FALSE;
8986
8987           /* Clear the DF_TEXTREL flag.  It will be set again if we
8988              write out an actual text relocation; we may not, because
8989              at this point we do not know whether e.g. any .eh_frame
8990              absolute relocations have been converted to PC-relative.  */
8991           info->flags &= ~DF_TEXTREL;
8992         }
8993
8994       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
8995         return FALSE;
8996
8997       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
8998       if (htab->is_vxworks)
8999         {
9000           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
9001              use any of the DT_MIPS_* tags.  */
9002           if (sreldyn && sreldyn->size > 0)
9003             {
9004               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
9005                 return FALSE;
9006
9007               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
9008                 return FALSE;
9009
9010               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
9011                 return FALSE;
9012             }
9013         }
9014       else
9015         {
9016           if (sreldyn && sreldyn->size > 0)
9017             {
9018               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
9019                 return FALSE;
9020
9021               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
9022                 return FALSE;
9023
9024               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
9025                 return FALSE;
9026             }
9027
9028           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
9029             return FALSE;
9030
9031           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
9032             return FALSE;
9033
9034           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
9035             return FALSE;
9036
9037           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
9038             return FALSE;
9039
9040           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
9041             return FALSE;
9042
9043           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
9044             return FALSE;
9045
9046           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
9047             return FALSE;
9048
9049           if (IRIX_COMPAT (dynobj) == ict_irix5
9050               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
9051             return FALSE;
9052
9053           if (IRIX_COMPAT (dynobj) == ict_irix6
9054               && (bfd_get_section_by_name
9055                   (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
9056               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
9057             return FALSE;
9058         }
9059       if (htab->splt->size > 0)
9060         {
9061           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
9062             return FALSE;
9063
9064           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
9065             return FALSE;
9066
9067           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
9068             return FALSE;
9069
9070           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
9071             return FALSE;
9072         }
9073       if (htab->is_vxworks
9074           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
9075         return FALSE;
9076     }
9077
9078   return TRUE;
9079 }
9080 \f
9081 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
9082    Adjust its R_ADDEND field so that it is correct for the output file.
9083    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
9084    and sections respectively; both use symbol indexes.  */
9085
9086 static void
9087 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
9088                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
9089                         asection **local_sections, Elf_Internal_Rela *rel)
9090 {
9091   unsigned int r_type, r_symndx;
9092   Elf_Internal_Sym *sym;
9093   asection *sec;
9094
9095   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9096     {
9097       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9098       if (gprel16_reloc_p (r_type)
9099           || r_type == R_MIPS_GPREL32
9100           || literal_reloc_p (r_type))
9101         {
9102           rel->r_addend += _bfd_get_gp_value (input_bfd);
9103           rel->r_addend -= _bfd_get_gp_value (output_bfd);
9104         }
9105
9106       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
9107       sym = local_syms + r_symndx;
9108
9109       /* Adjust REL's addend to account for section merging.  */
9110       if (!info->relocatable)
9111         {
9112           sec = local_sections[r_symndx];
9113           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
9114         }
9115
9116       /* This would normally be done by the rela_normal code in elflink.c.  */
9117       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
9118         rel->r_addend += local_sections[r_symndx]->output_offset;
9119     }
9120 }
9121
9122 /* Handle relocations against symbols from removed linkonce sections,
9123    or sections discarded by a linker script.  We use this wrapper around
9124    RELOC_AGAINST_DISCARDED_SECTION to handle triplets of compound relocs
9125    on 64-bit ELF targets.  In this case for any relocation handled, which
9126    always be the first in a triplet, the remaining two have to be processed
9127    together with the first, even if they are R_MIPS_NONE.  It is the symbol
9128    index referred by the first reloc that applies to all the three and the
9129    remaining two never refer to an object symbol.  And it is the final
9130    relocation (the last non-null one) that determines the output field of
9131    the whole relocation so retrieve the corresponding howto structure for
9132    the relocatable field to be cleared by RELOC_AGAINST_DISCARDED_SECTION.
9133
9134    Note that RELOC_AGAINST_DISCARDED_SECTION is a macro that uses "continue"
9135    and therefore requires to be pasted in a loop.  It also defines a block
9136    and does not protect any of its arguments, hence the extra brackets.  */
9137
9138 static void
9139 mips_reloc_against_discarded_section (bfd *output_bfd,
9140                                       struct bfd_link_info *info,
9141                                       bfd *input_bfd, asection *input_section,
9142                                       Elf_Internal_Rela **rel,
9143                                       const Elf_Internal_Rela **relend,
9144                                       bfd_boolean rel_reloc,
9145                                       reloc_howto_type *howto,
9146                                       bfd_byte *contents)
9147 {
9148   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
9149   int count = bed->s->int_rels_per_ext_rel;
9150   unsigned int r_type;
9151   int i;
9152
9153   for (i = count - 1; i > 0; i--)
9154     {
9155       r_type = ELF_R_TYPE (output_bfd, (*rel)[i].r_info);
9156       if (r_type != R_MIPS_NONE)
9157         {
9158           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9159           break;
9160         }
9161     }
9162   do
9163     {
9164        RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
9165                                         (*rel), count, (*relend),
9166                                         howto, i, contents);
9167     }
9168   while (0);
9169 }
9170
9171 /* Relocate a MIPS ELF section.  */
9172
9173 bfd_boolean
9174 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
9175                                 bfd *input_bfd, asection *input_section,
9176                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
9177                                 Elf_Internal_Sym *local_syms,
9178                                 asection **local_sections)
9179 {
9180   Elf_Internal_Rela *rel;
9181   const Elf_Internal_Rela *relend;
9182   bfd_vma addend = 0;
9183   bfd_boolean use_saved_addend_p = FALSE;
9184   const struct elf_backend_data *bed;
9185
9186   bed = get_elf_backend_data (output_bfd);
9187   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
9188   for (rel = relocs; rel < relend; ++rel)
9189     {
9190       const char *name;
9191       bfd_vma value = 0;
9192       reloc_howto_type *howto;
9193       bfd_boolean cross_mode_jump_p;
9194       /* TRUE if the relocation is a RELA relocation, rather than a
9195          REL relocation.  */
9196       bfd_boolean rela_relocation_p = TRUE;
9197       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9198       const char *msg;
9199       unsigned long r_symndx;
9200       asection *sec;
9201       Elf_Internal_Shdr *symtab_hdr;
9202       struct elf_link_hash_entry *h;
9203       bfd_boolean rel_reloc;
9204
9205       rel_reloc = (NEWABI_P (input_bfd)
9206                    && mips_elf_rel_relocation_p (input_bfd, input_section,
9207                                                  relocs, rel));
9208       /* Find the relocation howto for this relocation.  */
9209       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9210
9211       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
9212       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9213       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9214         {
9215           sec = local_sections[r_symndx];
9216           h = NULL;
9217         }
9218       else
9219         {
9220           unsigned long extsymoff;
9221
9222           extsymoff = 0;
9223           if (!elf_bad_symtab (input_bfd))
9224             extsymoff = symtab_hdr->sh_info;
9225           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
9226           while (h->root.type == bfd_link_hash_indirect
9227                  || h->root.type == bfd_link_hash_warning)
9228             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9229
9230           sec = NULL;
9231           if (h->root.type == bfd_link_hash_defined
9232               || h->root.type == bfd_link_hash_defweak)
9233             sec = h->root.u.def.section;
9234         }
9235
9236       if (sec != NULL && discarded_section (sec))
9237         {
9238           mips_reloc_against_discarded_section (output_bfd, info, input_bfd,
9239                                                 input_section, &rel, &relend,
9240                                                 rel_reloc, howto, contents);
9241           continue;
9242         }
9243
9244       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
9245         {
9246           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
9247              64-bit code, but make sure all their addresses are in the
9248              lowermost or uppermost 32-bit section of the 64-bit address
9249              space.  Thus, when they use an R_MIPS_64 they mean what is
9250              usually meant by R_MIPS_32, with the exception that the
9251              stored value is sign-extended to 64 bits.  */
9252           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
9253
9254           /* On big-endian systems, we need to lie about the position
9255              of the reloc.  */
9256           if (bfd_big_endian (input_bfd))
9257             rel->r_offset += 4;
9258         }
9259
9260       if (!use_saved_addend_p)
9261         {
9262           /* If these relocations were originally of the REL variety,
9263              we must pull the addend out of the field that will be
9264              relocated.  Otherwise, we simply use the contents of the
9265              RELA relocation.  */
9266           if (mips_elf_rel_relocation_p (input_bfd, input_section,
9267                                          relocs, rel))
9268             {
9269               rela_relocation_p = FALSE;
9270               addend = mips_elf_read_rel_addend (input_bfd, rel,
9271                                                  howto, contents);
9272               if (hi16_reloc_p (r_type)
9273                   || (got16_reloc_p (r_type)
9274                       && mips_elf_local_relocation_p (input_bfd, rel,
9275                                                       local_sections)))
9276                 {
9277                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
9278                                                      contents, &addend))
9279                     {
9280                       if (h)
9281                         name = h->root.root.string;
9282                       else
9283                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9284                                                  local_syms + r_symndx,
9285                                                  sec);
9286                       (*_bfd_error_handler)
9287                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
9288                          input_bfd, input_section, name, howto->name,
9289                          rel->r_offset);
9290                     }
9291                 }
9292               else
9293                 addend <<= howto->rightshift;
9294             }
9295           else
9296             addend = rel->r_addend;
9297           mips_elf_adjust_addend (output_bfd, info, input_bfd,
9298                                   local_syms, local_sections, rel);
9299         }
9300
9301       if (info->relocatable)
9302         {
9303           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
9304               && bfd_big_endian (input_bfd))
9305             rel->r_offset -= 4;
9306
9307           if (!rela_relocation_p && rel->r_addend)
9308             {
9309               addend += rel->r_addend;
9310               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
9311                 addend = mips_elf_high (addend);
9312               else if (r_type == R_MIPS_HIGHER)
9313                 addend = mips_elf_higher (addend);
9314               else if (r_type == R_MIPS_HIGHEST)
9315                 addend = mips_elf_highest (addend);
9316               else
9317                 addend >>= howto->rightshift;
9318
9319               /* We use the source mask, rather than the destination
9320                  mask because the place to which we are writing will be
9321                  source of the addend in the final link.  */
9322               addend &= howto->src_mask;
9323
9324               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9325                 /* See the comment above about using R_MIPS_64 in the 32-bit
9326                    ABI.  Here, we need to update the addend.  It would be
9327                    possible to get away with just using the R_MIPS_32 reloc
9328                    but for endianness.  */
9329                 {
9330                   bfd_vma sign_bits;
9331                   bfd_vma low_bits;
9332                   bfd_vma high_bits;
9333
9334                   if (addend & ((bfd_vma) 1 << 31))
9335 #ifdef BFD64
9336                     sign_bits = ((bfd_vma) 1 << 32) - 1;
9337 #else
9338                     sign_bits = -1;
9339 #endif
9340                   else
9341                     sign_bits = 0;
9342
9343                   /* If we don't know that we have a 64-bit type,
9344                      do two separate stores.  */
9345                   if (bfd_big_endian (input_bfd))
9346                     {
9347                       /* Store the sign-bits (which are most significant)
9348                          first.  */
9349                       low_bits = sign_bits;
9350                       high_bits = addend;
9351                     }
9352                   else
9353                     {
9354                       low_bits = addend;
9355                       high_bits = sign_bits;
9356                     }
9357                   bfd_put_32 (input_bfd, low_bits,
9358                               contents + rel->r_offset);
9359                   bfd_put_32 (input_bfd, high_bits,
9360                               contents + rel->r_offset + 4);
9361                   continue;
9362                 }
9363
9364               if (! mips_elf_perform_relocation (info, howto, rel, addend,
9365                                                  input_bfd, input_section,
9366                                                  contents, FALSE))
9367                 return FALSE;
9368             }
9369
9370           /* Go on to the next relocation.  */
9371           continue;
9372         }
9373
9374       /* In the N32 and 64-bit ABIs there may be multiple consecutive
9375          relocations for the same offset.  In that case we are
9376          supposed to treat the output of each relocation as the addend
9377          for the next.  */
9378       if (rel + 1 < relend
9379           && rel->r_offset == rel[1].r_offset
9380           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
9381         use_saved_addend_p = TRUE;
9382       else
9383         use_saved_addend_p = FALSE;
9384
9385       /* Figure out what value we are supposed to relocate.  */
9386       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
9387                                              input_section, info, rel,
9388                                              addend, howto, local_syms,
9389                                              local_sections, &value,
9390                                              &name, &cross_mode_jump_p,
9391                                              use_saved_addend_p))
9392         {
9393         case bfd_reloc_continue:
9394           /* There's nothing to do.  */
9395           continue;
9396
9397         case bfd_reloc_undefined:
9398           /* mips_elf_calculate_relocation already called the
9399              undefined_symbol callback.  There's no real point in
9400              trying to perform the relocation at this point, so we
9401              just skip ahead to the next relocation.  */
9402           continue;
9403
9404         case bfd_reloc_notsupported:
9405           msg = _("internal error: unsupported relocation error");
9406           info->callbacks->warning
9407             (info, msg, name, input_bfd, input_section, rel->r_offset);
9408           return FALSE;
9409
9410         case bfd_reloc_overflow:
9411           if (use_saved_addend_p)
9412             /* Ignore overflow until we reach the last relocation for
9413                a given location.  */
9414             ;
9415           else
9416             {
9417               struct mips_elf_link_hash_table *htab;
9418
9419               htab = mips_elf_hash_table (info);
9420               BFD_ASSERT (htab != NULL);
9421               BFD_ASSERT (name != NULL);
9422               if (!htab->small_data_overflow_reported
9423                   && (gprel16_reloc_p (howto->type)
9424                       || literal_reloc_p (howto->type)))
9425                 {
9426                   msg = _("small-data section exceeds 64KB;"
9427                           " lower small-data size limit (see option -G)");
9428
9429                   htab->small_data_overflow_reported = TRUE;
9430                   (*info->callbacks->einfo) ("%P: %s\n", msg);
9431                 }
9432               if (! ((*info->callbacks->reloc_overflow)
9433                      (info, NULL, name, howto->name, (bfd_vma) 0,
9434                       input_bfd, input_section, rel->r_offset)))
9435                 return FALSE;
9436             }
9437           break;
9438
9439         case bfd_reloc_ok:
9440           break;
9441
9442         case bfd_reloc_outofrange:
9443           if (jal_reloc_p (howto->type))
9444             {
9445               msg = _("JALX to a non-word-aligned address");
9446               info->callbacks->warning
9447                 (info, msg, name, input_bfd, input_section, rel->r_offset);
9448               return FALSE;
9449             }
9450           /* Fall through.  */
9451
9452         default:
9453           abort ();
9454           break;
9455         }
9456
9457       /* If we've got another relocation for the address, keep going
9458          until we reach the last one.  */
9459       if (use_saved_addend_p)
9460         {
9461           addend = value;
9462           continue;
9463         }
9464
9465       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9466         /* See the comment above about using R_MIPS_64 in the 32-bit
9467            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
9468            that calculated the right value.  Now, however, we
9469            sign-extend the 32-bit result to 64-bits, and store it as a
9470            64-bit value.  We are especially generous here in that we
9471            go to extreme lengths to support this usage on systems with
9472            only a 32-bit VMA.  */
9473         {
9474           bfd_vma sign_bits;
9475           bfd_vma low_bits;
9476           bfd_vma high_bits;
9477
9478           if (value & ((bfd_vma) 1 << 31))
9479 #ifdef BFD64
9480             sign_bits = ((bfd_vma) 1 << 32) - 1;
9481 #else
9482             sign_bits = -1;
9483 #endif
9484           else
9485             sign_bits = 0;
9486
9487           /* If we don't know that we have a 64-bit type,
9488              do two separate stores.  */
9489           if (bfd_big_endian (input_bfd))
9490             {
9491               /* Undo what we did above.  */
9492               rel->r_offset -= 4;
9493               /* Store the sign-bits (which are most significant)
9494                  first.  */
9495               low_bits = sign_bits;
9496               high_bits = value;
9497             }
9498           else
9499             {
9500               low_bits = value;
9501               high_bits = sign_bits;
9502             }
9503           bfd_put_32 (input_bfd, low_bits,
9504                       contents + rel->r_offset);
9505           bfd_put_32 (input_bfd, high_bits,
9506                       contents + rel->r_offset + 4);
9507           continue;
9508         }
9509
9510       /* Actually perform the relocation.  */
9511       if (! mips_elf_perform_relocation (info, howto, rel, value,
9512                                          input_bfd, input_section,
9513                                          contents, cross_mode_jump_p))
9514         return FALSE;
9515     }
9516
9517   return TRUE;
9518 }
9519 \f
9520 /* A function that iterates over each entry in la25_stubs and fills
9521    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
9522
9523 static int
9524 mips_elf_create_la25_stub (void **slot, void *data)
9525 {
9526   struct mips_htab_traverse_info *hti;
9527   struct mips_elf_link_hash_table *htab;
9528   struct mips_elf_la25_stub *stub;
9529   asection *s;
9530   bfd_byte *loc;
9531   bfd_vma offset, target, target_high, target_low;
9532
9533   stub = (struct mips_elf_la25_stub *) *slot;
9534   hti = (struct mips_htab_traverse_info *) data;
9535   htab = mips_elf_hash_table (hti->info);
9536   BFD_ASSERT (htab != NULL);
9537
9538   /* Create the section contents, if we haven't already.  */
9539   s = stub->stub_section;
9540   loc = s->contents;
9541   if (loc == NULL)
9542     {
9543       loc = bfd_malloc (s->size);
9544       if (loc == NULL)
9545         {
9546           hti->error = TRUE;
9547           return FALSE;
9548         }
9549       s->contents = loc;
9550     }
9551
9552   /* Work out where in the section this stub should go.  */
9553   offset = stub->offset;
9554
9555   /* Work out the target address.  */
9556   target = mips_elf_get_la25_target (stub, &s);
9557   target += s->output_section->vma + s->output_offset;
9558
9559   target_high = ((target + 0x8000) >> 16) & 0xffff;
9560   target_low = (target & 0xffff);
9561
9562   if (stub->stub_section != htab->strampoline)
9563     {
9564       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
9565          of the section and write the two instructions at the end.  */
9566       memset (loc, 0, offset);
9567       loc += offset;
9568       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9569         {
9570           bfd_put_micromips_32 (hti->output_bfd,
9571                                 LA25_LUI_MICROMIPS (target_high),
9572                                 loc);
9573           bfd_put_micromips_32 (hti->output_bfd,
9574                                 LA25_ADDIU_MICROMIPS (target_low),
9575                                 loc + 4);
9576         }
9577       else
9578         {
9579           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9580           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
9581         }
9582     }
9583   else
9584     {
9585       /* This is trampoline.  */
9586       loc += offset;
9587       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9588         {
9589           bfd_put_micromips_32 (hti->output_bfd,
9590                                 LA25_LUI_MICROMIPS (target_high), loc);
9591           bfd_put_micromips_32 (hti->output_bfd,
9592                                 LA25_J_MICROMIPS (target), loc + 4);
9593           bfd_put_micromips_32 (hti->output_bfd,
9594                                 LA25_ADDIU_MICROMIPS (target_low), loc + 8);
9595           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9596         }
9597       else
9598         {
9599           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9600           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
9601           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
9602           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9603         }
9604     }
9605   return TRUE;
9606 }
9607
9608 /* If NAME is one of the special IRIX6 symbols defined by the linker,
9609    adjust it appropriately now.  */
9610
9611 static void
9612 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
9613                                       const char *name, Elf_Internal_Sym *sym)
9614 {
9615   /* The linker script takes care of providing names and values for
9616      these, but we must place them into the right sections.  */
9617   static const char* const text_section_symbols[] = {
9618     "_ftext",
9619     "_etext",
9620     "__dso_displacement",
9621     "__elf_header",
9622     "__program_header_table",
9623     NULL
9624   };
9625
9626   static const char* const data_section_symbols[] = {
9627     "_fdata",
9628     "_edata",
9629     "_end",
9630     "_fbss",
9631     NULL
9632   };
9633
9634   const char* const *p;
9635   int i;
9636
9637   for (i = 0; i < 2; ++i)
9638     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
9639          *p;
9640          ++p)
9641       if (strcmp (*p, name) == 0)
9642         {
9643           /* All of these symbols are given type STT_SECTION by the
9644              IRIX6 linker.  */
9645           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9646           sym->st_other = STO_PROTECTED;
9647
9648           /* The IRIX linker puts these symbols in special sections.  */
9649           if (i == 0)
9650             sym->st_shndx = SHN_MIPS_TEXT;
9651           else
9652             sym->st_shndx = SHN_MIPS_DATA;
9653
9654           break;
9655         }
9656 }
9657
9658 /* Finish up dynamic symbol handling.  We set the contents of various
9659    dynamic sections here.  */
9660
9661 bfd_boolean
9662 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
9663                                      struct bfd_link_info *info,
9664                                      struct elf_link_hash_entry *h,
9665                                      Elf_Internal_Sym *sym)
9666 {
9667   bfd *dynobj;
9668   asection *sgot;
9669   struct mips_got_info *g, *gg;
9670   const char *name;
9671   int idx;
9672   struct mips_elf_link_hash_table *htab;
9673   struct mips_elf_link_hash_entry *hmips;
9674
9675   htab = mips_elf_hash_table (info);
9676   BFD_ASSERT (htab != NULL);
9677   dynobj = elf_hash_table (info)->dynobj;
9678   hmips = (struct mips_elf_link_hash_entry *) h;
9679
9680   BFD_ASSERT (!htab->is_vxworks);
9681
9682   if (h->plt.offset != MINUS_ONE && hmips->no_fn_stub)
9683     {
9684       /* We've decided to create a PLT entry for this symbol.  */
9685       bfd_byte *loc;
9686       bfd_vma header_address, plt_index, got_address;
9687       bfd_vma got_address_high, got_address_low, load;
9688       const bfd_vma *plt_entry;
9689
9690       BFD_ASSERT (htab->use_plts_and_copy_relocs);
9691       BFD_ASSERT (h->dynindx != -1);
9692       BFD_ASSERT (htab->splt != NULL);
9693       BFD_ASSERT (h->plt.offset <= htab->splt->size);
9694       BFD_ASSERT (!h->def_regular);
9695
9696       /* Calculate the address of the PLT header.  */
9697       header_address = (htab->splt->output_section->vma
9698                         + htab->splt->output_offset);
9699
9700       /* Calculate the index of the entry.  */
9701       plt_index = ((h->plt.offset - htab->plt_header_size)
9702                    / htab->plt_entry_size);
9703
9704       /* Calculate the address of the .got.plt entry.  */
9705       got_address = (htab->sgotplt->output_section->vma
9706                      + htab->sgotplt->output_offset
9707                      + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9708       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
9709       got_address_low = got_address & 0xffff;
9710
9711       /* Initially point the .got.plt entry at the PLT header.  */
9712       loc = (htab->sgotplt->contents
9713              + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9714       if (ABI_64_P (output_bfd))
9715         bfd_put_64 (output_bfd, header_address, loc);
9716       else
9717         bfd_put_32 (output_bfd, header_address, loc);
9718
9719       /* Find out where the .plt entry should go.  */
9720       loc = htab->splt->contents + h->plt.offset;
9721
9722       /* Pick the load opcode.  */
9723       load = MIPS_ELF_LOAD_WORD (output_bfd);
9724
9725       /* Fill in the PLT entry itself.  */
9726       plt_entry = mips_exec_plt_entry;
9727       bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
9728       bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load, loc + 4);
9729
9730       if (! LOAD_INTERLOCKS_P (output_bfd))
9731         {
9732           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
9733           bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
9734         }
9735       else
9736         {
9737           bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
9738           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 12);
9739         }
9740
9741       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
9742       mips_elf_output_dynamic_relocation (output_bfd, htab->srelplt,
9743                                           plt_index, h->dynindx,
9744                                           R_MIPS_JUMP_SLOT, got_address);
9745
9746       /* We distinguish between PLT entries and lazy-binding stubs by
9747          giving the former an st_other value of STO_MIPS_PLT.  Set the
9748          flag and leave the value if there are any relocations in the
9749          binary where pointer equality matters.  */
9750       sym->st_shndx = SHN_UNDEF;
9751       if (h->pointer_equality_needed)
9752         sym->st_other = STO_MIPS_PLT;
9753       else
9754         sym->st_value = 0;
9755     }
9756   else if (h->plt.offset != MINUS_ONE)
9757     {
9758       /* We've decided to create a lazy-binding stub.  */
9759       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
9760
9761       /* This symbol has a stub.  Set it up.  */
9762
9763       BFD_ASSERT (h->dynindx != -1);
9764
9765       BFD_ASSERT ((htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9766                   || (h->dynindx <= 0xffff));
9767
9768       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
9769          sign extension at runtime in the stub, resulting in a negative
9770          index value.  */
9771       if (h->dynindx & ~0x7fffffff)
9772         return FALSE;
9773
9774       /* Fill the stub.  */
9775       idx = 0;
9776       bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
9777       idx += 4;
9778       bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + idx);
9779       idx += 4;
9780       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9781         {
9782           bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
9783                       stub + idx);
9784           idx += 4;
9785         }
9786       bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
9787       idx += 4;
9788
9789       /* If a large stub is not required and sign extension is not a
9790          problem, then use legacy code in the stub.  */
9791       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9792         bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff), stub + idx);
9793       else if (h->dynindx & ~0x7fff)
9794         bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff), stub + idx);
9795       else
9796         bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
9797                     stub + idx);
9798
9799       BFD_ASSERT (h->plt.offset <= htab->sstubs->size);
9800       memcpy (htab->sstubs->contents + h->plt.offset,
9801               stub, htab->function_stub_size);
9802
9803       /* Mark the symbol as undefined.  plt.offset != -1 occurs
9804          only for the referenced symbol.  */
9805       sym->st_shndx = SHN_UNDEF;
9806
9807       /* The run-time linker uses the st_value field of the symbol
9808          to reset the global offset table entry for this external
9809          to its stub address when unlinking a shared object.  */
9810       sym->st_value = (htab->sstubs->output_section->vma
9811                        + htab->sstubs->output_offset
9812                        + h->plt.offset);
9813     }
9814
9815   /* If we have a MIPS16 function with a stub, the dynamic symbol must
9816      refer to the stub, since only the stub uses the standard calling
9817      conventions.  */
9818   if (h->dynindx != -1 && hmips->fn_stub != NULL)
9819     {
9820       BFD_ASSERT (hmips->need_fn_stub);
9821       sym->st_value = (hmips->fn_stub->output_section->vma
9822                        + hmips->fn_stub->output_offset);
9823       sym->st_size = hmips->fn_stub->size;
9824       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
9825     }
9826
9827   BFD_ASSERT (h->dynindx != -1
9828               || h->forced_local);
9829
9830   sgot = htab->sgot;
9831   g = htab->got_info;
9832   BFD_ASSERT (g != NULL);
9833
9834   /* Run through the global symbol table, creating GOT entries for all
9835      the symbols that need them.  */
9836   if (hmips->global_got_area != GGA_NONE)
9837     {
9838       bfd_vma offset;
9839       bfd_vma value;
9840
9841       value = sym->st_value;
9842       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
9843       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
9844     }
9845
9846   if (hmips->global_got_area != GGA_NONE && g->next)
9847     {
9848       struct mips_got_entry e, *p;
9849       bfd_vma entry;
9850       bfd_vma offset;
9851
9852       gg = g;
9853
9854       e.abfd = output_bfd;
9855       e.symndx = -1;
9856       e.d.h = hmips;
9857       e.tls_type = 0;
9858
9859       for (g = g->next; g->next != gg; g = g->next)
9860         {
9861           if (g->got_entries
9862               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
9863                                                            &e)))
9864             {
9865               offset = p->gotidx;
9866               BFD_ASSERT (offset > 0 && offset < htab->sgot->size);
9867               if (info->shared
9868                   || (elf_hash_table (info)->dynamic_sections_created
9869                       && p->d.h != NULL
9870                       && p->d.h->root.def_dynamic
9871                       && !p->d.h->root.def_regular))
9872                 {
9873                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
9874                      the various compatibility problems, it's easier to mock
9875                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
9876                      mips_elf_create_dynamic_relocation to calculate the
9877                      appropriate addend.  */
9878                   Elf_Internal_Rela rel[3];
9879
9880                   memset (rel, 0, sizeof (rel));
9881                   if (ABI_64_P (output_bfd))
9882                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
9883                   else
9884                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
9885                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
9886
9887                   entry = 0;
9888                   if (! (mips_elf_create_dynamic_relocation
9889                          (output_bfd, info, rel,
9890                           e.d.h, NULL, sym->st_value, &entry, sgot)))
9891                     return FALSE;
9892                 }
9893               else
9894                 entry = sym->st_value;
9895               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
9896             }
9897         }
9898     }
9899
9900   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
9901   name = h->root.root.string;
9902   if (h == elf_hash_table (info)->hdynamic
9903       || h == elf_hash_table (info)->hgot)
9904     sym->st_shndx = SHN_ABS;
9905   else if (strcmp (name, "_DYNAMIC_LINK") == 0
9906            || strcmp (name, "_DYNAMIC_LINKING") == 0)
9907     {
9908       sym->st_shndx = SHN_ABS;
9909       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9910       sym->st_value = 1;
9911     }
9912   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
9913     {
9914       sym->st_shndx = SHN_ABS;
9915       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9916       sym->st_value = elf_gp (output_bfd);
9917     }
9918   else if (SGI_COMPAT (output_bfd))
9919     {
9920       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
9921           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
9922         {
9923           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9924           sym->st_other = STO_PROTECTED;
9925           sym->st_value = 0;
9926           sym->st_shndx = SHN_MIPS_DATA;
9927         }
9928       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
9929         {
9930           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9931           sym->st_other = STO_PROTECTED;
9932           sym->st_value = mips_elf_hash_table (info)->procedure_count;
9933           sym->st_shndx = SHN_ABS;
9934         }
9935       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
9936         {
9937           if (h->type == STT_FUNC)
9938             sym->st_shndx = SHN_MIPS_TEXT;
9939           else if (h->type == STT_OBJECT)
9940             sym->st_shndx = SHN_MIPS_DATA;
9941         }
9942     }
9943
9944   /* Emit a copy reloc, if needed.  */
9945   if (h->needs_copy)
9946     {
9947       asection *s;
9948       bfd_vma symval;
9949
9950       BFD_ASSERT (h->dynindx != -1);
9951       BFD_ASSERT (htab->use_plts_and_copy_relocs);
9952
9953       s = mips_elf_rel_dyn_section (info, FALSE);
9954       symval = (h->root.u.def.section->output_section->vma
9955                 + h->root.u.def.section->output_offset
9956                 + h->root.u.def.value);
9957       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
9958                                           h->dynindx, R_MIPS_COPY, symval);
9959     }
9960
9961   /* Handle the IRIX6-specific symbols.  */
9962   if (IRIX_COMPAT (output_bfd) == ict_irix6)
9963     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
9964
9965   /* Keep dynamic MIPS16 symbols odd.  This allows the dynamic linker to
9966      treat MIPS16 symbols like any other.  */
9967   if (ELF_ST_IS_MIPS16 (sym->st_other))
9968     {
9969       BFD_ASSERT (sym->st_value & 1);
9970       sym->st_other -= STO_MIPS16;
9971     }
9972
9973   return TRUE;
9974 }
9975
9976 /* Likewise, for VxWorks.  */
9977
9978 bfd_boolean
9979 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
9980                                          struct bfd_link_info *info,
9981                                          struct elf_link_hash_entry *h,
9982                                          Elf_Internal_Sym *sym)
9983 {
9984   bfd *dynobj;
9985   asection *sgot;
9986   struct mips_got_info *g;
9987   struct mips_elf_link_hash_table *htab;
9988   struct mips_elf_link_hash_entry *hmips;
9989
9990   htab = mips_elf_hash_table (info);
9991   BFD_ASSERT (htab != NULL);
9992   dynobj = elf_hash_table (info)->dynobj;
9993   hmips = (struct mips_elf_link_hash_entry *) h;
9994
9995   if (h->plt.offset != (bfd_vma) -1)
9996     {
9997       bfd_byte *loc;
9998       bfd_vma plt_address, plt_index, got_address, got_offset, branch_offset;
9999       Elf_Internal_Rela rel;
10000       static const bfd_vma *plt_entry;
10001
10002       BFD_ASSERT (h->dynindx != -1);
10003       BFD_ASSERT (htab->splt != NULL);
10004       BFD_ASSERT (h->plt.offset <= htab->splt->size);
10005
10006       /* Calculate the address of the .plt entry.  */
10007       plt_address = (htab->splt->output_section->vma
10008                      + htab->splt->output_offset
10009                      + h->plt.offset);
10010
10011       /* Calculate the index of the entry.  */
10012       plt_index = ((h->plt.offset - htab->plt_header_size)
10013                    / htab->plt_entry_size);
10014
10015       /* Calculate the address of the .got.plt entry.  */
10016       got_address = (htab->sgotplt->output_section->vma
10017                      + htab->sgotplt->output_offset
10018                      + plt_index * 4);
10019
10020       /* Calculate the offset of the .got.plt entry from
10021          _GLOBAL_OFFSET_TABLE_.  */
10022       got_offset = mips_elf_gotplt_index (info, h);
10023
10024       /* Calculate the offset for the branch at the start of the PLT
10025          entry.  The branch jumps to the beginning of .plt.  */
10026       branch_offset = -(h->plt.offset / 4 + 1) & 0xffff;
10027
10028       /* Fill in the initial value of the .got.plt entry.  */
10029       bfd_put_32 (output_bfd, plt_address,
10030                   htab->sgotplt->contents + plt_index * 4);
10031
10032       /* Find out where the .plt entry should go.  */
10033       loc = htab->splt->contents + h->plt.offset;
10034
10035       if (info->shared)
10036         {
10037           plt_entry = mips_vxworks_shared_plt_entry;
10038           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10039           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10040         }
10041       else
10042         {
10043           bfd_vma got_address_high, got_address_low;
10044
10045           plt_entry = mips_vxworks_exec_plt_entry;
10046           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10047           got_address_low = got_address & 0xffff;
10048
10049           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10050           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10051           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
10052           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
10053           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10054           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10055           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10056           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10057
10058           loc = (htab->srelplt2->contents
10059                  + (plt_index * 3 + 2) * sizeof (Elf32_External_Rela));
10060
10061           /* Emit a relocation for the .got.plt entry.  */
10062           rel.r_offset = got_address;
10063           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10064           rel.r_addend = h->plt.offset;
10065           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10066
10067           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
10068           loc += sizeof (Elf32_External_Rela);
10069           rel.r_offset = plt_address + 8;
10070           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10071           rel.r_addend = got_offset;
10072           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10073
10074           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
10075           loc += sizeof (Elf32_External_Rela);
10076           rel.r_offset += 4;
10077           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10078           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10079         }
10080
10081       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10082       loc = htab->srelplt->contents + plt_index * sizeof (Elf32_External_Rela);
10083       rel.r_offset = got_address;
10084       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
10085       rel.r_addend = 0;
10086       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10087
10088       if (!h->def_regular)
10089         sym->st_shndx = SHN_UNDEF;
10090     }
10091
10092   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
10093
10094   sgot = htab->sgot;
10095   g = htab->got_info;
10096   BFD_ASSERT (g != NULL);
10097
10098   /* See if this symbol has an entry in the GOT.  */
10099   if (hmips->global_got_area != GGA_NONE)
10100     {
10101       bfd_vma offset;
10102       Elf_Internal_Rela outrel;
10103       bfd_byte *loc;
10104       asection *s;
10105
10106       /* Install the symbol value in the GOT.   */
10107       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
10108       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
10109
10110       /* Add a dynamic relocation for it.  */
10111       s = mips_elf_rel_dyn_section (info, FALSE);
10112       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
10113       outrel.r_offset = (sgot->output_section->vma
10114                          + sgot->output_offset
10115                          + offset);
10116       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
10117       outrel.r_addend = 0;
10118       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
10119     }
10120
10121   /* Emit a copy reloc, if needed.  */
10122   if (h->needs_copy)
10123     {
10124       Elf_Internal_Rela rel;
10125
10126       BFD_ASSERT (h->dynindx != -1);
10127
10128       rel.r_offset = (h->root.u.def.section->output_section->vma
10129                       + h->root.u.def.section->output_offset
10130                       + h->root.u.def.value);
10131       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
10132       rel.r_addend = 0;
10133       bfd_elf32_swap_reloca_out (output_bfd, &rel,
10134                                  htab->srelbss->contents
10135                                  + (htab->srelbss->reloc_count
10136                                     * sizeof (Elf32_External_Rela)));
10137       ++htab->srelbss->reloc_count;
10138     }
10139
10140   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
10141   if (ELF_ST_IS_COMPRESSED (sym->st_other))
10142     sym->st_value &= ~1;
10143
10144   return TRUE;
10145 }
10146
10147 /* Write out a plt0 entry to the beginning of .plt.  */
10148
10149 static void
10150 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10151 {
10152   bfd_byte *loc;
10153   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
10154   static const bfd_vma *plt_entry;
10155   struct mips_elf_link_hash_table *htab;
10156
10157   htab = mips_elf_hash_table (info);
10158   BFD_ASSERT (htab != NULL);
10159
10160   if (ABI_64_P (output_bfd))
10161     plt_entry = mips_n64_exec_plt0_entry;
10162   else if (ABI_N32_P (output_bfd))
10163     plt_entry = mips_n32_exec_plt0_entry;
10164   else
10165     plt_entry = mips_o32_exec_plt0_entry;
10166
10167   /* Calculate the value of .got.plt.  */
10168   gotplt_value = (htab->sgotplt->output_section->vma
10169                   + htab->sgotplt->output_offset);
10170   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
10171   gotplt_value_low = gotplt_value & 0xffff;
10172
10173   /* The PLT sequence is not safe for N64 if .got.plt's address can
10174      not be loaded in two instructions.  */
10175   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
10176               || ~(gotplt_value | 0x7fffffff) == 0);
10177
10178   /* Install the PLT header.  */
10179   loc = htab->splt->contents;
10180   bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
10181   bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
10182   bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
10183   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10184   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10185   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10186   bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10187   bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10188 }
10189
10190 /* Install the PLT header for a VxWorks executable and finalize the
10191    contents of .rela.plt.unloaded.  */
10192
10193 static void
10194 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10195 {
10196   Elf_Internal_Rela rela;
10197   bfd_byte *loc;
10198   bfd_vma got_value, got_value_high, got_value_low, plt_address;
10199   static const bfd_vma *plt_entry;
10200   struct mips_elf_link_hash_table *htab;
10201
10202   htab = mips_elf_hash_table (info);
10203   BFD_ASSERT (htab != NULL);
10204
10205   plt_entry = mips_vxworks_exec_plt0_entry;
10206
10207   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
10208   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
10209                + htab->root.hgot->root.u.def.section->output_offset
10210                + htab->root.hgot->root.u.def.value);
10211
10212   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
10213   got_value_low = got_value & 0xffff;
10214
10215   /* Calculate the address of the PLT header.  */
10216   plt_address = htab->splt->output_section->vma + htab->splt->output_offset;
10217
10218   /* Install the PLT header.  */
10219   loc = htab->splt->contents;
10220   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
10221   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
10222   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
10223   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10224   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10225   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10226
10227   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
10228   loc = htab->srelplt2->contents;
10229   rela.r_offset = plt_address;
10230   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10231   rela.r_addend = 0;
10232   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10233   loc += sizeof (Elf32_External_Rela);
10234
10235   /* Output the relocation for the following addiu of
10236      %lo(_GLOBAL_OFFSET_TABLE_).  */
10237   rela.r_offset += 4;
10238   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10239   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10240   loc += sizeof (Elf32_External_Rela);
10241
10242   /* Fix up the remaining relocations.  They may have the wrong
10243      symbol index for _G_O_T_ or _P_L_T_ depending on the order
10244      in which symbols were output.  */
10245   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
10246     {
10247       Elf_Internal_Rela rel;
10248
10249       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10250       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10251       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10252       loc += sizeof (Elf32_External_Rela);
10253
10254       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10255       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10256       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10257       loc += sizeof (Elf32_External_Rela);
10258
10259       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10260       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10261       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10262       loc += sizeof (Elf32_External_Rela);
10263     }
10264 }
10265
10266 /* Install the PLT header for a VxWorks shared library.  */
10267
10268 static void
10269 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
10270 {
10271   unsigned int i;
10272   struct mips_elf_link_hash_table *htab;
10273
10274   htab = mips_elf_hash_table (info);
10275   BFD_ASSERT (htab != NULL);
10276
10277   /* We just need to copy the entry byte-by-byte.  */
10278   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
10279     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
10280                 htab->splt->contents + i * 4);
10281 }
10282
10283 /* Finish up the dynamic sections.  */
10284
10285 bfd_boolean
10286 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
10287                                        struct bfd_link_info *info)
10288 {
10289   bfd *dynobj;
10290   asection *sdyn;
10291   asection *sgot;
10292   struct mips_got_info *gg, *g;
10293   struct mips_elf_link_hash_table *htab;
10294
10295   htab = mips_elf_hash_table (info);
10296   BFD_ASSERT (htab != NULL);
10297
10298   dynobj = elf_hash_table (info)->dynobj;
10299
10300   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
10301
10302   sgot = htab->sgot;
10303   gg = htab->got_info;
10304
10305   if (elf_hash_table (info)->dynamic_sections_created)
10306     {
10307       bfd_byte *b;
10308       int dyn_to_skip = 0, dyn_skipped = 0;
10309
10310       BFD_ASSERT (sdyn != NULL);
10311       BFD_ASSERT (gg != NULL);
10312
10313       g = mips_elf_bfd_got (output_bfd, FALSE);
10314       BFD_ASSERT (g != NULL);
10315
10316       for (b = sdyn->contents;
10317            b < sdyn->contents + sdyn->size;
10318            b += MIPS_ELF_DYN_SIZE (dynobj))
10319         {
10320           Elf_Internal_Dyn dyn;
10321           const char *name;
10322           size_t elemsize;
10323           asection *s;
10324           bfd_boolean swap_out_p;
10325
10326           /* Read in the current dynamic entry.  */
10327           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10328
10329           /* Assume that we're going to modify it and write it out.  */
10330           swap_out_p = TRUE;
10331
10332           switch (dyn.d_tag)
10333             {
10334             case DT_RELENT:
10335               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
10336               break;
10337
10338             case DT_RELAENT:
10339               BFD_ASSERT (htab->is_vxworks);
10340               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
10341               break;
10342
10343             case DT_STRSZ:
10344               /* Rewrite DT_STRSZ.  */
10345               dyn.d_un.d_val =
10346                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
10347               break;
10348
10349             case DT_PLTGOT:
10350               s = htab->sgot;
10351               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10352               break;
10353
10354             case DT_MIPS_PLTGOT:
10355               s = htab->sgotplt;
10356               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10357               break;
10358
10359             case DT_MIPS_RLD_VERSION:
10360               dyn.d_un.d_val = 1; /* XXX */
10361               break;
10362
10363             case DT_MIPS_FLAGS:
10364               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
10365               break;
10366
10367             case DT_MIPS_TIME_STAMP:
10368               {
10369                 time_t t;
10370                 time (&t);
10371                 dyn.d_un.d_val = t;
10372               }
10373               break;
10374
10375             case DT_MIPS_ICHECKSUM:
10376               /* XXX FIXME: */
10377               swap_out_p = FALSE;
10378               break;
10379
10380             case DT_MIPS_IVERSION:
10381               /* XXX FIXME: */
10382               swap_out_p = FALSE;
10383               break;
10384
10385             case DT_MIPS_BASE_ADDRESS:
10386               s = output_bfd->sections;
10387               BFD_ASSERT (s != NULL);
10388               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
10389               break;
10390
10391             case DT_MIPS_LOCAL_GOTNO:
10392               dyn.d_un.d_val = g->local_gotno;
10393               break;
10394
10395             case DT_MIPS_UNREFEXTNO:
10396               /* The index into the dynamic symbol table which is the
10397                  entry of the first external symbol that is not
10398                  referenced within the same object.  */
10399               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
10400               break;
10401
10402             case DT_MIPS_GOTSYM:
10403               if (htab->global_gotsym)
10404                 {
10405                   dyn.d_un.d_val = htab->global_gotsym->dynindx;
10406                   break;
10407                 }
10408               /* In case if we don't have global got symbols we default
10409                  to setting DT_MIPS_GOTSYM to the same value as
10410                  DT_MIPS_SYMTABNO, so we just fall through.  */
10411
10412             case DT_MIPS_SYMTABNO:
10413               name = ".dynsym";
10414               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
10415               s = bfd_get_section_by_name (output_bfd, name);
10416               BFD_ASSERT (s != NULL);
10417
10418               dyn.d_un.d_val = s->size / elemsize;
10419               break;
10420
10421             case DT_MIPS_HIPAGENO:
10422               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
10423               break;
10424
10425             case DT_MIPS_RLD_MAP:
10426               {
10427                 struct elf_link_hash_entry *h;
10428                 h = mips_elf_hash_table (info)->rld_symbol;
10429                 if (!h)
10430                   {
10431                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10432                     swap_out_p = FALSE;
10433                     break;
10434                   }
10435                 s = h->root.u.def.section;
10436                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
10437                                   + h->root.u.def.value);
10438               }
10439               break;
10440
10441             case DT_MIPS_OPTIONS:
10442               s = (bfd_get_section_by_name
10443                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
10444               dyn.d_un.d_ptr = s->vma;
10445               break;
10446
10447             case DT_RELASZ:
10448               BFD_ASSERT (htab->is_vxworks);
10449               /* The count does not include the JUMP_SLOT relocations.  */
10450               if (htab->srelplt)
10451                 dyn.d_un.d_val -= htab->srelplt->size;
10452               break;
10453
10454             case DT_PLTREL:
10455               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10456               if (htab->is_vxworks)
10457                 dyn.d_un.d_val = DT_RELA;
10458               else
10459                 dyn.d_un.d_val = DT_REL;
10460               break;
10461
10462             case DT_PLTRELSZ:
10463               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10464               dyn.d_un.d_val = htab->srelplt->size;
10465               break;
10466
10467             case DT_JMPREL:
10468               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10469               dyn.d_un.d_ptr = (htab->srelplt->output_section->vma
10470                                 + htab->srelplt->output_offset);
10471               break;
10472
10473             case DT_TEXTREL:
10474               /* If we didn't need any text relocations after all, delete
10475                  the dynamic tag.  */
10476               if (!(info->flags & DF_TEXTREL))
10477                 {
10478                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10479                   swap_out_p = FALSE;
10480                 }
10481               break;
10482
10483             case DT_FLAGS:
10484               /* If we didn't need any text relocations after all, clear
10485                  DF_TEXTREL from DT_FLAGS.  */
10486               if (!(info->flags & DF_TEXTREL))
10487                 dyn.d_un.d_val &= ~DF_TEXTREL;
10488               else
10489                 swap_out_p = FALSE;
10490               break;
10491
10492             default:
10493               swap_out_p = FALSE;
10494               if (htab->is_vxworks
10495                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
10496                 swap_out_p = TRUE;
10497               break;
10498             }
10499
10500           if (swap_out_p || dyn_skipped)
10501             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10502               (dynobj, &dyn, b - dyn_skipped);
10503
10504           if (dyn_to_skip)
10505             {
10506               dyn_skipped += dyn_to_skip;
10507               dyn_to_skip = 0;
10508             }
10509         }
10510
10511       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
10512       if (dyn_skipped > 0)
10513         memset (b - dyn_skipped, 0, dyn_skipped);
10514     }
10515
10516   if (sgot != NULL && sgot->size > 0
10517       && !bfd_is_abs_section (sgot->output_section))
10518     {
10519       if (htab->is_vxworks)
10520         {
10521           /* The first entry of the global offset table points to the
10522              ".dynamic" section.  The second is initialized by the
10523              loader and contains the shared library identifier.
10524              The third is also initialized by the loader and points
10525              to the lazy resolution stub.  */
10526           MIPS_ELF_PUT_WORD (output_bfd,
10527                              sdyn->output_offset + sdyn->output_section->vma,
10528                              sgot->contents);
10529           MIPS_ELF_PUT_WORD (output_bfd, 0,
10530                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10531           MIPS_ELF_PUT_WORD (output_bfd, 0,
10532                              sgot->contents
10533                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
10534         }
10535       else
10536         {
10537           /* The first entry of the global offset table will be filled at
10538              runtime. The second entry will be used by some runtime loaders.
10539              This isn't the case of IRIX rld.  */
10540           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
10541           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10542                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10543         }
10544
10545       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
10546          = MIPS_ELF_GOT_SIZE (output_bfd);
10547     }
10548
10549   /* Generate dynamic relocations for the non-primary gots.  */
10550   if (gg != NULL && gg->next)
10551     {
10552       Elf_Internal_Rela rel[3];
10553       bfd_vma addend = 0;
10554
10555       memset (rel, 0, sizeof (rel));
10556       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
10557
10558       for (g = gg->next; g->next != gg; g = g->next)
10559         {
10560           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
10561             + g->next->tls_gotno;
10562
10563           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
10564                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10565           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10566                              sgot->contents
10567                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10568
10569           if (! info->shared)
10570             continue;
10571
10572           while (got_index < g->assigned_gotno)
10573             {
10574               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
10575                 = got_index++ * MIPS_ELF_GOT_SIZE (output_bfd);
10576               if (!(mips_elf_create_dynamic_relocation
10577                     (output_bfd, info, rel, NULL,
10578                      bfd_abs_section_ptr,
10579                      0, &addend, sgot)))
10580                 return FALSE;
10581               BFD_ASSERT (addend == 0);
10582             }
10583         }
10584     }
10585
10586   /* The generation of dynamic relocations for the non-primary gots
10587      adds more dynamic relocations.  We cannot count them until
10588      here.  */
10589
10590   if (elf_hash_table (info)->dynamic_sections_created)
10591     {
10592       bfd_byte *b;
10593       bfd_boolean swap_out_p;
10594
10595       BFD_ASSERT (sdyn != NULL);
10596
10597       for (b = sdyn->contents;
10598            b < sdyn->contents + sdyn->size;
10599            b += MIPS_ELF_DYN_SIZE (dynobj))
10600         {
10601           Elf_Internal_Dyn dyn;
10602           asection *s;
10603
10604           /* Read in the current dynamic entry.  */
10605           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10606
10607           /* Assume that we're going to modify it and write it out.  */
10608           swap_out_p = TRUE;
10609
10610           switch (dyn.d_tag)
10611             {
10612             case DT_RELSZ:
10613               /* Reduce DT_RELSZ to account for any relocations we
10614                  decided not to make.  This is for the n64 irix rld,
10615                  which doesn't seem to apply any relocations if there
10616                  are trailing null entries.  */
10617               s = mips_elf_rel_dyn_section (info, FALSE);
10618               dyn.d_un.d_val = (s->reloc_count
10619                                 * (ABI_64_P (output_bfd)
10620                                    ? sizeof (Elf64_Mips_External_Rel)
10621                                    : sizeof (Elf32_External_Rel)));
10622               /* Adjust the section size too.  Tools like the prelinker
10623                  can reasonably expect the values to the same.  */
10624               elf_section_data (s->output_section)->this_hdr.sh_size
10625                 = dyn.d_un.d_val;
10626               break;
10627
10628             default:
10629               swap_out_p = FALSE;
10630               break;
10631             }
10632
10633           if (swap_out_p)
10634             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10635               (dynobj, &dyn, b);
10636         }
10637     }
10638
10639   {
10640     asection *s;
10641     Elf32_compact_rel cpt;
10642
10643     if (SGI_COMPAT (output_bfd))
10644       {
10645         /* Write .compact_rel section out.  */
10646         s = bfd_get_linker_section (dynobj, ".compact_rel");
10647         if (s != NULL)
10648           {
10649             cpt.id1 = 1;
10650             cpt.num = s->reloc_count;
10651             cpt.id2 = 2;
10652             cpt.offset = (s->output_section->filepos
10653                           + sizeof (Elf32_External_compact_rel));
10654             cpt.reserved0 = 0;
10655             cpt.reserved1 = 0;
10656             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
10657                                             ((Elf32_External_compact_rel *)
10658                                              s->contents));
10659
10660             /* Clean up a dummy stub function entry in .text.  */
10661             if (htab->sstubs != NULL)
10662               {
10663                 file_ptr dummy_offset;
10664
10665                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
10666                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
10667                 memset (htab->sstubs->contents + dummy_offset, 0,
10668                         htab->function_stub_size);
10669               }
10670           }
10671       }
10672
10673     /* The psABI says that the dynamic relocations must be sorted in
10674        increasing order of r_symndx.  The VxWorks EABI doesn't require
10675        this, and because the code below handles REL rather than RELA
10676        relocations, using it for VxWorks would be outright harmful.  */
10677     if (!htab->is_vxworks)
10678       {
10679         s = mips_elf_rel_dyn_section (info, FALSE);
10680         if (s != NULL
10681             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
10682           {
10683             reldyn_sorting_bfd = output_bfd;
10684
10685             if (ABI_64_P (output_bfd))
10686               qsort ((Elf64_External_Rel *) s->contents + 1,
10687                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
10688                      sort_dynamic_relocs_64);
10689             else
10690               qsort ((Elf32_External_Rel *) s->contents + 1,
10691                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
10692                      sort_dynamic_relocs);
10693           }
10694       }
10695   }
10696
10697   if (htab->splt && htab->splt->size > 0)
10698     {
10699       if (htab->is_vxworks)
10700         {
10701           if (info->shared)
10702             mips_vxworks_finish_shared_plt (output_bfd, info);
10703           else
10704             mips_vxworks_finish_exec_plt (output_bfd, info);
10705         }
10706       else
10707         {
10708           BFD_ASSERT (!info->shared);
10709           mips_finish_exec_plt (output_bfd, info);
10710         }
10711     }
10712   return TRUE;
10713 }
10714
10715
10716 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
10717
10718 static void
10719 mips_set_isa_flags (bfd *abfd)
10720 {
10721   flagword val;
10722
10723   switch (bfd_get_mach (abfd))
10724     {
10725     default:
10726     case bfd_mach_mips3000:
10727       val = E_MIPS_ARCH_1;
10728       break;
10729
10730     case bfd_mach_mips3900:
10731       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
10732       break;
10733
10734     case bfd_mach_mips6000:
10735       val = E_MIPS_ARCH_2;
10736       break;
10737
10738     case bfd_mach_mips4000:
10739     case bfd_mach_mips4300:
10740     case bfd_mach_mips4400:
10741     case bfd_mach_mips4600:
10742       val = E_MIPS_ARCH_3;
10743       break;
10744
10745     case bfd_mach_mips4010:
10746       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
10747       break;
10748
10749     case bfd_mach_mips4100:
10750       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
10751       break;
10752
10753     case bfd_mach_mips4111:
10754       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
10755       break;
10756
10757     case bfd_mach_mips4120:
10758       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
10759       break;
10760
10761     case bfd_mach_mips4650:
10762       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
10763       break;
10764
10765     case bfd_mach_mips5400:
10766       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
10767       break;
10768
10769     case bfd_mach_mips5500:
10770       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
10771       break;
10772
10773     case bfd_mach_mips5900:
10774       val = E_MIPS_ARCH_3 | E_MIPS_MACH_5900;
10775       break;
10776
10777     case bfd_mach_mips9000:
10778       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
10779       break;
10780
10781     case bfd_mach_mips5000:
10782     case bfd_mach_mips7000:
10783     case bfd_mach_mips8000:
10784     case bfd_mach_mips10000:
10785     case bfd_mach_mips12000:
10786     case bfd_mach_mips14000:
10787     case bfd_mach_mips16000:
10788       val = E_MIPS_ARCH_4;
10789       break;
10790
10791     case bfd_mach_mips5:
10792       val = E_MIPS_ARCH_5;
10793       break;
10794
10795     case bfd_mach_mips_loongson_2e:
10796       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
10797       break;
10798
10799     case bfd_mach_mips_loongson_2f:
10800       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
10801       break;
10802
10803     case bfd_mach_mips_sb1:
10804       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
10805       break;
10806
10807     case bfd_mach_mips_loongson_3a:
10808       val = E_MIPS_ARCH_64 | E_MIPS_MACH_LS3A;
10809       break;
10810
10811     case bfd_mach_mips_octeon:
10812     case bfd_mach_mips_octeonp:
10813       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
10814       break;
10815
10816     case bfd_mach_mips_xlr:
10817       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
10818       break;
10819
10820     case bfd_mach_mips_octeon2:
10821       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
10822       break;
10823
10824     case bfd_mach_mipsisa32:
10825       val = E_MIPS_ARCH_32;
10826       break;
10827
10828     case bfd_mach_mipsisa64:
10829       val = E_MIPS_ARCH_64;
10830       break;
10831
10832     case bfd_mach_mipsisa32r2:
10833       val = E_MIPS_ARCH_32R2;
10834       break;
10835
10836     case bfd_mach_mipsisa64r2:
10837       val = E_MIPS_ARCH_64R2;
10838       break;
10839     }
10840   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
10841   elf_elfheader (abfd)->e_flags |= val;
10842
10843 }
10844
10845
10846 /* The final processing done just before writing out a MIPS ELF object
10847    file.  This gets the MIPS architecture right based on the machine
10848    number.  This is used by both the 32-bit and the 64-bit ABI.  */
10849
10850 void
10851 _bfd_mips_elf_final_write_processing (bfd *abfd,
10852                                       bfd_boolean linker ATTRIBUTE_UNUSED)
10853 {
10854   unsigned int i;
10855   Elf_Internal_Shdr **hdrpp;
10856   const char *name;
10857   asection *sec;
10858
10859   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
10860      is nonzero.  This is for compatibility with old objects, which used
10861      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
10862   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
10863     mips_set_isa_flags (abfd);
10864
10865   /* Set the sh_info field for .gptab sections and other appropriate
10866      info for each special section.  */
10867   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
10868        i < elf_numsections (abfd);
10869        i++, hdrpp++)
10870     {
10871       switch ((*hdrpp)->sh_type)
10872         {
10873         case SHT_MIPS_MSYM:
10874         case SHT_MIPS_LIBLIST:
10875           sec = bfd_get_section_by_name (abfd, ".dynstr");
10876           if (sec != NULL)
10877             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
10878           break;
10879
10880         case SHT_MIPS_GPTAB:
10881           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
10882           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
10883           BFD_ASSERT (name != NULL
10884                       && CONST_STRNEQ (name, ".gptab."));
10885           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
10886           BFD_ASSERT (sec != NULL);
10887           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
10888           break;
10889
10890         case SHT_MIPS_CONTENT:
10891           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
10892           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
10893           BFD_ASSERT (name != NULL
10894                       && CONST_STRNEQ (name, ".MIPS.content"));
10895           sec = bfd_get_section_by_name (abfd,
10896                                          name + sizeof ".MIPS.content" - 1);
10897           BFD_ASSERT (sec != NULL);
10898           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
10899           break;
10900
10901         case SHT_MIPS_SYMBOL_LIB:
10902           sec = bfd_get_section_by_name (abfd, ".dynsym");
10903           if (sec != NULL)
10904             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
10905           sec = bfd_get_section_by_name (abfd, ".liblist");
10906           if (sec != NULL)
10907             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
10908           break;
10909
10910         case SHT_MIPS_EVENTS:
10911           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
10912           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
10913           BFD_ASSERT (name != NULL);
10914           if (CONST_STRNEQ (name, ".MIPS.events"))
10915             sec = bfd_get_section_by_name (abfd,
10916                                            name + sizeof ".MIPS.events" - 1);
10917           else
10918             {
10919               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
10920               sec = bfd_get_section_by_name (abfd,
10921                                              (name
10922                                               + sizeof ".MIPS.post_rel" - 1));
10923             }
10924           BFD_ASSERT (sec != NULL);
10925           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
10926           break;
10927
10928         }
10929     }
10930 }
10931 \f
10932 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
10933    segments.  */
10934
10935 int
10936 _bfd_mips_elf_additional_program_headers (bfd *abfd,
10937                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
10938 {
10939   asection *s;
10940   int ret = 0;
10941
10942   /* See if we need a PT_MIPS_REGINFO segment.  */
10943   s = bfd_get_section_by_name (abfd, ".reginfo");
10944   if (s && (s->flags & SEC_LOAD))
10945     ++ret;
10946
10947   /* See if we need a PT_MIPS_OPTIONS segment.  */
10948   if (IRIX_COMPAT (abfd) == ict_irix6
10949       && bfd_get_section_by_name (abfd,
10950                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
10951     ++ret;
10952
10953   /* See if we need a PT_MIPS_RTPROC segment.  */
10954   if (IRIX_COMPAT (abfd) == ict_irix5
10955       && bfd_get_section_by_name (abfd, ".dynamic")
10956       && bfd_get_section_by_name (abfd, ".mdebug"))
10957     ++ret;
10958
10959   /* Allocate a PT_NULL header in dynamic objects.  See
10960      _bfd_mips_elf_modify_segment_map for details.  */
10961   if (!SGI_COMPAT (abfd)
10962       && bfd_get_section_by_name (abfd, ".dynamic"))
10963     ++ret;
10964
10965   return ret;
10966 }
10967
10968 /* Modify the segment map for an IRIX5 executable.  */
10969
10970 bfd_boolean
10971 _bfd_mips_elf_modify_segment_map (bfd *abfd,
10972                                   struct bfd_link_info *info)
10973 {
10974   asection *s;
10975   struct elf_segment_map *m, **pm;
10976   bfd_size_type amt;
10977
10978   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
10979      segment.  */
10980   s = bfd_get_section_by_name (abfd, ".reginfo");
10981   if (s != NULL && (s->flags & SEC_LOAD) != 0)
10982     {
10983       for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
10984         if (m->p_type == PT_MIPS_REGINFO)
10985           break;
10986       if (m == NULL)
10987         {
10988           amt = sizeof *m;
10989           m = bfd_zalloc (abfd, amt);
10990           if (m == NULL)
10991             return FALSE;
10992
10993           m->p_type = PT_MIPS_REGINFO;
10994           m->count = 1;
10995           m->sections[0] = s;
10996
10997           /* We want to put it after the PHDR and INTERP segments.  */
10998           pm = &elf_tdata (abfd)->segment_map;
10999           while (*pm != NULL
11000                  && ((*pm)->p_type == PT_PHDR
11001                      || (*pm)->p_type == PT_INTERP))
11002             pm = &(*pm)->next;
11003
11004           m->next = *pm;
11005           *pm = m;
11006         }
11007     }
11008
11009   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
11010      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
11011      PT_MIPS_OPTIONS segment immediately following the program header
11012      table.  */
11013   if (NEWABI_P (abfd)
11014       /* On non-IRIX6 new abi, we'll have already created a segment
11015          for this section, so don't create another.  I'm not sure this
11016          is not also the case for IRIX 6, but I can't test it right
11017          now.  */
11018       && IRIX_COMPAT (abfd) == ict_irix6)
11019     {
11020       for (s = abfd->sections; s; s = s->next)
11021         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
11022           break;
11023
11024       if (s)
11025         {
11026           struct elf_segment_map *options_segment;
11027
11028           pm = &elf_tdata (abfd)->segment_map;
11029           while (*pm != NULL
11030                  && ((*pm)->p_type == PT_PHDR
11031                      || (*pm)->p_type == PT_INTERP))
11032             pm = &(*pm)->next;
11033
11034           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
11035             {
11036               amt = sizeof (struct elf_segment_map);
11037               options_segment = bfd_zalloc (abfd, amt);
11038               options_segment->next = *pm;
11039               options_segment->p_type = PT_MIPS_OPTIONS;
11040               options_segment->p_flags = PF_R;
11041               options_segment->p_flags_valid = TRUE;
11042               options_segment->count = 1;
11043               options_segment->sections[0] = s;
11044               *pm = options_segment;
11045             }
11046         }
11047     }
11048   else
11049     {
11050       if (IRIX_COMPAT (abfd) == ict_irix5)
11051         {
11052           /* If there are .dynamic and .mdebug sections, we make a room
11053              for the RTPROC header.  FIXME: Rewrite without section names.  */
11054           if (bfd_get_section_by_name (abfd, ".interp") == NULL
11055               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
11056               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
11057             {
11058               for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11059                 if (m->p_type == PT_MIPS_RTPROC)
11060                   break;
11061               if (m == NULL)
11062                 {
11063                   amt = sizeof *m;
11064                   m = bfd_zalloc (abfd, amt);
11065                   if (m == NULL)
11066                     return FALSE;
11067
11068                   m->p_type = PT_MIPS_RTPROC;
11069
11070                   s = bfd_get_section_by_name (abfd, ".rtproc");
11071                   if (s == NULL)
11072                     {
11073                       m->count = 0;
11074                       m->p_flags = 0;
11075                       m->p_flags_valid = 1;
11076                     }
11077                   else
11078                     {
11079                       m->count = 1;
11080                       m->sections[0] = s;
11081                     }
11082
11083                   /* We want to put it after the DYNAMIC segment.  */
11084                   pm = &elf_tdata (abfd)->segment_map;
11085                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
11086                     pm = &(*pm)->next;
11087                   if (*pm != NULL)
11088                     pm = &(*pm)->next;
11089
11090                   m->next = *pm;
11091                   *pm = m;
11092                 }
11093             }
11094         }
11095       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
11096          .dynstr, .dynsym, and .hash sections, and everything in
11097          between.  */
11098       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL;
11099            pm = &(*pm)->next)
11100         if ((*pm)->p_type == PT_DYNAMIC)
11101           break;
11102       m = *pm;
11103       if (m != NULL && IRIX_COMPAT (abfd) == ict_none)
11104         {
11105           /* For a normal mips executable the permissions for the PT_DYNAMIC
11106              segment are read, write and execute. We do that here since
11107              the code in elf.c sets only the read permission. This matters
11108              sometimes for the dynamic linker.  */
11109           if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
11110             {
11111               m->p_flags = PF_R | PF_W | PF_X;
11112               m->p_flags_valid = 1;
11113             }
11114         }
11115       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
11116          glibc's dynamic linker has traditionally derived the number of
11117          tags from the p_filesz field, and sometimes allocates stack
11118          arrays of that size.  An overly-big PT_DYNAMIC segment can
11119          be actively harmful in such cases.  Making PT_DYNAMIC contain
11120          other sections can also make life hard for the prelinker,
11121          which might move one of the other sections to a different
11122          PT_LOAD segment.  */
11123       if (SGI_COMPAT (abfd)
11124           && m != NULL
11125           && m->count == 1
11126           && strcmp (m->sections[0]->name, ".dynamic") == 0)
11127         {
11128           static const char *sec_names[] =
11129           {
11130             ".dynamic", ".dynstr", ".dynsym", ".hash"
11131           };
11132           bfd_vma low, high;
11133           unsigned int i, c;
11134           struct elf_segment_map *n;
11135
11136           low = ~(bfd_vma) 0;
11137           high = 0;
11138           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
11139             {
11140               s = bfd_get_section_by_name (abfd, sec_names[i]);
11141               if (s != NULL && (s->flags & SEC_LOAD) != 0)
11142                 {
11143                   bfd_size_type sz;
11144
11145                   if (low > s->vma)
11146                     low = s->vma;
11147                   sz = s->size;
11148                   if (high < s->vma + sz)
11149                     high = s->vma + sz;
11150                 }
11151             }
11152
11153           c = 0;
11154           for (s = abfd->sections; s != NULL; s = s->next)
11155             if ((s->flags & SEC_LOAD) != 0
11156                 && s->vma >= low
11157                 && s->vma + s->size <= high)
11158               ++c;
11159
11160           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
11161           n = bfd_zalloc (abfd, amt);
11162           if (n == NULL)
11163             return FALSE;
11164           *n = *m;
11165           n->count = c;
11166
11167           i = 0;
11168           for (s = abfd->sections; s != NULL; s = s->next)
11169             {
11170               if ((s->flags & SEC_LOAD) != 0
11171                   && s->vma >= low
11172                   && s->vma + s->size <= high)
11173                 {
11174                   n->sections[i] = s;
11175                   ++i;
11176                 }
11177             }
11178
11179           *pm = n;
11180         }
11181     }
11182
11183   /* Allocate a spare program header in dynamic objects so that tools
11184      like the prelinker can add an extra PT_LOAD entry.
11185
11186      If the prelinker needs to make room for a new PT_LOAD entry, its
11187      standard procedure is to move the first (read-only) sections into
11188      the new (writable) segment.  However, the MIPS ABI requires
11189      .dynamic to be in a read-only segment, and the section will often
11190      start within sizeof (ElfNN_Phdr) bytes of the last program header.
11191
11192      Although the prelinker could in principle move .dynamic to a
11193      writable segment, it seems better to allocate a spare program
11194      header instead, and avoid the need to move any sections.
11195      There is a long tradition of allocating spare dynamic tags,
11196      so allocating a spare program header seems like a natural
11197      extension.
11198
11199      If INFO is NULL, we may be copying an already prelinked binary
11200      with objcopy or strip, so do not add this header.  */
11201   if (info != NULL
11202       && !SGI_COMPAT (abfd)
11203       && bfd_get_section_by_name (abfd, ".dynamic"))
11204     {
11205       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL; pm = &(*pm)->next)
11206         if ((*pm)->p_type == PT_NULL)
11207           break;
11208       if (*pm == NULL)
11209         {
11210           m = bfd_zalloc (abfd, sizeof (*m));
11211           if (m == NULL)
11212             return FALSE;
11213
11214           m->p_type = PT_NULL;
11215           *pm = m;
11216         }
11217     }
11218
11219   return TRUE;
11220 }
11221 \f
11222 /* Return the section that should be marked against GC for a given
11223    relocation.  */
11224
11225 asection *
11226 _bfd_mips_elf_gc_mark_hook (asection *sec,
11227                             struct bfd_link_info *info,
11228                             Elf_Internal_Rela *rel,
11229                             struct elf_link_hash_entry *h,
11230                             Elf_Internal_Sym *sym)
11231 {
11232   /* ??? Do mips16 stub sections need to be handled special?  */
11233
11234   if (h != NULL)
11235     switch (ELF_R_TYPE (sec->owner, rel->r_info))
11236       {
11237       case R_MIPS_GNU_VTINHERIT:
11238       case R_MIPS_GNU_VTENTRY:
11239         return NULL;
11240       }
11241
11242   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
11243 }
11244
11245 /* Update the got entry reference counts for the section being removed.  */
11246
11247 bfd_boolean
11248 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
11249                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
11250                              asection *sec ATTRIBUTE_UNUSED,
11251                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
11252 {
11253 #if 0
11254   Elf_Internal_Shdr *symtab_hdr;
11255   struct elf_link_hash_entry **sym_hashes;
11256   bfd_signed_vma *local_got_refcounts;
11257   const Elf_Internal_Rela *rel, *relend;
11258   unsigned long r_symndx;
11259   struct elf_link_hash_entry *h;
11260
11261   if (info->relocatable)
11262     return TRUE;
11263
11264   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11265   sym_hashes = elf_sym_hashes (abfd);
11266   local_got_refcounts = elf_local_got_refcounts (abfd);
11267
11268   relend = relocs + sec->reloc_count;
11269   for (rel = relocs; rel < relend; rel++)
11270     switch (ELF_R_TYPE (abfd, rel->r_info))
11271       {
11272       case R_MIPS16_GOT16:
11273       case R_MIPS16_CALL16:
11274       case R_MIPS_GOT16:
11275       case R_MIPS_CALL16:
11276       case R_MIPS_CALL_HI16:
11277       case R_MIPS_CALL_LO16:
11278       case R_MIPS_GOT_HI16:
11279       case R_MIPS_GOT_LO16:
11280       case R_MIPS_GOT_DISP:
11281       case R_MIPS_GOT_PAGE:
11282       case R_MIPS_GOT_OFST:
11283       case R_MICROMIPS_GOT16:
11284       case R_MICROMIPS_CALL16:
11285       case R_MICROMIPS_CALL_HI16:
11286       case R_MICROMIPS_CALL_LO16:
11287       case R_MICROMIPS_GOT_HI16:
11288       case R_MICROMIPS_GOT_LO16:
11289       case R_MICROMIPS_GOT_DISP:
11290       case R_MICROMIPS_GOT_PAGE:
11291       case R_MICROMIPS_GOT_OFST:
11292         /* ??? It would seem that the existing MIPS code does no sort
11293            of reference counting or whatnot on its GOT and PLT entries,
11294            so it is not possible to garbage collect them at this time.  */
11295         break;
11296
11297       default:
11298         break;
11299       }
11300 #endif
11301
11302   return TRUE;
11303 }
11304 \f
11305 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
11306    hiding the old indirect symbol.  Process additional relocation
11307    information.  Also called for weakdefs, in which case we just let
11308    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
11309
11310 void
11311 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
11312                                     struct elf_link_hash_entry *dir,
11313                                     struct elf_link_hash_entry *ind)
11314 {
11315   struct mips_elf_link_hash_entry *dirmips, *indmips;
11316
11317   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
11318
11319   dirmips = (struct mips_elf_link_hash_entry *) dir;
11320   indmips = (struct mips_elf_link_hash_entry *) ind;
11321   /* Any absolute non-dynamic relocations against an indirect or weak
11322      definition will be against the target symbol.  */
11323   if (indmips->has_static_relocs)
11324     dirmips->has_static_relocs = TRUE;
11325
11326   if (ind->root.type != bfd_link_hash_indirect)
11327     return;
11328
11329   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
11330   if (indmips->readonly_reloc)
11331     dirmips->readonly_reloc = TRUE;
11332   if (indmips->no_fn_stub)
11333     dirmips->no_fn_stub = TRUE;
11334   if (indmips->fn_stub)
11335     {
11336       dirmips->fn_stub = indmips->fn_stub;
11337       indmips->fn_stub = NULL;
11338     }
11339   if (indmips->need_fn_stub)
11340     {
11341       dirmips->need_fn_stub = TRUE;
11342       indmips->need_fn_stub = FALSE;
11343     }
11344   if (indmips->call_stub)
11345     {
11346       dirmips->call_stub = indmips->call_stub;
11347       indmips->call_stub = NULL;
11348     }
11349   if (indmips->call_fp_stub)
11350     {
11351       dirmips->call_fp_stub = indmips->call_fp_stub;
11352       indmips->call_fp_stub = NULL;
11353     }
11354   if (indmips->global_got_area < dirmips->global_got_area)
11355     dirmips->global_got_area = indmips->global_got_area;
11356   if (indmips->global_got_area < GGA_NONE)
11357     indmips->global_got_area = GGA_NONE;
11358   if (indmips->has_nonpic_branches)
11359     dirmips->has_nonpic_branches = TRUE;
11360 }
11361 \f
11362 #define PDR_SIZE 32
11363
11364 bfd_boolean
11365 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
11366                             struct bfd_link_info *info)
11367 {
11368   asection *o;
11369   bfd_boolean ret = FALSE;
11370   unsigned char *tdata;
11371   size_t i, skip;
11372
11373   o = bfd_get_section_by_name (abfd, ".pdr");
11374   if (! o)
11375     return FALSE;
11376   if (o->size == 0)
11377     return FALSE;
11378   if (o->size % PDR_SIZE != 0)
11379     return FALSE;
11380   if (o->output_section != NULL
11381       && bfd_is_abs_section (o->output_section))
11382     return FALSE;
11383
11384   tdata = bfd_zmalloc (o->size / PDR_SIZE);
11385   if (! tdata)
11386     return FALSE;
11387
11388   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
11389                                             info->keep_memory);
11390   if (!cookie->rels)
11391     {
11392       free (tdata);
11393       return FALSE;
11394     }
11395
11396   cookie->rel = cookie->rels;
11397   cookie->relend = cookie->rels + o->reloc_count;
11398
11399   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
11400     {
11401       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
11402         {
11403           tdata[i] = 1;
11404           skip ++;
11405         }
11406     }
11407
11408   if (skip != 0)
11409     {
11410       mips_elf_section_data (o)->u.tdata = tdata;
11411       o->size -= skip * PDR_SIZE;
11412       ret = TRUE;
11413     }
11414   else
11415     free (tdata);
11416
11417   if (! info->keep_memory)
11418     free (cookie->rels);
11419
11420   return ret;
11421 }
11422
11423 bfd_boolean
11424 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
11425 {
11426   if (strcmp (sec->name, ".pdr") == 0)
11427     return TRUE;
11428   return FALSE;
11429 }
11430
11431 bfd_boolean
11432 _bfd_mips_elf_write_section (bfd *output_bfd,
11433                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
11434                              asection *sec, bfd_byte *contents)
11435 {
11436   bfd_byte *to, *from, *end;
11437   int i;
11438
11439   if (strcmp (sec->name, ".pdr") != 0)
11440     return FALSE;
11441
11442   if (mips_elf_section_data (sec)->u.tdata == NULL)
11443     return FALSE;
11444
11445   to = contents;
11446   end = contents + sec->size;
11447   for (from = contents, i = 0;
11448        from < end;
11449        from += PDR_SIZE, i++)
11450     {
11451       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
11452         continue;
11453       if (to != from)
11454         memcpy (to, from, PDR_SIZE);
11455       to += PDR_SIZE;
11456     }
11457   bfd_set_section_contents (output_bfd, sec->output_section, contents,
11458                             sec->output_offset, sec->size);
11459   return TRUE;
11460 }
11461 \f
11462 /* microMIPS code retains local labels for linker relaxation.  Omit them
11463    from output by default for clarity.  */
11464
11465 bfd_boolean
11466 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
11467 {
11468   return _bfd_elf_is_local_label_name (abfd, sym->name);
11469 }
11470
11471 /* MIPS ELF uses a special find_nearest_line routine in order the
11472    handle the ECOFF debugging information.  */
11473
11474 struct mips_elf_find_line
11475 {
11476   struct ecoff_debug_info d;
11477   struct ecoff_find_line i;
11478 };
11479
11480 bfd_boolean
11481 _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section,
11482                                  asymbol **symbols, bfd_vma offset,
11483                                  const char **filename_ptr,
11484                                  const char **functionname_ptr,
11485                                  unsigned int *line_ptr)
11486 {
11487   asection *msec;
11488
11489   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
11490                                      filename_ptr, functionname_ptr,
11491                                      line_ptr))
11492     return TRUE;
11493
11494   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
11495                                      section, symbols, offset,
11496                                      filename_ptr, functionname_ptr,
11497                                      line_ptr, NULL, ABI_64_P (abfd) ? 8 : 0,
11498                                      &elf_tdata (abfd)->dwarf2_find_line_info))
11499     return TRUE;
11500
11501   msec = bfd_get_section_by_name (abfd, ".mdebug");
11502   if (msec != NULL)
11503     {
11504       flagword origflags;
11505       struct mips_elf_find_line *fi;
11506       const struct ecoff_debug_swap * const swap =
11507         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
11508
11509       /* If we are called during a link, mips_elf_final_link may have
11510          cleared the SEC_HAS_CONTENTS field.  We force it back on here
11511          if appropriate (which it normally will be).  */
11512       origflags = msec->flags;
11513       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
11514         msec->flags |= SEC_HAS_CONTENTS;
11515
11516       fi = elf_tdata (abfd)->find_line_info;
11517       if (fi == NULL)
11518         {
11519           bfd_size_type external_fdr_size;
11520           char *fraw_src;
11521           char *fraw_end;
11522           struct fdr *fdr_ptr;
11523           bfd_size_type amt = sizeof (struct mips_elf_find_line);
11524
11525           fi = bfd_zalloc (abfd, amt);
11526           if (fi == NULL)
11527             {
11528               msec->flags = origflags;
11529               return FALSE;
11530             }
11531
11532           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
11533             {
11534               msec->flags = origflags;
11535               return FALSE;
11536             }
11537
11538           /* Swap in the FDR information.  */
11539           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
11540           fi->d.fdr = bfd_alloc (abfd, amt);
11541           if (fi->d.fdr == NULL)
11542             {
11543               msec->flags = origflags;
11544               return FALSE;
11545             }
11546           external_fdr_size = swap->external_fdr_size;
11547           fdr_ptr = fi->d.fdr;
11548           fraw_src = (char *) fi->d.external_fdr;
11549           fraw_end = (fraw_src
11550                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
11551           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
11552             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
11553
11554           elf_tdata (abfd)->find_line_info = fi;
11555
11556           /* Note that we don't bother to ever free this information.
11557              find_nearest_line is either called all the time, as in
11558              objdump -l, so the information should be saved, or it is
11559              rarely called, as in ld error messages, so the memory
11560              wasted is unimportant.  Still, it would probably be a
11561              good idea for free_cached_info to throw it away.  */
11562         }
11563
11564       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
11565                                   &fi->i, filename_ptr, functionname_ptr,
11566                                   line_ptr))
11567         {
11568           msec->flags = origflags;
11569           return TRUE;
11570         }
11571
11572       msec->flags = origflags;
11573     }
11574
11575   /* Fall back on the generic ELF find_nearest_line routine.  */
11576
11577   return _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
11578                                      filename_ptr, functionname_ptr,
11579                                      line_ptr);
11580 }
11581
11582 bfd_boolean
11583 _bfd_mips_elf_find_inliner_info (bfd *abfd,
11584                                  const char **filename_ptr,
11585                                  const char **functionname_ptr,
11586                                  unsigned int *line_ptr)
11587 {
11588   bfd_boolean found;
11589   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
11590                                          functionname_ptr, line_ptr,
11591                                          & elf_tdata (abfd)->dwarf2_find_line_info);
11592   return found;
11593 }
11594
11595 \f
11596 /* When are writing out the .options or .MIPS.options section,
11597    remember the bytes we are writing out, so that we can install the
11598    GP value in the section_processing routine.  */
11599
11600 bfd_boolean
11601 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
11602                                     const void *location,
11603                                     file_ptr offset, bfd_size_type count)
11604 {
11605   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
11606     {
11607       bfd_byte *c;
11608
11609       if (elf_section_data (section) == NULL)
11610         {
11611           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
11612           section->used_by_bfd = bfd_zalloc (abfd, amt);
11613           if (elf_section_data (section) == NULL)
11614             return FALSE;
11615         }
11616       c = mips_elf_section_data (section)->u.tdata;
11617       if (c == NULL)
11618         {
11619           c = bfd_zalloc (abfd, section->size);
11620           if (c == NULL)
11621             return FALSE;
11622           mips_elf_section_data (section)->u.tdata = c;
11623         }
11624
11625       memcpy (c + offset, location, count);
11626     }
11627
11628   return _bfd_elf_set_section_contents (abfd, section, location, offset,
11629                                         count);
11630 }
11631
11632 /* This is almost identical to bfd_generic_get_... except that some
11633    MIPS relocations need to be handled specially.  Sigh.  */
11634
11635 bfd_byte *
11636 _bfd_elf_mips_get_relocated_section_contents
11637   (bfd *abfd,
11638    struct bfd_link_info *link_info,
11639    struct bfd_link_order *link_order,
11640    bfd_byte *data,
11641    bfd_boolean relocatable,
11642    asymbol **symbols)
11643 {
11644   /* Get enough memory to hold the stuff */
11645   bfd *input_bfd = link_order->u.indirect.section->owner;
11646   asection *input_section = link_order->u.indirect.section;
11647   bfd_size_type sz;
11648
11649   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
11650   arelent **reloc_vector = NULL;
11651   long reloc_count;
11652
11653   if (reloc_size < 0)
11654     goto error_return;
11655
11656   reloc_vector = bfd_malloc (reloc_size);
11657   if (reloc_vector == NULL && reloc_size != 0)
11658     goto error_return;
11659
11660   /* read in the section */
11661   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
11662   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
11663     goto error_return;
11664
11665   reloc_count = bfd_canonicalize_reloc (input_bfd,
11666                                         input_section,
11667                                         reloc_vector,
11668                                         symbols);
11669   if (reloc_count < 0)
11670     goto error_return;
11671
11672   if (reloc_count > 0)
11673     {
11674       arelent **parent;
11675       /* for mips */
11676       int gp_found;
11677       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
11678
11679       {
11680         struct bfd_hash_entry *h;
11681         struct bfd_link_hash_entry *lh;
11682         /* Skip all this stuff if we aren't mixing formats.  */
11683         if (abfd && input_bfd
11684             && abfd->xvec == input_bfd->xvec)
11685           lh = 0;
11686         else
11687           {
11688             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
11689             lh = (struct bfd_link_hash_entry *) h;
11690           }
11691       lookup:
11692         if (lh)
11693           {
11694             switch (lh->type)
11695               {
11696               case bfd_link_hash_undefined:
11697               case bfd_link_hash_undefweak:
11698               case bfd_link_hash_common:
11699                 gp_found = 0;
11700                 break;
11701               case bfd_link_hash_defined:
11702               case bfd_link_hash_defweak:
11703                 gp_found = 1;
11704                 gp = lh->u.def.value;
11705                 break;
11706               case bfd_link_hash_indirect:
11707               case bfd_link_hash_warning:
11708                 lh = lh->u.i.link;
11709                 /* @@FIXME  ignoring warning for now */
11710                 goto lookup;
11711               case bfd_link_hash_new:
11712               default:
11713                 abort ();
11714               }
11715           }
11716         else
11717           gp_found = 0;
11718       }
11719       /* end mips */
11720       for (parent = reloc_vector; *parent != NULL; parent++)
11721         {
11722           char *error_message = NULL;
11723           bfd_reloc_status_type r;
11724
11725           /* Specific to MIPS: Deal with relocation types that require
11726              knowing the gp of the output bfd.  */
11727           asymbol *sym = *(*parent)->sym_ptr_ptr;
11728
11729           /* If we've managed to find the gp and have a special
11730              function for the relocation then go ahead, else default
11731              to the generic handling.  */
11732           if (gp_found
11733               && (*parent)->howto->special_function
11734               == _bfd_mips_elf32_gprel16_reloc)
11735             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
11736                                                input_section, relocatable,
11737                                                data, gp);
11738           else
11739             r = bfd_perform_relocation (input_bfd, *parent, data,
11740                                         input_section,
11741                                         relocatable ? abfd : NULL,
11742                                         &error_message);
11743
11744           if (relocatable)
11745             {
11746               asection *os = input_section->output_section;
11747
11748               /* A partial link, so keep the relocs */
11749               os->orelocation[os->reloc_count] = *parent;
11750               os->reloc_count++;
11751             }
11752
11753           if (r != bfd_reloc_ok)
11754             {
11755               switch (r)
11756                 {
11757                 case bfd_reloc_undefined:
11758                   if (!((*link_info->callbacks->undefined_symbol)
11759                         (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11760                          input_bfd, input_section, (*parent)->address, TRUE)))
11761                     goto error_return;
11762                   break;
11763                 case bfd_reloc_dangerous:
11764                   BFD_ASSERT (error_message != NULL);
11765                   if (!((*link_info->callbacks->reloc_dangerous)
11766                         (link_info, error_message, input_bfd, input_section,
11767                          (*parent)->address)))
11768                     goto error_return;
11769                   break;
11770                 case bfd_reloc_overflow:
11771                   if (!((*link_info->callbacks->reloc_overflow)
11772                         (link_info, NULL,
11773                          bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11774                          (*parent)->howto->name, (*parent)->addend,
11775                          input_bfd, input_section, (*parent)->address)))
11776                     goto error_return;
11777                   break;
11778                 case bfd_reloc_outofrange:
11779                 default:
11780                   abort ();
11781                   break;
11782                 }
11783
11784             }
11785         }
11786     }
11787   if (reloc_vector != NULL)
11788     free (reloc_vector);
11789   return data;
11790
11791 error_return:
11792   if (reloc_vector != NULL)
11793     free (reloc_vector);
11794   return NULL;
11795 }
11796 \f
11797 static bfd_boolean
11798 mips_elf_relax_delete_bytes (bfd *abfd,
11799                              asection *sec, bfd_vma addr, int count)
11800 {
11801   Elf_Internal_Shdr *symtab_hdr;
11802   unsigned int sec_shndx;
11803   bfd_byte *contents;
11804   Elf_Internal_Rela *irel, *irelend;
11805   Elf_Internal_Sym *isym;
11806   Elf_Internal_Sym *isymend;
11807   struct elf_link_hash_entry **sym_hashes;
11808   struct elf_link_hash_entry **end_hashes;
11809   struct elf_link_hash_entry **start_hashes;
11810   unsigned int symcount;
11811
11812   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
11813   contents = elf_section_data (sec)->this_hdr.contents;
11814
11815   irel = elf_section_data (sec)->relocs;
11816   irelend = irel + sec->reloc_count;
11817
11818   /* Actually delete the bytes.  */
11819   memmove (contents + addr, contents + addr + count,
11820            (size_t) (sec->size - addr - count));
11821   sec->size -= count;
11822
11823   /* Adjust all the relocs.  */
11824   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
11825     {
11826       /* Get the new reloc address.  */
11827       if (irel->r_offset > addr)
11828         irel->r_offset -= count;
11829     }
11830
11831   BFD_ASSERT (addr % 2 == 0);
11832   BFD_ASSERT (count % 2 == 0);
11833
11834   /* Adjust the local symbols defined in this section.  */
11835   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11836   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
11837   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
11838     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
11839       isym->st_value -= count;
11840
11841   /* Now adjust the global symbols defined in this section.  */
11842   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
11843               - symtab_hdr->sh_info);
11844   sym_hashes = start_hashes = elf_sym_hashes (abfd);
11845   end_hashes = sym_hashes + symcount;
11846
11847   for (; sym_hashes < end_hashes; sym_hashes++)
11848     {
11849       struct elf_link_hash_entry *sym_hash = *sym_hashes;
11850
11851       if ((sym_hash->root.type == bfd_link_hash_defined
11852            || sym_hash->root.type == bfd_link_hash_defweak)
11853           && sym_hash->root.u.def.section == sec)
11854         {
11855           bfd_vma value = sym_hash->root.u.def.value;
11856
11857           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
11858             value &= MINUS_TWO;
11859           if (value > addr)
11860             sym_hash->root.u.def.value -= count;
11861         }
11862     }
11863
11864   return TRUE;
11865 }
11866
11867
11868 /* Opcodes needed for microMIPS relaxation as found in
11869    opcodes/micromips-opc.c.  */
11870
11871 struct opcode_descriptor {
11872   unsigned long match;
11873   unsigned long mask;
11874 };
11875
11876 /* The $ra register aka $31.  */
11877
11878 #define RA 31
11879
11880 /* 32-bit instruction format register fields.  */
11881
11882 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
11883 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
11884
11885 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
11886
11887 #define OP16_VALID_REG(r) \
11888   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
11889
11890
11891 /* 32-bit and 16-bit branches.  */
11892
11893 static const struct opcode_descriptor b_insns_32[] = {
11894   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
11895   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
11896   { 0, 0 }  /* End marker for find_match().  */
11897 };
11898
11899 static const struct opcode_descriptor bc_insn_32 =
11900   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
11901
11902 static const struct opcode_descriptor bz_insn_32 =
11903   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
11904
11905 static const struct opcode_descriptor bzal_insn_32 =
11906   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
11907
11908 static const struct opcode_descriptor beq_insn_32 =
11909   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
11910
11911 static const struct opcode_descriptor b_insn_16 =
11912   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
11913
11914 static const struct opcode_descriptor bz_insn_16 =
11915   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
11916
11917
11918 /* 32-bit and 16-bit branch EQ and NE zero.  */
11919
11920 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
11921    eq and second the ne.  This convention is used when replacing a
11922    32-bit BEQ/BNE with the 16-bit version.  */
11923
11924 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
11925
11926 static const struct opcode_descriptor bz_rs_insns_32[] = {
11927   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
11928   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
11929   { 0, 0 }  /* End marker for find_match().  */
11930 };
11931
11932 static const struct opcode_descriptor bz_rt_insns_32[] = {
11933   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
11934   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
11935   { 0, 0 }  /* End marker for find_match().  */
11936 };
11937
11938 static const struct opcode_descriptor bzc_insns_32[] = {
11939   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
11940   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
11941   { 0, 0 }  /* End marker for find_match().  */
11942 };
11943
11944 static const struct opcode_descriptor bz_insns_16[] = {
11945   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
11946   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
11947   { 0, 0 }  /* End marker for find_match().  */
11948 };
11949
11950 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
11951
11952 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0x17) + 2)
11953 #define BZ16_REG_FIELD(r) \
11954   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 7)
11955
11956
11957 /* 32-bit instructions with a delay slot.  */
11958
11959 static const struct opcode_descriptor jal_insn_32_bd16 =
11960   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
11961
11962 static const struct opcode_descriptor jal_insn_32_bd32 =
11963   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
11964
11965 static const struct opcode_descriptor jal_x_insn_32_bd32 =
11966   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
11967
11968 static const struct opcode_descriptor j_insn_32 =
11969   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
11970
11971 static const struct opcode_descriptor jalr_insn_32 =
11972   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
11973
11974 /* This table can be compacted, because no opcode replacement is made.  */
11975
11976 static const struct opcode_descriptor ds_insns_32_bd16[] = {
11977   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
11978
11979   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
11980   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
11981
11982   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
11983   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
11984   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
11985   { 0, 0 }  /* End marker for find_match().  */
11986 };
11987
11988 /* This table can be compacted, because no opcode replacement is made.  */
11989
11990 static const struct opcode_descriptor ds_insns_32_bd32[] = {
11991   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
11992
11993   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
11994   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
11995   { 0, 0 }  /* End marker for find_match().  */
11996 };
11997
11998
11999 /* 16-bit instructions with a delay slot.  */
12000
12001 static const struct opcode_descriptor jalr_insn_16_bd16 =
12002   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
12003
12004 static const struct opcode_descriptor jalr_insn_16_bd32 =
12005   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
12006
12007 static const struct opcode_descriptor jr_insn_16 =
12008   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
12009
12010 #define JR16_REG(opcode) ((opcode) & 0x1f)
12011
12012 /* This table can be compacted, because no opcode replacement is made.  */
12013
12014 static const struct opcode_descriptor ds_insns_16_bd16[] = {
12015   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
12016
12017   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
12018   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
12019   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
12020   { 0, 0 }  /* End marker for find_match().  */
12021 };
12022
12023
12024 /* LUI instruction.  */
12025
12026 static const struct opcode_descriptor lui_insn =
12027  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
12028
12029
12030 /* ADDIU instruction.  */
12031
12032 static const struct opcode_descriptor addiu_insn =
12033   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
12034
12035 static const struct opcode_descriptor addiupc_insn =
12036   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
12037
12038 #define ADDIUPC_REG_FIELD(r) \
12039   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
12040
12041
12042 /* Relaxable instructions in a JAL delay slot: MOVE.  */
12043
12044 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
12045    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
12046 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
12047 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
12048
12049 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
12050 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
12051
12052 static const struct opcode_descriptor move_insns_32[] = {
12053   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
12054   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
12055   { 0, 0 }  /* End marker for find_match().  */
12056 };
12057
12058 static const struct opcode_descriptor move_insn_16 =
12059   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
12060
12061
12062 /* NOP instructions.  */
12063
12064 static const struct opcode_descriptor nop_insn_32 =
12065   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
12066
12067 static const struct opcode_descriptor nop_insn_16 =
12068   { /* "nop",   "",             */ 0x0c00,     0xffff };
12069
12070
12071 /* Instruction match support.  */
12072
12073 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
12074
12075 static int
12076 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
12077 {
12078   unsigned long indx;
12079
12080   for (indx = 0; insn[indx].mask != 0; indx++)
12081     if (MATCH (opcode, insn[indx]))
12082       return indx;
12083
12084   return -1;
12085 }
12086
12087
12088 /* Branch and delay slot decoding support.  */
12089
12090 /* If PTR points to what *might* be a 16-bit branch or jump, then
12091    return the minimum length of its delay slot, otherwise return 0.
12092    Non-zero results are not definitive as we might be checking against
12093    the second half of another instruction.  */
12094
12095 static int
12096 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
12097 {
12098   unsigned long opcode;
12099   int bdsize;
12100
12101   opcode = bfd_get_16 (abfd, ptr);
12102   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
12103     /* 16-bit branch/jump with a 32-bit delay slot.  */
12104     bdsize = 4;
12105   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
12106            || find_match (opcode, ds_insns_16_bd16) >= 0)
12107     /* 16-bit branch/jump with a 16-bit delay slot.  */
12108     bdsize = 2;
12109   else
12110     /* No delay slot.  */
12111     bdsize = 0;
12112
12113   return bdsize;
12114 }
12115
12116 /* If PTR points to what *might* be a 32-bit branch or jump, then
12117    return the minimum length of its delay slot, otherwise return 0.
12118    Non-zero results are not definitive as we might be checking against
12119    the second half of another instruction.  */
12120
12121 static int
12122 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
12123 {
12124   unsigned long opcode;
12125   int bdsize;
12126
12127   opcode = bfd_get_micromips_32 (abfd, ptr);
12128   if (find_match (opcode, ds_insns_32_bd32) >= 0)
12129     /* 32-bit branch/jump with a 32-bit delay slot.  */
12130     bdsize = 4;
12131   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
12132     /* 32-bit branch/jump with a 16-bit delay slot.  */
12133     bdsize = 2;
12134   else
12135     /* No delay slot.  */
12136     bdsize = 0;
12137
12138   return bdsize;
12139 }
12140
12141 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
12142    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
12143
12144 static bfd_boolean
12145 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12146 {
12147   unsigned long opcode;
12148
12149   opcode = bfd_get_16 (abfd, ptr);
12150   if (MATCH (opcode, b_insn_16)
12151                                                 /* B16  */
12152       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
12153                                                 /* JR16  */
12154       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
12155                                                 /* BEQZ16, BNEZ16  */
12156       || (MATCH (opcode, jalr_insn_16_bd32)
12157                                                 /* JALR16  */
12158           && reg != JR16_REG (opcode) && reg != RA))
12159     return TRUE;
12160
12161   return FALSE;
12162 }
12163
12164 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
12165    then return TRUE, otherwise FALSE.  */
12166
12167 static bfd_boolean
12168 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12169 {
12170   unsigned long opcode;
12171
12172   opcode = bfd_get_micromips_32 (abfd, ptr);
12173   if (MATCH (opcode, j_insn_32)
12174                                                 /* J  */
12175       || MATCH (opcode, bc_insn_32)
12176                                                 /* BC1F, BC1T, BC2F, BC2T  */
12177       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
12178                                                 /* JAL, JALX  */
12179       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
12180                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
12181       || (MATCH (opcode, bzal_insn_32)
12182                                                 /* BGEZAL, BLTZAL  */
12183           && reg != OP32_SREG (opcode) && reg != RA)
12184       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
12185                                                 /* JALR, JALR.HB, BEQ, BNE  */
12186           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
12187     return TRUE;
12188
12189   return FALSE;
12190 }
12191
12192 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
12193    IRELEND) at OFFSET indicate that there must be a compact branch there,
12194    then return TRUE, otherwise FALSE.  */
12195
12196 static bfd_boolean
12197 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
12198                      const Elf_Internal_Rela *internal_relocs,
12199                      const Elf_Internal_Rela *irelend)
12200 {
12201   const Elf_Internal_Rela *irel;
12202   unsigned long opcode;
12203
12204   opcode = bfd_get_micromips_32 (abfd, ptr);
12205   if (find_match (opcode, bzc_insns_32) < 0)
12206     return FALSE;
12207
12208   for (irel = internal_relocs; irel < irelend; irel++)
12209     if (irel->r_offset == offset
12210         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
12211       return TRUE;
12212
12213   return FALSE;
12214 }
12215
12216 /* Bitsize checking.  */
12217 #define IS_BITSIZE(val, N)                                              \
12218   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
12219     - (1ULL << ((N) - 1))) == (val))
12220
12221 \f
12222 bfd_boolean
12223 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
12224                              struct bfd_link_info *link_info,
12225                              bfd_boolean *again)
12226 {
12227   Elf_Internal_Shdr *symtab_hdr;
12228   Elf_Internal_Rela *internal_relocs;
12229   Elf_Internal_Rela *irel, *irelend;
12230   bfd_byte *contents = NULL;
12231   Elf_Internal_Sym *isymbuf = NULL;
12232
12233   /* Assume nothing changes.  */
12234   *again = FALSE;
12235
12236   /* We don't have to do anything for a relocatable link, if
12237      this section does not have relocs, or if this is not a
12238      code section.  */
12239
12240   if (link_info->relocatable
12241       || (sec->flags & SEC_RELOC) == 0
12242       || sec->reloc_count == 0
12243       || (sec->flags & SEC_CODE) == 0)
12244     return TRUE;
12245
12246   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12247
12248   /* Get a copy of the native relocations.  */
12249   internal_relocs = (_bfd_elf_link_read_relocs
12250                      (abfd, sec, NULL, (Elf_Internal_Rela *) NULL,
12251                       link_info->keep_memory));
12252   if (internal_relocs == NULL)
12253     goto error_return;
12254
12255   /* Walk through them looking for relaxing opportunities.  */
12256   irelend = internal_relocs + sec->reloc_count;
12257   for (irel = internal_relocs; irel < irelend; irel++)
12258     {
12259       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
12260       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
12261       bfd_boolean target_is_micromips_code_p;
12262       unsigned long opcode;
12263       bfd_vma symval;
12264       bfd_vma pcrval;
12265       bfd_byte *ptr;
12266       int fndopc;
12267
12268       /* The number of bytes to delete for relaxation and from where
12269          to delete these bytes starting at irel->r_offset.  */
12270       int delcnt = 0;
12271       int deloff = 0;
12272
12273       /* If this isn't something that can be relaxed, then ignore
12274          this reloc.  */
12275       if (r_type != R_MICROMIPS_HI16
12276           && r_type != R_MICROMIPS_PC16_S1
12277           && r_type != R_MICROMIPS_26_S1)
12278         continue;
12279
12280       /* Get the section contents if we haven't done so already.  */
12281       if (contents == NULL)
12282         {
12283           /* Get cached copy if it exists.  */
12284           if (elf_section_data (sec)->this_hdr.contents != NULL)
12285             contents = elf_section_data (sec)->this_hdr.contents;
12286           /* Go get them off disk.  */
12287           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
12288             goto error_return;
12289         }
12290       ptr = contents + irel->r_offset;
12291
12292       /* Read this BFD's local symbols if we haven't done so already.  */
12293       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
12294         {
12295           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
12296           if (isymbuf == NULL)
12297             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12298                                             symtab_hdr->sh_info, 0,
12299                                             NULL, NULL, NULL);
12300           if (isymbuf == NULL)
12301             goto error_return;
12302         }
12303
12304       /* Get the value of the symbol referred to by the reloc.  */
12305       if (r_symndx < symtab_hdr->sh_info)
12306         {
12307           /* A local symbol.  */
12308           Elf_Internal_Sym *isym;
12309           asection *sym_sec;
12310
12311           isym = isymbuf + r_symndx;
12312           if (isym->st_shndx == SHN_UNDEF)
12313             sym_sec = bfd_und_section_ptr;
12314           else if (isym->st_shndx == SHN_ABS)
12315             sym_sec = bfd_abs_section_ptr;
12316           else if (isym->st_shndx == SHN_COMMON)
12317             sym_sec = bfd_com_section_ptr;
12318           else
12319             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
12320           symval = (isym->st_value
12321                     + sym_sec->output_section->vma
12322                     + sym_sec->output_offset);
12323           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
12324         }
12325       else
12326         {
12327           unsigned long indx;
12328           struct elf_link_hash_entry *h;
12329
12330           /* An external symbol.  */
12331           indx = r_symndx - symtab_hdr->sh_info;
12332           h = elf_sym_hashes (abfd)[indx];
12333           BFD_ASSERT (h != NULL);
12334
12335           if (h->root.type != bfd_link_hash_defined
12336               && h->root.type != bfd_link_hash_defweak)
12337             /* This appears to be a reference to an undefined
12338                symbol.  Just ignore it -- it will be caught by the
12339                regular reloc processing.  */
12340             continue;
12341
12342           symval = (h->root.u.def.value
12343                     + h->root.u.def.section->output_section->vma
12344                     + h->root.u.def.section->output_offset);
12345           target_is_micromips_code_p = (!h->needs_plt
12346                                         && ELF_ST_IS_MICROMIPS (h->other));
12347         }
12348
12349
12350       /* For simplicity of coding, we are going to modify the
12351          section contents, the section relocs, and the BFD symbol
12352          table.  We must tell the rest of the code not to free up this
12353          information.  It would be possible to instead create a table
12354          of changes which have to be made, as is done in coff-mips.c;
12355          that would be more work, but would require less memory when
12356          the linker is run.  */
12357
12358       /* Only 32-bit instructions relaxed.  */
12359       if (irel->r_offset + 4 > sec->size)
12360         continue;
12361
12362       opcode = bfd_get_micromips_32 (abfd, ptr);
12363
12364       /* This is the pc-relative distance from the instruction the
12365          relocation is applied to, to the symbol referred.  */
12366       pcrval = (symval
12367                 - (sec->output_section->vma + sec->output_offset)
12368                 - irel->r_offset);
12369
12370       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
12371          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
12372          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
12373
12374            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
12375
12376          where pcrval has first to be adjusted to apply against the LO16
12377          location (we make the adjustment later on, when we have figured
12378          out the offset).  */
12379       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
12380         {
12381           bfd_boolean bzc = FALSE;
12382           unsigned long nextopc;
12383           unsigned long reg;
12384           bfd_vma offset;
12385
12386           /* Give up if the previous reloc was a HI16 against this symbol
12387              too.  */
12388           if (irel > internal_relocs
12389               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
12390               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
12391             continue;
12392
12393           /* Or if the next reloc is not a LO16 against this symbol.  */
12394           if (irel + 1 >= irelend
12395               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
12396               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
12397             continue;
12398
12399           /* Or if the second next reloc is a LO16 against this symbol too.  */
12400           if (irel + 2 >= irelend
12401               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
12402               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
12403             continue;
12404
12405           /* See if the LUI instruction *might* be in a branch delay slot.
12406              We check whether what looks like a 16-bit branch or jump is
12407              actually an immediate argument to a compact branch, and let
12408              it through if so.  */
12409           if (irel->r_offset >= 2
12410               && check_br16_dslot (abfd, ptr - 2)
12411               && !(irel->r_offset >= 4
12412                    && (bzc = check_relocated_bzc (abfd,
12413                                                   ptr - 4, irel->r_offset - 4,
12414                                                   internal_relocs, irelend))))
12415             continue;
12416           if (irel->r_offset >= 4
12417               && !bzc
12418               && check_br32_dslot (abfd, ptr - 4))
12419             continue;
12420
12421           reg = OP32_SREG (opcode);
12422
12423           /* We only relax adjacent instructions or ones separated with
12424              a branch or jump that has a delay slot.  The branch or jump
12425              must not fiddle with the register used to hold the address.
12426              Subtract 4 for the LUI itself.  */
12427           offset = irel[1].r_offset - irel[0].r_offset;
12428           switch (offset - 4)
12429             {
12430             case 0:
12431               break;
12432             case 2:
12433               if (check_br16 (abfd, ptr + 4, reg))
12434                 break;
12435               continue;
12436             case 4:
12437               if (check_br32 (abfd, ptr + 4, reg))
12438                 break;
12439               continue;
12440             default:
12441               continue;
12442             }
12443
12444           nextopc = bfd_get_micromips_32 (abfd, contents + irel[1].r_offset);
12445
12446           /* Give up unless the same register is used with both
12447              relocations.  */
12448           if (OP32_SREG (nextopc) != reg)
12449             continue;
12450
12451           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
12452              and rounding up to take masking of the two LSBs into account.  */
12453           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
12454
12455           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
12456           if (IS_BITSIZE (symval, 16))
12457             {
12458               /* Fix the relocation's type.  */
12459               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
12460
12461               /* Instructions using R_MICROMIPS_LO16 have the base or
12462                  source register in bits 20:16.  This register becomes $0
12463                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
12464               nextopc &= ~0x001f0000;
12465               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
12466                           contents + irel[1].r_offset);
12467             }
12468
12469           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
12470              We add 4 to take LUI deletion into account while checking
12471              the PC-relative distance.  */
12472           else if (symval % 4 == 0
12473                    && IS_BITSIZE (pcrval + 4, 25)
12474                    && MATCH (nextopc, addiu_insn)
12475                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
12476                    && OP16_VALID_REG (OP32_TREG (nextopc)))
12477             {
12478               /* Fix the relocation's type.  */
12479               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
12480
12481               /* Replace ADDIU with the ADDIUPC version.  */
12482               nextopc = (addiupc_insn.match
12483                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
12484
12485               bfd_put_micromips_32 (abfd, nextopc,
12486                                     contents + irel[1].r_offset);
12487             }
12488
12489           /* Can't do anything, give up, sigh...  */
12490           else
12491             continue;
12492
12493           /* Fix the relocation's type.  */
12494           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
12495
12496           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
12497           delcnt = 4;
12498           deloff = 0;
12499         }
12500
12501       /* Compact branch relaxation -- due to the multitude of macros
12502          employed by the compiler/assembler, compact branches are not
12503          always generated.  Obviously, this can/will be fixed elsewhere,
12504          but there is no drawback in double checking it here.  */
12505       else if (r_type == R_MICROMIPS_PC16_S1
12506                && irel->r_offset + 5 < sec->size
12507                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12508                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
12509                && MATCH (bfd_get_16 (abfd, ptr + 4), nop_insn_16))
12510         {
12511           unsigned long reg;
12512
12513           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12514
12515           /* Replace BEQZ/BNEZ with the compact version.  */
12516           opcode = (bzc_insns_32[fndopc].match
12517                     | BZC32_REG_FIELD (reg)
12518                     | (opcode & 0xffff));               /* Addend value.  */
12519
12520           bfd_put_micromips_32 (abfd, opcode, ptr);
12521
12522           /* Delete the 16-bit delay slot NOP: two bytes from
12523              irel->offset + 4.  */
12524           delcnt = 2;
12525           deloff = 4;
12526         }
12527
12528       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
12529          to check the distance from the next instruction, so subtract 2.  */
12530       else if (r_type == R_MICROMIPS_PC16_S1
12531                && IS_BITSIZE (pcrval - 2, 11)
12532                && find_match (opcode, b_insns_32) >= 0)
12533         {
12534           /* Fix the relocation's type.  */
12535           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
12536
12537           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12538           bfd_put_16 (abfd,
12539                       (b_insn_16.match
12540                        | (opcode & 0x3ff)),             /* Addend value.  */
12541                       ptr);
12542
12543           /* Delete 2 bytes from irel->r_offset + 2.  */
12544           delcnt = 2;
12545           deloff = 2;
12546         }
12547
12548       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
12549          to check the distance from the next instruction, so subtract 2.  */
12550       else if (r_type == R_MICROMIPS_PC16_S1
12551                && IS_BITSIZE (pcrval - 2, 8)
12552                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12553                     && OP16_VALID_REG (OP32_SREG (opcode)))
12554                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
12555                        && OP16_VALID_REG (OP32_TREG (opcode)))))
12556         {
12557           unsigned long reg;
12558
12559           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12560
12561           /* Fix the relocation's type.  */
12562           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
12563
12564           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12565           bfd_put_16 (abfd,
12566                       (bz_insns_16[fndopc].match
12567                        | BZ16_REG_FIELD (reg)
12568                        | (opcode & 0x7f)),              /* Addend value.  */
12569                       ptr);
12570
12571           /* Delete 2 bytes from irel->r_offset + 2.  */
12572           delcnt = 2;
12573           deloff = 2;
12574         }
12575
12576       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
12577       else if (r_type == R_MICROMIPS_26_S1
12578                && target_is_micromips_code_p
12579                && irel->r_offset + 7 < sec->size
12580                && MATCH (opcode, jal_insn_32_bd32))
12581         {
12582           unsigned long n32opc;
12583           bfd_boolean relaxed = FALSE;
12584
12585           n32opc = bfd_get_micromips_32 (abfd, ptr + 4);
12586
12587           if (MATCH (n32opc, nop_insn_32))
12588             {
12589               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
12590               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
12591
12592               relaxed = TRUE;
12593             }
12594           else if (find_match (n32opc, move_insns_32) >= 0)
12595             {
12596               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
12597               bfd_put_16 (abfd,
12598                           (move_insn_16.match
12599                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
12600                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
12601                           ptr + 4);
12602
12603               relaxed = TRUE;
12604             }
12605           /* Other 32-bit instructions relaxable to 16-bit
12606              instructions will be handled here later.  */
12607
12608           if (relaxed)
12609             {
12610               /* JAL with 32-bit delay slot that is changed to a JALS
12611                  with 16-bit delay slot.  */
12612               bfd_put_micromips_32 (abfd, jal_insn_32_bd16.match, ptr);
12613
12614               /* Delete 2 bytes from irel->r_offset + 6.  */
12615               delcnt = 2;
12616               deloff = 6;
12617             }
12618         }
12619
12620       if (delcnt != 0)
12621         {
12622           /* Note that we've changed the relocs, section contents, etc.  */
12623           elf_section_data (sec)->relocs = internal_relocs;
12624           elf_section_data (sec)->this_hdr.contents = contents;
12625           symtab_hdr->contents = (unsigned char *) isymbuf;
12626
12627           /* Delete bytes depending on the delcnt and deloff.  */
12628           if (!mips_elf_relax_delete_bytes (abfd, sec,
12629                                             irel->r_offset + deloff, delcnt))
12630             goto error_return;
12631
12632           /* That will change things, so we should relax again.
12633              Note that this is not required, and it may be slow.  */
12634           *again = TRUE;
12635         }
12636     }
12637
12638   if (isymbuf != NULL
12639       && symtab_hdr->contents != (unsigned char *) isymbuf)
12640     {
12641       if (! link_info->keep_memory)
12642         free (isymbuf);
12643       else
12644         {
12645           /* Cache the symbols for elf_link_input_bfd.  */
12646           symtab_hdr->contents = (unsigned char *) isymbuf;
12647         }
12648     }
12649
12650   if (contents != NULL
12651       && elf_section_data (sec)->this_hdr.contents != contents)
12652     {
12653       if (! link_info->keep_memory)
12654         free (contents);
12655       else
12656         {
12657           /* Cache the section contents for elf_link_input_bfd.  */
12658           elf_section_data (sec)->this_hdr.contents = contents;
12659         }
12660     }
12661
12662   if (internal_relocs != NULL
12663       && elf_section_data (sec)->relocs != internal_relocs)
12664     free (internal_relocs);
12665
12666   return TRUE;
12667
12668  error_return:
12669   if (isymbuf != NULL
12670       && symtab_hdr->contents != (unsigned char *) isymbuf)
12671     free (isymbuf);
12672   if (contents != NULL
12673       && elf_section_data (sec)->this_hdr.contents != contents)
12674     free (contents);
12675   if (internal_relocs != NULL
12676       && elf_section_data (sec)->relocs != internal_relocs)
12677     free (internal_relocs);
12678
12679   return FALSE;
12680 }
12681 \f
12682 /* Create a MIPS ELF linker hash table.  */
12683
12684 struct bfd_link_hash_table *
12685 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
12686 {
12687   struct mips_elf_link_hash_table *ret;
12688   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
12689
12690   ret = bfd_zmalloc (amt);
12691   if (ret == NULL)
12692     return NULL;
12693
12694   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
12695                                       mips_elf_link_hash_newfunc,
12696                                       sizeof (struct mips_elf_link_hash_entry),
12697                                       MIPS_ELF_DATA))
12698     {
12699       free (ret);
12700       return NULL;
12701     }
12702
12703   return &ret->root.root;
12704 }
12705
12706 /* Likewise, but indicate that the target is VxWorks.  */
12707
12708 struct bfd_link_hash_table *
12709 _bfd_mips_vxworks_link_hash_table_create (bfd *abfd)
12710 {
12711   struct bfd_link_hash_table *ret;
12712
12713   ret = _bfd_mips_elf_link_hash_table_create (abfd);
12714   if (ret)
12715     {
12716       struct mips_elf_link_hash_table *htab;
12717
12718       htab = (struct mips_elf_link_hash_table *) ret;
12719       htab->use_plts_and_copy_relocs = TRUE;
12720       htab->is_vxworks = TRUE;
12721     }
12722   return ret;
12723 }
12724
12725 /* A function that the linker calls if we are allowed to use PLTs
12726    and copy relocs.  */
12727
12728 void
12729 _bfd_mips_elf_use_plts_and_copy_relocs (struct bfd_link_info *info)
12730 {
12731   mips_elf_hash_table (info)->use_plts_and_copy_relocs = TRUE;
12732 }
12733 \f
12734 /* We need to use a special link routine to handle the .reginfo and
12735    the .mdebug sections.  We need to merge all instances of these
12736    sections together, not write them all out sequentially.  */
12737
12738 bfd_boolean
12739 _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info)
12740 {
12741   asection *o;
12742   struct bfd_link_order *p;
12743   asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec;
12744   asection *rtproc_sec;
12745   Elf32_RegInfo reginfo;
12746   struct ecoff_debug_info debug;
12747   struct mips_htab_traverse_info hti;
12748   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12749   const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap;
12750   HDRR *symhdr = &debug.symbolic_header;
12751   void *mdebug_handle = NULL;
12752   asection *s;
12753   EXTR esym;
12754   unsigned int i;
12755   bfd_size_type amt;
12756   struct mips_elf_link_hash_table *htab;
12757
12758   static const char * const secname[] =
12759   {
12760     ".text", ".init", ".fini", ".data",
12761     ".rodata", ".sdata", ".sbss", ".bss"
12762   };
12763   static const int sc[] =
12764   {
12765     scText, scInit, scFini, scData,
12766     scRData, scSData, scSBss, scBss
12767   };
12768
12769   /* Sort the dynamic symbols so that those with GOT entries come after
12770      those without.  */
12771   htab = mips_elf_hash_table (info);
12772   BFD_ASSERT (htab != NULL);
12773
12774   if (!mips_elf_sort_hash_table (abfd, info))
12775     return FALSE;
12776
12777   /* Create any scheduled LA25 stubs.  */
12778   hti.info = info;
12779   hti.output_bfd = abfd;
12780   hti.error = FALSE;
12781   htab_traverse (htab->la25_stubs, mips_elf_create_la25_stub, &hti);
12782   if (hti.error)
12783     return FALSE;
12784
12785   /* Get a value for the GP register.  */
12786   if (elf_gp (abfd) == 0)
12787     {
12788       struct bfd_link_hash_entry *h;
12789
12790       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
12791       if (h != NULL && h->type == bfd_link_hash_defined)
12792         elf_gp (abfd) = (h->u.def.value
12793                          + h->u.def.section->output_section->vma
12794                          + h->u.def.section->output_offset);
12795       else if (htab->is_vxworks
12796                && (h = bfd_link_hash_lookup (info->hash,
12797                                              "_GLOBAL_OFFSET_TABLE_",
12798                                              FALSE, FALSE, TRUE))
12799                && h->type == bfd_link_hash_defined)
12800         elf_gp (abfd) = (h->u.def.section->output_section->vma
12801                          + h->u.def.section->output_offset
12802                          + h->u.def.value);
12803       else if (info->relocatable)
12804         {
12805           bfd_vma lo = MINUS_ONE;
12806
12807           /* Find the GP-relative section with the lowest offset.  */
12808           for (o = abfd->sections; o != NULL; o = o->next)
12809             if (o->vma < lo
12810                 && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL))
12811               lo = o->vma;
12812
12813           /* And calculate GP relative to that.  */
12814           elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (info);
12815         }
12816       else
12817         {
12818           /* If the relocate_section function needs to do a reloc
12819              involving the GP value, it should make a reloc_dangerous
12820              callback to warn that GP is not defined.  */
12821         }
12822     }
12823
12824   /* Go through the sections and collect the .reginfo and .mdebug
12825      information.  */
12826   reginfo_sec = NULL;
12827   mdebug_sec = NULL;
12828   gptab_data_sec = NULL;
12829   gptab_bss_sec = NULL;
12830   for (o = abfd->sections; o != NULL; o = o->next)
12831     {
12832       if (strcmp (o->name, ".reginfo") == 0)
12833         {
12834           memset (&reginfo, 0, sizeof reginfo);
12835
12836           /* We have found the .reginfo section in the output file.
12837              Look through all the link_orders comprising it and merge
12838              the information together.  */
12839           for (p = o->map_head.link_order; p != NULL; p = p->next)
12840             {
12841               asection *input_section;
12842               bfd *input_bfd;
12843               Elf32_External_RegInfo ext;
12844               Elf32_RegInfo sub;
12845
12846               if (p->type != bfd_indirect_link_order)
12847                 {
12848                   if (p->type == bfd_data_link_order)
12849                     continue;
12850                   abort ();
12851                 }
12852
12853               input_section = p->u.indirect.section;
12854               input_bfd = input_section->owner;
12855
12856               if (! bfd_get_section_contents (input_bfd, input_section,
12857                                               &ext, 0, sizeof ext))
12858                 return FALSE;
12859
12860               bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub);
12861
12862               reginfo.ri_gprmask |= sub.ri_gprmask;
12863               reginfo.ri_cprmask[0] |= sub.ri_cprmask[0];
12864               reginfo.ri_cprmask[1] |= sub.ri_cprmask[1];
12865               reginfo.ri_cprmask[2] |= sub.ri_cprmask[2];
12866               reginfo.ri_cprmask[3] |= sub.ri_cprmask[3];
12867
12868               /* ri_gp_value is set by the function
12869                  mips_elf32_section_processing when the section is
12870                  finally written out.  */
12871
12872               /* Hack: reset the SEC_HAS_CONTENTS flag so that
12873                  elf_link_input_bfd ignores this section.  */
12874               input_section->flags &= ~SEC_HAS_CONTENTS;
12875             }
12876
12877           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
12878           BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo));
12879
12880           /* Skip this section later on (I don't think this currently
12881              matters, but someday it might).  */
12882           o->map_head.link_order = NULL;
12883
12884           reginfo_sec = o;
12885         }
12886
12887       if (strcmp (o->name, ".mdebug") == 0)
12888         {
12889           struct extsym_info einfo;
12890           bfd_vma last;
12891
12892           /* We have found the .mdebug section in the output file.
12893              Look through all the link_orders comprising it and merge
12894              the information together.  */
12895           symhdr->magic = swap->sym_magic;
12896           /* FIXME: What should the version stamp be?  */
12897           symhdr->vstamp = 0;
12898           symhdr->ilineMax = 0;
12899           symhdr->cbLine = 0;
12900           symhdr->idnMax = 0;
12901           symhdr->ipdMax = 0;
12902           symhdr->isymMax = 0;
12903           symhdr->ioptMax = 0;
12904           symhdr->iauxMax = 0;
12905           symhdr->issMax = 0;
12906           symhdr->issExtMax = 0;
12907           symhdr->ifdMax = 0;
12908           symhdr->crfd = 0;
12909           symhdr->iextMax = 0;
12910
12911           /* We accumulate the debugging information itself in the
12912              debug_info structure.  */
12913           debug.line = NULL;
12914           debug.external_dnr = NULL;
12915           debug.external_pdr = NULL;
12916           debug.external_sym = NULL;
12917           debug.external_opt = NULL;
12918           debug.external_aux = NULL;
12919           debug.ss = NULL;
12920           debug.ssext = debug.ssext_end = NULL;
12921           debug.external_fdr = NULL;
12922           debug.external_rfd = NULL;
12923           debug.external_ext = debug.external_ext_end = NULL;
12924
12925           mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info);
12926           if (mdebug_handle == NULL)
12927             return FALSE;
12928
12929           esym.jmptbl = 0;
12930           esym.cobol_main = 0;
12931           esym.weakext = 0;
12932           esym.reserved = 0;
12933           esym.ifd = ifdNil;
12934           esym.asym.iss = issNil;
12935           esym.asym.st = stLocal;
12936           esym.asym.reserved = 0;
12937           esym.asym.index = indexNil;
12938           last = 0;
12939           for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++)
12940             {
12941               esym.asym.sc = sc[i];
12942               s = bfd_get_section_by_name (abfd, secname[i]);
12943               if (s != NULL)
12944                 {
12945                   esym.asym.value = s->vma;
12946                   last = s->vma + s->size;
12947                 }
12948               else
12949                 esym.asym.value = last;
12950               if (!bfd_ecoff_debug_one_external (abfd, &debug, swap,
12951                                                  secname[i], &esym))
12952                 return FALSE;
12953             }
12954
12955           for (p = o->map_head.link_order; p != NULL; p = p->next)
12956             {
12957               asection *input_section;
12958               bfd *input_bfd;
12959               const struct ecoff_debug_swap *input_swap;
12960               struct ecoff_debug_info input_debug;
12961               char *eraw_src;
12962               char *eraw_end;
12963
12964               if (p->type != bfd_indirect_link_order)
12965                 {
12966                   if (p->type == bfd_data_link_order)
12967                     continue;
12968                   abort ();
12969                 }
12970
12971               input_section = p->u.indirect.section;
12972               input_bfd = input_section->owner;
12973
12974               if (!is_mips_elf (input_bfd))
12975                 {
12976                   /* I don't know what a non MIPS ELF bfd would be
12977                      doing with a .mdebug section, but I don't really
12978                      want to deal with it.  */
12979                   continue;
12980                 }
12981
12982               input_swap = (get_elf_backend_data (input_bfd)
12983                             ->elf_backend_ecoff_debug_swap);
12984
12985               BFD_ASSERT (p->size == input_section->size);
12986
12987               /* The ECOFF linking code expects that we have already
12988                  read in the debugging information and set up an
12989                  ecoff_debug_info structure, so we do that now.  */
12990               if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section,
12991                                                    &input_debug))
12992                 return FALSE;
12993
12994               if (! (bfd_ecoff_debug_accumulate
12995                      (mdebug_handle, abfd, &debug, swap, input_bfd,
12996                       &input_debug, input_swap, info)))
12997                 return FALSE;
12998
12999               /* Loop through the external symbols.  For each one with
13000                  interesting information, try to find the symbol in
13001                  the linker global hash table and save the information
13002                  for the output external symbols.  */
13003               eraw_src = input_debug.external_ext;
13004               eraw_end = (eraw_src
13005                           + (input_debug.symbolic_header.iextMax
13006                              * input_swap->external_ext_size));
13007               for (;
13008                    eraw_src < eraw_end;
13009                    eraw_src += input_swap->external_ext_size)
13010                 {
13011                   EXTR ext;
13012                   const char *name;
13013                   struct mips_elf_link_hash_entry *h;
13014
13015                   (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext);
13016                   if (ext.asym.sc == scNil
13017                       || ext.asym.sc == scUndefined
13018                       || ext.asym.sc == scSUndefined)
13019                     continue;
13020
13021                   name = input_debug.ssext + ext.asym.iss;
13022                   h = mips_elf_link_hash_lookup (mips_elf_hash_table (info),
13023                                                  name, FALSE, FALSE, TRUE);
13024                   if (h == NULL || h->esym.ifd != -2)
13025                     continue;
13026
13027                   if (ext.ifd != -1)
13028                     {
13029                       BFD_ASSERT (ext.ifd
13030                                   < input_debug.symbolic_header.ifdMax);
13031                       ext.ifd = input_debug.ifdmap[ext.ifd];
13032                     }
13033
13034                   h->esym = ext;
13035                 }
13036
13037               /* Free up the information we just read.  */
13038               free (input_debug.line);
13039               free (input_debug.external_dnr);
13040               free (input_debug.external_pdr);
13041               free (input_debug.external_sym);
13042               free (input_debug.external_opt);
13043               free (input_debug.external_aux);
13044               free (input_debug.ss);
13045               free (input_debug.ssext);
13046               free (input_debug.external_fdr);
13047               free (input_debug.external_rfd);
13048               free (input_debug.external_ext);
13049
13050               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13051                  elf_link_input_bfd ignores this section.  */
13052               input_section->flags &= ~SEC_HAS_CONTENTS;
13053             }
13054
13055           if (SGI_COMPAT (abfd) && info->shared)
13056             {
13057               /* Create .rtproc section.  */
13058               rtproc_sec = bfd_get_linker_section (abfd, ".rtproc");
13059               if (rtproc_sec == NULL)
13060                 {
13061                   flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
13062                                     | SEC_LINKER_CREATED | SEC_READONLY);
13063
13064                   rtproc_sec = bfd_make_section_anyway_with_flags (abfd,
13065                                                                    ".rtproc",
13066                                                                    flags);
13067                   if (rtproc_sec == NULL
13068                       || ! bfd_set_section_alignment (abfd, rtproc_sec, 4))
13069                     return FALSE;
13070                 }
13071
13072               if (! mips_elf_create_procedure_table (mdebug_handle, abfd,
13073                                                      info, rtproc_sec,
13074                                                      &debug))
13075                 return FALSE;
13076             }
13077
13078           /* Build the external symbol information.  */
13079           einfo.abfd = abfd;
13080           einfo.info = info;
13081           einfo.debug = &debug;
13082           einfo.swap = swap;
13083           einfo.failed = FALSE;
13084           mips_elf_link_hash_traverse (mips_elf_hash_table (info),
13085                                        mips_elf_output_extsym, &einfo);
13086           if (einfo.failed)
13087             return FALSE;
13088
13089           /* Set the size of the .mdebug section.  */
13090           o->size = bfd_ecoff_debug_size (abfd, &debug, swap);
13091
13092           /* Skip this section later on (I don't think this currently
13093              matters, but someday it might).  */
13094           o->map_head.link_order = NULL;
13095
13096           mdebug_sec = o;
13097         }
13098
13099       if (CONST_STRNEQ (o->name, ".gptab."))
13100         {
13101           const char *subname;
13102           unsigned int c;
13103           Elf32_gptab *tab;
13104           Elf32_External_gptab *ext_tab;
13105           unsigned int j;
13106
13107           /* The .gptab.sdata and .gptab.sbss sections hold
13108              information describing how the small data area would
13109              change depending upon the -G switch.  These sections
13110              not used in executables files.  */
13111           if (! info->relocatable)
13112             {
13113               for (p = o->map_head.link_order; p != NULL; p = p->next)
13114                 {
13115                   asection *input_section;
13116
13117                   if (p->type != bfd_indirect_link_order)
13118                     {
13119                       if (p->type == bfd_data_link_order)
13120                         continue;
13121                       abort ();
13122                     }
13123
13124                   input_section = p->u.indirect.section;
13125
13126                   /* Hack: reset the SEC_HAS_CONTENTS flag so that
13127                      elf_link_input_bfd ignores this section.  */
13128                   input_section->flags &= ~SEC_HAS_CONTENTS;
13129                 }
13130
13131               /* Skip this section later on (I don't think this
13132                  currently matters, but someday it might).  */
13133               o->map_head.link_order = NULL;
13134
13135               /* Really remove the section.  */
13136               bfd_section_list_remove (abfd, o);
13137               --abfd->section_count;
13138
13139               continue;
13140             }
13141
13142           /* There is one gptab for initialized data, and one for
13143              uninitialized data.  */
13144           if (strcmp (o->name, ".gptab.sdata") == 0)
13145             gptab_data_sec = o;
13146           else if (strcmp (o->name, ".gptab.sbss") == 0)
13147             gptab_bss_sec = o;
13148           else
13149             {
13150               (*_bfd_error_handler)
13151                 (_("%s: illegal section name `%s'"),
13152                  bfd_get_filename (abfd), o->name);
13153               bfd_set_error (bfd_error_nonrepresentable_section);
13154               return FALSE;
13155             }
13156
13157           /* The linker script always combines .gptab.data and
13158              .gptab.sdata into .gptab.sdata, and likewise for
13159              .gptab.bss and .gptab.sbss.  It is possible that there is
13160              no .sdata or .sbss section in the output file, in which
13161              case we must change the name of the output section.  */
13162           subname = o->name + sizeof ".gptab" - 1;
13163           if (bfd_get_section_by_name (abfd, subname) == NULL)
13164             {
13165               if (o == gptab_data_sec)
13166                 o->name = ".gptab.data";
13167               else
13168                 o->name = ".gptab.bss";
13169               subname = o->name + sizeof ".gptab" - 1;
13170               BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL);
13171             }
13172
13173           /* Set up the first entry.  */
13174           c = 1;
13175           amt = c * sizeof (Elf32_gptab);
13176           tab = bfd_malloc (amt);
13177           if (tab == NULL)
13178             return FALSE;
13179           tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd);
13180           tab[0].gt_header.gt_unused = 0;
13181
13182           /* Combine the input sections.  */
13183           for (p = o->map_head.link_order; p != NULL; p = p->next)
13184             {
13185               asection *input_section;
13186               bfd *input_bfd;
13187               bfd_size_type size;
13188               unsigned long last;
13189               bfd_size_type gpentry;
13190
13191               if (p->type != bfd_indirect_link_order)
13192                 {
13193                   if (p->type == bfd_data_link_order)
13194                     continue;
13195                   abort ();
13196                 }
13197
13198               input_section = p->u.indirect.section;
13199               input_bfd = input_section->owner;
13200
13201               /* Combine the gptab entries for this input section one
13202                  by one.  We know that the input gptab entries are
13203                  sorted by ascending -G value.  */
13204               size = input_section->size;
13205               last = 0;
13206               for (gpentry = sizeof (Elf32_External_gptab);
13207                    gpentry < size;
13208                    gpentry += sizeof (Elf32_External_gptab))
13209                 {
13210                   Elf32_External_gptab ext_gptab;
13211                   Elf32_gptab int_gptab;
13212                   unsigned long val;
13213                   unsigned long add;
13214                   bfd_boolean exact;
13215                   unsigned int look;
13216
13217                   if (! (bfd_get_section_contents
13218                          (input_bfd, input_section, &ext_gptab, gpentry,
13219                           sizeof (Elf32_External_gptab))))
13220                     {
13221                       free (tab);
13222                       return FALSE;
13223                     }
13224
13225                   bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab,
13226                                                 &int_gptab);
13227                   val = int_gptab.gt_entry.gt_g_value;
13228                   add = int_gptab.gt_entry.gt_bytes - last;
13229
13230                   exact = FALSE;
13231                   for (look = 1; look < c; look++)
13232                     {
13233                       if (tab[look].gt_entry.gt_g_value >= val)
13234                         tab[look].gt_entry.gt_bytes += add;
13235
13236                       if (tab[look].gt_entry.gt_g_value == val)
13237                         exact = TRUE;
13238                     }
13239
13240                   if (! exact)
13241                     {
13242                       Elf32_gptab *new_tab;
13243                       unsigned int max;
13244
13245                       /* We need a new table entry.  */
13246                       amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab);
13247                       new_tab = bfd_realloc (tab, amt);
13248                       if (new_tab == NULL)
13249                         {
13250                           free (tab);
13251                           return FALSE;
13252                         }
13253                       tab = new_tab;
13254                       tab[c].gt_entry.gt_g_value = val;
13255                       tab[c].gt_entry.gt_bytes = add;
13256
13257                       /* Merge in the size for the next smallest -G
13258                          value, since that will be implied by this new
13259                          value.  */
13260                       max = 0;
13261                       for (look = 1; look < c; look++)
13262                         {
13263                           if (tab[look].gt_entry.gt_g_value < val
13264                               && (max == 0
13265                                   || (tab[look].gt_entry.gt_g_value
13266                                       > tab[max].gt_entry.gt_g_value)))
13267                             max = look;
13268                         }
13269                       if (max != 0)
13270                         tab[c].gt_entry.gt_bytes +=
13271                           tab[max].gt_entry.gt_bytes;
13272
13273                       ++c;
13274                     }
13275
13276                   last = int_gptab.gt_entry.gt_bytes;
13277                 }
13278
13279               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13280                  elf_link_input_bfd ignores this section.  */
13281               input_section->flags &= ~SEC_HAS_CONTENTS;
13282             }
13283
13284           /* The table must be sorted by -G value.  */
13285           if (c > 2)
13286             qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare);
13287
13288           /* Swap out the table.  */
13289           amt = (bfd_size_type) c * sizeof (Elf32_External_gptab);
13290           ext_tab = bfd_alloc (abfd, amt);
13291           if (ext_tab == NULL)
13292             {
13293               free (tab);
13294               return FALSE;
13295             }
13296
13297           for (j = 0; j < c; j++)
13298             bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j);
13299           free (tab);
13300
13301           o->size = c * sizeof (Elf32_External_gptab);
13302           o->contents = (bfd_byte *) ext_tab;
13303
13304           /* Skip this section later on (I don't think this currently
13305              matters, but someday it might).  */
13306           o->map_head.link_order = NULL;
13307         }
13308     }
13309
13310   /* Invoke the regular ELF backend linker to do all the work.  */
13311   if (!bfd_elf_final_link (abfd, info))
13312     return FALSE;
13313
13314   /* Now write out the computed sections.  */
13315
13316   if (reginfo_sec != NULL)
13317     {
13318       Elf32_External_RegInfo ext;
13319
13320       bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext);
13321       if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext))
13322         return FALSE;
13323     }
13324
13325   if (mdebug_sec != NULL)
13326     {
13327       BFD_ASSERT (abfd->output_has_begun);
13328       if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug,
13329                                                swap, info,
13330                                                mdebug_sec->filepos))
13331         return FALSE;
13332
13333       bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info);
13334     }
13335
13336   if (gptab_data_sec != NULL)
13337     {
13338       if (! bfd_set_section_contents (abfd, gptab_data_sec,
13339                                       gptab_data_sec->contents,
13340                                       0, gptab_data_sec->size))
13341         return FALSE;
13342     }
13343
13344   if (gptab_bss_sec != NULL)
13345     {
13346       if (! bfd_set_section_contents (abfd, gptab_bss_sec,
13347                                       gptab_bss_sec->contents,
13348                                       0, gptab_bss_sec->size))
13349         return FALSE;
13350     }
13351
13352   if (SGI_COMPAT (abfd))
13353     {
13354       rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
13355       if (rtproc_sec != NULL)
13356         {
13357           if (! bfd_set_section_contents (abfd, rtproc_sec,
13358                                           rtproc_sec->contents,
13359                                           0, rtproc_sec->size))
13360             return FALSE;
13361         }
13362     }
13363
13364   return TRUE;
13365 }
13366 \f
13367 /* Structure for saying that BFD machine EXTENSION extends BASE.  */
13368
13369 struct mips_mach_extension {
13370   unsigned long extension, base;
13371 };
13372
13373
13374 /* An array describing how BFD machines relate to one another.  The entries
13375    are ordered topologically with MIPS I extensions listed last.  */
13376
13377 static const struct mips_mach_extension mips_mach_extensions[] = {
13378   /* MIPS64r2 extensions.  */
13379   { bfd_mach_mips_octeon2, bfd_mach_mips_octeonp },
13380   { bfd_mach_mips_octeonp, bfd_mach_mips_octeon },
13381   { bfd_mach_mips_octeon, bfd_mach_mipsisa64r2 },
13382
13383   /* MIPS64 extensions.  */
13384   { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 },
13385   { bfd_mach_mips_sb1, bfd_mach_mipsisa64 },
13386   { bfd_mach_mips_xlr, bfd_mach_mipsisa64 },
13387   { bfd_mach_mips_loongson_3a, bfd_mach_mipsisa64 },
13388
13389   /* MIPS V extensions.  */
13390   { bfd_mach_mipsisa64, bfd_mach_mips5 },
13391
13392   /* R10000 extensions.  */
13393   { bfd_mach_mips12000, bfd_mach_mips10000 },
13394   { bfd_mach_mips14000, bfd_mach_mips10000 },
13395   { bfd_mach_mips16000, bfd_mach_mips10000 },
13396
13397   /* R5000 extensions.  Note: the vr5500 ISA is an extension of the core
13398      vr5400 ISA, but doesn't include the multimedia stuff.  It seems
13399      better to allow vr5400 and vr5500 code to be merged anyway, since
13400      many libraries will just use the core ISA.  Perhaps we could add
13401      some sort of ASE flag if this ever proves a problem.  */
13402   { bfd_mach_mips5500, bfd_mach_mips5400 },
13403   { bfd_mach_mips5400, bfd_mach_mips5000 },
13404
13405   /* MIPS IV extensions.  */
13406   { bfd_mach_mips5, bfd_mach_mips8000 },
13407   { bfd_mach_mips10000, bfd_mach_mips8000 },
13408   { bfd_mach_mips5000, bfd_mach_mips8000 },
13409   { bfd_mach_mips7000, bfd_mach_mips8000 },
13410   { bfd_mach_mips9000, bfd_mach_mips8000 },
13411
13412   /* VR4100 extensions.  */
13413   { bfd_mach_mips4120, bfd_mach_mips4100 },
13414   { bfd_mach_mips4111, bfd_mach_mips4100 },
13415
13416   /* MIPS III extensions.  */
13417   { bfd_mach_mips_loongson_2e, bfd_mach_mips4000 },
13418   { bfd_mach_mips_loongson_2f, bfd_mach_mips4000 },
13419   { bfd_mach_mips8000, bfd_mach_mips4000 },
13420   { bfd_mach_mips4650, bfd_mach_mips4000 },
13421   { bfd_mach_mips4600, bfd_mach_mips4000 },
13422   { bfd_mach_mips4400, bfd_mach_mips4000 },
13423   { bfd_mach_mips4300, bfd_mach_mips4000 },
13424   { bfd_mach_mips4100, bfd_mach_mips4000 },
13425   { bfd_mach_mips4010, bfd_mach_mips4000 },
13426   { bfd_mach_mips5900, bfd_mach_mips4000 },
13427
13428   /* MIPS32 extensions.  */
13429   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
13430
13431   /* MIPS II extensions.  */
13432   { bfd_mach_mips4000, bfd_mach_mips6000 },
13433   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
13434
13435   /* MIPS I extensions.  */
13436   { bfd_mach_mips6000, bfd_mach_mips3000 },
13437   { bfd_mach_mips3900, bfd_mach_mips3000 }
13438 };
13439
13440
13441 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
13442
13443 static bfd_boolean
13444 mips_mach_extends_p (unsigned long base, unsigned long extension)
13445 {
13446   size_t i;
13447
13448   if (extension == base)
13449     return TRUE;
13450
13451   if (base == bfd_mach_mipsisa32
13452       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
13453     return TRUE;
13454
13455   if (base == bfd_mach_mipsisa32r2
13456       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
13457     return TRUE;
13458
13459   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
13460     if (extension == mips_mach_extensions[i].extension)
13461       {
13462         extension = mips_mach_extensions[i].base;
13463         if (extension == base)
13464           return TRUE;
13465       }
13466
13467   return FALSE;
13468 }
13469
13470
13471 /* Return true if the given ELF header flags describe a 32-bit binary.  */
13472
13473 static bfd_boolean
13474 mips_32bit_flags_p (flagword flags)
13475 {
13476   return ((flags & EF_MIPS_32BITMODE) != 0
13477           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
13478           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
13479           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
13480           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
13481           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
13482           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2);
13483 }
13484
13485
13486 /* Merge object attributes from IBFD into OBFD.  Raise an error if
13487    there are conflicting attributes.  */
13488 static bfd_boolean
13489 mips_elf_merge_obj_attributes (bfd *ibfd, bfd *obfd)
13490 {
13491   obj_attribute *in_attr;
13492   obj_attribute *out_attr;
13493   bfd *abi_fp_bfd;
13494
13495   abi_fp_bfd = mips_elf_tdata (obfd)->abi_fp_bfd;
13496   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
13497   if (!abi_fp_bfd && in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13498     mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
13499
13500   if (!elf_known_obj_attributes_proc (obfd)[0].i)
13501     {
13502       /* This is the first object.  Copy the attributes.  */
13503       _bfd_elf_copy_obj_attributes (ibfd, obfd);
13504
13505       /* Use the Tag_null value to indicate the attributes have been
13506          initialized.  */
13507       elf_known_obj_attributes_proc (obfd)[0].i = 1;
13508
13509       return TRUE;
13510     }
13511
13512   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
13513      non-conflicting ones.  */
13514   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
13515   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
13516     {
13517       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
13518       if (out_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
13519         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
13520       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13521         switch (out_attr[Tag_GNU_MIPS_ABI_FP].i)
13522           {
13523           case 1:
13524             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13525               {
13526               case 2:
13527                 _bfd_error_handler
13528                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13529                    obfd, abi_fp_bfd, ibfd, "-mdouble-float", "-msingle-float");
13530                 break;
13531
13532               case 3:
13533                 _bfd_error_handler
13534                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13535                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13536                 break;
13537
13538               case 4:
13539                 _bfd_error_handler
13540                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13541                    obfd, abi_fp_bfd, ibfd,
13542                    "-mdouble-float", "-mips32r2 -mfp64");
13543                 break;
13544
13545               default:
13546                 _bfd_error_handler
13547                   (_("Warning: %B uses %s (set by %B), "
13548                      "%B uses unknown floating point ABI %d"),
13549                    obfd, abi_fp_bfd, ibfd,
13550                    "-mdouble-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13551                 break;
13552               }
13553             break;
13554
13555           case 2:
13556             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13557               {
13558               case 1:
13559                 _bfd_error_handler
13560                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13561                    obfd, abi_fp_bfd, ibfd, "-msingle-float", "-mdouble-float");
13562                 break;
13563
13564               case 3:
13565                 _bfd_error_handler
13566                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13567                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13568                 break;
13569
13570               case 4:
13571                 _bfd_error_handler
13572                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13573                    obfd, abi_fp_bfd, ibfd,
13574                    "-msingle-float", "-mips32r2 -mfp64");
13575                 break;
13576
13577               default:
13578                 _bfd_error_handler
13579                   (_("Warning: %B uses %s (set by %B), "
13580                      "%B uses unknown floating point ABI %d"),
13581                    obfd, abi_fp_bfd, ibfd,
13582                    "-msingle-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13583                 break;
13584               }
13585             break;
13586
13587           case 3:
13588             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13589               {
13590               case 1:
13591               case 2:
13592               case 4:
13593                 _bfd_error_handler
13594                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13595                    obfd, abi_fp_bfd, ibfd, "-msoft-float", "-mhard-float");
13596                 break;
13597
13598               default:
13599                 _bfd_error_handler
13600                   (_("Warning: %B uses %s (set by %B), "
13601                      "%B uses unknown floating point ABI %d"),
13602                    obfd, abi_fp_bfd, ibfd,
13603                    "-msoft-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13604                 break;
13605               }
13606             break;
13607
13608           case 4:
13609             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13610               {
13611               case 1:
13612                 _bfd_error_handler
13613                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13614                    obfd, abi_fp_bfd, ibfd,
13615                    "-mips32r2 -mfp64", "-mdouble-float");
13616                 break;
13617
13618               case 2:
13619                 _bfd_error_handler
13620                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13621                    obfd, abi_fp_bfd, ibfd,
13622                    "-mips32r2 -mfp64", "-msingle-float");
13623                 break;
13624
13625               case 3:
13626                 _bfd_error_handler
13627                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13628                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13629                 break;
13630
13631               default:
13632                 _bfd_error_handler
13633                   (_("Warning: %B uses %s (set by %B), "
13634                      "%B uses unknown floating point ABI %d"),
13635                    obfd, abi_fp_bfd, ibfd,
13636                    "-mips32r2 -mfp64", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13637                 break;
13638               }
13639             break;
13640
13641           default:
13642             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13643               {
13644               case 1:
13645                 _bfd_error_handler
13646                   (_("Warning: %B uses unknown floating point ABI %d "
13647                      "(set by %B), %B uses %s"),
13648                    obfd, abi_fp_bfd, ibfd,
13649                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mdouble-float");
13650                 break;
13651
13652               case 2:
13653                 _bfd_error_handler
13654                   (_("Warning: %B uses unknown floating point ABI %d "
13655                      "(set by %B), %B uses %s"),
13656                    obfd, abi_fp_bfd, ibfd,
13657                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msingle-float");
13658                 break;
13659
13660               case 3:
13661                 _bfd_error_handler
13662                   (_("Warning: %B uses unknown floating point ABI %d "
13663                      "(set by %B), %B uses %s"),
13664                    obfd, abi_fp_bfd, ibfd,
13665                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msoft-float");
13666                 break;
13667
13668               case 4:
13669                 _bfd_error_handler
13670                   (_("Warning: %B uses unknown floating point ABI %d "
13671                      "(set by %B), %B uses %s"),
13672                    obfd, abi_fp_bfd, ibfd,
13673                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mips32r2 -mfp64");
13674                 break;
13675
13676               default:
13677                 _bfd_error_handler
13678                   (_("Warning: %B uses unknown floating point ABI %d "
13679                      "(set by %B), %B uses unknown floating point ABI %d"),
13680                    obfd, abi_fp_bfd, ibfd,
13681                    out_attr[Tag_GNU_MIPS_ABI_FP].i,
13682                    in_attr[Tag_GNU_MIPS_ABI_FP].i);
13683                 break;
13684               }
13685             break;
13686           }
13687     }
13688
13689   /* Merge Tag_compatibility attributes and any common GNU ones.  */
13690   _bfd_elf_merge_object_attributes (ibfd, obfd);
13691
13692   return TRUE;
13693 }
13694
13695 /* Merge backend specific data from an object file to the output
13696    object file when linking.  */
13697
13698 bfd_boolean
13699 _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
13700 {
13701   flagword old_flags;
13702   flagword new_flags;
13703   bfd_boolean ok;
13704   bfd_boolean null_input_bfd = TRUE;
13705   asection *sec;
13706
13707   /* Check if we have the same endianness.  */
13708   if (! _bfd_generic_verify_endian_match (ibfd, obfd))
13709     {
13710       (*_bfd_error_handler)
13711         (_("%B: endianness incompatible with that of the selected emulation"),
13712          ibfd);
13713       return FALSE;
13714     }
13715
13716   if (!is_mips_elf (ibfd) || !is_mips_elf (obfd))
13717     return TRUE;
13718
13719   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
13720     {
13721       (*_bfd_error_handler)
13722         (_("%B: ABI is incompatible with that of the selected emulation"),
13723          ibfd);
13724       return FALSE;
13725     }
13726
13727   if (!mips_elf_merge_obj_attributes (ibfd, obfd))
13728     return FALSE;
13729
13730   new_flags = elf_elfheader (ibfd)->e_flags;
13731   elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER;
13732   old_flags = elf_elfheader (obfd)->e_flags;
13733
13734   if (! elf_flags_init (obfd))
13735     {
13736       elf_flags_init (obfd) = TRUE;
13737       elf_elfheader (obfd)->e_flags = new_flags;
13738       elf_elfheader (obfd)->e_ident[EI_CLASS]
13739         = elf_elfheader (ibfd)->e_ident[EI_CLASS];
13740
13741       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
13742           && (bfd_get_arch_info (obfd)->the_default
13743               || mips_mach_extends_p (bfd_get_mach (obfd),
13744                                       bfd_get_mach (ibfd))))
13745         {
13746           if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
13747                                    bfd_get_mach (ibfd)))
13748             return FALSE;
13749         }
13750
13751       return TRUE;
13752     }
13753
13754   /* Check flag compatibility.  */
13755
13756   new_flags &= ~EF_MIPS_NOREORDER;
13757   old_flags &= ~EF_MIPS_NOREORDER;
13758
13759   /* Some IRIX 6 BSD-compatibility objects have this bit set.  It
13760      doesn't seem to matter.  */
13761   new_flags &= ~EF_MIPS_XGOT;
13762   old_flags &= ~EF_MIPS_XGOT;
13763
13764   /* MIPSpro generates ucode info in n64 objects.  Again, we should
13765      just be able to ignore this.  */
13766   new_flags &= ~EF_MIPS_UCODE;
13767   old_flags &= ~EF_MIPS_UCODE;
13768
13769   /* DSOs should only be linked with CPIC code.  */
13770   if ((ibfd->flags & DYNAMIC) != 0)
13771     new_flags |= EF_MIPS_PIC | EF_MIPS_CPIC;
13772
13773   if (new_flags == old_flags)
13774     return TRUE;
13775
13776   /* Check to see if the input BFD actually contains any sections.
13777      If not, its flags may not have been initialised either, but it cannot
13778      actually cause any incompatibility.  */
13779   for (sec = ibfd->sections; sec != NULL; sec = sec->next)
13780     {
13781       /* Ignore synthetic sections and empty .text, .data and .bss sections
13782          which are automatically generated by gas.  Also ignore fake
13783          (s)common sections, since merely defining a common symbol does
13784          not affect compatibility.  */
13785       if ((sec->flags & SEC_IS_COMMON) == 0
13786           && strcmp (sec->name, ".reginfo")
13787           && strcmp (sec->name, ".mdebug")
13788           && (sec->size != 0
13789               || (strcmp (sec->name, ".text")
13790                   && strcmp (sec->name, ".data")
13791                   && strcmp (sec->name, ".bss"))))
13792         {
13793           null_input_bfd = FALSE;
13794           break;
13795         }
13796     }
13797   if (null_input_bfd)
13798     return TRUE;
13799
13800   ok = TRUE;
13801
13802   if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)
13803       != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0))
13804     {
13805       (*_bfd_error_handler)
13806         (_("%B: warning: linking abicalls files with non-abicalls files"),
13807          ibfd);
13808       ok = TRUE;
13809     }
13810
13811   if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC))
13812     elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC;
13813   if (! (new_flags & EF_MIPS_PIC))
13814     elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC;
13815
13816   new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13817   old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13818
13819   /* Compare the ISAs.  */
13820   if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags))
13821     {
13822       (*_bfd_error_handler)
13823         (_("%B: linking 32-bit code with 64-bit code"),
13824          ibfd);
13825       ok = FALSE;
13826     }
13827   else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd)))
13828     {
13829       /* OBFD's ISA isn't the same as, or an extension of, IBFD's.  */
13830       if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd)))
13831         {
13832           /* Copy the architecture info from IBFD to OBFD.  Also copy
13833              the 32-bit flag (if set) so that we continue to recognise
13834              OBFD as a 32-bit binary.  */
13835           bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd));
13836           elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
13837           elf_elfheader (obfd)->e_flags
13838             |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13839
13840           /* Copy across the ABI flags if OBFD doesn't use them
13841              and if that was what caused us to treat IBFD as 32-bit.  */
13842           if ((old_flags & EF_MIPS_ABI) == 0
13843               && mips_32bit_flags_p (new_flags)
13844               && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI))
13845             elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI;
13846         }
13847       else
13848         {
13849           /* The ISAs aren't compatible.  */
13850           (*_bfd_error_handler)
13851             (_("%B: linking %s module with previous %s modules"),
13852              ibfd,
13853              bfd_printable_name (ibfd),
13854              bfd_printable_name (obfd));
13855           ok = FALSE;
13856         }
13857     }
13858
13859   new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13860   old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13861
13862   /* Compare ABIs.  The 64-bit ABI does not use EF_MIPS_ABI.  But, it
13863      does set EI_CLASS differently from any 32-bit ABI.  */
13864   if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI)
13865       || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
13866           != elf_elfheader (obfd)->e_ident[EI_CLASS]))
13867     {
13868       /* Only error if both are set (to different values).  */
13869       if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI))
13870           || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
13871               != elf_elfheader (obfd)->e_ident[EI_CLASS]))
13872         {
13873           (*_bfd_error_handler)
13874             (_("%B: ABI mismatch: linking %s module with previous %s modules"),
13875              ibfd,
13876              elf_mips_abi_name (ibfd),
13877              elf_mips_abi_name (obfd));
13878           ok = FALSE;
13879         }
13880       new_flags &= ~EF_MIPS_ABI;
13881       old_flags &= ~EF_MIPS_ABI;
13882     }
13883
13884   /* Compare ASEs.  Forbid linking MIPS16 and microMIPS ASE modules together
13885      and allow arbitrary mixing of the remaining ASEs (retain the union).  */
13886   if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE))
13887     {
13888       int old_micro = old_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
13889       int new_micro = new_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
13890       int old_m16 = old_flags & EF_MIPS_ARCH_ASE_M16;
13891       int new_m16 = new_flags & EF_MIPS_ARCH_ASE_M16;
13892       int micro_mis = old_m16 && new_micro;
13893       int m16_mis = old_micro && new_m16;
13894
13895       if (m16_mis || micro_mis)
13896         {
13897           (*_bfd_error_handler)
13898             (_("%B: ASE mismatch: linking %s module with previous %s modules"),
13899              ibfd,
13900              m16_mis ? "MIPS16" : "microMIPS",
13901              m16_mis ? "microMIPS" : "MIPS16");
13902           ok = FALSE;
13903         }
13904
13905       elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE;
13906
13907       new_flags &= ~ EF_MIPS_ARCH_ASE;
13908       old_flags &= ~ EF_MIPS_ARCH_ASE;
13909     }
13910
13911   /* Warn about any other mismatches */
13912   if (new_flags != old_flags)
13913     {
13914       (*_bfd_error_handler)
13915         (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"),
13916          ibfd, (unsigned long) new_flags,
13917          (unsigned long) old_flags);
13918       ok = FALSE;
13919     }
13920
13921   if (! ok)
13922     {
13923       bfd_set_error (bfd_error_bad_value);
13924       return FALSE;
13925     }
13926
13927   return TRUE;
13928 }
13929
13930 /* Function to keep MIPS specific file flags like as EF_MIPS_PIC.  */
13931
13932 bfd_boolean
13933 _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags)
13934 {
13935   BFD_ASSERT (!elf_flags_init (abfd)
13936               || elf_elfheader (abfd)->e_flags == flags);
13937
13938   elf_elfheader (abfd)->e_flags = flags;
13939   elf_flags_init (abfd) = TRUE;
13940   return TRUE;
13941 }
13942
13943 char *
13944 _bfd_mips_elf_get_target_dtag (bfd_vma dtag)
13945 {
13946   switch (dtag)
13947     {
13948     default: return "";
13949     case DT_MIPS_RLD_VERSION:
13950       return "MIPS_RLD_VERSION";
13951     case DT_MIPS_TIME_STAMP:
13952       return "MIPS_TIME_STAMP";
13953     case DT_MIPS_ICHECKSUM:
13954       return "MIPS_ICHECKSUM";
13955     case DT_MIPS_IVERSION:
13956       return "MIPS_IVERSION";
13957     case DT_MIPS_FLAGS:
13958       return "MIPS_FLAGS";
13959     case DT_MIPS_BASE_ADDRESS:
13960       return "MIPS_BASE_ADDRESS";
13961     case DT_MIPS_MSYM:
13962       return "MIPS_MSYM";
13963     case DT_MIPS_CONFLICT:
13964       return "MIPS_CONFLICT";
13965     case DT_MIPS_LIBLIST:
13966       return "MIPS_LIBLIST";
13967     case DT_MIPS_LOCAL_GOTNO:
13968       return "MIPS_LOCAL_GOTNO";
13969     case DT_MIPS_CONFLICTNO:
13970       return "MIPS_CONFLICTNO";
13971     case DT_MIPS_LIBLISTNO:
13972       return "MIPS_LIBLISTNO";
13973     case DT_MIPS_SYMTABNO:
13974       return "MIPS_SYMTABNO";
13975     case DT_MIPS_UNREFEXTNO:
13976       return "MIPS_UNREFEXTNO";
13977     case DT_MIPS_GOTSYM:
13978       return "MIPS_GOTSYM";
13979     case DT_MIPS_HIPAGENO:
13980       return "MIPS_HIPAGENO";
13981     case DT_MIPS_RLD_MAP:
13982       return "MIPS_RLD_MAP";
13983     case DT_MIPS_DELTA_CLASS:
13984       return "MIPS_DELTA_CLASS";
13985     case DT_MIPS_DELTA_CLASS_NO:
13986       return "MIPS_DELTA_CLASS_NO";
13987     case DT_MIPS_DELTA_INSTANCE:
13988       return "MIPS_DELTA_INSTANCE";
13989     case DT_MIPS_DELTA_INSTANCE_NO:
13990       return "MIPS_DELTA_INSTANCE_NO";
13991     case DT_MIPS_DELTA_RELOC:
13992       return "MIPS_DELTA_RELOC";
13993     case DT_MIPS_DELTA_RELOC_NO:
13994       return "MIPS_DELTA_RELOC_NO";
13995     case DT_MIPS_DELTA_SYM:
13996       return "MIPS_DELTA_SYM";
13997     case DT_MIPS_DELTA_SYM_NO:
13998       return "MIPS_DELTA_SYM_NO";
13999     case DT_MIPS_DELTA_CLASSSYM:
14000       return "MIPS_DELTA_CLASSSYM";
14001     case DT_MIPS_DELTA_CLASSSYM_NO:
14002       return "MIPS_DELTA_CLASSSYM_NO";
14003     case DT_MIPS_CXX_FLAGS:
14004       return "MIPS_CXX_FLAGS";
14005     case DT_MIPS_PIXIE_INIT:
14006       return "MIPS_PIXIE_INIT";
14007     case DT_MIPS_SYMBOL_LIB:
14008       return "MIPS_SYMBOL_LIB";
14009     case DT_MIPS_LOCALPAGE_GOTIDX:
14010       return "MIPS_LOCALPAGE_GOTIDX";
14011     case DT_MIPS_LOCAL_GOTIDX:
14012       return "MIPS_LOCAL_GOTIDX";
14013     case DT_MIPS_HIDDEN_GOTIDX:
14014       return "MIPS_HIDDEN_GOTIDX";
14015     case DT_MIPS_PROTECTED_GOTIDX:
14016       return "MIPS_PROTECTED_GOT_IDX";
14017     case DT_MIPS_OPTIONS:
14018       return "MIPS_OPTIONS";
14019     case DT_MIPS_INTERFACE:
14020       return "MIPS_INTERFACE";
14021     case DT_MIPS_DYNSTR_ALIGN:
14022       return "DT_MIPS_DYNSTR_ALIGN";
14023     case DT_MIPS_INTERFACE_SIZE:
14024       return "DT_MIPS_INTERFACE_SIZE";
14025     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
14026       return "DT_MIPS_RLD_TEXT_RESOLVE_ADDR";
14027     case DT_MIPS_PERF_SUFFIX:
14028       return "DT_MIPS_PERF_SUFFIX";
14029     case DT_MIPS_COMPACT_SIZE:
14030       return "DT_MIPS_COMPACT_SIZE";
14031     case DT_MIPS_GP_VALUE:
14032       return "DT_MIPS_GP_VALUE";
14033     case DT_MIPS_AUX_DYNAMIC:
14034       return "DT_MIPS_AUX_DYNAMIC";
14035     case DT_MIPS_PLTGOT:
14036       return "DT_MIPS_PLTGOT";
14037     case DT_MIPS_RWPLT:
14038       return "DT_MIPS_RWPLT";
14039     }
14040 }
14041
14042 bfd_boolean
14043 _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr)
14044 {
14045   FILE *file = ptr;
14046
14047   BFD_ASSERT (abfd != NULL && ptr != NULL);
14048
14049   /* Print normal ELF private data.  */
14050   _bfd_elf_print_private_bfd_data (abfd, ptr);
14051
14052   /* xgettext:c-format */
14053   fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
14054
14055   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
14056     fprintf (file, _(" [abi=O32]"));
14057   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64)
14058     fprintf (file, _(" [abi=O64]"));
14059   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32)
14060     fprintf (file, _(" [abi=EABI32]"));
14061   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
14062     fprintf (file, _(" [abi=EABI64]"));
14063   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI))
14064     fprintf (file, _(" [abi unknown]"));
14065   else if (ABI_N32_P (abfd))
14066     fprintf (file, _(" [abi=N32]"));
14067   else if (ABI_64_P (abfd))
14068     fprintf (file, _(" [abi=64]"));
14069   else
14070     fprintf (file, _(" [no abi set]"));
14071
14072   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1)
14073     fprintf (file, " [mips1]");
14074   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2)
14075     fprintf (file, " [mips2]");
14076   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3)
14077     fprintf (file, " [mips3]");
14078   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4)
14079     fprintf (file, " [mips4]");
14080   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5)
14081     fprintf (file, " [mips5]");
14082   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32)
14083     fprintf (file, " [mips32]");
14084   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64)
14085     fprintf (file, " [mips64]");
14086   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2)
14087     fprintf (file, " [mips32r2]");
14088   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2)
14089     fprintf (file, " [mips64r2]");
14090   else
14091     fprintf (file, _(" [unknown ISA]"));
14092
14093   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
14094     fprintf (file, " [mdmx]");
14095
14096   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
14097     fprintf (file, " [mips16]");
14098
14099   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
14100     fprintf (file, " [micromips]");
14101
14102   if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE)
14103     fprintf (file, " [32bitmode]");
14104   else
14105     fprintf (file, _(" [not 32bitmode]"));
14106
14107   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NOREORDER)
14108     fprintf (file, " [noreorder]");
14109
14110   if (elf_elfheader (abfd)->e_flags & EF_MIPS_PIC)
14111     fprintf (file, " [PIC]");
14112
14113   if (elf_elfheader (abfd)->e_flags & EF_MIPS_CPIC)
14114     fprintf (file, " [CPIC]");
14115
14116   if (elf_elfheader (abfd)->e_flags & EF_MIPS_XGOT)
14117     fprintf (file, " [XGOT]");
14118
14119   if (elf_elfheader (abfd)->e_flags & EF_MIPS_UCODE)
14120     fprintf (file, " [UCODE]");
14121
14122   fputc ('\n', file);
14123
14124   return TRUE;
14125 }
14126
14127 const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] =
14128 {
14129   { STRING_COMMA_LEN (".lit4"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14130   { STRING_COMMA_LEN (".lit8"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14131   { STRING_COMMA_LEN (".mdebug"), 0, SHT_MIPS_DEBUG, 0 },
14132   { STRING_COMMA_LEN (".sbss"),  -2, SHT_NOBITS,     SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14133   { STRING_COMMA_LEN (".sdata"), -2, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14134   { STRING_COMMA_LEN (".ucode"),  0, SHT_MIPS_UCODE, 0 },
14135   { NULL,                     0,  0, 0,              0 }
14136 };
14137
14138 /* Merge non visibility st_other attributes.  Ensure that the
14139    STO_OPTIONAL flag is copied into h->other, even if this is not a
14140    definiton of the symbol.  */
14141 void
14142 _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
14143                                       const Elf_Internal_Sym *isym,
14144                                       bfd_boolean definition,
14145                                       bfd_boolean dynamic ATTRIBUTE_UNUSED)
14146 {
14147   if ((isym->st_other & ~ELF_ST_VISIBILITY (-1)) != 0)
14148     {
14149       unsigned char other;
14150
14151       other = (definition ? isym->st_other : h->other);
14152       other &= ~ELF_ST_VISIBILITY (-1);
14153       h->other = other | ELF_ST_VISIBILITY (h->other);
14154     }
14155
14156   if (!definition
14157       && ELF_MIPS_IS_OPTIONAL (isym->st_other))
14158     h->other |= STO_OPTIONAL;
14159 }
14160
14161 /* Decide whether an undefined symbol is special and can be ignored.
14162    This is the case for OPTIONAL symbols on IRIX.  */
14163 bfd_boolean
14164 _bfd_mips_elf_ignore_undef_symbol (struct elf_link_hash_entry *h)
14165 {
14166   return ELF_MIPS_IS_OPTIONAL (h->other) ? TRUE : FALSE;
14167 }
14168
14169 bfd_boolean
14170 _bfd_mips_elf_common_definition (Elf_Internal_Sym *sym)
14171 {
14172   return (sym->st_shndx == SHN_COMMON
14173           || sym->st_shndx == SHN_MIPS_ACOMMON
14174           || sym->st_shndx == SHN_MIPS_SCOMMON);
14175 }
14176
14177 /* Return address for Ith PLT stub in section PLT, for relocation REL
14178    or (bfd_vma) -1 if it should not be included.  */
14179
14180 bfd_vma
14181 _bfd_mips_elf_plt_sym_val (bfd_vma i, const asection *plt,
14182                            const arelent *rel ATTRIBUTE_UNUSED)
14183 {
14184   return (plt->vma
14185           + 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry)
14186           + i * 4 * ARRAY_SIZE (mips_exec_plt_entry));
14187 }
14188
14189 void
14190 _bfd_mips_post_process_headers (bfd *abfd, struct bfd_link_info *link_info)
14191 {
14192   struct mips_elf_link_hash_table *htab;
14193   Elf_Internal_Ehdr *i_ehdrp;
14194
14195   i_ehdrp = elf_elfheader (abfd);
14196   if (link_info)
14197     {
14198       htab = mips_elf_hash_table (link_info);
14199       BFD_ASSERT (htab != NULL);
14200
14201       if (htab->use_plts_and_copy_relocs && !htab->is_vxworks)
14202         i_ehdrp->e_ident[EI_ABIVERSION] = 1;
14203     }
14204 }