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 /* Types of TLS GOT entry.  */
51 enum mips_got_tls_type {
52   GOT_TLS_NONE,
53   GOT_TLS_GD,
54   GOT_TLS_LDM,
55   GOT_TLS_IE
56 };
57
58 /* This structure is used to hold information about one GOT entry.
59    There are four types of entry:
60
61       (1) an absolute address
62             requires: abfd == NULL
63             fields: d.address
64
65       (2) a SYMBOL + OFFSET address, where SYMBOL is local to an input bfd
66             requires: abfd != NULL, symndx >= 0, tls_type != GOT_TLS_LDM
67             fields: abfd, symndx, d.addend, tls_type
68
69       (3) a SYMBOL address, where SYMBOL is not local to an input bfd
70             requires: abfd != NULL, symndx == -1
71             fields: d.h, tls_type
72
73       (4) a TLS LDM slot
74             requires: abfd != NULL, symndx == 0, tls_type == GOT_TLS_LDM
75             fields: none; there's only one of these per GOT.  */
76 struct mips_got_entry
77 {
78   /* One input bfd that needs the GOT entry.  */
79   bfd *abfd;
80   /* The index of the symbol, as stored in the relocation r_info, if
81      we have a local symbol; -1 otherwise.  */
82   long symndx;
83   union
84   {
85     /* If abfd == NULL, an address that must be stored in the got.  */
86     bfd_vma address;
87     /* If abfd != NULL && symndx != -1, the addend of the relocation
88        that should be added to the symbol value.  */
89     bfd_vma addend;
90     /* If abfd != NULL && symndx == -1, the hash table entry
91        corresponding to a symbol in the GOT.  The symbol's entry
92        is in the local area if h->global_got_area is GGA_NONE,
93        otherwise it is in the global area.  */
94     struct mips_elf_link_hash_entry *h;
95   } d;
96
97   /* The TLS type of this GOT entry.  An LDM GOT entry will be a local
98      symbol entry with r_symndx == 0.  */
99   unsigned char tls_type;
100
101   /* True if we have filled in the GOT contents for a TLS entry,
102      and created the associated relocations.  */
103   unsigned char tls_initialized;
104
105   /* The offset from the beginning of the .got section to the entry
106      corresponding to this symbol+addend.  If it's a global symbol
107      whose offset is yet to be decided, it's going to be -1.  */
108   long gotidx;
109 };
110
111 /* This structure describes a range of addends: [MIN_ADDEND, MAX_ADDEND].
112    The structures form a non-overlapping list that is sorted by increasing
113    MIN_ADDEND.  */
114 struct mips_got_page_range
115 {
116   struct mips_got_page_range *next;
117   bfd_signed_vma min_addend;
118   bfd_signed_vma max_addend;
119 };
120
121 /* This structure describes the range of addends that are applied to page
122    relocations against a given symbol.  */
123 struct mips_got_page_entry
124 {
125   /* The input bfd in which the symbol is defined.  */
126   bfd *abfd;
127   /* The index of the symbol, as stored in the relocation r_info.  */
128   long symndx;
129   /* The ranges for this page entry.  */
130   struct mips_got_page_range *ranges;
131   /* The maximum number of page entries needed for RANGES.  */
132   bfd_vma num_pages;
133 };
134
135 /* This structure is used to hold .got information when linking.  */
136
137 struct mips_got_info
138 {
139   /* The number of global .got entries.  */
140   unsigned int global_gotno;
141   /* The number of global .got entries that are in the GGA_RELOC_ONLY area.  */
142   unsigned int reloc_only_gotno;
143   /* The number of .got slots used for TLS.  */
144   unsigned int tls_gotno;
145   /* The first unused TLS .got entry.  Used only during
146      mips_elf_initialize_tls_index.  */
147   unsigned int tls_assigned_gotno;
148   /* The number of local .got entries, eventually including page entries.  */
149   unsigned int local_gotno;
150   /* The maximum number of page entries needed.  */
151   unsigned int page_gotno;
152   /* The number of relocations needed for the GOT entries.  */
153   unsigned int relocs;
154   /* The number of local .got entries we have used.  */
155   unsigned int assigned_gotno;
156   /* A hash table holding members of the got.  */
157   struct htab *got_entries;
158   /* A hash table of mips_got_page_entry structures.  */
159   struct htab *got_page_entries;
160   /* In multi-got links, a pointer to the next got (err, rather, most
161      of the time, it points to the previous got).  */
162   struct mips_got_info *next;
163 };
164
165 /* Structure passed when merging bfds' gots.  */
166
167 struct mips_elf_got_per_bfd_arg
168 {
169   /* The output bfd.  */
170   bfd *obfd;
171   /* The link information.  */
172   struct bfd_link_info *info;
173   /* A pointer to the primary got, i.e., the one that's going to get
174      the implicit relocations from DT_MIPS_LOCAL_GOTNO and
175      DT_MIPS_GOTSYM.  */
176   struct mips_got_info *primary;
177   /* A non-primary got we're trying to merge with other input bfd's
178      gots.  */
179   struct mips_got_info *current;
180   /* The maximum number of got entries that can be addressed with a
181      16-bit offset.  */
182   unsigned int max_count;
183   /* The maximum number of page entries needed by each got.  */
184   unsigned int max_pages;
185   /* The total number of global entries which will live in the
186      primary got and be automatically relocated.  This includes
187      those not referenced by the primary GOT but included in
188      the "master" GOT.  */
189   unsigned int global_count;
190 };
191
192 /* A structure used to pass information to htab_traverse callbacks
193    when laying out the GOT.  */
194
195 struct mips_elf_traverse_got_arg
196 {
197   struct bfd_link_info *info;
198   struct mips_got_info *g;
199   int value;
200 };
201
202 struct _mips_elf_section_data
203 {
204   struct bfd_elf_section_data elf;
205   union
206   {
207     bfd_byte *tdata;
208   } u;
209 };
210
211 #define mips_elf_section_data(sec) \
212   ((struct _mips_elf_section_data *) elf_section_data (sec))
213
214 #define is_mips_elf(bfd)                                \
215   (bfd_get_flavour (bfd) == bfd_target_elf_flavour      \
216    && elf_tdata (bfd) != NULL                           \
217    && elf_object_id (bfd) == MIPS_ELF_DATA)
218
219 /* The ABI says that every symbol used by dynamic relocations must have
220    a global GOT entry.  Among other things, this provides the dynamic
221    linker with a free, directly-indexed cache.  The GOT can therefore
222    contain symbols that are not referenced by GOT relocations themselves
223    (in other words, it may have symbols that are not referenced by things
224    like R_MIPS_GOT16 and R_MIPS_GOT_PAGE).
225
226    GOT relocations are less likely to overflow if we put the associated
227    GOT entries towards the beginning.  We therefore divide the global
228    GOT entries into two areas: "normal" and "reloc-only".  Entries in
229    the first area can be used for both dynamic relocations and GP-relative
230    accesses, while those in the "reloc-only" area are for dynamic
231    relocations only.
232
233    These GGA_* ("Global GOT Area") values are organised so that lower
234    values are more general than higher values.  Also, non-GGA_NONE
235    values are ordered by the position of the area in the GOT.  */
236 #define GGA_NORMAL 0
237 #define GGA_RELOC_ONLY 1
238 #define GGA_NONE 2
239
240 /* Information about a non-PIC interface to a PIC function.  There are
241    two ways of creating these interfaces.  The first is to add:
242
243         lui     $25,%hi(func)
244         addiu   $25,$25,%lo(func)
245
246    immediately before a PIC function "func".  The second is to add:
247
248         lui     $25,%hi(func)
249         j       func
250         addiu   $25,$25,%lo(func)
251
252    to a separate trampoline section.
253
254    Stubs of the first kind go in a new section immediately before the
255    target function.  Stubs of the second kind go in a single section
256    pointed to by the hash table's "strampoline" field.  */
257 struct mips_elf_la25_stub {
258   /* The generated section that contains this stub.  */
259   asection *stub_section;
260
261   /* The offset of the stub from the start of STUB_SECTION.  */
262   bfd_vma offset;
263
264   /* One symbol for the original function.  Its location is available
265      in H->root.root.u.def.  */
266   struct mips_elf_link_hash_entry *h;
267 };
268
269 /* Macros for populating a mips_elf_la25_stub.  */
270
271 #define LA25_LUI(VAL) (0x3c190000 | (VAL))      /* lui t9,VAL */
272 #define LA25_J(VAL) (0x08000000 | (((VAL) >> 2) & 0x3ffffff)) /* j VAL */
273 #define LA25_ADDIU(VAL) (0x27390000 | (VAL))    /* addiu t9,t9,VAL */
274 #define LA25_LUI_MICROMIPS(VAL)                                         \
275   (0x41b90000 | (VAL))                          /* lui t9,VAL */
276 #define LA25_J_MICROMIPS(VAL)                                           \
277   (0xd4000000 | (((VAL) >> 1) & 0x3ffffff))     /* j VAL */
278 #define LA25_ADDIU_MICROMIPS(VAL)                                       \
279   (0x33390000 | (VAL))                          /* addiu t9,t9,VAL */
280
281 /* This structure is passed to mips_elf_sort_hash_table_f when sorting
282    the dynamic symbols.  */
283
284 struct mips_elf_hash_sort_data
285 {
286   /* The symbol in the global GOT with the lowest dynamic symbol table
287      index.  */
288   struct elf_link_hash_entry *low;
289   /* The least dynamic symbol table index corresponding to a non-TLS
290      symbol with a GOT entry.  */
291   long min_got_dynindx;
292   /* The greatest dynamic symbol table index corresponding to a symbol
293      with a GOT entry that is not referenced (e.g., a dynamic symbol
294      with dynamic relocations pointing to it from non-primary GOTs).  */
295   long max_unref_got_dynindx;
296   /* The greatest dynamic symbol table index not corresponding to a
297      symbol without a GOT entry.  */
298   long max_non_got_dynindx;
299 };
300
301 /* The MIPS ELF linker needs additional information for each symbol in
302    the global hash table.  */
303
304 struct mips_elf_link_hash_entry
305 {
306   struct elf_link_hash_entry root;
307
308   /* External symbol information.  */
309   EXTR esym;
310
311   /* The la25 stub we have created for ths symbol, if any.  */
312   struct mips_elf_la25_stub *la25_stub;
313
314   /* Number of R_MIPS_32, R_MIPS_REL32, or R_MIPS_64 relocs against
315      this symbol.  */
316   unsigned int possibly_dynamic_relocs;
317
318   /* If there is a stub that 32 bit functions should use to call this
319      16 bit function, this points to the section containing the stub.  */
320   asection *fn_stub;
321
322   /* If there is a stub that 16 bit functions should use to call this
323      32 bit function, this points to the section containing the stub.  */
324   asection *call_stub;
325
326   /* This is like the call_stub field, but it is used if the function
327      being called returns a floating point value.  */
328   asection *call_fp_stub;
329
330   /* The highest GGA_* value that satisfies all references to this symbol.  */
331   unsigned int global_got_area : 2;
332
333   /* True if all GOT relocations against this symbol are for calls.  This is
334      a looser condition than no_fn_stub below, because there may be other
335      non-call non-GOT relocations against the symbol.  */
336   unsigned int got_only_for_calls : 1;
337
338   /* True if one of the relocations described by possibly_dynamic_relocs
339      is against a readonly section.  */
340   unsigned int readonly_reloc : 1;
341
342   /* True if there is a relocation against this symbol that must be
343      resolved by the static linker (in other words, if the relocation
344      cannot possibly be made dynamic).  */
345   unsigned int has_static_relocs : 1;
346
347   /* True if we must not create a .MIPS.stubs entry for this symbol.
348      This is set, for example, if there are relocations related to
349      taking the function's address, i.e. any but R_MIPS_CALL*16 ones.
350      See "MIPS ABI Supplement, 3rd Edition", p. 4-20.  */
351   unsigned int no_fn_stub : 1;
352
353   /* Whether we need the fn_stub; this is true if this symbol appears
354      in any relocs other than a 16 bit call.  */
355   unsigned int need_fn_stub : 1;
356
357   /* True if this symbol is referenced by branch relocations from
358      any non-PIC input file.  This is used to determine whether an
359      la25 stub is required.  */
360   unsigned int has_nonpic_branches : 1;
361
362   /* Does this symbol need a traditional MIPS lazy-binding stub
363      (as opposed to a PLT entry)?  */
364   unsigned int needs_lazy_stub : 1;
365 };
366
367 /* MIPS ELF linker hash table.  */
368
369 struct mips_elf_link_hash_table
370 {
371   struct elf_link_hash_table root;
372
373   /* The number of .rtproc entries.  */
374   bfd_size_type procedure_count;
375
376   /* The size of the .compact_rel section (if SGI_COMPAT).  */
377   bfd_size_type compact_rel_size;
378
379   /* This flag indicates that the value of DT_MIPS_RLD_MAP dynamic entry
380      is set to the address of __rld_obj_head as in IRIX5 and IRIX6.  */
381   bfd_boolean use_rld_obj_head;
382
383   /* The  __rld_map or __rld_obj_head symbol. */
384   struct elf_link_hash_entry *rld_symbol;
385
386   /* This is set if we see any mips16 stub sections.  */
387   bfd_boolean mips16_stubs_seen;
388
389   /* True if we can generate copy relocs and PLTs.  */
390   bfd_boolean use_plts_and_copy_relocs;
391
392   /* True if we're generating code for VxWorks.  */
393   bfd_boolean is_vxworks;
394
395   /* True if we already reported the small-data section overflow.  */
396   bfd_boolean small_data_overflow_reported;
397
398   /* Shortcuts to some dynamic sections, or NULL if they are not
399      being used.  */
400   asection *srelbss;
401   asection *sdynbss;
402   asection *srelplt;
403   asection *srelplt2;
404   asection *sgotplt;
405   asection *splt;
406   asection *sstubs;
407   asection *sgot;
408
409   /* The master GOT information.  */
410   struct mips_got_info *got_info;
411
412   /* The global symbol in the GOT with the lowest index in the dynamic
413      symbol table.  */
414   struct elf_link_hash_entry *global_gotsym;
415
416   /* The size of the PLT header in bytes.  */
417   bfd_vma plt_header_size;
418
419   /* The size of a PLT entry in bytes.  */
420   bfd_vma plt_entry_size;
421
422   /* The number of functions that need a lazy-binding stub.  */
423   bfd_vma lazy_stub_count;
424
425   /* The size of a function stub entry in bytes.  */
426   bfd_vma function_stub_size;
427
428   /* The number of reserved entries at the beginning of the GOT.  */
429   unsigned int reserved_gotno;
430
431   /* The section used for mips_elf_la25_stub trampolines.
432      See the comment above that structure for details.  */
433   asection *strampoline;
434
435   /* A table of mips_elf_la25_stubs, indexed by (input_section, offset)
436      pairs.  */
437   htab_t la25_stubs;
438
439   /* A function FN (NAME, IS, OS) that creates a new input section
440      called NAME and links it to output section OS.  If IS is nonnull,
441      the new section should go immediately before it, otherwise it
442      should go at the (current) beginning of OS.
443
444      The function returns the new section on success, otherwise it
445      returns null.  */
446   asection *(*add_stub_section) (const char *, asection *, asection *);
447 };
448
449 /* Get the MIPS ELF linker hash table from a link_info structure.  */
450
451 #define mips_elf_hash_table(p) \
452   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
453   == MIPS_ELF_DATA ? ((struct mips_elf_link_hash_table *) ((p)->hash)) : NULL)
454
455 /* A structure used to communicate with htab_traverse callbacks.  */
456 struct mips_htab_traverse_info
457 {
458   /* The usual link-wide information.  */
459   struct bfd_link_info *info;
460   bfd *output_bfd;
461
462   /* Starts off FALSE and is set to TRUE if the link should be aborted.  */
463   bfd_boolean error;
464 };
465
466 /* MIPS ELF private object data.  */
467
468 struct mips_elf_obj_tdata
469 {
470   /* Generic ELF private object data.  */
471   struct elf_obj_tdata root;
472
473   /* Input BFD providing Tag_GNU_MIPS_ABI_FP attribute for output.  */
474   bfd *abi_fp_bfd;
475
476   /* The GOT requirements of input bfds.  */
477   struct mips_got_info *got;
478 };
479
480 /* Get MIPS ELF private object data from BFD's tdata.  */
481
482 #define mips_elf_tdata(bfd) \
483   ((struct mips_elf_obj_tdata *) (bfd)->tdata.any)
484
485 #define TLS_RELOC_P(r_type) \
486   (r_type == R_MIPS_TLS_DTPMOD32                \
487    || r_type == R_MIPS_TLS_DTPMOD64             \
488    || r_type == R_MIPS_TLS_DTPREL32             \
489    || r_type == R_MIPS_TLS_DTPREL64             \
490    || r_type == R_MIPS_TLS_GD                   \
491    || r_type == R_MIPS_TLS_LDM                  \
492    || r_type == R_MIPS_TLS_DTPREL_HI16          \
493    || r_type == R_MIPS_TLS_DTPREL_LO16          \
494    || r_type == R_MIPS_TLS_GOTTPREL             \
495    || r_type == R_MIPS_TLS_TPREL32              \
496    || r_type == R_MIPS_TLS_TPREL64              \
497    || r_type == R_MIPS_TLS_TPREL_HI16           \
498    || r_type == R_MIPS_TLS_TPREL_LO16           \
499    || r_type == R_MIPS16_TLS_GD                 \
500    || r_type == R_MIPS16_TLS_LDM                \
501    || r_type == R_MIPS16_TLS_DTPREL_HI16        \
502    || r_type == R_MIPS16_TLS_DTPREL_LO16        \
503    || r_type == R_MIPS16_TLS_GOTTPREL           \
504    || r_type == R_MIPS16_TLS_TPREL_HI16         \
505    || r_type == R_MIPS16_TLS_TPREL_LO16         \
506    || r_type == R_MICROMIPS_TLS_GD              \
507    || r_type == R_MICROMIPS_TLS_LDM             \
508    || r_type == R_MICROMIPS_TLS_DTPREL_HI16     \
509    || r_type == R_MICROMIPS_TLS_DTPREL_LO16     \
510    || r_type == R_MICROMIPS_TLS_GOTTPREL        \
511    || r_type == R_MICROMIPS_TLS_TPREL_HI16      \
512    || r_type == R_MICROMIPS_TLS_TPREL_LO16)
513
514 /* Structure used to pass information to mips_elf_output_extsym.  */
515
516 struct extsym_info
517 {
518   bfd *abfd;
519   struct bfd_link_info *info;
520   struct ecoff_debug_info *debug;
521   const struct ecoff_debug_swap *swap;
522   bfd_boolean failed;
523 };
524
525 /* The names of the runtime procedure table symbols used on IRIX5.  */
526
527 static const char * const mips_elf_dynsym_rtproc_names[] =
528 {
529   "_procedure_table",
530   "_procedure_string_table",
531   "_procedure_table_size",
532   NULL
533 };
534
535 /* These structures are used to generate the .compact_rel section on
536    IRIX5.  */
537
538 typedef struct
539 {
540   unsigned long id1;            /* Always one?  */
541   unsigned long num;            /* Number of compact relocation entries.  */
542   unsigned long id2;            /* Always two?  */
543   unsigned long offset;         /* The file offset of the first relocation.  */
544   unsigned long reserved0;      /* Zero?  */
545   unsigned long reserved1;      /* Zero?  */
546 } Elf32_compact_rel;
547
548 typedef struct
549 {
550   bfd_byte id1[4];
551   bfd_byte num[4];
552   bfd_byte id2[4];
553   bfd_byte offset[4];
554   bfd_byte reserved0[4];
555   bfd_byte reserved1[4];
556 } Elf32_External_compact_rel;
557
558 typedef struct
559 {
560   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
561   unsigned int rtype : 4;       /* Relocation types. See below.  */
562   unsigned int dist2to : 8;
563   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
564   unsigned long konst;          /* KONST field. See below.  */
565   unsigned long vaddr;          /* VADDR to be relocated.  */
566 } Elf32_crinfo;
567
568 typedef struct
569 {
570   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
571   unsigned int rtype : 4;       /* Relocation types. See below.  */
572   unsigned int dist2to : 8;
573   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
574   unsigned long konst;          /* KONST field. See below.  */
575 } Elf32_crinfo2;
576
577 typedef struct
578 {
579   bfd_byte info[4];
580   bfd_byte konst[4];
581   bfd_byte vaddr[4];
582 } Elf32_External_crinfo;
583
584 typedef struct
585 {
586   bfd_byte info[4];
587   bfd_byte konst[4];
588 } Elf32_External_crinfo2;
589
590 /* These are the constants used to swap the bitfields in a crinfo.  */
591
592 #define CRINFO_CTYPE (0x1)
593 #define CRINFO_CTYPE_SH (31)
594 #define CRINFO_RTYPE (0xf)
595 #define CRINFO_RTYPE_SH (27)
596 #define CRINFO_DIST2TO (0xff)
597 #define CRINFO_DIST2TO_SH (19)
598 #define CRINFO_RELVADDR (0x7ffff)
599 #define CRINFO_RELVADDR_SH (0)
600
601 /* A compact relocation info has long (3 words) or short (2 words)
602    formats.  A short format doesn't have VADDR field and relvaddr
603    fields contains ((VADDR - vaddr of the previous entry) >> 2).  */
604 #define CRF_MIPS_LONG                   1
605 #define CRF_MIPS_SHORT                  0
606
607 /* There are 4 types of compact relocation at least. The value KONST
608    has different meaning for each type:
609
610    (type)               (konst)
611    CT_MIPS_REL32        Address in data
612    CT_MIPS_WORD         Address in word (XXX)
613    CT_MIPS_GPHI_LO      GP - vaddr
614    CT_MIPS_JMPAD        Address to jump
615    */
616
617 #define CRT_MIPS_REL32                  0xa
618 #define CRT_MIPS_WORD                   0xb
619 #define CRT_MIPS_GPHI_LO                0xc
620 #define CRT_MIPS_JMPAD                  0xd
621
622 #define mips_elf_set_cr_format(x,format)        ((x).ctype = (format))
623 #define mips_elf_set_cr_type(x,type)            ((x).rtype = (type))
624 #define mips_elf_set_cr_dist2to(x,v)            ((x).dist2to = (v))
625 #define mips_elf_set_cr_relvaddr(x,d)           ((x).relvaddr = (d)<<2)
626 \f
627 /* The structure of the runtime procedure descriptor created by the
628    loader for use by the static exception system.  */
629
630 typedef struct runtime_pdr {
631         bfd_vma adr;            /* Memory address of start of procedure.  */
632         long    regmask;        /* Save register mask.  */
633         long    regoffset;      /* Save register offset.  */
634         long    fregmask;       /* Save floating point register mask.  */
635         long    fregoffset;     /* Save floating point register offset.  */
636         long    frameoffset;    /* Frame size.  */
637         short   framereg;       /* Frame pointer register.  */
638         short   pcreg;          /* Offset or reg of return pc.  */
639         long    irpss;          /* Index into the runtime string table.  */
640         long    reserved;
641         struct exception_info *exception_info;/* Pointer to exception array.  */
642 } RPDR, *pRPDR;
643 #define cbRPDR sizeof (RPDR)
644 #define rpdNil ((pRPDR) 0)
645 \f
646 static struct mips_got_entry *mips_elf_create_local_got_entry
647   (bfd *, struct bfd_link_info *, bfd *, bfd_vma, unsigned long,
648    struct mips_elf_link_hash_entry *, int);
649 static bfd_boolean mips_elf_sort_hash_table_f
650   (struct mips_elf_link_hash_entry *, void *);
651 static bfd_vma mips_elf_high
652   (bfd_vma);
653 static bfd_boolean mips_elf_create_dynamic_relocation
654   (bfd *, struct bfd_link_info *, const Elf_Internal_Rela *,
655    struct mips_elf_link_hash_entry *, asection *, bfd_vma,
656    bfd_vma *, asection *);
657 static bfd_vma mips_elf_adjust_gp
658   (bfd *, struct mips_got_info *, bfd *);
659
660 /* This will be used when we sort the dynamic relocation records.  */
661 static bfd *reldyn_sorting_bfd;
662
663 /* True if ABFD is for CPUs with load interlocking that include
664    non-MIPS1 CPUs and R3900.  */
665 #define LOAD_INTERLOCKS_P(abfd) \
666   (   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) != E_MIPS_ARCH_1) \
667    || ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_3900))
668
669 /* True if ABFD is for CPUs that are faster if JAL is converted to BAL.
670    This should be safe for all architectures.  We enable this predicate
671    for RM9000 for now.  */
672 #define JAL_TO_BAL_P(abfd) \
673   ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_9000)
674
675 /* True if ABFD is for CPUs that are faster if JALR is converted to BAL.
676    This should be safe for all architectures.  We enable this predicate for
677    all CPUs.  */
678 #define JALR_TO_BAL_P(abfd) 1
679
680 /* True if ABFD is for CPUs that are faster if JR is converted to B.
681    This should be safe for all architectures.  We enable this predicate for
682    all CPUs.  */
683 #define JR_TO_B_P(abfd) 1
684
685 /* True if ABFD is a PIC object.  */
686 #define PIC_OBJECT_P(abfd) \
687   ((elf_elfheader (abfd)->e_flags & EF_MIPS_PIC) != 0)
688
689 /* Nonzero if ABFD is using the N32 ABI.  */
690 #define ABI_N32_P(abfd) \
691   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI2) != 0)
692
693 /* Nonzero if ABFD is using the N64 ABI.  */
694 #define ABI_64_P(abfd) \
695   (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS64)
696
697 /* Nonzero if ABFD is using NewABI conventions.  */
698 #define NEWABI_P(abfd) (ABI_N32_P (abfd) || ABI_64_P (abfd))
699
700 /* The IRIX compatibility level we are striving for.  */
701 #define IRIX_COMPAT(abfd) \
702   (get_elf_backend_data (abfd)->elf_backend_mips_irix_compat (abfd))
703
704 /* Whether we are trying to be compatible with IRIX at all.  */
705 #define SGI_COMPAT(abfd) \
706   (IRIX_COMPAT (abfd) != ict_none)
707
708 /* The name of the options section.  */
709 #define MIPS_ELF_OPTIONS_SECTION_NAME(abfd) \
710   (NEWABI_P (abfd) ? ".MIPS.options" : ".options")
711
712 /* True if NAME is the recognized name of any SHT_MIPS_OPTIONS section.
713    Some IRIX system files do not use MIPS_ELF_OPTIONS_SECTION_NAME.  */
714 #define MIPS_ELF_OPTIONS_SECTION_NAME_P(NAME) \
715   (strcmp (NAME, ".MIPS.options") == 0 || strcmp (NAME, ".options") == 0)
716
717 /* Whether the section is readonly.  */
718 #define MIPS_ELF_READONLY_SECTION(sec) \
719   ((sec->flags & (SEC_ALLOC | SEC_LOAD | SEC_READONLY))         \
720    == (SEC_ALLOC | SEC_LOAD | SEC_READONLY))
721
722 /* The name of the stub section.  */
723 #define MIPS_ELF_STUB_SECTION_NAME(abfd) ".MIPS.stubs"
724
725 /* The size of an external REL relocation.  */
726 #define MIPS_ELF_REL_SIZE(abfd) \
727   (get_elf_backend_data (abfd)->s->sizeof_rel)
728
729 /* The size of an external RELA relocation.  */
730 #define MIPS_ELF_RELA_SIZE(abfd) \
731   (get_elf_backend_data (abfd)->s->sizeof_rela)
732
733 /* The size of an external dynamic table entry.  */
734 #define MIPS_ELF_DYN_SIZE(abfd) \
735   (get_elf_backend_data (abfd)->s->sizeof_dyn)
736
737 /* The size of a GOT entry.  */
738 #define MIPS_ELF_GOT_SIZE(abfd) \
739   (get_elf_backend_data (abfd)->s->arch_size / 8)
740
741 /* The size of the .rld_map section. */
742 #define MIPS_ELF_RLD_MAP_SIZE(abfd) \
743   (get_elf_backend_data (abfd)->s->arch_size / 8)
744
745 /* The size of a symbol-table entry.  */
746 #define MIPS_ELF_SYM_SIZE(abfd) \
747   (get_elf_backend_data (abfd)->s->sizeof_sym)
748
749 /* The default alignment for sections, as a power of two.  */
750 #define MIPS_ELF_LOG_FILE_ALIGN(abfd)                           \
751   (get_elf_backend_data (abfd)->s->log_file_align)
752
753 /* Get word-sized data.  */
754 #define MIPS_ELF_GET_WORD(abfd, ptr) \
755   (ABI_64_P (abfd) ? bfd_get_64 (abfd, ptr) : bfd_get_32 (abfd, ptr))
756
757 /* Put out word-sized data.  */
758 #define MIPS_ELF_PUT_WORD(abfd, val, ptr)       \
759   (ABI_64_P (abfd)                              \
760    ? bfd_put_64 (abfd, val, ptr)                \
761    : bfd_put_32 (abfd, val, ptr))
762
763 /* The opcode for word-sized loads (LW or LD).  */
764 #define MIPS_ELF_LOAD_WORD(abfd) \
765   (ABI_64_P (abfd) ? 0xdc000000 : 0x8c000000)
766
767 /* Add a dynamic symbol table-entry.  */
768 #define MIPS_ELF_ADD_DYNAMIC_ENTRY(info, tag, val)      \
769   _bfd_elf_add_dynamic_entry (info, tag, val)
770
771 #define MIPS_ELF_RTYPE_TO_HOWTO(abfd, rtype, rela)                      \
772   (get_elf_backend_data (abfd)->elf_backend_mips_rtype_to_howto (rtype, rela))
773
774 /* The name of the dynamic relocation section.  */
775 #define MIPS_ELF_REL_DYN_NAME(INFO) \
776   (mips_elf_hash_table (INFO)->is_vxworks ? ".rela.dyn" : ".rel.dyn")
777
778 /* In case we're on a 32-bit machine, construct a 64-bit "-1" value
779    from smaller values.  Start with zero, widen, *then* decrement.  */
780 #define MINUS_ONE       (((bfd_vma)0) - 1)
781 #define MINUS_TWO       (((bfd_vma)0) - 2)
782
783 /* The value to write into got[1] for SVR4 targets, to identify it is
784    a GNU object.  The dynamic linker can then use got[1] to store the
785    module pointer.  */
786 #define MIPS_ELF_GNU_GOT1_MASK(abfd) \
787   ((bfd_vma) 1 << (ABI_64_P (abfd) ? 63 : 31))
788
789 /* The offset of $gp from the beginning of the .got section.  */
790 #define ELF_MIPS_GP_OFFSET(INFO) \
791   (mips_elf_hash_table (INFO)->is_vxworks ? 0x0 : 0x7ff0)
792
793 /* The maximum size of the GOT for it to be addressable using 16-bit
794    offsets from $gp.  */
795 #define MIPS_ELF_GOT_MAX_SIZE(INFO) (ELF_MIPS_GP_OFFSET (INFO) + 0x7fff)
796
797 /* Instructions which appear in a stub.  */
798 #define STUB_LW(abfd)                                                   \
799   ((ABI_64_P (abfd)                                                     \
800     ? 0xdf998010                                /* ld t9,0x8010(gp) */  \
801     : 0x8f998010))                              /* lw t9,0x8010(gp) */
802 #define STUB_MOVE(abfd)                                                 \
803    ((ABI_64_P (abfd)                                                    \
804      ? 0x03e0782d                               /* daddu t7,ra */       \
805      : 0x03e07821))                             /* addu t7,ra */
806 #define STUB_LUI(VAL) (0x3c180000 + (VAL))      /* lui t8,VAL */
807 #define STUB_JALR 0x0320f809                    /* jalr t9,ra */
808 #define STUB_ORI(VAL) (0x37180000 + (VAL))      /* ori t8,t8,VAL */
809 #define STUB_LI16U(VAL) (0x34180000 + (VAL))    /* ori t8,zero,VAL unsigned */
810 #define STUB_LI16S(abfd, VAL)                                           \
811    ((ABI_64_P (abfd)                                                    \
812     ? (0x64180000 + (VAL))      /* daddiu t8,zero,VAL sign extended */  \
813     : (0x24180000 + (VAL))))    /* addiu t8,zero,VAL sign extended */
814
815 #define MIPS_FUNCTION_STUB_NORMAL_SIZE 16
816 #define MIPS_FUNCTION_STUB_BIG_SIZE 20
817
818 /* The name of the dynamic interpreter.  This is put in the .interp
819    section.  */
820
821 #define ELF_DYNAMIC_INTERPRETER(abfd)           \
822    (ABI_N32_P (abfd) ? "/usr/lib32/libc.so.1"   \
823     : ABI_64_P (abfd) ? "/usr/lib64/libc.so.1"  \
824     : "/usr/lib/libc.so.1")
825
826 #ifdef BFD64
827 #define MNAME(bfd,pre,pos) \
828   (ABI_64_P (bfd) ? CONCAT4 (pre,64,_,pos) : CONCAT4 (pre,32,_,pos))
829 #define ELF_R_SYM(bfd, i)                                       \
830   (ABI_64_P (bfd) ? ELF64_R_SYM (i) : ELF32_R_SYM (i))
831 #define ELF_R_TYPE(bfd, i)                                      \
832   (ABI_64_P (bfd) ? ELF64_MIPS_R_TYPE (i) : ELF32_R_TYPE (i))
833 #define ELF_R_INFO(bfd, s, t)                                   \
834   (ABI_64_P (bfd) ? ELF64_R_INFO (s, t) : ELF32_R_INFO (s, t))
835 #else
836 #define MNAME(bfd,pre,pos) CONCAT4 (pre,32,_,pos)
837 #define ELF_R_SYM(bfd, i)                                       \
838   (ELF32_R_SYM (i))
839 #define ELF_R_TYPE(bfd, i)                                      \
840   (ELF32_R_TYPE (i))
841 #define ELF_R_INFO(bfd, s, t)                                   \
842   (ELF32_R_INFO (s, t))
843 #endif
844 \f
845   /* The mips16 compiler uses a couple of special sections to handle
846      floating point arguments.
847
848      Section names that look like .mips16.fn.FNNAME contain stubs that
849      copy floating point arguments from the fp regs to the gp regs and
850      then jump to FNNAME.  If any 32 bit function calls FNNAME, the
851      call should be redirected to the stub instead.  If no 32 bit
852      function calls FNNAME, the stub should be discarded.  We need to
853      consider any reference to the function, not just a call, because
854      if the address of the function is taken we will need the stub,
855      since the address might be passed to a 32 bit function.
856
857      Section names that look like .mips16.call.FNNAME contain stubs
858      that copy floating point arguments from the gp regs to the fp
859      regs and then jump to FNNAME.  If FNNAME is a 32 bit function,
860      then any 16 bit function that calls FNNAME should be redirected
861      to the stub instead.  If FNNAME is not a 32 bit function, the
862      stub should be discarded.
863
864      .mips16.call.fp.FNNAME sections are similar, but contain stubs
865      which call FNNAME and then copy the return value from the fp regs
866      to the gp regs.  These stubs store the return value in $18 while
867      calling FNNAME; any function which might call one of these stubs
868      must arrange to save $18 around the call.  (This case is not
869      needed for 32 bit functions that call 16 bit functions, because
870      16 bit functions always return floating point values in both
871      $f0/$f1 and $2/$3.)
872
873      Note that in all cases FNNAME might be defined statically.
874      Therefore, FNNAME is not used literally.  Instead, the relocation
875      information will indicate which symbol the section is for.
876
877      We record any stubs that we find in the symbol table.  */
878
879 #define FN_STUB ".mips16.fn."
880 #define CALL_STUB ".mips16.call."
881 #define CALL_FP_STUB ".mips16.call.fp."
882
883 #define FN_STUB_P(name) CONST_STRNEQ (name, FN_STUB)
884 #define CALL_STUB_P(name) CONST_STRNEQ (name, CALL_STUB)
885 #define CALL_FP_STUB_P(name) CONST_STRNEQ (name, CALL_FP_STUB)
886 \f
887 /* The format of the first PLT entry in an O32 executable.  */
888 static const bfd_vma mips_o32_exec_plt0_entry[] =
889 {
890   0x3c1c0000,   /* lui $28, %hi(&GOTPLT[0])                             */
891   0x8f990000,   /* lw $25, %lo(&GOTPLT[0])($28)                         */
892   0x279c0000,   /* addiu $28, $28, %lo(&GOTPLT[0])                      */
893   0x031cc023,   /* subu $24, $24, $28                                   */
894   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
895   0x0018c082,   /* srl $24, $24, 2                                      */
896   0x0320f809,   /* jalr $25                                             */
897   0x2718fffe    /* subu $24, $24, 2                                     */
898 };
899
900 /* The format of the first PLT entry in an N32 executable.  Different
901    because gp ($28) is not available; we use t2 ($14) instead.  */
902 static const bfd_vma mips_n32_exec_plt0_entry[] =
903 {
904   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
905   0x8dd90000,   /* lw $25, %lo(&GOTPLT[0])($14)                         */
906   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
907   0x030ec023,   /* subu $24, $24, $14                                   */
908   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
909   0x0018c082,   /* srl $24, $24, 2                                      */
910   0x0320f809,   /* jalr $25                                             */
911   0x2718fffe    /* subu $24, $24, 2                                     */
912 };
913
914 /* The format of the first PLT entry in an N64 executable.  Different
915    from N32 because of the increased size of GOT entries.  */
916 static const bfd_vma mips_n64_exec_plt0_entry[] =
917 {
918   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
919   0xddd90000,   /* ld $25, %lo(&GOTPLT[0])($14)                         */
920   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
921   0x030ec023,   /* subu $24, $24, $14                                   */
922   0x03e0782d,   /* move $15, $31        # 64-bit move (daddu)           */
923   0x0018c0c2,   /* srl $24, $24, 3                                      */
924   0x0320f809,   /* jalr $25                                             */
925   0x2718fffe    /* subu $24, $24, 2                                     */
926 };
927
928 /* The format of subsequent PLT entries.  */
929 static const bfd_vma mips_exec_plt_entry[] =
930 {
931   0x3c0f0000,   /* lui $15, %hi(.got.plt entry)                 */
932   0x01f90000,   /* l[wd] $25, %lo(.got.plt entry)($15)          */
933   0x25f80000,   /* addiu $24, $15, %lo(.got.plt entry)          */
934   0x03200008    /* jr $25                                       */
935 };
936
937 /* The format of the first PLT entry in a VxWorks executable.  */
938 static const bfd_vma mips_vxworks_exec_plt0_entry[] =
939 {
940   0x3c190000,   /* lui t9, %hi(_GLOBAL_OFFSET_TABLE_)           */
941   0x27390000,   /* addiu t9, t9, %lo(_GLOBAL_OFFSET_TABLE_)     */
942   0x8f390008,   /* lw t9, 8(t9)                                 */
943   0x00000000,   /* nop                                          */
944   0x03200008,   /* jr t9                                        */
945   0x00000000    /* nop                                          */
946 };
947
948 /* The format of subsequent PLT entries.  */
949 static const bfd_vma mips_vxworks_exec_plt_entry[] =
950 {
951   0x10000000,   /* b .PLT_resolver                      */
952   0x24180000,   /* li t8, <pltindex>                    */
953   0x3c190000,   /* lui t9, %hi(<.got.plt slot>)         */
954   0x27390000,   /* addiu t9, t9, %lo(<.got.plt slot>)   */
955   0x8f390000,   /* lw t9, 0(t9)                         */
956   0x00000000,   /* nop                                  */
957   0x03200008,   /* jr t9                                */
958   0x00000000    /* nop                                  */
959 };
960
961 /* The format of the first PLT entry in a VxWorks shared object.  */
962 static const bfd_vma mips_vxworks_shared_plt0_entry[] =
963 {
964   0x8f990008,   /* lw t9, 8(gp)         */
965   0x00000000,   /* nop                  */
966   0x03200008,   /* jr t9                */
967   0x00000000,   /* nop                  */
968   0x00000000,   /* nop                  */
969   0x00000000    /* nop                  */
970 };
971
972 /* The format of subsequent PLT entries.  */
973 static const bfd_vma mips_vxworks_shared_plt_entry[] =
974 {
975   0x10000000,   /* b .PLT_resolver      */
976   0x24180000    /* li t8, <pltindex>    */
977 };
978 \f
979 /* microMIPS 32-bit opcode helper installer.  */
980
981 static void
982 bfd_put_micromips_32 (const bfd *abfd, bfd_vma opcode, bfd_byte *ptr)
983 {
984   bfd_put_16 (abfd, (opcode >> 16) & 0xffff, ptr);
985   bfd_put_16 (abfd,  opcode        & 0xffff, ptr + 2);
986 }
987
988 /* microMIPS 32-bit opcode helper retriever.  */
989
990 static bfd_vma
991 bfd_get_micromips_32 (const bfd *abfd, const bfd_byte *ptr)
992 {
993   return (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
994 }
995 \f
996 /* Look up an entry in a MIPS ELF linker hash table.  */
997
998 #define mips_elf_link_hash_lookup(table, string, create, copy, follow)  \
999   ((struct mips_elf_link_hash_entry *)                                  \
1000    elf_link_hash_lookup (&(table)->root, (string), (create),            \
1001                          (copy), (follow)))
1002
1003 /* Traverse a MIPS ELF linker hash table.  */
1004
1005 #define mips_elf_link_hash_traverse(table, func, info)                  \
1006   (elf_link_hash_traverse                                               \
1007    (&(table)->root,                                                     \
1008     (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func),    \
1009     (info)))
1010
1011 /* Find the base offsets for thread-local storage in this object,
1012    for GD/LD and IE/LE respectively.  */
1013
1014 #define TP_OFFSET 0x7000
1015 #define DTP_OFFSET 0x8000
1016
1017 static bfd_vma
1018 dtprel_base (struct bfd_link_info *info)
1019 {
1020   /* If tls_sec is NULL, we should have signalled an error already.  */
1021   if (elf_hash_table (info)->tls_sec == NULL)
1022     return 0;
1023   return elf_hash_table (info)->tls_sec->vma + DTP_OFFSET;
1024 }
1025
1026 static bfd_vma
1027 tprel_base (struct bfd_link_info *info)
1028 {
1029   /* If tls_sec is NULL, we should have signalled an error already.  */
1030   if (elf_hash_table (info)->tls_sec == NULL)
1031     return 0;
1032   return elf_hash_table (info)->tls_sec->vma + TP_OFFSET;
1033 }
1034
1035 /* Create an entry in a MIPS ELF linker hash table.  */
1036
1037 static struct bfd_hash_entry *
1038 mips_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
1039                             struct bfd_hash_table *table, const char *string)
1040 {
1041   struct mips_elf_link_hash_entry *ret =
1042     (struct mips_elf_link_hash_entry *) entry;
1043
1044   /* Allocate the structure if it has not already been allocated by a
1045      subclass.  */
1046   if (ret == NULL)
1047     ret = bfd_hash_allocate (table, sizeof (struct mips_elf_link_hash_entry));
1048   if (ret == NULL)
1049     return (struct bfd_hash_entry *) ret;
1050
1051   /* Call the allocation method of the superclass.  */
1052   ret = ((struct mips_elf_link_hash_entry *)
1053          _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret,
1054                                      table, string));
1055   if (ret != NULL)
1056     {
1057       /* Set local fields.  */
1058       memset (&ret->esym, 0, sizeof (EXTR));
1059       /* We use -2 as a marker to indicate that the information has
1060          not been set.  -1 means there is no associated ifd.  */
1061       ret->esym.ifd = -2;
1062       ret->la25_stub = 0;
1063       ret->possibly_dynamic_relocs = 0;
1064       ret->fn_stub = NULL;
1065       ret->call_stub = NULL;
1066       ret->call_fp_stub = NULL;
1067       ret->global_got_area = GGA_NONE;
1068       ret->got_only_for_calls = TRUE;
1069       ret->readonly_reloc = FALSE;
1070       ret->has_static_relocs = FALSE;
1071       ret->no_fn_stub = FALSE;
1072       ret->need_fn_stub = FALSE;
1073       ret->has_nonpic_branches = FALSE;
1074       ret->needs_lazy_stub = FALSE;
1075     }
1076
1077   return (struct bfd_hash_entry *) ret;
1078 }
1079
1080 /* Allocate MIPS ELF private object data.  */
1081
1082 bfd_boolean
1083 _bfd_mips_elf_mkobject (bfd *abfd)
1084 {
1085   return bfd_elf_allocate_object (abfd, sizeof (struct mips_elf_obj_tdata),
1086                                   MIPS_ELF_DATA);
1087 }
1088
1089 bfd_boolean
1090 _bfd_mips_elf_new_section_hook (bfd *abfd, asection *sec)
1091 {
1092   if (!sec->used_by_bfd)
1093     {
1094       struct _mips_elf_section_data *sdata;
1095       bfd_size_type amt = sizeof (*sdata);
1096
1097       sdata = bfd_zalloc (abfd, amt);
1098       if (sdata == NULL)
1099         return FALSE;
1100       sec->used_by_bfd = sdata;
1101     }
1102
1103   return _bfd_elf_new_section_hook (abfd, sec);
1104 }
1105 \f
1106 /* Read ECOFF debugging information from a .mdebug section into a
1107    ecoff_debug_info structure.  */
1108
1109 bfd_boolean
1110 _bfd_mips_elf_read_ecoff_info (bfd *abfd, asection *section,
1111                                struct ecoff_debug_info *debug)
1112 {
1113   HDRR *symhdr;
1114   const struct ecoff_debug_swap *swap;
1115   char *ext_hdr;
1116
1117   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1118   memset (debug, 0, sizeof (*debug));
1119
1120   ext_hdr = bfd_malloc (swap->external_hdr_size);
1121   if (ext_hdr == NULL && swap->external_hdr_size != 0)
1122     goto error_return;
1123
1124   if (! bfd_get_section_contents (abfd, section, ext_hdr, 0,
1125                                   swap->external_hdr_size))
1126     goto error_return;
1127
1128   symhdr = &debug->symbolic_header;
1129   (*swap->swap_hdr_in) (abfd, ext_hdr, symhdr);
1130
1131   /* The symbolic header contains absolute file offsets and sizes to
1132      read.  */
1133 #define READ(ptr, offset, count, size, type)                            \
1134   if (symhdr->count == 0)                                               \
1135     debug->ptr = NULL;                                                  \
1136   else                                                                  \
1137     {                                                                   \
1138       bfd_size_type amt = (bfd_size_type) size * symhdr->count;         \
1139       debug->ptr = bfd_malloc (amt);                                    \
1140       if (debug->ptr == NULL)                                           \
1141         goto error_return;                                              \
1142       if (bfd_seek (abfd, symhdr->offset, SEEK_SET) != 0                \
1143           || bfd_bread (debug->ptr, amt, abfd) != amt)                  \
1144         goto error_return;                                              \
1145     }
1146
1147   READ (line, cbLineOffset, cbLine, sizeof (unsigned char), unsigned char *);
1148   READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *);
1149   READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *);
1150   READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *);
1151   READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *);
1152   READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext),
1153         union aux_ext *);
1154   READ (ss, cbSsOffset, issMax, sizeof (char), char *);
1155   READ (ssext, cbSsExtOffset, issExtMax, sizeof (char), char *);
1156   READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *);
1157   READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *);
1158   READ (external_ext, cbExtOffset, iextMax, swap->external_ext_size, void *);
1159 #undef READ
1160
1161   debug->fdr = NULL;
1162
1163   return TRUE;
1164
1165  error_return:
1166   if (ext_hdr != NULL)
1167     free (ext_hdr);
1168   if (debug->line != NULL)
1169     free (debug->line);
1170   if (debug->external_dnr != NULL)
1171     free (debug->external_dnr);
1172   if (debug->external_pdr != NULL)
1173     free (debug->external_pdr);
1174   if (debug->external_sym != NULL)
1175     free (debug->external_sym);
1176   if (debug->external_opt != NULL)
1177     free (debug->external_opt);
1178   if (debug->external_aux != NULL)
1179     free (debug->external_aux);
1180   if (debug->ss != NULL)
1181     free (debug->ss);
1182   if (debug->ssext != NULL)
1183     free (debug->ssext);
1184   if (debug->external_fdr != NULL)
1185     free (debug->external_fdr);
1186   if (debug->external_rfd != NULL)
1187     free (debug->external_rfd);
1188   if (debug->external_ext != NULL)
1189     free (debug->external_ext);
1190   return FALSE;
1191 }
1192 \f
1193 /* Swap RPDR (runtime procedure table entry) for output.  */
1194
1195 static void
1196 ecoff_swap_rpdr_out (bfd *abfd, const RPDR *in, struct rpdr_ext *ex)
1197 {
1198   H_PUT_S32 (abfd, in->adr, ex->p_adr);
1199   H_PUT_32 (abfd, in->regmask, ex->p_regmask);
1200   H_PUT_32 (abfd, in->regoffset, ex->p_regoffset);
1201   H_PUT_32 (abfd, in->fregmask, ex->p_fregmask);
1202   H_PUT_32 (abfd, in->fregoffset, ex->p_fregoffset);
1203   H_PUT_32 (abfd, in->frameoffset, ex->p_frameoffset);
1204
1205   H_PUT_16 (abfd, in->framereg, ex->p_framereg);
1206   H_PUT_16 (abfd, in->pcreg, ex->p_pcreg);
1207
1208   H_PUT_32 (abfd, in->irpss, ex->p_irpss);
1209 }
1210
1211 /* Create a runtime procedure table from the .mdebug section.  */
1212
1213 static bfd_boolean
1214 mips_elf_create_procedure_table (void *handle, bfd *abfd,
1215                                  struct bfd_link_info *info, asection *s,
1216                                  struct ecoff_debug_info *debug)
1217 {
1218   const struct ecoff_debug_swap *swap;
1219   HDRR *hdr = &debug->symbolic_header;
1220   RPDR *rpdr, *rp;
1221   struct rpdr_ext *erp;
1222   void *rtproc;
1223   struct pdr_ext *epdr;
1224   struct sym_ext *esym;
1225   char *ss, **sv;
1226   char *str;
1227   bfd_size_type size;
1228   bfd_size_type count;
1229   unsigned long sindex;
1230   unsigned long i;
1231   PDR pdr;
1232   SYMR sym;
1233   const char *no_name_func = _("static procedure (no name)");
1234
1235   epdr = NULL;
1236   rpdr = NULL;
1237   esym = NULL;
1238   ss = NULL;
1239   sv = NULL;
1240
1241   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1242
1243   sindex = strlen (no_name_func) + 1;
1244   count = hdr->ipdMax;
1245   if (count > 0)
1246     {
1247       size = swap->external_pdr_size;
1248
1249       epdr = bfd_malloc (size * count);
1250       if (epdr == NULL)
1251         goto error_return;
1252
1253       if (! _bfd_ecoff_get_accumulated_pdr (handle, (bfd_byte *) epdr))
1254         goto error_return;
1255
1256       size = sizeof (RPDR);
1257       rp = rpdr = bfd_malloc (size * count);
1258       if (rpdr == NULL)
1259         goto error_return;
1260
1261       size = sizeof (char *);
1262       sv = bfd_malloc (size * count);
1263       if (sv == NULL)
1264         goto error_return;
1265
1266       count = hdr->isymMax;
1267       size = swap->external_sym_size;
1268       esym = bfd_malloc (size * count);
1269       if (esym == NULL)
1270         goto error_return;
1271
1272       if (! _bfd_ecoff_get_accumulated_sym (handle, (bfd_byte *) esym))
1273         goto error_return;
1274
1275       count = hdr->issMax;
1276       ss = bfd_malloc (count);
1277       if (ss == NULL)
1278         goto error_return;
1279       if (! _bfd_ecoff_get_accumulated_ss (handle, (bfd_byte *) ss))
1280         goto error_return;
1281
1282       count = hdr->ipdMax;
1283       for (i = 0; i < (unsigned long) count; i++, rp++)
1284         {
1285           (*swap->swap_pdr_in) (abfd, epdr + i, &pdr);
1286           (*swap->swap_sym_in) (abfd, &esym[pdr.isym], &sym);
1287           rp->adr = sym.value;
1288           rp->regmask = pdr.regmask;
1289           rp->regoffset = pdr.regoffset;
1290           rp->fregmask = pdr.fregmask;
1291           rp->fregoffset = pdr.fregoffset;
1292           rp->frameoffset = pdr.frameoffset;
1293           rp->framereg = pdr.framereg;
1294           rp->pcreg = pdr.pcreg;
1295           rp->irpss = sindex;
1296           sv[i] = ss + sym.iss;
1297           sindex += strlen (sv[i]) + 1;
1298         }
1299     }
1300
1301   size = sizeof (struct rpdr_ext) * (count + 2) + sindex;
1302   size = BFD_ALIGN (size, 16);
1303   rtproc = bfd_alloc (abfd, size);
1304   if (rtproc == NULL)
1305     {
1306       mips_elf_hash_table (info)->procedure_count = 0;
1307       goto error_return;
1308     }
1309
1310   mips_elf_hash_table (info)->procedure_count = count + 2;
1311
1312   erp = rtproc;
1313   memset (erp, 0, sizeof (struct rpdr_ext));
1314   erp++;
1315   str = (char *) rtproc + sizeof (struct rpdr_ext) * (count + 2);
1316   strcpy (str, no_name_func);
1317   str += strlen (no_name_func) + 1;
1318   for (i = 0; i < count; i++)
1319     {
1320       ecoff_swap_rpdr_out (abfd, rpdr + i, erp + i);
1321       strcpy (str, sv[i]);
1322       str += strlen (sv[i]) + 1;
1323     }
1324   H_PUT_S32 (abfd, -1, (erp + count)->p_adr);
1325
1326   /* Set the size and contents of .rtproc section.  */
1327   s->size = size;
1328   s->contents = rtproc;
1329
1330   /* Skip this section later on (I don't think this currently
1331      matters, but someday it might).  */
1332   s->map_head.link_order = NULL;
1333
1334   if (epdr != NULL)
1335     free (epdr);
1336   if (rpdr != NULL)
1337     free (rpdr);
1338   if (esym != NULL)
1339     free (esym);
1340   if (ss != NULL)
1341     free (ss);
1342   if (sv != NULL)
1343     free (sv);
1344
1345   return TRUE;
1346
1347  error_return:
1348   if (epdr != NULL)
1349     free (epdr);
1350   if (rpdr != NULL)
1351     free (rpdr);
1352   if (esym != NULL)
1353     free (esym);
1354   if (ss != NULL)
1355     free (ss);
1356   if (sv != NULL)
1357     free (sv);
1358   return FALSE;
1359 }
1360 \f
1361 /* We're going to create a stub for H.  Create a symbol for the stub's
1362    value and size, to help make the disassembly easier to read.  */
1363
1364 static bfd_boolean
1365 mips_elf_create_stub_symbol (struct bfd_link_info *info,
1366                              struct mips_elf_link_hash_entry *h,
1367                              const char *prefix, asection *s, bfd_vma value,
1368                              bfd_vma size)
1369 {
1370   struct bfd_link_hash_entry *bh;
1371   struct elf_link_hash_entry *elfh;
1372   const char *name;
1373
1374   if (ELF_ST_IS_MICROMIPS (h->root.other))
1375     value |= 1;
1376
1377   /* Create a new symbol.  */
1378   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1379   bh = NULL;
1380   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1381                                          BSF_LOCAL, s, value, NULL,
1382                                          TRUE, FALSE, &bh))
1383     return FALSE;
1384
1385   /* Make it a local function.  */
1386   elfh = (struct elf_link_hash_entry *) bh;
1387   elfh->type = ELF_ST_INFO (STB_LOCAL, STT_FUNC);
1388   elfh->size = size;
1389   elfh->forced_local = 1;
1390   return TRUE;
1391 }
1392
1393 /* We're about to redefine H.  Create a symbol to represent H's
1394    current value and size, to help make the disassembly easier
1395    to read.  */
1396
1397 static bfd_boolean
1398 mips_elf_create_shadow_symbol (struct bfd_link_info *info,
1399                                struct mips_elf_link_hash_entry *h,
1400                                const char *prefix)
1401 {
1402   struct bfd_link_hash_entry *bh;
1403   struct elf_link_hash_entry *elfh;
1404   const char *name;
1405   asection *s;
1406   bfd_vma value;
1407
1408   /* Read the symbol's value.  */
1409   BFD_ASSERT (h->root.root.type == bfd_link_hash_defined
1410               || h->root.root.type == bfd_link_hash_defweak);
1411   s = h->root.root.u.def.section;
1412   value = h->root.root.u.def.value;
1413
1414   /* Create a new symbol.  */
1415   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1416   bh = NULL;
1417   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1418                                          BSF_LOCAL, s, value, NULL,
1419                                          TRUE, FALSE, &bh))
1420     return FALSE;
1421
1422   /* Make it local and copy the other attributes from H.  */
1423   elfh = (struct elf_link_hash_entry *) bh;
1424   elfh->type = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (h->root.type));
1425   elfh->other = h->root.other;
1426   elfh->size = h->root.size;
1427   elfh->forced_local = 1;
1428   return TRUE;
1429 }
1430
1431 /* Return TRUE if relocations in SECTION can refer directly to a MIPS16
1432    function rather than to a hard-float stub.  */
1433
1434 static bfd_boolean
1435 section_allows_mips16_refs_p (asection *section)
1436 {
1437   const char *name;
1438
1439   name = bfd_get_section_name (section->owner, section);
1440   return (FN_STUB_P (name)
1441           || CALL_STUB_P (name)
1442           || CALL_FP_STUB_P (name)
1443           || strcmp (name, ".pdr") == 0);
1444 }
1445
1446 /* [RELOCS, RELEND) are the relocations against SEC, which is a MIPS16
1447    stub section of some kind.  Return the R_SYMNDX of the target
1448    function, or 0 if we can't decide which function that is.  */
1449
1450 static unsigned long
1451 mips16_stub_symndx (const struct elf_backend_data *bed,
1452                     asection *sec ATTRIBUTE_UNUSED,
1453                     const Elf_Internal_Rela *relocs,
1454                     const Elf_Internal_Rela *relend)
1455 {
1456   int int_rels_per_ext_rel = bed->s->int_rels_per_ext_rel;
1457   const Elf_Internal_Rela *rel;
1458
1459   /* Trust the first R_MIPS_NONE relocation, if any, but not a subsequent
1460      one in a compound relocation.  */
1461   for (rel = relocs; rel < relend; rel += int_rels_per_ext_rel)
1462     if (ELF_R_TYPE (sec->owner, rel->r_info) == R_MIPS_NONE)
1463       return ELF_R_SYM (sec->owner, rel->r_info);
1464
1465   /* Otherwise trust the first relocation, whatever its kind.  This is
1466      the traditional behavior.  */
1467   if (relocs < relend)
1468     return ELF_R_SYM (sec->owner, relocs->r_info);
1469
1470   return 0;
1471 }
1472
1473 /* Check the mips16 stubs for a particular symbol, and see if we can
1474    discard them.  */
1475
1476 static void
1477 mips_elf_check_mips16_stubs (struct bfd_link_info *info,
1478                              struct mips_elf_link_hash_entry *h)
1479 {
1480   /* Dynamic symbols must use the standard call interface, in case other
1481      objects try to call them.  */
1482   if (h->fn_stub != NULL
1483       && h->root.dynindx != -1)
1484     {
1485       mips_elf_create_shadow_symbol (info, h, ".mips16.");
1486       h->need_fn_stub = TRUE;
1487     }
1488
1489   if (h->fn_stub != NULL
1490       && ! h->need_fn_stub)
1491     {
1492       /* We don't need the fn_stub; the only references to this symbol
1493          are 16 bit calls.  Clobber the size to 0 to prevent it from
1494          being included in the link.  */
1495       h->fn_stub->size = 0;
1496       h->fn_stub->flags &= ~SEC_RELOC;
1497       h->fn_stub->reloc_count = 0;
1498       h->fn_stub->flags |= SEC_EXCLUDE;
1499     }
1500
1501   if (h->call_stub != NULL
1502       && ELF_ST_IS_MIPS16 (h->root.other))
1503     {
1504       /* We don't need the call_stub; this is a 16 bit function, so
1505          calls from other 16 bit functions are OK.  Clobber the size
1506          to 0 to prevent it from being included in the link.  */
1507       h->call_stub->size = 0;
1508       h->call_stub->flags &= ~SEC_RELOC;
1509       h->call_stub->reloc_count = 0;
1510       h->call_stub->flags |= SEC_EXCLUDE;
1511     }
1512
1513   if (h->call_fp_stub != NULL
1514       && ELF_ST_IS_MIPS16 (h->root.other))
1515     {
1516       /* We don't need the call_stub; this is a 16 bit function, so
1517          calls from other 16 bit functions are OK.  Clobber the size
1518          to 0 to prevent it from being included in the link.  */
1519       h->call_fp_stub->size = 0;
1520       h->call_fp_stub->flags &= ~SEC_RELOC;
1521       h->call_fp_stub->reloc_count = 0;
1522       h->call_fp_stub->flags |= SEC_EXCLUDE;
1523     }
1524 }
1525
1526 /* Hashtable callbacks for mips_elf_la25_stubs.  */
1527
1528 static hashval_t
1529 mips_elf_la25_stub_hash (const void *entry_)
1530 {
1531   const struct mips_elf_la25_stub *entry;
1532
1533   entry = (struct mips_elf_la25_stub *) entry_;
1534   return entry->h->root.root.u.def.section->id
1535     + entry->h->root.root.u.def.value;
1536 }
1537
1538 static int
1539 mips_elf_la25_stub_eq (const void *entry1_, const void *entry2_)
1540 {
1541   const struct mips_elf_la25_stub *entry1, *entry2;
1542
1543   entry1 = (struct mips_elf_la25_stub *) entry1_;
1544   entry2 = (struct mips_elf_la25_stub *) entry2_;
1545   return ((entry1->h->root.root.u.def.section
1546            == entry2->h->root.root.u.def.section)
1547           && (entry1->h->root.root.u.def.value
1548               == entry2->h->root.root.u.def.value));
1549 }
1550
1551 /* Called by the linker to set up the la25 stub-creation code.  FN is
1552    the linker's implementation of add_stub_function.  Return true on
1553    success.  */
1554
1555 bfd_boolean
1556 _bfd_mips_elf_init_stubs (struct bfd_link_info *info,
1557                           asection *(*fn) (const char *, asection *,
1558                                            asection *))
1559 {
1560   struct mips_elf_link_hash_table *htab;
1561
1562   htab = mips_elf_hash_table (info);
1563   if (htab == NULL)
1564     return FALSE;
1565
1566   htab->add_stub_section = fn;
1567   htab->la25_stubs = htab_try_create (1, mips_elf_la25_stub_hash,
1568                                       mips_elf_la25_stub_eq, NULL);
1569   if (htab->la25_stubs == NULL)
1570     return FALSE;
1571
1572   return TRUE;
1573 }
1574
1575 /* Return true if H is a locally-defined PIC function, in the sense
1576    that it or its fn_stub might need $25 to be valid on entry.
1577    Note that MIPS16 functions set up $gp using PC-relative instructions,
1578    so they themselves never need $25 to be valid.  Only non-MIPS16
1579    entry points are of interest here.  */
1580
1581 static bfd_boolean
1582 mips_elf_local_pic_function_p (struct mips_elf_link_hash_entry *h)
1583 {
1584   return ((h->root.root.type == bfd_link_hash_defined
1585            || h->root.root.type == bfd_link_hash_defweak)
1586           && h->root.def_regular
1587           && !bfd_is_abs_section (h->root.root.u.def.section)
1588           && (!ELF_ST_IS_MIPS16 (h->root.other)
1589               || (h->fn_stub && h->need_fn_stub))
1590           && (PIC_OBJECT_P (h->root.root.u.def.section->owner)
1591               || ELF_ST_IS_MIPS_PIC (h->root.other)));
1592 }
1593
1594 /* Set *SEC to the input section that contains the target of STUB.
1595    Return the offset of the target from the start of that section.  */
1596
1597 static bfd_vma
1598 mips_elf_get_la25_target (struct mips_elf_la25_stub *stub,
1599                           asection **sec)
1600 {
1601   if (ELF_ST_IS_MIPS16 (stub->h->root.other))
1602     {
1603       BFD_ASSERT (stub->h->need_fn_stub);
1604       *sec = stub->h->fn_stub;
1605       return 0;
1606     }
1607   else
1608     {
1609       *sec = stub->h->root.root.u.def.section;
1610       return stub->h->root.root.u.def.value;
1611     }
1612 }
1613
1614 /* STUB describes an la25 stub that we have decided to implement
1615    by inserting an LUI/ADDIU pair before the target function.
1616    Create the section and redirect the function symbol to it.  */
1617
1618 static bfd_boolean
1619 mips_elf_add_la25_intro (struct mips_elf_la25_stub *stub,
1620                          struct bfd_link_info *info)
1621 {
1622   struct mips_elf_link_hash_table *htab;
1623   char *name;
1624   asection *s, *input_section;
1625   unsigned int align;
1626
1627   htab = mips_elf_hash_table (info);
1628   if (htab == NULL)
1629     return FALSE;
1630
1631   /* Create a unique name for the new section.  */
1632   name = bfd_malloc (11 + sizeof (".text.stub."));
1633   if (name == NULL)
1634     return FALSE;
1635   sprintf (name, ".text.stub.%d", (int) htab_elements (htab->la25_stubs));
1636
1637   /* Create the section.  */
1638   mips_elf_get_la25_target (stub, &input_section);
1639   s = htab->add_stub_section (name, input_section,
1640                               input_section->output_section);
1641   if (s == NULL)
1642     return FALSE;
1643
1644   /* Make sure that any padding goes before the stub.  */
1645   align = input_section->alignment_power;
1646   if (!bfd_set_section_alignment (s->owner, s, align))
1647     return FALSE;
1648   if (align > 3)
1649     s->size = (1 << align) - 8;
1650
1651   /* Create a symbol for the stub.  */
1652   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 8);
1653   stub->stub_section = s;
1654   stub->offset = s->size;
1655
1656   /* Allocate room for it.  */
1657   s->size += 8;
1658   return TRUE;
1659 }
1660
1661 /* STUB describes an la25 stub that we have decided to implement
1662    with a separate trampoline.  Allocate room for it and redirect
1663    the function symbol to it.  */
1664
1665 static bfd_boolean
1666 mips_elf_add_la25_trampoline (struct mips_elf_la25_stub *stub,
1667                               struct bfd_link_info *info)
1668 {
1669   struct mips_elf_link_hash_table *htab;
1670   asection *s;
1671
1672   htab = mips_elf_hash_table (info);
1673   if (htab == NULL)
1674     return FALSE;
1675
1676   /* Create a trampoline section, if we haven't already.  */
1677   s = htab->strampoline;
1678   if (s == NULL)
1679     {
1680       asection *input_section = stub->h->root.root.u.def.section;
1681       s = htab->add_stub_section (".text", NULL,
1682                                   input_section->output_section);
1683       if (s == NULL || !bfd_set_section_alignment (s->owner, s, 4))
1684         return FALSE;
1685       htab->strampoline = s;
1686     }
1687
1688   /* Create a symbol for the stub.  */
1689   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 16);
1690   stub->stub_section = s;
1691   stub->offset = s->size;
1692
1693   /* Allocate room for it.  */
1694   s->size += 16;
1695   return TRUE;
1696 }
1697
1698 /* H describes a symbol that needs an la25 stub.  Make sure that an
1699    appropriate stub exists and point H at it.  */
1700
1701 static bfd_boolean
1702 mips_elf_add_la25_stub (struct bfd_link_info *info,
1703                         struct mips_elf_link_hash_entry *h)
1704 {
1705   struct mips_elf_link_hash_table *htab;
1706   struct mips_elf_la25_stub search, *stub;
1707   bfd_boolean use_trampoline_p;
1708   asection *s;
1709   bfd_vma value;
1710   void **slot;
1711
1712   /* Describe the stub we want.  */
1713   search.stub_section = NULL;
1714   search.offset = 0;
1715   search.h = h;
1716
1717   /* See if we've already created an equivalent stub.  */
1718   htab = mips_elf_hash_table (info);
1719   if (htab == NULL)
1720     return FALSE;
1721
1722   slot = htab_find_slot (htab->la25_stubs, &search, INSERT);
1723   if (slot == NULL)
1724     return FALSE;
1725
1726   stub = (struct mips_elf_la25_stub *) *slot;
1727   if (stub != NULL)
1728     {
1729       /* We can reuse the existing stub.  */
1730       h->la25_stub = stub;
1731       return TRUE;
1732     }
1733
1734   /* Create a permanent copy of ENTRY and add it to the hash table.  */
1735   stub = bfd_malloc (sizeof (search));
1736   if (stub == NULL)
1737     return FALSE;
1738   *stub = search;
1739   *slot = stub;
1740
1741   /* Prefer to use LUI/ADDIU stubs if the function is at the beginning
1742      of the section and if we would need no more than 2 nops.  */
1743   value = mips_elf_get_la25_target (stub, &s);
1744   use_trampoline_p = (value != 0 || s->alignment_power > 4);
1745
1746   h->la25_stub = stub;
1747   return (use_trampoline_p
1748           ? mips_elf_add_la25_trampoline (stub, info)
1749           : mips_elf_add_la25_intro (stub, info));
1750 }
1751
1752 /* A mips_elf_link_hash_traverse callback that is called before sizing
1753    sections.  DATA points to a mips_htab_traverse_info structure.  */
1754
1755 static bfd_boolean
1756 mips_elf_check_symbols (struct mips_elf_link_hash_entry *h, void *data)
1757 {
1758   struct mips_htab_traverse_info *hti;
1759
1760   hti = (struct mips_htab_traverse_info *) data;
1761   if (!hti->info->relocatable)
1762     mips_elf_check_mips16_stubs (hti->info, h);
1763
1764   if (mips_elf_local_pic_function_p (h))
1765     {
1766       /* PR 12845: If H is in a section that has been garbage
1767          collected it will have its output section set to *ABS*.  */
1768       if (bfd_is_abs_section (h->root.root.u.def.section->output_section))
1769         return TRUE;
1770
1771       /* H is a function that might need $25 to be valid on entry.
1772          If we're creating a non-PIC relocatable object, mark H as
1773          being PIC.  If we're creating a non-relocatable object with
1774          non-PIC branches and jumps to H, make sure that H has an la25
1775          stub.  */
1776       if (hti->info->relocatable)
1777         {
1778           if (!PIC_OBJECT_P (hti->output_bfd))
1779             h->root.other = ELF_ST_SET_MIPS_PIC (h->root.other);
1780         }
1781       else if (h->has_nonpic_branches && !mips_elf_add_la25_stub (hti->info, h))
1782         {
1783           hti->error = TRUE;
1784           return FALSE;
1785         }
1786     }
1787   return TRUE;
1788 }
1789 \f
1790 /* R_MIPS16_26 is used for the mips16 jal and jalx instructions.
1791    Most mips16 instructions are 16 bits, but these instructions
1792    are 32 bits.
1793
1794    The format of these instructions is:
1795
1796    +--------------+--------------------------------+
1797    |     JALX     | X|   Imm 20:16  |   Imm 25:21  |
1798    +--------------+--------------------------------+
1799    |                Immediate  15:0                |
1800    +-----------------------------------------------+
1801
1802    JALX is the 5-bit value 00011.  X is 0 for jal, 1 for jalx.
1803    Note that the immediate value in the first word is swapped.
1804
1805    When producing a relocatable object file, R_MIPS16_26 is
1806    handled mostly like R_MIPS_26.  In particular, the addend is
1807    stored as a straight 26-bit value in a 32-bit instruction.
1808    (gas makes life simpler for itself by never adjusting a
1809    R_MIPS16_26 reloc to be against a section, so the addend is
1810    always zero).  However, the 32 bit instruction is stored as 2
1811    16-bit values, rather than a single 32-bit value.  In a
1812    big-endian file, the result is the same; in a little-endian
1813    file, the two 16-bit halves of the 32 bit value are swapped.
1814    This is so that a disassembler can recognize the jal
1815    instruction.
1816
1817    When doing a final link, R_MIPS16_26 is treated as a 32 bit
1818    instruction stored as two 16-bit values.  The addend A is the
1819    contents of the targ26 field.  The calculation is the same as
1820    R_MIPS_26.  When storing the calculated value, reorder the
1821    immediate value as shown above, and don't forget to store the
1822    value as two 16-bit values.
1823
1824    To put it in MIPS ABI terms, the relocation field is T-targ26-16,
1825    defined as
1826
1827    big-endian:
1828    +--------+----------------------+
1829    |        |                      |
1830    |        |    targ26-16         |
1831    |31    26|25                   0|
1832    +--------+----------------------+
1833
1834    little-endian:
1835    +----------+------+-------------+
1836    |          |      |             |
1837    |  sub1    |      |     sub2    |
1838    |0        9|10  15|16         31|
1839    +----------+--------------------+
1840    where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is
1841    ((sub1 << 16) | sub2)).
1842
1843    When producing a relocatable object file, the calculation is
1844    (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1845    When producing a fully linked file, the calculation is
1846    let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1847    ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff)
1848
1849    The table below lists the other MIPS16 instruction relocations.
1850    Each one is calculated in the same way as the non-MIPS16 relocation
1851    given on the right, but using the extended MIPS16 layout of 16-bit
1852    immediate fields:
1853
1854         R_MIPS16_GPREL          R_MIPS_GPREL16
1855         R_MIPS16_GOT16          R_MIPS_GOT16
1856         R_MIPS16_CALL16         R_MIPS_CALL16
1857         R_MIPS16_HI16           R_MIPS_HI16
1858         R_MIPS16_LO16           R_MIPS_LO16
1859
1860    A typical instruction will have a format like this:
1861
1862    +--------------+--------------------------------+
1863    |    EXTEND    |     Imm 10:5    |   Imm 15:11  |
1864    +--------------+--------------------------------+
1865    |    Major     |   rx   |   ry   |   Imm  4:0   |
1866    +--------------+--------------------------------+
1867
1868    EXTEND is the five bit value 11110.  Major is the instruction
1869    opcode.
1870
1871    All we need to do here is shuffle the bits appropriately.
1872    As above, the two 16-bit halves must be swapped on a
1873    little-endian system.  */
1874
1875 static inline bfd_boolean
1876 mips16_reloc_p (int r_type)
1877 {
1878   switch (r_type)
1879     {
1880     case R_MIPS16_26:
1881     case R_MIPS16_GPREL:
1882     case R_MIPS16_GOT16:
1883     case R_MIPS16_CALL16:
1884     case R_MIPS16_HI16:
1885     case R_MIPS16_LO16:
1886     case R_MIPS16_TLS_GD:
1887     case R_MIPS16_TLS_LDM:
1888     case R_MIPS16_TLS_DTPREL_HI16:
1889     case R_MIPS16_TLS_DTPREL_LO16:
1890     case R_MIPS16_TLS_GOTTPREL:
1891     case R_MIPS16_TLS_TPREL_HI16:
1892     case R_MIPS16_TLS_TPREL_LO16:
1893       return TRUE;
1894
1895     default:
1896       return FALSE;
1897     }
1898 }
1899
1900 /* Check if a microMIPS reloc.  */
1901
1902 static inline bfd_boolean
1903 micromips_reloc_p (unsigned int r_type)
1904 {
1905   return r_type >= R_MICROMIPS_min && r_type < R_MICROMIPS_max;
1906 }
1907
1908 /* Similar to MIPS16, the two 16-bit halves in microMIPS must be swapped
1909    on a little-endian system.  This does not apply to R_MICROMIPS_PC7_S1
1910    and R_MICROMIPS_PC10_S1 relocs that apply to 16-bit instructions.  */
1911
1912 static inline bfd_boolean
1913 micromips_reloc_shuffle_p (unsigned int r_type)
1914 {
1915   return (micromips_reloc_p (r_type)
1916           && r_type != R_MICROMIPS_PC7_S1
1917           && r_type != R_MICROMIPS_PC10_S1);
1918 }
1919
1920 static inline bfd_boolean
1921 got16_reloc_p (int r_type)
1922 {
1923   return (r_type == R_MIPS_GOT16
1924           || r_type == R_MIPS16_GOT16
1925           || r_type == R_MICROMIPS_GOT16);
1926 }
1927
1928 static inline bfd_boolean
1929 call16_reloc_p (int r_type)
1930 {
1931   return (r_type == R_MIPS_CALL16
1932           || r_type == R_MIPS16_CALL16
1933           || r_type == R_MICROMIPS_CALL16);
1934 }
1935
1936 static inline bfd_boolean
1937 got_disp_reloc_p (unsigned int r_type)
1938 {
1939   return r_type == R_MIPS_GOT_DISP || r_type == R_MICROMIPS_GOT_DISP;
1940 }
1941
1942 static inline bfd_boolean
1943 got_page_reloc_p (unsigned int r_type)
1944 {
1945   return r_type == R_MIPS_GOT_PAGE || r_type == R_MICROMIPS_GOT_PAGE;
1946 }
1947
1948 static inline bfd_boolean
1949 got_ofst_reloc_p (unsigned int r_type)
1950 {
1951   return r_type == R_MIPS_GOT_OFST || r_type == R_MICROMIPS_GOT_OFST;
1952 }
1953
1954 static inline bfd_boolean
1955 got_hi16_reloc_p (unsigned int r_type)
1956 {
1957   return r_type == R_MIPS_GOT_HI16 || r_type == R_MICROMIPS_GOT_HI16;
1958 }
1959
1960 static inline bfd_boolean
1961 got_lo16_reloc_p (unsigned int r_type)
1962 {
1963   return r_type == R_MIPS_GOT_LO16 || r_type == R_MICROMIPS_GOT_LO16;
1964 }
1965
1966 static inline bfd_boolean
1967 call_hi16_reloc_p (unsigned int r_type)
1968 {
1969   return r_type == R_MIPS_CALL_HI16 || r_type == R_MICROMIPS_CALL_HI16;
1970 }
1971
1972 static inline bfd_boolean
1973 call_lo16_reloc_p (unsigned int r_type)
1974 {
1975   return r_type == R_MIPS_CALL_LO16 || r_type == R_MICROMIPS_CALL_LO16;
1976 }
1977
1978 static inline bfd_boolean
1979 hi16_reloc_p (int r_type)
1980 {
1981   return (r_type == R_MIPS_HI16
1982           || r_type == R_MIPS16_HI16
1983           || r_type == R_MICROMIPS_HI16);
1984 }
1985
1986 static inline bfd_boolean
1987 lo16_reloc_p (int r_type)
1988 {
1989   return (r_type == R_MIPS_LO16
1990           || r_type == R_MIPS16_LO16
1991           || r_type == R_MICROMIPS_LO16);
1992 }
1993
1994 static inline bfd_boolean
1995 mips16_call_reloc_p (int r_type)
1996 {
1997   return r_type == R_MIPS16_26 || r_type == R_MIPS16_CALL16;
1998 }
1999
2000 static inline bfd_boolean
2001 jal_reloc_p (int r_type)
2002 {
2003   return (r_type == R_MIPS_26
2004           || r_type == R_MIPS16_26
2005           || r_type == R_MICROMIPS_26_S1);
2006 }
2007
2008 static inline bfd_boolean
2009 micromips_branch_reloc_p (int r_type)
2010 {
2011   return (r_type == R_MICROMIPS_26_S1
2012           || r_type == R_MICROMIPS_PC16_S1
2013           || r_type == R_MICROMIPS_PC10_S1
2014           || r_type == R_MICROMIPS_PC7_S1);
2015 }
2016
2017 static inline bfd_boolean
2018 tls_gd_reloc_p (unsigned int r_type)
2019 {
2020   return (r_type == R_MIPS_TLS_GD
2021           || r_type == R_MIPS16_TLS_GD
2022           || r_type == R_MICROMIPS_TLS_GD);
2023 }
2024
2025 static inline bfd_boolean
2026 tls_ldm_reloc_p (unsigned int r_type)
2027 {
2028   return (r_type == R_MIPS_TLS_LDM
2029           || r_type == R_MIPS16_TLS_LDM
2030           || r_type == R_MICROMIPS_TLS_LDM);
2031 }
2032
2033 static inline bfd_boolean
2034 tls_gottprel_reloc_p (unsigned int r_type)
2035 {
2036   return (r_type == R_MIPS_TLS_GOTTPREL
2037           || r_type == R_MIPS16_TLS_GOTTPREL
2038           || r_type == R_MICROMIPS_TLS_GOTTPREL);
2039 }
2040
2041 void
2042 _bfd_mips_elf_reloc_unshuffle (bfd *abfd, int r_type,
2043                                bfd_boolean jal_shuffle, bfd_byte *data)
2044 {
2045   bfd_vma first, second, val;
2046
2047   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2048     return;
2049
2050   /* Pick up the first and second halfwords of the instruction.  */
2051   first = bfd_get_16 (abfd, data);
2052   second = bfd_get_16 (abfd, data + 2);
2053   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2054     val = first << 16 | second;
2055   else if (r_type != R_MIPS16_26)
2056     val = (((first & 0xf800) << 16) | ((second & 0xffe0) << 11)
2057            | ((first & 0x1f) << 11) | (first & 0x7e0) | (second & 0x1f));
2058   else
2059     val = (((first & 0xfc00) << 16) | ((first & 0x3e0) << 11)
2060            | ((first & 0x1f) << 21) | second);
2061   bfd_put_32 (abfd, val, data);
2062 }
2063
2064 void
2065 _bfd_mips_elf_reloc_shuffle (bfd *abfd, int r_type,
2066                              bfd_boolean jal_shuffle, bfd_byte *data)
2067 {
2068   bfd_vma first, second, val;
2069
2070   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2071     return;
2072
2073   val = bfd_get_32 (abfd, data);
2074   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2075     {
2076       second = val & 0xffff;
2077       first = val >> 16;
2078     }
2079   else if (r_type != R_MIPS16_26)
2080     {
2081       second = ((val >> 11) & 0xffe0) | (val & 0x1f);
2082       first = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0);
2083     }
2084   else
2085     {
2086       second = val & 0xffff;
2087       first = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0)
2088                | ((val >> 21) & 0x1f);
2089     }
2090   bfd_put_16 (abfd, second, data + 2);
2091   bfd_put_16 (abfd, first, data);
2092 }
2093
2094 bfd_reloc_status_type
2095 _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol,
2096                                arelent *reloc_entry, asection *input_section,
2097                                bfd_boolean relocatable, void *data, bfd_vma gp)
2098 {
2099   bfd_vma relocation;
2100   bfd_signed_vma val;
2101   bfd_reloc_status_type status;
2102
2103   if (bfd_is_com_section (symbol->section))
2104     relocation = 0;
2105   else
2106     relocation = symbol->value;
2107
2108   relocation += symbol->section->output_section->vma;
2109   relocation += symbol->section->output_offset;
2110
2111   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2112     return bfd_reloc_outofrange;
2113
2114   /* Set val to the offset into the section or symbol.  */
2115   val = reloc_entry->addend;
2116
2117   _bfd_mips_elf_sign_extend (val, 16);
2118
2119   /* Adjust val for the final section location and GP value.  If we
2120      are producing relocatable output, we don't want to do this for
2121      an external symbol.  */
2122   if (! relocatable
2123       || (symbol->flags & BSF_SECTION_SYM) != 0)
2124     val += relocation - gp;
2125
2126   if (reloc_entry->howto->partial_inplace)
2127     {
2128       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2129                                        (bfd_byte *) data
2130                                        + reloc_entry->address);
2131       if (status != bfd_reloc_ok)
2132         return status;
2133     }
2134   else
2135     reloc_entry->addend = val;
2136
2137   if (relocatable)
2138     reloc_entry->address += input_section->output_offset;
2139
2140   return bfd_reloc_ok;
2141 }
2142
2143 /* Used to store a REL high-part relocation such as R_MIPS_HI16 or
2144    R_MIPS_GOT16.  REL is the relocation, INPUT_SECTION is the section
2145    that contains the relocation field and DATA points to the start of
2146    INPUT_SECTION.  */
2147
2148 struct mips_hi16
2149 {
2150   struct mips_hi16 *next;
2151   bfd_byte *data;
2152   asection *input_section;
2153   arelent rel;
2154 };
2155
2156 /* FIXME: This should not be a static variable.  */
2157
2158 static struct mips_hi16 *mips_hi16_list;
2159
2160 /* A howto special_function for REL *HI16 relocations.  We can only
2161    calculate the correct value once we've seen the partnering
2162    *LO16 relocation, so just save the information for later.
2163
2164    The ABI requires that the *LO16 immediately follow the *HI16.
2165    However, as a GNU extension, we permit an arbitrary number of
2166    *HI16s to be associated with a single *LO16.  This significantly
2167    simplies the relocation handling in gcc.  */
2168
2169 bfd_reloc_status_type
2170 _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2171                           asymbol *symbol ATTRIBUTE_UNUSED, void *data,
2172                           asection *input_section, bfd *output_bfd,
2173                           char **error_message ATTRIBUTE_UNUSED)
2174 {
2175   struct mips_hi16 *n;
2176
2177   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2178     return bfd_reloc_outofrange;
2179
2180   n = bfd_malloc (sizeof *n);
2181   if (n == NULL)
2182     return bfd_reloc_outofrange;
2183
2184   n->next = mips_hi16_list;
2185   n->data = data;
2186   n->input_section = input_section;
2187   n->rel = *reloc_entry;
2188   mips_hi16_list = n;
2189
2190   if (output_bfd != NULL)
2191     reloc_entry->address += input_section->output_offset;
2192
2193   return bfd_reloc_ok;
2194 }
2195
2196 /* A howto special_function for REL R_MIPS*_GOT16 relocations.  This is just
2197    like any other 16-bit relocation when applied to global symbols, but is
2198    treated in the same as R_MIPS_HI16 when applied to local symbols.  */
2199
2200 bfd_reloc_status_type
2201 _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2202                            void *data, asection *input_section,
2203                            bfd *output_bfd, char **error_message)
2204 {
2205   if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2206       || bfd_is_und_section (bfd_get_section (symbol))
2207       || bfd_is_com_section (bfd_get_section (symbol)))
2208     /* The relocation is against a global symbol.  */
2209     return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2210                                         input_section, output_bfd,
2211                                         error_message);
2212
2213   return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
2214                                    input_section, output_bfd, error_message);
2215 }
2216
2217 /* A howto special_function for REL *LO16 relocations.  The *LO16 itself
2218    is a straightforward 16 bit inplace relocation, but we must deal with
2219    any partnering high-part relocations as well.  */
2220
2221 bfd_reloc_status_type
2222 _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2223                           void *data, asection *input_section,
2224                           bfd *output_bfd, char **error_message)
2225 {
2226   bfd_vma vallo;
2227   bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2228
2229   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2230     return bfd_reloc_outofrange;
2231
2232   _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2233                                  location);
2234   vallo = bfd_get_32 (abfd, location);
2235   _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2236                                location);
2237
2238   while (mips_hi16_list != NULL)
2239     {
2240       bfd_reloc_status_type ret;
2241       struct mips_hi16 *hi;
2242
2243       hi = mips_hi16_list;
2244
2245       /* R_MIPS*_GOT16 relocations are something of a special case.  We
2246          want to install the addend in the same way as for a R_MIPS*_HI16
2247          relocation (with a rightshift of 16).  However, since GOT16
2248          relocations can also be used with global symbols, their howto
2249          has a rightshift of 0.  */
2250       if (hi->rel.howto->type == R_MIPS_GOT16)
2251         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE);
2252       else if (hi->rel.howto->type == R_MIPS16_GOT16)
2253         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS16_HI16, FALSE);
2254       else if (hi->rel.howto->type == R_MICROMIPS_GOT16)
2255         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MICROMIPS_HI16, FALSE);
2256
2257       /* VALLO is a signed 16-bit number.  Bias it by 0x8000 so that any
2258          carry or borrow will induce a change of +1 or -1 in the high part.  */
2259       hi->rel.addend += (vallo + 0x8000) & 0xffff;
2260
2261       ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data,
2262                                          hi->input_section, output_bfd,
2263                                          error_message);
2264       if (ret != bfd_reloc_ok)
2265         return ret;
2266
2267       mips_hi16_list = hi->next;
2268       free (hi);
2269     }
2270
2271   return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2272                                       input_section, output_bfd,
2273                                       error_message);
2274 }
2275
2276 /* A generic howto special_function.  This calculates and installs the
2277    relocation itself, thus avoiding the oft-discussed problems in
2278    bfd_perform_relocation and bfd_install_relocation.  */
2279
2280 bfd_reloc_status_type
2281 _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2282                              asymbol *symbol, void *data ATTRIBUTE_UNUSED,
2283                              asection *input_section, bfd *output_bfd,
2284                              char **error_message ATTRIBUTE_UNUSED)
2285 {
2286   bfd_signed_vma val;
2287   bfd_reloc_status_type status;
2288   bfd_boolean relocatable;
2289
2290   relocatable = (output_bfd != NULL);
2291
2292   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2293     return bfd_reloc_outofrange;
2294
2295   /* Build up the field adjustment in VAL.  */
2296   val = 0;
2297   if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)
2298     {
2299       /* Either we're calculating the final field value or we have a
2300          relocation against a section symbol.  Add in the section's
2301          offset or address.  */
2302       val += symbol->section->output_section->vma;
2303       val += symbol->section->output_offset;
2304     }
2305
2306   if (!relocatable)
2307     {
2308       /* We're calculating the final field value.  Add in the symbol's value
2309          and, if pc-relative, subtract the address of the field itself.  */
2310       val += symbol->value;
2311       if (reloc_entry->howto->pc_relative)
2312         {
2313           val -= input_section->output_section->vma;
2314           val -= input_section->output_offset;
2315           val -= reloc_entry->address;
2316         }
2317     }
2318
2319   /* VAL is now the final adjustment.  If we're keeping this relocation
2320      in the output file, and if the relocation uses a separate addend,
2321      we just need to add VAL to that addend.  Otherwise we need to add
2322      VAL to the relocation field itself.  */
2323   if (relocatable && !reloc_entry->howto->partial_inplace)
2324     reloc_entry->addend += val;
2325   else
2326     {
2327       bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2328
2329       /* Add in the separate addend, if any.  */
2330       val += reloc_entry->addend;
2331
2332       /* Add VAL to the relocation field.  */
2333       _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2334                                      location);
2335       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2336                                        location);
2337       _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2338                                    location);
2339
2340       if (status != bfd_reloc_ok)
2341         return status;
2342     }
2343
2344   if (relocatable)
2345     reloc_entry->address += input_section->output_offset;
2346
2347   return bfd_reloc_ok;
2348 }
2349 \f
2350 /* Swap an entry in a .gptab section.  Note that these routines rely
2351    on the equivalence of the two elements of the union.  */
2352
2353 static void
2354 bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex,
2355                               Elf32_gptab *in)
2356 {
2357   in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value);
2358   in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes);
2359 }
2360
2361 static void
2362 bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in,
2363                                Elf32_External_gptab *ex)
2364 {
2365   H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value);
2366   H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes);
2367 }
2368
2369 static void
2370 bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in,
2371                                 Elf32_External_compact_rel *ex)
2372 {
2373   H_PUT_32 (abfd, in->id1, ex->id1);
2374   H_PUT_32 (abfd, in->num, ex->num);
2375   H_PUT_32 (abfd, in->id2, ex->id2);
2376   H_PUT_32 (abfd, in->offset, ex->offset);
2377   H_PUT_32 (abfd, in->reserved0, ex->reserved0);
2378   H_PUT_32 (abfd, in->reserved1, ex->reserved1);
2379 }
2380
2381 static void
2382 bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in,
2383                            Elf32_External_crinfo *ex)
2384 {
2385   unsigned long l;
2386
2387   l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH)
2388        | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH)
2389        | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH)
2390        | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH));
2391   H_PUT_32 (abfd, l, ex->info);
2392   H_PUT_32 (abfd, in->konst, ex->konst);
2393   H_PUT_32 (abfd, in->vaddr, ex->vaddr);
2394 }
2395 \f
2396 /* A .reginfo section holds a single Elf32_RegInfo structure.  These
2397    routines swap this structure in and out.  They are used outside of
2398    BFD, so they are globally visible.  */
2399
2400 void
2401 bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex,
2402                                 Elf32_RegInfo *in)
2403 {
2404   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2405   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2406   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2407   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2408   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2409   in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value);
2410 }
2411
2412 void
2413 bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in,
2414                                  Elf32_External_RegInfo *ex)
2415 {
2416   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2417   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2418   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2419   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2420   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2421   H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value);
2422 }
2423
2424 /* In the 64 bit ABI, the .MIPS.options section holds register
2425    information in an Elf64_Reginfo structure.  These routines swap
2426    them in and out.  They are globally visible because they are used
2427    outside of BFD.  These routines are here so that gas can call them
2428    without worrying about whether the 64 bit ABI has been included.  */
2429
2430 void
2431 bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex,
2432                                 Elf64_Internal_RegInfo *in)
2433 {
2434   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2435   in->ri_pad = H_GET_32 (abfd, ex->ri_pad);
2436   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2437   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2438   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2439   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2440   in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value);
2441 }
2442
2443 void
2444 bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in,
2445                                  Elf64_External_RegInfo *ex)
2446 {
2447   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2448   H_PUT_32 (abfd, in->ri_pad, ex->ri_pad);
2449   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2450   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2451   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2452   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2453   H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value);
2454 }
2455
2456 /* Swap in an options header.  */
2457
2458 void
2459 bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex,
2460                               Elf_Internal_Options *in)
2461 {
2462   in->kind = H_GET_8 (abfd, ex->kind);
2463   in->size = H_GET_8 (abfd, ex->size);
2464   in->section = H_GET_16 (abfd, ex->section);
2465   in->info = H_GET_32 (abfd, ex->info);
2466 }
2467
2468 /* Swap out an options header.  */
2469
2470 void
2471 bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in,
2472                                Elf_External_Options *ex)
2473 {
2474   H_PUT_8 (abfd, in->kind, ex->kind);
2475   H_PUT_8 (abfd, in->size, ex->size);
2476   H_PUT_16 (abfd, in->section, ex->section);
2477   H_PUT_32 (abfd, in->info, ex->info);
2478 }
2479 \f
2480 /* This function is called via qsort() to sort the dynamic relocation
2481    entries by increasing r_symndx value.  */
2482
2483 static int
2484 sort_dynamic_relocs (const void *arg1, const void *arg2)
2485 {
2486   Elf_Internal_Rela int_reloc1;
2487   Elf_Internal_Rela int_reloc2;
2488   int diff;
2489
2490   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
2491   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
2492
2493   diff = ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info);
2494   if (diff != 0)
2495     return diff;
2496
2497   if (int_reloc1.r_offset < int_reloc2.r_offset)
2498     return -1;
2499   if (int_reloc1.r_offset > int_reloc2.r_offset)
2500     return 1;
2501   return 0;
2502 }
2503
2504 /* Like sort_dynamic_relocs, but used for elf64 relocations.  */
2505
2506 static int
2507 sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED,
2508                         const void *arg2 ATTRIBUTE_UNUSED)
2509 {
2510 #ifdef BFD64
2511   Elf_Internal_Rela int_reloc1[3];
2512   Elf_Internal_Rela int_reloc2[3];
2513
2514   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2515     (reldyn_sorting_bfd, arg1, int_reloc1);
2516   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2517     (reldyn_sorting_bfd, arg2, int_reloc2);
2518
2519   if (ELF64_R_SYM (int_reloc1[0].r_info) < ELF64_R_SYM (int_reloc2[0].r_info))
2520     return -1;
2521   if (ELF64_R_SYM (int_reloc1[0].r_info) > ELF64_R_SYM (int_reloc2[0].r_info))
2522     return 1;
2523
2524   if (int_reloc1[0].r_offset < int_reloc2[0].r_offset)
2525     return -1;
2526   if (int_reloc1[0].r_offset > int_reloc2[0].r_offset)
2527     return 1;
2528   return 0;
2529 #else
2530   abort ();
2531 #endif
2532 }
2533
2534
2535 /* This routine is used to write out ECOFF debugging external symbol
2536    information.  It is called via mips_elf_link_hash_traverse.  The
2537    ECOFF external symbol information must match the ELF external
2538    symbol information.  Unfortunately, at this point we don't know
2539    whether a symbol is required by reloc information, so the two
2540    tables may wind up being different.  We must sort out the external
2541    symbol information before we can set the final size of the .mdebug
2542    section, and we must set the size of the .mdebug section before we
2543    can relocate any sections, and we can't know which symbols are
2544    required by relocation until we relocate the sections.
2545    Fortunately, it is relatively unlikely that any symbol will be
2546    stripped but required by a reloc.  In particular, it can not happen
2547    when generating a final executable.  */
2548
2549 static bfd_boolean
2550 mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data)
2551 {
2552   struct extsym_info *einfo = data;
2553   bfd_boolean strip;
2554   asection *sec, *output_section;
2555
2556   if (h->root.indx == -2)
2557     strip = FALSE;
2558   else if ((h->root.def_dynamic
2559             || h->root.ref_dynamic
2560             || h->root.type == bfd_link_hash_new)
2561            && !h->root.def_regular
2562            && !h->root.ref_regular)
2563     strip = TRUE;
2564   else if (einfo->info->strip == strip_all
2565            || (einfo->info->strip == strip_some
2566                && bfd_hash_lookup (einfo->info->keep_hash,
2567                                    h->root.root.root.string,
2568                                    FALSE, FALSE) == NULL))
2569     strip = TRUE;
2570   else
2571     strip = FALSE;
2572
2573   if (strip)
2574     return TRUE;
2575
2576   if (h->esym.ifd == -2)
2577     {
2578       h->esym.jmptbl = 0;
2579       h->esym.cobol_main = 0;
2580       h->esym.weakext = 0;
2581       h->esym.reserved = 0;
2582       h->esym.ifd = ifdNil;
2583       h->esym.asym.value = 0;
2584       h->esym.asym.st = stGlobal;
2585
2586       if (h->root.root.type == bfd_link_hash_undefined
2587           || h->root.root.type == bfd_link_hash_undefweak)
2588         {
2589           const char *name;
2590
2591           /* Use undefined class.  Also, set class and type for some
2592              special symbols.  */
2593           name = h->root.root.root.string;
2594           if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
2595               || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
2596             {
2597               h->esym.asym.sc = scData;
2598               h->esym.asym.st = stLabel;
2599               h->esym.asym.value = 0;
2600             }
2601           else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
2602             {
2603               h->esym.asym.sc = scAbs;
2604               h->esym.asym.st = stLabel;
2605               h->esym.asym.value =
2606                 mips_elf_hash_table (einfo->info)->procedure_count;
2607             }
2608           else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd))
2609             {
2610               h->esym.asym.sc = scAbs;
2611               h->esym.asym.st = stLabel;
2612               h->esym.asym.value = elf_gp (einfo->abfd);
2613             }
2614           else
2615             h->esym.asym.sc = scUndefined;
2616         }
2617       else if (h->root.root.type != bfd_link_hash_defined
2618           && h->root.root.type != bfd_link_hash_defweak)
2619         h->esym.asym.sc = scAbs;
2620       else
2621         {
2622           const char *name;
2623
2624           sec = h->root.root.u.def.section;
2625           output_section = sec->output_section;
2626
2627           /* When making a shared library and symbol h is the one from
2628              the another shared library, OUTPUT_SECTION may be null.  */
2629           if (output_section == NULL)
2630             h->esym.asym.sc = scUndefined;
2631           else
2632             {
2633               name = bfd_section_name (output_section->owner, output_section);
2634
2635               if (strcmp (name, ".text") == 0)
2636                 h->esym.asym.sc = scText;
2637               else if (strcmp (name, ".data") == 0)
2638                 h->esym.asym.sc = scData;
2639               else if (strcmp (name, ".sdata") == 0)
2640                 h->esym.asym.sc = scSData;
2641               else if (strcmp (name, ".rodata") == 0
2642                        || strcmp (name, ".rdata") == 0)
2643                 h->esym.asym.sc = scRData;
2644               else if (strcmp (name, ".bss") == 0)
2645                 h->esym.asym.sc = scBss;
2646               else if (strcmp (name, ".sbss") == 0)
2647                 h->esym.asym.sc = scSBss;
2648               else if (strcmp (name, ".init") == 0)
2649                 h->esym.asym.sc = scInit;
2650               else if (strcmp (name, ".fini") == 0)
2651                 h->esym.asym.sc = scFini;
2652               else
2653                 h->esym.asym.sc = scAbs;
2654             }
2655         }
2656
2657       h->esym.asym.reserved = 0;
2658       h->esym.asym.index = indexNil;
2659     }
2660
2661   if (h->root.root.type == bfd_link_hash_common)
2662     h->esym.asym.value = h->root.root.u.c.size;
2663   else if (h->root.root.type == bfd_link_hash_defined
2664            || h->root.root.type == bfd_link_hash_defweak)
2665     {
2666       if (h->esym.asym.sc == scCommon)
2667         h->esym.asym.sc = scBss;
2668       else if (h->esym.asym.sc == scSCommon)
2669         h->esym.asym.sc = scSBss;
2670
2671       sec = h->root.root.u.def.section;
2672       output_section = sec->output_section;
2673       if (output_section != NULL)
2674         h->esym.asym.value = (h->root.root.u.def.value
2675                               + sec->output_offset
2676                               + output_section->vma);
2677       else
2678         h->esym.asym.value = 0;
2679     }
2680   else
2681     {
2682       struct mips_elf_link_hash_entry *hd = h;
2683
2684       while (hd->root.root.type == bfd_link_hash_indirect)
2685         hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link;
2686
2687       if (hd->needs_lazy_stub)
2688         {
2689           /* Set type and value for a symbol with a function stub.  */
2690           h->esym.asym.st = stProc;
2691           sec = hd->root.root.u.def.section;
2692           if (sec == NULL)
2693             h->esym.asym.value = 0;
2694           else
2695             {
2696               output_section = sec->output_section;
2697               if (output_section != NULL)
2698                 h->esym.asym.value = (hd->root.plt.offset
2699                                       + sec->output_offset
2700                                       + output_section->vma);
2701               else
2702                 h->esym.asym.value = 0;
2703             }
2704         }
2705     }
2706
2707   if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap,
2708                                       h->root.root.root.string,
2709                                       &h->esym))
2710     {
2711       einfo->failed = TRUE;
2712       return FALSE;
2713     }
2714
2715   return TRUE;
2716 }
2717
2718 /* A comparison routine used to sort .gptab entries.  */
2719
2720 static int
2721 gptab_compare (const void *p1, const void *p2)
2722 {
2723   const Elf32_gptab *a1 = p1;
2724   const Elf32_gptab *a2 = p2;
2725
2726   return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value;
2727 }
2728 \f
2729 /* Functions to manage the got entry hash table.  */
2730
2731 /* Use all 64 bits of a bfd_vma for the computation of a 32-bit
2732    hash number.  */
2733
2734 static INLINE hashval_t
2735 mips_elf_hash_bfd_vma (bfd_vma addr)
2736 {
2737 #ifdef BFD64
2738   return addr + (addr >> 32);
2739 #else
2740   return addr;
2741 #endif
2742 }
2743
2744 static hashval_t
2745 mips_elf_got_entry_hash (const void *entry_)
2746 {
2747   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2748
2749   return (entry->symndx
2750           + ((entry->tls_type == GOT_TLS_LDM) << 18)
2751           + (entry->tls_type == GOT_TLS_LDM ? 0
2752              : !entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address)
2753              : entry->symndx >= 0 ? (entry->abfd->id
2754                                      + mips_elf_hash_bfd_vma (entry->d.addend))
2755              : entry->d.h->root.root.root.hash));
2756 }
2757
2758 static int
2759 mips_elf_got_entry_eq (const void *entry1, const void *entry2)
2760 {
2761   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2762   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2763
2764   return (e1->symndx == e2->symndx
2765           && e1->tls_type == e2->tls_type
2766           && (e1->tls_type == GOT_TLS_LDM ? TRUE
2767               : !e1->abfd ? !e2->abfd && e1->d.address == e2->d.address
2768               : e1->symndx >= 0 ? (e1->abfd == e2->abfd
2769                                    && e1->d.addend == e2->d.addend)
2770               : e2->abfd && e1->d.h == e2->d.h));
2771 }
2772
2773 static hashval_t
2774 mips_got_page_entry_hash (const void *entry_)
2775 {
2776   const struct mips_got_page_entry *entry;
2777
2778   entry = (const struct mips_got_page_entry *) entry_;
2779   return entry->abfd->id + entry->symndx;
2780 }
2781
2782 static int
2783 mips_got_page_entry_eq (const void *entry1_, const void *entry2_)
2784 {
2785   const struct mips_got_page_entry *entry1, *entry2;
2786
2787   entry1 = (const struct mips_got_page_entry *) entry1_;
2788   entry2 = (const struct mips_got_page_entry *) entry2_;
2789   return entry1->abfd == entry2->abfd && entry1->symndx == entry2->symndx;
2790 }
2791 \f
2792 /* Create and return a new mips_got_info structure.  */
2793
2794 static struct mips_got_info *
2795 mips_elf_create_got_info (bfd *abfd)
2796 {
2797   struct mips_got_info *g;
2798
2799   g = bfd_zalloc (abfd, sizeof (struct mips_got_info));
2800   if (g == NULL)
2801     return NULL;
2802
2803   g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
2804                                     mips_elf_got_entry_eq, NULL);
2805   if (g->got_entries == NULL)
2806     return NULL;
2807
2808   g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
2809                                          mips_got_page_entry_eq, NULL);
2810   if (g->got_page_entries == NULL)
2811     return NULL;
2812
2813   return g;
2814 }
2815
2816 /* Return the GOT info for input bfd ABFD, trying to create a new one if
2817    CREATE_P and if ABFD doesn't already have a GOT.  */
2818
2819 static struct mips_got_info *
2820 mips_elf_bfd_got (bfd *abfd, bfd_boolean create_p)
2821 {
2822   struct mips_elf_obj_tdata *tdata;
2823
2824   if (!is_mips_elf (abfd))
2825     return NULL;
2826
2827   tdata = mips_elf_tdata (abfd);
2828   if (!tdata->got && create_p)
2829     tdata->got = mips_elf_create_got_info (abfd);
2830   return tdata->got;
2831 }
2832
2833 /* Record that ABFD should use output GOT G.  */
2834
2835 static void
2836 mips_elf_replace_bfd_got (bfd *abfd, struct mips_got_info *g)
2837 {
2838   struct mips_elf_obj_tdata *tdata;
2839
2840   BFD_ASSERT (is_mips_elf (abfd));
2841   tdata = mips_elf_tdata (abfd);
2842   if (tdata->got)
2843     {
2844       /* The GOT structure itself and the hash table entries are
2845          allocated to a bfd, but the hash tables aren't.  */
2846       htab_delete (tdata->got->got_entries);
2847       htab_delete (tdata->got->got_page_entries);
2848     }
2849   tdata->got = g;
2850 }
2851
2852 /* Return the dynamic relocation section.  If it doesn't exist, try to
2853    create a new it if CREATE_P, otherwise return NULL.  Also return NULL
2854    if creation fails.  */
2855
2856 static asection *
2857 mips_elf_rel_dyn_section (struct bfd_link_info *info, bfd_boolean create_p)
2858 {
2859   const char *dname;
2860   asection *sreloc;
2861   bfd *dynobj;
2862
2863   dname = MIPS_ELF_REL_DYN_NAME (info);
2864   dynobj = elf_hash_table (info)->dynobj;
2865   sreloc = bfd_get_linker_section (dynobj, dname);
2866   if (sreloc == NULL && create_p)
2867     {
2868       sreloc = bfd_make_section_anyway_with_flags (dynobj, dname,
2869                                                    (SEC_ALLOC
2870                                                     | SEC_LOAD
2871                                                     | SEC_HAS_CONTENTS
2872                                                     | SEC_IN_MEMORY
2873                                                     | SEC_LINKER_CREATED
2874                                                     | SEC_READONLY));
2875       if (sreloc == NULL
2876           || ! bfd_set_section_alignment (dynobj, sreloc,
2877                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
2878         return NULL;
2879     }
2880   return sreloc;
2881 }
2882
2883 /* Return the GOT_TLS_* type required by relocation type R_TYPE.  */
2884
2885 static int
2886 mips_elf_reloc_tls_type (unsigned int r_type)
2887 {
2888   if (tls_gd_reloc_p (r_type))
2889     return GOT_TLS_GD;
2890
2891   if (tls_ldm_reloc_p (r_type))
2892     return GOT_TLS_LDM;
2893
2894   if (tls_gottprel_reloc_p (r_type))
2895     return GOT_TLS_IE;
2896
2897   return GOT_TLS_NONE;
2898 }
2899
2900 /* Return the number of GOT slots needed for GOT TLS type TYPE.  */
2901
2902 static int
2903 mips_tls_got_entries (unsigned int type)
2904 {
2905   switch (type)
2906     {
2907     case GOT_TLS_GD:
2908     case GOT_TLS_LDM:
2909       return 2;
2910
2911     case GOT_TLS_IE:
2912       return 1;
2913
2914     case GOT_TLS_NONE:
2915       return 0;
2916     }
2917   abort ();
2918 }
2919
2920 /* Count the number of relocations needed for a TLS GOT entry, with
2921    access types from TLS_TYPE, and symbol H (or a local symbol if H
2922    is NULL).  */
2923
2924 static int
2925 mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type,
2926                      struct elf_link_hash_entry *h)
2927 {
2928   int indx = 0;
2929   bfd_boolean need_relocs = FALSE;
2930   bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
2931
2932   if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, h)
2933       && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, h)))
2934     indx = h->dynindx;
2935
2936   if ((info->shared || indx != 0)
2937       && (h == NULL
2938           || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2939           || h->root.type != bfd_link_hash_undefweak))
2940     need_relocs = TRUE;
2941
2942   if (!need_relocs)
2943     return 0;
2944
2945   switch (tls_type)
2946     {
2947     case GOT_TLS_GD:
2948       return indx != 0 ? 2 : 1;
2949
2950     case GOT_TLS_IE:
2951       return 1;
2952
2953     case GOT_TLS_LDM:
2954       return info->shared ? 1 : 0;
2955
2956     default:
2957       return 0;
2958     }
2959 }
2960
2961 /* Add the number of GOT entries and TLS relocations required by ENTRY
2962    to G.  */
2963
2964 static void
2965 mips_elf_count_got_entry (struct bfd_link_info *info,
2966                           struct mips_got_info *g,
2967                           struct mips_got_entry *entry)
2968 {
2969   if (entry->tls_type)
2970     {
2971       g->tls_gotno += mips_tls_got_entries (entry->tls_type);
2972       g->relocs += mips_tls_got_relocs (info, entry->tls_type,
2973                                         entry->symndx < 0
2974                                         ? &entry->d.h->root : NULL);
2975     }
2976   else if (entry->symndx >= 0 || entry->d.h->global_got_area == GGA_NONE)
2977     g->local_gotno += 1;
2978   else
2979     g->global_gotno += 1;
2980 }
2981
2982 /* Output a simple dynamic relocation into SRELOC.  */
2983
2984 static void
2985 mips_elf_output_dynamic_relocation (bfd *output_bfd,
2986                                     asection *sreloc,
2987                                     unsigned long reloc_index,
2988                                     unsigned long indx,
2989                                     int r_type,
2990                                     bfd_vma offset)
2991 {
2992   Elf_Internal_Rela rel[3];
2993
2994   memset (rel, 0, sizeof (rel));
2995
2996   rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type);
2997   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
2998
2999   if (ABI_64_P (output_bfd))
3000     {
3001       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
3002         (output_bfd, &rel[0],
3003          (sreloc->contents
3004           + reloc_index * sizeof (Elf64_Mips_External_Rel)));
3005     }
3006   else
3007     bfd_elf32_swap_reloc_out
3008       (output_bfd, &rel[0],
3009        (sreloc->contents
3010         + reloc_index * sizeof (Elf32_External_Rel)));
3011 }
3012
3013 /* Initialize a set of TLS GOT entries for one symbol.  */
3014
3015 static void
3016 mips_elf_initialize_tls_slots (bfd *abfd, struct bfd_link_info *info,
3017                                struct mips_got_entry *entry,
3018                                struct mips_elf_link_hash_entry *h,
3019                                bfd_vma value)
3020 {
3021   struct mips_elf_link_hash_table *htab;
3022   int indx;
3023   asection *sreloc, *sgot;
3024   bfd_vma got_offset, got_offset2;
3025   bfd_boolean need_relocs = FALSE;
3026
3027   htab = mips_elf_hash_table (info);
3028   if (htab == NULL)
3029     return;
3030
3031   sgot = htab->sgot;
3032
3033   indx = 0;
3034   if (h != NULL)
3035     {
3036       bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3037
3038       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, &h->root)
3039           && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3040         indx = h->root.dynindx;
3041     }
3042
3043   if (entry->tls_initialized)
3044     return;
3045
3046   if ((info->shared || indx != 0)
3047       && (h == NULL
3048           || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT
3049           || h->root.type != bfd_link_hash_undefweak))
3050     need_relocs = TRUE;
3051
3052   /* MINUS_ONE means the symbol is not defined in this object.  It may not
3053      be defined at all; assume that the value doesn't matter in that
3054      case.  Otherwise complain if we would use the value.  */
3055   BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs)
3056               || h->root.root.type == bfd_link_hash_undefweak);
3057
3058   /* Emit necessary relocations.  */
3059   sreloc = mips_elf_rel_dyn_section (info, FALSE);
3060   got_offset = entry->gotidx;
3061
3062   switch (entry->tls_type)
3063     {
3064     case GOT_TLS_GD:
3065       /* General Dynamic.  */
3066       got_offset2 = got_offset + MIPS_ELF_GOT_SIZE (abfd);
3067
3068       if (need_relocs)
3069         {
3070           mips_elf_output_dynamic_relocation
3071             (abfd, sreloc, sreloc->reloc_count++, indx,
3072              ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3073              sgot->output_offset + sgot->output_section->vma + got_offset);
3074
3075           if (indx)
3076             mips_elf_output_dynamic_relocation
3077               (abfd, sreloc, sreloc->reloc_count++, indx,
3078                ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32,
3079                sgot->output_offset + sgot->output_section->vma + got_offset2);
3080           else
3081             MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3082                                sgot->contents + got_offset2);
3083         }
3084       else
3085         {
3086           MIPS_ELF_PUT_WORD (abfd, 1,
3087                              sgot->contents + got_offset);
3088           MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3089                              sgot->contents + got_offset2);
3090         }
3091       break;
3092
3093     case GOT_TLS_IE:
3094       /* Initial Exec model.  */
3095       if (need_relocs)
3096         {
3097           if (indx == 0)
3098             MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma,
3099                                sgot->contents + got_offset);
3100           else
3101             MIPS_ELF_PUT_WORD (abfd, 0,
3102                                sgot->contents + got_offset);
3103
3104           mips_elf_output_dynamic_relocation
3105             (abfd, sreloc, sreloc->reloc_count++, indx,
3106              ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32,
3107              sgot->output_offset + sgot->output_section->vma + got_offset);
3108         }
3109       else
3110         MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info),
3111                            sgot->contents + got_offset);
3112       break;
3113
3114     case GOT_TLS_LDM:
3115       /* The initial offset is zero, and the LD offsets will include the
3116          bias by DTP_OFFSET.  */
3117       MIPS_ELF_PUT_WORD (abfd, 0,
3118                          sgot->contents + got_offset
3119                          + MIPS_ELF_GOT_SIZE (abfd));
3120
3121       if (!info->shared)
3122         MIPS_ELF_PUT_WORD (abfd, 1,
3123                            sgot->contents + got_offset);
3124       else
3125         mips_elf_output_dynamic_relocation
3126           (abfd, sreloc, sreloc->reloc_count++, indx,
3127            ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3128            sgot->output_offset + sgot->output_section->vma + got_offset);
3129       break;
3130
3131     default:
3132       abort ();
3133     }
3134
3135   entry->tls_initialized = TRUE;
3136 }
3137
3138 /* Return the offset from _GLOBAL_OFFSET_TABLE_ of the .got.plt entry
3139    for global symbol H.  .got.plt comes before the GOT, so the offset
3140    will be negative.  */
3141
3142 static bfd_vma
3143 mips_elf_gotplt_index (struct bfd_link_info *info,
3144                        struct elf_link_hash_entry *h)
3145 {
3146   bfd_vma plt_index, got_address, got_value;
3147   struct mips_elf_link_hash_table *htab;
3148
3149   htab = mips_elf_hash_table (info);
3150   BFD_ASSERT (htab != NULL);
3151
3152   BFD_ASSERT (h->plt.offset != (bfd_vma) -1);
3153
3154   /* This function only works for VxWorks, because a non-VxWorks .got.plt
3155      section starts with reserved entries.  */
3156   BFD_ASSERT (htab->is_vxworks);
3157
3158   /* Calculate the index of the symbol's PLT entry.  */
3159   plt_index = (h->plt.offset - htab->plt_header_size) / htab->plt_entry_size;
3160
3161   /* Calculate the address of the associated .got.plt entry.  */
3162   got_address = (htab->sgotplt->output_section->vma
3163                  + htab->sgotplt->output_offset
3164                  + plt_index * 4);
3165
3166   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
3167   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
3168                + htab->root.hgot->root.u.def.section->output_offset
3169                + htab->root.hgot->root.u.def.value);
3170
3171   return got_address - got_value;
3172 }
3173
3174 /* Return the GOT offset for address VALUE.   If there is not yet a GOT
3175    entry for this value, create one.  If R_SYMNDX refers to a TLS symbol,
3176    create a TLS GOT entry instead.  Return -1 if no satisfactory GOT
3177    offset can be found.  */
3178
3179 static bfd_vma
3180 mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3181                           bfd_vma value, unsigned long r_symndx,
3182                           struct mips_elf_link_hash_entry *h, int r_type)
3183 {
3184   struct mips_elf_link_hash_table *htab;
3185   struct mips_got_entry *entry;
3186
3187   htab = mips_elf_hash_table (info);
3188   BFD_ASSERT (htab != NULL);
3189
3190   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value,
3191                                            r_symndx, h, r_type);
3192   if (!entry)
3193     return MINUS_ONE;
3194
3195   if (entry->tls_type)
3196     mips_elf_initialize_tls_slots (abfd, info, entry, h, value);
3197   return entry->gotidx;
3198 }
3199
3200 /* Return the GOT index of global symbol H in the primary GOT.  */
3201
3202 static bfd_vma
3203 mips_elf_primary_global_got_index (bfd *obfd, struct bfd_link_info *info,
3204                                    struct elf_link_hash_entry *h)
3205 {
3206   struct mips_elf_link_hash_table *htab;
3207   long global_got_dynindx;
3208   struct mips_got_info *g;
3209   bfd_vma got_index;
3210
3211   htab = mips_elf_hash_table (info);
3212   BFD_ASSERT (htab != NULL);
3213
3214   global_got_dynindx = 0;
3215   if (htab->global_gotsym != NULL)
3216     global_got_dynindx = htab->global_gotsym->dynindx;
3217
3218   /* Once we determine the global GOT entry with the lowest dynamic
3219      symbol table index, we must put all dynamic symbols with greater
3220      indices into the primary GOT.  That makes it easy to calculate the
3221      GOT offset.  */
3222   BFD_ASSERT (h->dynindx >= global_got_dynindx);
3223   g = mips_elf_bfd_got (obfd, FALSE);
3224   got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3225                * MIPS_ELF_GOT_SIZE (obfd));
3226   BFD_ASSERT (got_index < htab->sgot->size);
3227
3228   return got_index;
3229 }
3230
3231 /* Return the GOT index for the global symbol indicated by H, which is
3232    referenced by a relocation of type R_TYPE in IBFD.  */
3233
3234 static bfd_vma
3235 mips_elf_global_got_index (bfd *obfd, struct bfd_link_info *info, bfd *ibfd,
3236                            struct elf_link_hash_entry *h, int r_type)
3237 {
3238   struct mips_elf_link_hash_table *htab;
3239   struct mips_got_info *g;
3240   struct mips_got_entry lookup, *entry;
3241   bfd_vma gotidx;
3242
3243   htab = mips_elf_hash_table (info);
3244   BFD_ASSERT (htab != NULL);
3245
3246   g = mips_elf_bfd_got (ibfd, FALSE);
3247   BFD_ASSERT (g);
3248
3249   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3250   if (!lookup.tls_type && g == mips_elf_bfd_got (obfd, FALSE))
3251     return mips_elf_primary_global_got_index (obfd, info, h);
3252
3253   lookup.abfd = ibfd;
3254   lookup.symndx = -1;
3255   lookup.d.h = (struct mips_elf_link_hash_entry *) h;
3256   entry = htab_find (g->got_entries, &lookup);
3257   BFD_ASSERT (entry);
3258
3259   gotidx = entry->gotidx;
3260   BFD_ASSERT (gotidx > 0 && gotidx < htab->sgot->size);
3261
3262   if (lookup.tls_type)
3263     {
3264       bfd_vma value = MINUS_ONE;
3265
3266       if ((h->root.type == bfd_link_hash_defined
3267            || h->root.type == bfd_link_hash_defweak)
3268           && h->root.u.def.section->output_section)
3269         value = (h->root.u.def.value
3270                  + h->root.u.def.section->output_offset
3271                  + h->root.u.def.section->output_section->vma);
3272
3273       mips_elf_initialize_tls_slots (obfd, info, entry, lookup.d.h, value);
3274     }
3275   return gotidx;
3276 }
3277
3278 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3279    entries are supposed to be placed at small offsets in the GOT, i.e.,
3280    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3281    entry could be created.  If OFFSETP is nonnull, use it to return the
3282    offset of the GOT entry from VALUE.  */
3283
3284 static bfd_vma
3285 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3286                    bfd_vma value, bfd_vma *offsetp)
3287 {
3288   bfd_vma page, got_index;
3289   struct mips_got_entry *entry;
3290
3291   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3292   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3293                                            NULL, R_MIPS_GOT_PAGE);
3294
3295   if (!entry)
3296     return MINUS_ONE;
3297
3298   got_index = entry->gotidx;
3299
3300   if (offsetp)
3301     *offsetp = value - entry->d.address;
3302
3303   return got_index;
3304 }
3305
3306 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3307    EXTERNAL is true if the relocation was originally against a global
3308    symbol that binds locally.  */
3309
3310 static bfd_vma
3311 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3312                       bfd_vma value, bfd_boolean external)
3313 {
3314   struct mips_got_entry *entry;
3315
3316   /* GOT16 relocations against local symbols are followed by a LO16
3317      relocation; those against global symbols are not.  Thus if the
3318      symbol was originally local, the GOT16 relocation should load the
3319      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3320   if (! external)
3321     value = mips_elf_high (value) << 16;
3322
3323   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3324      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3325      same in all cases.  */
3326   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3327                                            NULL, R_MIPS_GOT16);
3328   if (entry)
3329     return entry->gotidx;
3330   else
3331     return MINUS_ONE;
3332 }
3333
3334 /* Returns the offset for the entry at the INDEXth position
3335    in the GOT.  */
3336
3337 static bfd_vma
3338 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3339                                 bfd *input_bfd, bfd_vma got_index)
3340 {
3341   struct mips_elf_link_hash_table *htab;
3342   asection *sgot;
3343   bfd_vma gp;
3344
3345   htab = mips_elf_hash_table (info);
3346   BFD_ASSERT (htab != NULL);
3347
3348   sgot = htab->sgot;
3349   gp = _bfd_get_gp_value (output_bfd)
3350     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3351
3352   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3353 }
3354
3355 /* Create and return a local GOT entry for VALUE, which was calculated
3356    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3357    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3358    instead.  */
3359
3360 static struct mips_got_entry *
3361 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3362                                  bfd *ibfd, bfd_vma value,
3363                                  unsigned long r_symndx,
3364                                  struct mips_elf_link_hash_entry *h,
3365                                  int r_type)
3366 {
3367   struct mips_got_entry lookup, *entry;
3368   void **loc;
3369   struct mips_got_info *g;
3370   struct mips_elf_link_hash_table *htab;
3371   bfd_vma gotidx;
3372
3373   htab = mips_elf_hash_table (info);
3374   BFD_ASSERT (htab != NULL);
3375
3376   g = mips_elf_bfd_got (ibfd, FALSE);
3377   if (g == NULL)
3378     {
3379       g = mips_elf_bfd_got (abfd, FALSE);
3380       BFD_ASSERT (g != NULL);
3381     }
3382
3383   /* This function shouldn't be called for symbols that live in the global
3384      area of the GOT.  */
3385   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3386
3387   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3388   if (lookup.tls_type)
3389     {
3390       lookup.abfd = ibfd;
3391       if (tls_ldm_reloc_p (r_type))
3392         {
3393           lookup.symndx = 0;
3394           lookup.d.addend = 0;
3395         }
3396       else if (h == NULL)
3397         {
3398           lookup.symndx = r_symndx;
3399           lookup.d.addend = 0;
3400         }
3401       else
3402         {
3403           lookup.symndx = -1;
3404           lookup.d.h = h;
3405         }
3406
3407       entry = (struct mips_got_entry *) htab_find (g->got_entries, &lookup);
3408       BFD_ASSERT (entry);
3409
3410       gotidx = entry->gotidx;
3411       BFD_ASSERT (gotidx > 0 && gotidx < htab->sgot->size);
3412
3413       return entry;
3414     }
3415
3416   lookup.abfd = NULL;
3417   lookup.symndx = -1;
3418   lookup.d.address = value;
3419   loc = htab_find_slot (g->got_entries, &lookup, INSERT);
3420   if (!loc)
3421     return NULL;
3422
3423   entry = (struct mips_got_entry *) *loc;
3424   if (entry)
3425     return entry;
3426
3427   if (g->assigned_gotno >= g->local_gotno)
3428     {
3429       /* We didn't allocate enough space in the GOT.  */
3430       (*_bfd_error_handler)
3431         (_("not enough GOT space for local GOT entries"));
3432       bfd_set_error (bfd_error_bad_value);
3433       return NULL;
3434     }
3435
3436   entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3437   if (!entry)
3438     return NULL;
3439
3440   lookup.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_gotno++;
3441   *entry = lookup;
3442   *loc = entry;
3443
3444   MIPS_ELF_PUT_WORD (abfd, value, htab->sgot->contents + entry->gotidx);
3445
3446   /* These GOT entries need a dynamic relocation on VxWorks.  */
3447   if (htab->is_vxworks)
3448     {
3449       Elf_Internal_Rela outrel;
3450       asection *s;
3451       bfd_byte *rloc;
3452       bfd_vma got_address;
3453
3454       s = mips_elf_rel_dyn_section (info, FALSE);
3455       got_address = (htab->sgot->output_section->vma
3456                      + htab->sgot->output_offset
3457                      + entry->gotidx);
3458
3459       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3460       outrel.r_offset = got_address;
3461       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3462       outrel.r_addend = value;
3463       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3464     }
3465
3466   return entry;
3467 }
3468
3469 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3470    The number might be exact or a worst-case estimate, depending on how
3471    much information is available to elf_backend_omit_section_dynsym at
3472    the current linking stage.  */
3473
3474 static bfd_size_type
3475 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3476 {
3477   bfd_size_type count;
3478
3479   count = 0;
3480   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
3481     {
3482       asection *p;
3483       const struct elf_backend_data *bed;
3484
3485       bed = get_elf_backend_data (output_bfd);
3486       for (p = output_bfd->sections; p ; p = p->next)
3487         if ((p->flags & SEC_EXCLUDE) == 0
3488             && (p->flags & SEC_ALLOC) != 0
3489             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3490           ++count;
3491     }
3492   return count;
3493 }
3494
3495 /* Sort the dynamic symbol table so that symbols that need GOT entries
3496    appear towards the end.  */
3497
3498 static bfd_boolean
3499 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3500 {
3501   struct mips_elf_link_hash_table *htab;
3502   struct mips_elf_hash_sort_data hsd;
3503   struct mips_got_info *g;
3504
3505   if (elf_hash_table (info)->dynsymcount == 0)
3506     return TRUE;
3507
3508   htab = mips_elf_hash_table (info);
3509   BFD_ASSERT (htab != NULL);
3510
3511   g = htab->got_info;
3512   if (g == NULL)
3513     return TRUE;
3514
3515   hsd.low = NULL;
3516   hsd.max_unref_got_dynindx
3517     = hsd.min_got_dynindx
3518     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3519   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3520   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3521                                 elf_hash_table (info)),
3522                                mips_elf_sort_hash_table_f,
3523                                &hsd);
3524
3525   /* There should have been enough room in the symbol table to
3526      accommodate both the GOT and non-GOT symbols.  */
3527   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3528   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3529               == elf_hash_table (info)->dynsymcount);
3530   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3531               == g->global_gotno);
3532
3533   /* Now we know which dynamic symbol has the lowest dynamic symbol
3534      table index in the GOT.  */
3535   htab->global_gotsym = hsd.low;
3536
3537   return TRUE;
3538 }
3539
3540 /* If H needs a GOT entry, assign it the highest available dynamic
3541    index.  Otherwise, assign it the lowest available dynamic
3542    index.  */
3543
3544 static bfd_boolean
3545 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3546 {
3547   struct mips_elf_hash_sort_data *hsd = data;
3548
3549   /* Symbols without dynamic symbol table entries aren't interesting
3550      at all.  */
3551   if (h->root.dynindx == -1)
3552     return TRUE;
3553
3554   switch (h->global_got_area)
3555     {
3556     case GGA_NONE:
3557       h->root.dynindx = hsd->max_non_got_dynindx++;
3558       break;
3559
3560     case GGA_NORMAL:
3561       h->root.dynindx = --hsd->min_got_dynindx;
3562       hsd->low = (struct elf_link_hash_entry *) h;
3563       break;
3564
3565     case GGA_RELOC_ONLY:
3566       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3567         hsd->low = (struct elf_link_hash_entry *) h;
3568       h->root.dynindx = hsd->max_unref_got_dynindx++;
3569       break;
3570     }
3571
3572   return TRUE;
3573 }
3574
3575 /* Record that input bfd ABFD requires a GOT entry like *LOOKUP
3576    (which is owned by the caller and shouldn't be added to the
3577    hash table directly).  */
3578
3579 static bfd_boolean
3580 mips_elf_record_got_entry (struct bfd_link_info *info, bfd *abfd,
3581                            struct mips_got_entry *lookup)
3582 {
3583   struct mips_elf_link_hash_table *htab;
3584   struct mips_got_entry *entry;
3585   struct mips_got_info *g;
3586   void **loc, **bfd_loc;
3587
3588   /* Make sure there's a slot for this entry in the master GOT.  */
3589   htab = mips_elf_hash_table (info);
3590   g = htab->got_info;
3591   loc = htab_find_slot (g->got_entries, lookup, INSERT);
3592   if (!loc)
3593     return FALSE;
3594
3595   /* Populate the entry if it isn't already.  */
3596   entry = (struct mips_got_entry *) *loc;
3597   if (!entry)
3598     {
3599       entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3600       if (!entry)
3601         return FALSE;
3602
3603       lookup->tls_initialized = FALSE;
3604       lookup->gotidx = -1;
3605       *entry = *lookup;
3606       *loc = entry;
3607     }
3608
3609   /* Reuse the same GOT entry for the BFD's GOT.  */
3610   g = mips_elf_bfd_got (abfd, TRUE);
3611   if (!g)
3612     return FALSE;
3613
3614   bfd_loc = htab_find_slot (g->got_entries, lookup, INSERT);
3615   if (!bfd_loc)
3616     return FALSE;
3617
3618   if (!*bfd_loc)
3619     *bfd_loc = entry;
3620   return TRUE;
3621 }
3622
3623 /* ABFD has a GOT relocation of type R_TYPE against H.  Reserve a GOT
3624    entry for it.  FOR_CALL is true if the caller is only interested in
3625    using the GOT entry for calls.  */
3626
3627 static bfd_boolean
3628 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3629                                    bfd *abfd, struct bfd_link_info *info,
3630                                    bfd_boolean for_call, int r_type)
3631 {
3632   struct mips_elf_link_hash_table *htab;
3633   struct mips_elf_link_hash_entry *hmips;
3634   struct mips_got_entry entry;
3635   unsigned char tls_type;
3636
3637   htab = mips_elf_hash_table (info);
3638   BFD_ASSERT (htab != NULL);
3639
3640   hmips = (struct mips_elf_link_hash_entry *) h;
3641   if (!for_call)
3642     hmips->got_only_for_calls = FALSE;
3643
3644   /* A global symbol in the GOT must also be in the dynamic symbol
3645      table.  */
3646   if (h->dynindx == -1)
3647     {
3648       switch (ELF_ST_VISIBILITY (h->other))
3649         {
3650         case STV_INTERNAL:
3651         case STV_HIDDEN:
3652           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3653           break;
3654         }
3655       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3656         return FALSE;
3657     }
3658
3659   tls_type = mips_elf_reloc_tls_type (r_type);
3660   if (tls_type == GOT_TLS_NONE && hmips->global_got_area > GGA_NORMAL)
3661     hmips->global_got_area = GGA_NORMAL;
3662
3663   entry.abfd = abfd;
3664   entry.symndx = -1;
3665   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3666   entry.tls_type = tls_type;
3667   return mips_elf_record_got_entry (info, abfd, &entry);
3668 }
3669
3670 /* ABFD has a GOT relocation of type R_TYPE against symbol SYMNDX + ADDEND,
3671    where SYMNDX is a local symbol.  Reserve a GOT entry for it.  */
3672
3673 static bfd_boolean
3674 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
3675                                   struct bfd_link_info *info, int r_type)
3676 {
3677   struct mips_elf_link_hash_table *htab;
3678   struct mips_got_info *g;
3679   struct mips_got_entry entry;
3680
3681   htab = mips_elf_hash_table (info);
3682   BFD_ASSERT (htab != NULL);
3683
3684   g = htab->got_info;
3685   BFD_ASSERT (g != NULL);
3686
3687   entry.abfd = abfd;
3688   entry.symndx = symndx;
3689   entry.d.addend = addend;
3690   entry.tls_type = mips_elf_reloc_tls_type (r_type);
3691   return mips_elf_record_got_entry (info, abfd, &entry);
3692 }
3693
3694 /* Return the maximum number of GOT page entries required for RANGE.  */
3695
3696 static bfd_vma
3697 mips_elf_pages_for_range (const struct mips_got_page_range *range)
3698 {
3699   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
3700 }
3701
3702 /* Record that ABFD has a page relocation against symbol SYMNDX and
3703    that ADDEND is the addend for that relocation.
3704
3705    This function creates an upper bound on the number of GOT slots
3706    required; no attempt is made to combine references to non-overridable
3707    global symbols across multiple input files.  */
3708
3709 static bfd_boolean
3710 mips_elf_record_got_page_entry (struct bfd_link_info *info, bfd *abfd,
3711                                 long symndx, bfd_signed_vma addend)
3712 {
3713   struct mips_elf_link_hash_table *htab;
3714   struct mips_got_info *g1, *g2;
3715   struct mips_got_page_entry lookup, *entry;
3716   struct mips_got_page_range **range_ptr, *range;
3717   bfd_vma old_pages, new_pages;
3718   void **loc, **bfd_loc;
3719
3720   htab = mips_elf_hash_table (info);
3721   BFD_ASSERT (htab != NULL);
3722
3723   g1 = htab->got_info;
3724   BFD_ASSERT (g1 != NULL);
3725
3726   /* Find the mips_got_page_entry hash table entry for this symbol.  */
3727   lookup.abfd = abfd;
3728   lookup.symndx = symndx;
3729   loc = htab_find_slot (g1->got_page_entries, &lookup, INSERT);
3730   if (loc == NULL)
3731     return FALSE;
3732
3733   /* Create a mips_got_page_entry if this is the first time we've
3734      seen the symbol.  */
3735   entry = (struct mips_got_page_entry *) *loc;
3736   if (!entry)
3737     {
3738       entry = bfd_alloc (abfd, sizeof (*entry));
3739       if (!entry)
3740         return FALSE;
3741
3742       entry->abfd = abfd;
3743       entry->symndx = symndx;
3744       entry->ranges = NULL;
3745       entry->num_pages = 0;
3746       *loc = entry;
3747     }
3748
3749   /* Add the same entry to the BFD's GOT.  */
3750   g2 = mips_elf_bfd_got (abfd, TRUE);
3751   if (!g2)
3752     return FALSE;
3753
3754   bfd_loc = htab_find_slot (g2->got_page_entries, &lookup, INSERT);
3755   if (!bfd_loc)
3756     return FALSE;
3757
3758   if (!*bfd_loc)
3759     *bfd_loc = entry;
3760
3761   /* Skip over ranges whose maximum extent cannot share a page entry
3762      with ADDEND.  */
3763   range_ptr = &entry->ranges;
3764   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
3765     range_ptr = &(*range_ptr)->next;
3766
3767   /* If we scanned to the end of the list, or found a range whose
3768      minimum extent cannot share a page entry with ADDEND, create
3769      a new singleton range.  */
3770   range = *range_ptr;
3771   if (!range || addend < range->min_addend - 0xffff)
3772     {
3773       range = bfd_alloc (abfd, sizeof (*range));
3774       if (!range)
3775         return FALSE;
3776
3777       range->next = *range_ptr;
3778       range->min_addend = addend;
3779       range->max_addend = addend;
3780
3781       *range_ptr = range;
3782       entry->num_pages++;
3783       g1->page_gotno++;
3784       g2->page_gotno++;
3785       return TRUE;
3786     }
3787
3788   /* Remember how many pages the old range contributed.  */
3789   old_pages = mips_elf_pages_for_range (range);
3790
3791   /* Update the ranges.  */
3792   if (addend < range->min_addend)
3793     range->min_addend = addend;
3794   else if (addend > range->max_addend)
3795     {
3796       if (range->next && addend >= range->next->min_addend - 0xffff)
3797         {
3798           old_pages += mips_elf_pages_for_range (range->next);
3799           range->max_addend = range->next->max_addend;
3800           range->next = range->next->next;
3801         }
3802       else
3803         range->max_addend = addend;
3804     }
3805
3806   /* Record any change in the total estimate.  */
3807   new_pages = mips_elf_pages_for_range (range);
3808   if (old_pages != new_pages)
3809     {
3810       entry->num_pages += new_pages - old_pages;
3811       g1->page_gotno += new_pages - old_pages;
3812       g2->page_gotno += new_pages - old_pages;
3813     }
3814
3815   return TRUE;
3816 }
3817
3818 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
3819
3820 static void
3821 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
3822                                        unsigned int n)
3823 {
3824   asection *s;
3825   struct mips_elf_link_hash_table *htab;
3826
3827   htab = mips_elf_hash_table (info);
3828   BFD_ASSERT (htab != NULL);
3829
3830   s = mips_elf_rel_dyn_section (info, FALSE);
3831   BFD_ASSERT (s != NULL);
3832
3833   if (htab->is_vxworks)
3834     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
3835   else
3836     {
3837       if (s->size == 0)
3838         {
3839           /* Make room for a null element.  */
3840           s->size += MIPS_ELF_REL_SIZE (abfd);
3841           ++s->reloc_count;
3842         }
3843       s->size += n * MIPS_ELF_REL_SIZE (abfd);
3844     }
3845 }
3846 \f
3847 /* A htab_traverse callback for GOT entries, with DATA pointing to a
3848    mips_elf_traverse_got_arg structure.  Count the number of GOT
3849    entries and TLS relocs.  Set DATA->value to true if we need
3850    to resolve indirect or warning symbols and then recreate the GOT.  */
3851
3852 static int
3853 mips_elf_check_recreate_got (void **entryp, void *data)
3854 {
3855   struct mips_got_entry *entry;
3856   struct mips_elf_traverse_got_arg *arg;
3857
3858   entry = (struct mips_got_entry *) *entryp;
3859   arg = (struct mips_elf_traverse_got_arg *) data;
3860   if (entry->abfd != NULL && entry->symndx == -1)
3861     {
3862       struct mips_elf_link_hash_entry *h;
3863
3864       h = entry->d.h;
3865       if (h->root.root.type == bfd_link_hash_indirect
3866           || h->root.root.type == bfd_link_hash_warning)
3867         {
3868           arg->value = TRUE;
3869           return 0;
3870         }
3871     }
3872   mips_elf_count_got_entry (arg->info, arg->g, entry);
3873   return 1;
3874 }
3875
3876 /* A htab_traverse callback for GOT entries, with DATA pointing to a
3877    mips_elf_traverse_got_arg structure.  Add all entries to DATA->g,
3878    converting entries for indirect and warning symbols into entries
3879    for the target symbol.  Set DATA->g to null on error.  */
3880
3881 static int
3882 mips_elf_recreate_got (void **entryp, void *data)
3883 {
3884   struct mips_got_entry new_entry, *entry;
3885   struct mips_elf_traverse_got_arg *arg;
3886   void **slot;
3887
3888   entry = (struct mips_got_entry *) *entryp;
3889   arg = (struct mips_elf_traverse_got_arg *) data;
3890   if (entry->abfd != NULL
3891       && entry->symndx == -1
3892       && (entry->d.h->root.root.type == bfd_link_hash_indirect
3893           || entry->d.h->root.root.type == bfd_link_hash_warning))
3894     {
3895       struct mips_elf_link_hash_entry *h;
3896
3897       new_entry = *entry;
3898       entry = &new_entry;
3899       h = entry->d.h;
3900       do
3901         {
3902           BFD_ASSERT (h->global_got_area == GGA_NONE);
3903           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
3904         }
3905       while (h->root.root.type == bfd_link_hash_indirect
3906              || h->root.root.type == bfd_link_hash_warning);
3907       entry->d.h = h;
3908     }
3909   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
3910   if (slot == NULL)
3911     {
3912       arg->g = NULL;
3913       return 0;
3914     }
3915   if (*slot == NULL)
3916     {
3917       if (entry == &new_entry)
3918         {
3919           entry = bfd_alloc (entry->abfd, sizeof (*entry));
3920           if (!entry)
3921             {
3922               arg->g = NULL;
3923               return 0;
3924             }
3925           *entry = new_entry;
3926         }
3927       *slot = entry;
3928       mips_elf_count_got_entry (arg->info, arg->g, entry);
3929     }
3930   return 1;
3931 }
3932
3933 /* If any entries in G->got_entries are for indirect or warning symbols,
3934    replace them with entries for the target symbol.  */
3935
3936 static bfd_boolean
3937 mips_elf_resolve_final_got_entries (struct bfd_link_info *info,
3938                                     struct mips_got_info *g)
3939 {
3940   struct mips_elf_traverse_got_arg tga;
3941   struct mips_got_info oldg;
3942
3943   oldg = *g;
3944
3945   tga.info = info;
3946   tga.g = g;
3947   tga.value = FALSE;
3948   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &tga);
3949   if (tga.value)
3950     {
3951       *g = oldg;
3952       g->got_entries = htab_create (htab_size (oldg.got_entries),
3953                                     mips_elf_got_entry_hash,
3954                                     mips_elf_got_entry_eq, NULL);
3955       if (!g->got_entries)
3956         return FALSE;
3957
3958       htab_traverse (oldg.got_entries, mips_elf_recreate_got, &tga);
3959       if (!tga.g)
3960         return FALSE;
3961
3962       htab_delete (oldg.got_entries);
3963     }
3964   return TRUE;
3965 }
3966
3967 /* A mips_elf_link_hash_traverse callback for which DATA points to the
3968    link_info structure.  Decide whether the hash entry needs an entry in
3969    the global part of the primary GOT, setting global_got_area accordingly.
3970    Count the number of global symbols that are in the primary GOT only
3971    because they have relocations against them (reloc_only_gotno).  */
3972
3973 static int
3974 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
3975 {
3976   struct bfd_link_info *info;
3977   struct mips_elf_link_hash_table *htab;
3978   struct mips_got_info *g;
3979
3980   info = (struct bfd_link_info *) data;
3981   htab = mips_elf_hash_table (info);
3982   g = htab->got_info;
3983   if (h->global_got_area != GGA_NONE)
3984     {
3985       /* Make a final decision about whether the symbol belongs in the
3986          local or global GOT.  Symbols that bind locally can (and in the
3987          case of forced-local symbols, must) live in the local GOT.
3988          Those that are aren't in the dynamic symbol table must also
3989          live in the local GOT.
3990
3991          Note that the former condition does not always imply the
3992          latter: symbols do not bind locally if they are completely
3993          undefined.  We'll report undefined symbols later if appropriate.  */
3994       if (h->root.dynindx == -1
3995           || (h->got_only_for_calls
3996               ? SYMBOL_CALLS_LOCAL (info, &h->root)
3997               : SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3998         /* The symbol belongs in the local GOT.  We no longer need this
3999            entry if it was only used for relocations; those relocations
4000            will be against the null or section symbol instead of H.  */
4001         h->global_got_area = GGA_NONE;
4002       else if (htab->is_vxworks
4003                && h->got_only_for_calls
4004                && h->root.plt.offset != MINUS_ONE)
4005         /* On VxWorks, calls can refer directly to the .got.plt entry;
4006            they don't need entries in the regular GOT.  .got.plt entries
4007            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4008         h->global_got_area = GGA_NONE;
4009       else if (h->global_got_area == GGA_RELOC_ONLY)
4010         {
4011           g->reloc_only_gotno++;
4012           g->global_gotno++;
4013         }
4014     }
4015   return 1;
4016 }
4017 \f
4018 /* A htab_traverse callback for GOT entries.  Add each one to the GOT
4019    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4020
4021 static int
4022 mips_elf_add_got_entry (void **entryp, void *data)
4023 {
4024   struct mips_got_entry *entry;
4025   struct mips_elf_traverse_got_arg *arg;
4026   void **slot;
4027
4028   entry = (struct mips_got_entry *) *entryp;
4029   arg = (struct mips_elf_traverse_got_arg *) data;
4030   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
4031   if (!slot)
4032     {
4033       arg->g = NULL;
4034       return 0;
4035     }
4036   if (!*slot)
4037     {
4038       *slot = entry;
4039       mips_elf_count_got_entry (arg->info, arg->g, entry);
4040     }
4041   return 1;
4042 }
4043
4044 /* A htab_traverse callback for GOT page entries.  Add each one to the GOT
4045    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4046
4047 static int
4048 mips_elf_add_got_page_entry (void **entryp, void *data)
4049 {
4050   struct mips_got_page_entry *entry;
4051   struct mips_elf_traverse_got_arg *arg;
4052   void **slot;
4053
4054   entry = (struct mips_got_page_entry *) *entryp;
4055   arg = (struct mips_elf_traverse_got_arg *) data;
4056   slot = htab_find_slot (arg->g->got_page_entries, entry, INSERT);
4057   if (!slot)
4058     {
4059       arg->g = NULL;
4060       return 0;
4061     }
4062   if (!*slot)
4063     {
4064       *slot = entry;
4065       arg->g->page_gotno += entry->num_pages;
4066     }
4067   return 1;
4068 }
4069
4070 /* Consider merging FROM, which is ABFD's GOT, into TO.  Return -1 if
4071    this would lead to overflow, 1 if they were merged successfully,
4072    and 0 if a merge failed due to lack of memory.  (These values are chosen
4073    so that nonnegative return values can be returned by a htab_traverse
4074    callback.)  */
4075
4076 static int
4077 mips_elf_merge_got_with (bfd *abfd, struct mips_got_info *from,
4078                          struct mips_got_info *to,
4079                          struct mips_elf_got_per_bfd_arg *arg)
4080 {
4081   struct mips_elf_traverse_got_arg tga;
4082   unsigned int estimate;
4083
4084   /* Work out how many page entries we would need for the combined GOT.  */
4085   estimate = arg->max_pages;
4086   if (estimate >= from->page_gotno + to->page_gotno)
4087     estimate = from->page_gotno + to->page_gotno;
4088
4089   /* And conservatively estimate how many local and TLS entries
4090      would be needed.  */
4091   estimate += from->local_gotno + to->local_gotno;
4092   estimate += from->tls_gotno + to->tls_gotno;
4093
4094   /* If we're merging with the primary got, any TLS relocations will
4095      come after the full set of global entries.  Otherwise estimate those
4096      conservatively as well.  */
4097   if (to == arg->primary && from->tls_gotno + to->tls_gotno)
4098     estimate += arg->global_count;
4099   else
4100     estimate += from->global_gotno + to->global_gotno;
4101
4102   /* Bail out if the combined GOT might be too big.  */
4103   if (estimate > arg->max_count)
4104     return -1;
4105
4106   /* Transfer the bfd's got information from FROM to TO.  */
4107   tga.info = arg->info;
4108   tga.g = to;
4109   htab_traverse (from->got_entries, mips_elf_add_got_entry, &tga);
4110   if (!tga.g)
4111     return 0;
4112
4113   htab_traverse (from->got_page_entries, mips_elf_add_got_page_entry, &tga);
4114   if (!tga.g)
4115     return 0;
4116
4117   mips_elf_replace_bfd_got (abfd, to);
4118   return 1;
4119 }
4120
4121 /* Attempt to merge GOT G, which belongs to ABFD.  Try to use as much
4122    as possible of the primary got, since it doesn't require explicit
4123    dynamic relocations, but don't use bfds that would reference global
4124    symbols out of the addressable range.  Failing the primary got,
4125    attempt to merge with the current got, or finish the current got
4126    and then make make the new got current.  */
4127
4128 static bfd_boolean
4129 mips_elf_merge_got (bfd *abfd, struct mips_got_info *g,
4130                     struct mips_elf_got_per_bfd_arg *arg)
4131 {
4132   unsigned int estimate;
4133   int result;
4134
4135   if (!mips_elf_resolve_final_got_entries (arg->info, g))
4136     return FALSE;
4137
4138   /* Work out the number of page, local and TLS entries.  */
4139   estimate = arg->max_pages;
4140   if (estimate > g->page_gotno)
4141     estimate = g->page_gotno;
4142   estimate += g->local_gotno + g->tls_gotno;
4143
4144   /* We place TLS GOT entries after both locals and globals.  The globals
4145      for the primary GOT may overflow the normal GOT size limit, so be
4146      sure not to merge a GOT which requires TLS with the primary GOT in that
4147      case.  This doesn't affect non-primary GOTs.  */
4148   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4149
4150   if (estimate <= arg->max_count)
4151     {
4152       /* If we don't have a primary GOT, use it as
4153          a starting point for the primary GOT.  */
4154       if (!arg->primary)
4155         {
4156           arg->primary = g;
4157           return TRUE;
4158         }
4159
4160       /* Try merging with the primary GOT.  */
4161       result = mips_elf_merge_got_with (abfd, g, arg->primary, arg);
4162       if (result >= 0)
4163         return result;
4164     }
4165
4166   /* If we can merge with the last-created got, do it.  */
4167   if (arg->current)
4168     {
4169       result = mips_elf_merge_got_with (abfd, g, arg->current, arg);
4170       if (result >= 0)
4171         return result;
4172     }
4173
4174   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4175      fits; if it turns out that it doesn't, we'll get relocation
4176      overflows anyway.  */
4177   g->next = arg->current;
4178   arg->current = g;
4179
4180   return TRUE;
4181 }
4182
4183 /* ENTRYP is a hash table entry for a mips_got_entry.  Set its gotidx
4184    to GOTIDX, duplicating the entry if it has already been assigned
4185    an index in a different GOT.  */
4186
4187 static bfd_boolean
4188 mips_elf_set_gotidx (void **entryp, long gotidx)
4189 {
4190   struct mips_got_entry *entry;
4191
4192   entry = (struct mips_got_entry *) *entryp;
4193   if (entry->gotidx > 0)
4194     {
4195       struct mips_got_entry *new_entry;
4196
4197       new_entry = bfd_alloc (entry->abfd, sizeof (*entry));
4198       if (!new_entry)
4199         return FALSE;
4200
4201       *new_entry = *entry;
4202       *entryp = new_entry;
4203       entry = new_entry;
4204     }
4205   entry->gotidx = gotidx;
4206   return TRUE;
4207 }
4208
4209 /* Set the TLS GOT index for the GOT entry in ENTRYP.  DATA points to a
4210    mips_elf_traverse_got_arg in which DATA->value is the size of one
4211    GOT entry.  Set DATA->g to null on failure.  */
4212
4213 static int
4214 mips_elf_initialize_tls_index (void **entryp, void *data)
4215 {
4216   struct mips_got_entry *entry;
4217   struct mips_elf_traverse_got_arg *arg;
4218
4219   /* We're only interested in TLS symbols.  */
4220   entry = (struct mips_got_entry *) *entryp;
4221   if (entry->tls_type == GOT_TLS_NONE)
4222     return 1;
4223
4224   arg = (struct mips_elf_traverse_got_arg *) data;
4225   if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->tls_assigned_gotno))
4226     {
4227       arg->g = NULL;
4228       return 0;
4229     }
4230
4231   /* Account for the entries we've just allocated.  */
4232   arg->g->tls_assigned_gotno += mips_tls_got_entries (entry->tls_type);
4233   return 1;
4234 }
4235
4236 /* A htab_traverse callback for GOT entries, where DATA points to a
4237    mips_elf_traverse_got_arg.  Set the global_got_area of each global
4238    symbol to DATA->value.  */
4239
4240 static int
4241 mips_elf_set_global_got_area (void **entryp, void *data)
4242 {
4243   struct mips_got_entry *entry;
4244   struct mips_elf_traverse_got_arg *arg;
4245
4246   entry = (struct mips_got_entry *) *entryp;
4247   arg = (struct mips_elf_traverse_got_arg *) data;
4248   if (entry->abfd != NULL
4249       && entry->symndx == -1
4250       && entry->d.h->global_got_area != GGA_NONE)
4251     entry->d.h->global_got_area = arg->value;
4252   return 1;
4253 }
4254
4255 /* A htab_traverse callback for secondary GOT entries, where DATA points
4256    to a mips_elf_traverse_got_arg.  Assign GOT indices to global entries
4257    and record the number of relocations they require.  DATA->value is
4258    the size of one GOT entry.  Set DATA->g to null on failure.  */
4259
4260 static int
4261 mips_elf_set_global_gotidx (void **entryp, void *data)
4262 {
4263   struct mips_got_entry *entry;
4264   struct mips_elf_traverse_got_arg *arg;
4265
4266   entry = (struct mips_got_entry *) *entryp;
4267   arg = (struct mips_elf_traverse_got_arg *) data;
4268   if (entry->abfd != NULL
4269       && entry->symndx == -1
4270       && entry->d.h->global_got_area != GGA_NONE)
4271     {
4272       if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->assigned_gotno))
4273         {
4274           arg->g = NULL;
4275           return 0;
4276         }
4277       arg->g->assigned_gotno += 1;
4278
4279       if (arg->info->shared
4280           || (elf_hash_table (arg->info)->dynamic_sections_created
4281               && entry->d.h->root.def_dynamic
4282               && !entry->d.h->root.def_regular))
4283         arg->g->relocs += 1;
4284     }
4285
4286   return 1;
4287 }
4288
4289 /* A htab_traverse callback for GOT entries for which DATA is the
4290    bfd_link_info.  Forbid any global symbols from having traditional
4291    lazy-binding stubs.  */
4292
4293 static int
4294 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4295 {
4296   struct bfd_link_info *info;
4297   struct mips_elf_link_hash_table *htab;
4298   struct mips_got_entry *entry;
4299
4300   entry = (struct mips_got_entry *) *entryp;
4301   info = (struct bfd_link_info *) data;
4302   htab = mips_elf_hash_table (info);
4303   BFD_ASSERT (htab != NULL);
4304
4305   if (entry->abfd != NULL
4306       && entry->symndx == -1
4307       && entry->d.h->needs_lazy_stub)
4308     {
4309       entry->d.h->needs_lazy_stub = FALSE;
4310       htab->lazy_stub_count--;
4311     }
4312
4313   return 1;
4314 }
4315
4316 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4317    the primary GOT.  */
4318 static bfd_vma
4319 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4320 {
4321   if (!g->next)
4322     return 0;
4323
4324   g = mips_elf_bfd_got (ibfd, FALSE);
4325   if (! g)
4326     return 0;
4327
4328   BFD_ASSERT (g->next);
4329
4330   g = g->next;
4331
4332   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4333     * MIPS_ELF_GOT_SIZE (abfd);
4334 }
4335
4336 /* Turn a single GOT that is too big for 16-bit addressing into
4337    a sequence of GOTs, each one 16-bit addressable.  */
4338
4339 static bfd_boolean
4340 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4341                     asection *got, bfd_size_type pages)
4342 {
4343   struct mips_elf_link_hash_table *htab;
4344   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4345   struct mips_elf_traverse_got_arg tga;
4346   struct mips_got_info *g, *gg;
4347   unsigned int assign, needed_relocs;
4348   bfd *dynobj, *ibfd;
4349
4350   dynobj = elf_hash_table (info)->dynobj;
4351   htab = mips_elf_hash_table (info);
4352   BFD_ASSERT (htab != NULL);
4353
4354   g = htab->got_info;
4355
4356   got_per_bfd_arg.obfd = abfd;
4357   got_per_bfd_arg.info = info;
4358   got_per_bfd_arg.current = NULL;
4359   got_per_bfd_arg.primary = NULL;
4360   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4361                                 / MIPS_ELF_GOT_SIZE (abfd))
4362                                - htab->reserved_gotno);
4363   got_per_bfd_arg.max_pages = pages;
4364   /* The number of globals that will be included in the primary GOT.
4365      See the calls to mips_elf_set_global_got_area below for more
4366      information.  */
4367   got_per_bfd_arg.global_count = g->global_gotno;
4368
4369   /* Try to merge the GOTs of input bfds together, as long as they
4370      don't seem to exceed the maximum GOT size, choosing one of them
4371      to be the primary GOT.  */
4372   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
4373     {
4374       gg = mips_elf_bfd_got (ibfd, FALSE);
4375       if (gg && !mips_elf_merge_got (ibfd, gg, &got_per_bfd_arg))
4376         return FALSE;
4377     }
4378
4379   /* If we do not find any suitable primary GOT, create an empty one.  */
4380   if (got_per_bfd_arg.primary == NULL)
4381     g->next = mips_elf_create_got_info (abfd);
4382   else
4383     g->next = got_per_bfd_arg.primary;
4384   g->next->next = got_per_bfd_arg.current;
4385
4386   /* GG is now the master GOT, and G is the primary GOT.  */
4387   gg = g;
4388   g = g->next;
4389
4390   /* Map the output bfd to the primary got.  That's what we're going
4391      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4392      didn't mark in check_relocs, and we want a quick way to find it.
4393      We can't just use gg->next because we're going to reverse the
4394      list.  */
4395   mips_elf_replace_bfd_got (abfd, g);
4396
4397   /* Every symbol that is referenced in a dynamic relocation must be
4398      present in the primary GOT, so arrange for them to appear after
4399      those that are actually referenced.  */
4400   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4401   g->global_gotno = gg->global_gotno;
4402
4403   tga.info = info;
4404   tga.value = GGA_RELOC_ONLY;
4405   htab_traverse (gg->got_entries, mips_elf_set_global_got_area, &tga);
4406   tga.value = GGA_NORMAL;
4407   htab_traverse (g->got_entries, mips_elf_set_global_got_area, &tga);
4408
4409   /* Now go through the GOTs assigning them offset ranges.
4410      [assigned_gotno, local_gotno[ will be set to the range of local
4411      entries in each GOT.  We can then compute the end of a GOT by
4412      adding local_gotno to global_gotno.  We reverse the list and make
4413      it circular since then we'll be able to quickly compute the
4414      beginning of a GOT, by computing the end of its predecessor.  To
4415      avoid special cases for the primary GOT, while still preserving
4416      assertions that are valid for both single- and multi-got links,
4417      we arrange for the main got struct to have the right number of
4418      global entries, but set its local_gotno such that the initial
4419      offset of the primary GOT is zero.  Remember that the primary GOT
4420      will become the last item in the circular linked list, so it
4421      points back to the master GOT.  */
4422   gg->local_gotno = -g->global_gotno;
4423   gg->global_gotno = g->global_gotno;
4424   gg->tls_gotno = 0;
4425   assign = 0;
4426   gg->next = gg;
4427
4428   do
4429     {
4430       struct mips_got_info *gn;
4431
4432       assign += htab->reserved_gotno;
4433       g->assigned_gotno = assign;
4434       g->local_gotno += assign;
4435       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4436       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4437
4438       /* Take g out of the direct list, and push it onto the reversed
4439          list that gg points to.  g->next is guaranteed to be nonnull after
4440          this operation, as required by mips_elf_initialize_tls_index. */
4441       gn = g->next;
4442       g->next = gg->next;
4443       gg->next = g;
4444
4445       /* Set up any TLS entries.  We always place the TLS entries after
4446          all non-TLS entries.  */
4447       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4448       tga.g = g;
4449       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4450       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
4451       if (!tga.g)
4452         return FALSE;
4453       BFD_ASSERT (g->tls_assigned_gotno == assign);
4454
4455       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4456       g = gn;
4457
4458       /* Forbid global symbols in every non-primary GOT from having
4459          lazy-binding stubs.  */
4460       if (g)
4461         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4462     }
4463   while (g);
4464
4465   got->size = assign * MIPS_ELF_GOT_SIZE (abfd);
4466
4467   needed_relocs = 0;
4468   for (g = gg->next; g && g->next != gg; g = g->next)
4469     {
4470       unsigned int save_assign;
4471
4472       /* Assign offsets to global GOT entries and count how many
4473          relocations they need.  */
4474       save_assign = g->assigned_gotno;
4475       g->assigned_gotno = g->local_gotno;
4476       tga.info = info;
4477       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4478       tga.g = g;
4479       htab_traverse (g->got_entries, mips_elf_set_global_gotidx, &tga);
4480       if (!tga.g)
4481         return FALSE;
4482       BFD_ASSERT (g->assigned_gotno == g->local_gotno + g->global_gotno);
4483       g->assigned_gotno = save_assign;
4484
4485       if (info->shared)
4486         {
4487           g->relocs += g->local_gotno - g->assigned_gotno;
4488           BFD_ASSERT (g->assigned_gotno == g->next->local_gotno
4489                       + g->next->global_gotno
4490                       + g->next->tls_gotno
4491                       + htab->reserved_gotno);
4492         }
4493       needed_relocs += g->relocs;
4494     }
4495   needed_relocs += g->relocs;
4496
4497   if (needed_relocs)
4498     mips_elf_allocate_dynamic_relocations (dynobj, info,
4499                                            needed_relocs);
4500
4501   return TRUE;
4502 }
4503
4504 \f
4505 /* Returns the first relocation of type r_type found, beginning with
4506    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4507
4508 static const Elf_Internal_Rela *
4509 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4510                           const Elf_Internal_Rela *relocation,
4511                           const Elf_Internal_Rela *relend)
4512 {
4513   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4514
4515   while (relocation < relend)
4516     {
4517       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4518           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4519         return relocation;
4520
4521       ++relocation;
4522     }
4523
4524   /* We didn't find it.  */
4525   return NULL;
4526 }
4527
4528 /* Return whether an input relocation is against a local symbol.  */
4529
4530 static bfd_boolean
4531 mips_elf_local_relocation_p (bfd *input_bfd,
4532                              const Elf_Internal_Rela *relocation,
4533                              asection **local_sections)
4534 {
4535   unsigned long r_symndx;
4536   Elf_Internal_Shdr *symtab_hdr;
4537   size_t extsymoff;
4538
4539   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4540   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4541   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
4542
4543   if (r_symndx < extsymoff)
4544     return TRUE;
4545   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
4546     return TRUE;
4547
4548   return FALSE;
4549 }
4550 \f
4551 /* Sign-extend VALUE, which has the indicated number of BITS.  */
4552
4553 bfd_vma
4554 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
4555 {
4556   if (value & ((bfd_vma) 1 << (bits - 1)))
4557     /* VALUE is negative.  */
4558     value |= ((bfd_vma) - 1) << bits;
4559
4560   return value;
4561 }
4562
4563 /* Return non-zero if the indicated VALUE has overflowed the maximum
4564    range expressible by a signed number with the indicated number of
4565    BITS.  */
4566
4567 static bfd_boolean
4568 mips_elf_overflow_p (bfd_vma value, int bits)
4569 {
4570   bfd_signed_vma svalue = (bfd_signed_vma) value;
4571
4572   if (svalue > (1 << (bits - 1)) - 1)
4573     /* The value is too big.  */
4574     return TRUE;
4575   else if (svalue < -(1 << (bits - 1)))
4576     /* The value is too small.  */
4577     return TRUE;
4578
4579   /* All is well.  */
4580   return FALSE;
4581 }
4582
4583 /* Calculate the %high function.  */
4584
4585 static bfd_vma
4586 mips_elf_high (bfd_vma value)
4587 {
4588   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
4589 }
4590
4591 /* Calculate the %higher function.  */
4592
4593 static bfd_vma
4594 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
4595 {
4596 #ifdef BFD64
4597   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
4598 #else
4599   abort ();
4600   return MINUS_ONE;
4601 #endif
4602 }
4603
4604 /* Calculate the %highest function.  */
4605
4606 static bfd_vma
4607 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
4608 {
4609 #ifdef BFD64
4610   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
4611 #else
4612   abort ();
4613   return MINUS_ONE;
4614 #endif
4615 }
4616 \f
4617 /* Create the .compact_rel section.  */
4618
4619 static bfd_boolean
4620 mips_elf_create_compact_rel_section
4621   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
4622 {
4623   flagword flags;
4624   register asection *s;
4625
4626   if (bfd_get_linker_section (abfd, ".compact_rel") == NULL)
4627     {
4628       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
4629                | SEC_READONLY);
4630
4631       s = bfd_make_section_anyway_with_flags (abfd, ".compact_rel", flags);
4632       if (s == NULL
4633           || ! bfd_set_section_alignment (abfd, s,
4634                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
4635         return FALSE;
4636
4637       s->size = sizeof (Elf32_External_compact_rel);
4638     }
4639
4640   return TRUE;
4641 }
4642
4643 /* Create the .got section to hold the global offset table.  */
4644
4645 static bfd_boolean
4646 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
4647 {
4648   flagword flags;
4649   register asection *s;
4650   struct elf_link_hash_entry *h;
4651   struct bfd_link_hash_entry *bh;
4652   struct mips_elf_link_hash_table *htab;
4653
4654   htab = mips_elf_hash_table (info);
4655   BFD_ASSERT (htab != NULL);
4656
4657   /* This function may be called more than once.  */
4658   if (htab->sgot)
4659     return TRUE;
4660
4661   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
4662            | SEC_LINKER_CREATED);
4663
4664   /* We have to use an alignment of 2**4 here because this is hardcoded
4665      in the function stub generation and in the linker script.  */
4666   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
4667   if (s == NULL
4668       || ! bfd_set_section_alignment (abfd, s, 4))
4669     return FALSE;
4670   htab->sgot = s;
4671
4672   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
4673      linker script because we don't want to define the symbol if we
4674      are not creating a global offset table.  */
4675   bh = NULL;
4676   if (! (_bfd_generic_link_add_one_symbol
4677          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
4678           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
4679     return FALSE;
4680
4681   h = (struct elf_link_hash_entry *) bh;
4682   h->non_elf = 0;
4683   h->def_regular = 1;
4684   h->type = STT_OBJECT;
4685   elf_hash_table (info)->hgot = h;
4686
4687   if (info->shared
4688       && ! bfd_elf_link_record_dynamic_symbol (info, h))
4689     return FALSE;
4690
4691   htab->got_info = mips_elf_create_got_info (abfd);
4692   mips_elf_section_data (s)->elf.this_hdr.sh_flags
4693     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
4694
4695   /* We also need a .got.plt section when generating PLTs.  */
4696   s = bfd_make_section_anyway_with_flags (abfd, ".got.plt",
4697                                           SEC_ALLOC | SEC_LOAD
4698                                           | SEC_HAS_CONTENTS
4699                                           | SEC_IN_MEMORY
4700                                           | SEC_LINKER_CREATED);
4701   if (s == NULL)
4702     return FALSE;
4703   htab->sgotplt = s;
4704
4705   return TRUE;
4706 }
4707 \f
4708 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
4709    __GOTT_INDEX__ symbols.  These symbols are only special for
4710    shared objects; they are not used in executables.  */
4711
4712 static bfd_boolean
4713 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
4714 {
4715   return (mips_elf_hash_table (info)->is_vxworks
4716           && info->shared
4717           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
4718               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
4719 }
4720
4721 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
4722    require an la25 stub.  See also mips_elf_local_pic_function_p,
4723    which determines whether the destination function ever requires a
4724    stub.  */
4725
4726 static bfd_boolean
4727 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type,
4728                                      bfd_boolean target_is_16_bit_code_p)
4729 {
4730   /* We specifically ignore branches and jumps from EF_PIC objects,
4731      where the onus is on the compiler or programmer to perform any
4732      necessary initialization of $25.  Sometimes such initialization
4733      is unnecessary; for example, -mno-shared functions do not use
4734      the incoming value of $25, and may therefore be called directly.  */
4735   if (PIC_OBJECT_P (input_bfd))
4736     return FALSE;
4737
4738   switch (r_type)
4739     {
4740     case R_MIPS_26:
4741     case R_MIPS_PC16:
4742     case R_MICROMIPS_26_S1:
4743     case R_MICROMIPS_PC7_S1:
4744     case R_MICROMIPS_PC10_S1:
4745     case R_MICROMIPS_PC16_S1:
4746     case R_MICROMIPS_PC23_S2:
4747       return TRUE;
4748
4749     case R_MIPS16_26:
4750       return !target_is_16_bit_code_p;
4751
4752     default:
4753       return FALSE;
4754     }
4755 }
4756 \f
4757 /* Calculate the value produced by the RELOCATION (which comes from
4758    the INPUT_BFD).  The ADDEND is the addend to use for this
4759    RELOCATION; RELOCATION->R_ADDEND is ignored.
4760
4761    The result of the relocation calculation is stored in VALUEP.
4762    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
4763    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
4764
4765    This function returns bfd_reloc_continue if the caller need take no
4766    further action regarding this relocation, bfd_reloc_notsupported if
4767    something goes dramatically wrong, bfd_reloc_overflow if an
4768    overflow occurs, and bfd_reloc_ok to indicate success.  */
4769
4770 static bfd_reloc_status_type
4771 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
4772                                asection *input_section,
4773                                struct bfd_link_info *info,
4774                                const Elf_Internal_Rela *relocation,
4775                                bfd_vma addend, reloc_howto_type *howto,
4776                                Elf_Internal_Sym *local_syms,
4777                                asection **local_sections, bfd_vma *valuep,
4778                                const char **namep,
4779                                bfd_boolean *cross_mode_jump_p,
4780                                bfd_boolean save_addend)
4781 {
4782   /* The eventual value we will return.  */
4783   bfd_vma value;
4784   /* The address of the symbol against which the relocation is
4785      occurring.  */
4786   bfd_vma symbol = 0;
4787   /* The final GP value to be used for the relocatable, executable, or
4788      shared object file being produced.  */
4789   bfd_vma gp;
4790   /* The place (section offset or address) of the storage unit being
4791      relocated.  */
4792   bfd_vma p;
4793   /* The value of GP used to create the relocatable object.  */
4794   bfd_vma gp0;
4795   /* The offset into the global offset table at which the address of
4796      the relocation entry symbol, adjusted by the addend, resides
4797      during execution.  */
4798   bfd_vma g = MINUS_ONE;
4799   /* The section in which the symbol referenced by the relocation is
4800      located.  */
4801   asection *sec = NULL;
4802   struct mips_elf_link_hash_entry *h = NULL;
4803   /* TRUE if the symbol referred to by this relocation is a local
4804      symbol.  */
4805   bfd_boolean local_p, was_local_p;
4806   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
4807   bfd_boolean gp_disp_p = FALSE;
4808   /* TRUE if the symbol referred to by this relocation is
4809      "__gnu_local_gp".  */
4810   bfd_boolean gnu_local_gp_p = FALSE;
4811   Elf_Internal_Shdr *symtab_hdr;
4812   size_t extsymoff;
4813   unsigned long r_symndx;
4814   int r_type;
4815   /* TRUE if overflow occurred during the calculation of the
4816      relocation value.  */
4817   bfd_boolean overflowed_p;
4818   /* TRUE if this relocation refers to a MIPS16 function.  */
4819   bfd_boolean target_is_16_bit_code_p = FALSE;
4820   bfd_boolean target_is_micromips_code_p = FALSE;
4821   struct mips_elf_link_hash_table *htab;
4822   bfd *dynobj;
4823
4824   dynobj = elf_hash_table (info)->dynobj;
4825   htab = mips_elf_hash_table (info);
4826   BFD_ASSERT (htab != NULL);
4827
4828   /* Parse the relocation.  */
4829   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4830   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
4831   p = (input_section->output_section->vma
4832        + input_section->output_offset
4833        + relocation->r_offset);
4834
4835   /* Assume that there will be no overflow.  */
4836   overflowed_p = FALSE;
4837
4838   /* Figure out whether or not the symbol is local, and get the offset
4839      used in the array of hash table entries.  */
4840   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4841   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
4842                                          local_sections);
4843   was_local_p = local_p;
4844   if (! elf_bad_symtab (input_bfd))
4845     extsymoff = symtab_hdr->sh_info;
4846   else
4847     {
4848       /* The symbol table does not follow the rule that local symbols
4849          must come before globals.  */
4850       extsymoff = 0;
4851     }
4852
4853   /* Figure out the value of the symbol.  */
4854   if (local_p)
4855     {
4856       Elf_Internal_Sym *sym;
4857
4858       sym = local_syms + r_symndx;
4859       sec = local_sections[r_symndx];
4860
4861       symbol = sec->output_section->vma + sec->output_offset;
4862       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION
4863           || (sec->flags & SEC_MERGE))
4864         symbol += sym->st_value;
4865       if ((sec->flags & SEC_MERGE)
4866           && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
4867         {
4868           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
4869           addend -= symbol;
4870           addend += sec->output_section->vma + sec->output_offset;
4871         }
4872
4873       /* MIPS16/microMIPS text labels should be treated as odd.  */
4874       if (ELF_ST_IS_COMPRESSED (sym->st_other))
4875         ++symbol;
4876
4877       /* Record the name of this symbol, for our caller.  */
4878       *namep = bfd_elf_string_from_elf_section (input_bfd,
4879                                                 symtab_hdr->sh_link,
4880                                                 sym->st_name);
4881       if (*namep == '\0')
4882         *namep = bfd_section_name (input_bfd, sec);
4883
4884       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
4885       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
4886     }
4887   else
4888     {
4889       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
4890
4891       /* For global symbols we look up the symbol in the hash-table.  */
4892       h = ((struct mips_elf_link_hash_entry *)
4893            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
4894       /* Find the real hash-table entry for this symbol.  */
4895       while (h->root.root.type == bfd_link_hash_indirect
4896              || h->root.root.type == bfd_link_hash_warning)
4897         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
4898
4899       /* Record the name of this symbol, for our caller.  */
4900       *namep = h->root.root.root.string;
4901
4902       /* See if this is the special _gp_disp symbol.  Note that such a
4903          symbol must always be a global symbol.  */
4904       if (strcmp (*namep, "_gp_disp") == 0
4905           && ! NEWABI_P (input_bfd))
4906         {
4907           /* Relocations against _gp_disp are permitted only with
4908              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
4909           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
4910             return bfd_reloc_notsupported;
4911
4912           gp_disp_p = TRUE;
4913         }
4914       /* See if this is the special _gp symbol.  Note that such a
4915          symbol must always be a global symbol.  */
4916       else if (strcmp (*namep, "__gnu_local_gp") == 0)
4917         gnu_local_gp_p = TRUE;
4918
4919
4920       /* If this symbol is defined, calculate its address.  Note that
4921          _gp_disp is a magic symbol, always implicitly defined by the
4922          linker, so it's inappropriate to check to see whether or not
4923          its defined.  */
4924       else if ((h->root.root.type == bfd_link_hash_defined
4925                 || h->root.root.type == bfd_link_hash_defweak)
4926                && h->root.root.u.def.section)
4927         {
4928           sec = h->root.root.u.def.section;
4929           if (sec->output_section)
4930             symbol = (h->root.root.u.def.value
4931                       + sec->output_section->vma
4932                       + sec->output_offset);
4933           else
4934             symbol = h->root.root.u.def.value;
4935         }
4936       else if (h->root.root.type == bfd_link_hash_undefweak)
4937         /* We allow relocations against undefined weak symbols, giving
4938            it the value zero, so that you can undefined weak functions
4939            and check to see if they exist by looking at their
4940            addresses.  */
4941         symbol = 0;
4942       else if (info->unresolved_syms_in_objects == RM_IGNORE
4943                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
4944         symbol = 0;
4945       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
4946                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
4947         {
4948           /* If this is a dynamic link, we should have created a
4949              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
4950              in in _bfd_mips_elf_create_dynamic_sections.
4951              Otherwise, we should define the symbol with a value of 0.
4952              FIXME: It should probably get into the symbol table
4953              somehow as well.  */
4954           BFD_ASSERT (! info->shared);
4955           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
4956           symbol = 0;
4957         }
4958       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
4959         {
4960           /* This is an optional symbol - an Irix specific extension to the
4961              ELF spec.  Ignore it for now.
4962              XXX - FIXME - there is more to the spec for OPTIONAL symbols
4963              than simply ignoring them, but we do not handle this for now.
4964              For information see the "64-bit ELF Object File Specification"
4965              which is available from here:
4966              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
4967           symbol = 0;
4968         }
4969       else if ((*info->callbacks->undefined_symbol)
4970                (info, h->root.root.root.string, input_bfd,
4971                 input_section, relocation->r_offset,
4972                 (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
4973                  || ELF_ST_VISIBILITY (h->root.other)))
4974         {
4975           return bfd_reloc_undefined;
4976         }
4977       else
4978         {
4979           return bfd_reloc_notsupported;
4980         }
4981
4982       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
4983       /* If the output section is the PLT section,
4984          then the target is not microMIPS.  */
4985       target_is_micromips_code_p = (htab->splt != sec
4986                                     && ELF_ST_IS_MICROMIPS (h->root.other));
4987     }
4988
4989   /* If this is a reference to a 16-bit function with a stub, we need
4990      to redirect the relocation to the stub unless:
4991
4992      (a) the relocation is for a MIPS16 JAL;
4993
4994      (b) the relocation is for a MIPS16 PIC call, and there are no
4995          non-MIPS16 uses of the GOT slot; or
4996
4997      (c) the section allows direct references to MIPS16 functions.  */
4998   if (r_type != R_MIPS16_26
4999       && !info->relocatable
5000       && ((h != NULL
5001            && h->fn_stub != NULL
5002            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5003           || (local_p
5004               && elf_tdata (input_bfd)->local_stubs != NULL
5005               && elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5006       && !section_allows_mips16_refs_p (input_section))
5007     {
5008       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5009          have already noticed that we were going to need the
5010          stub.  */
5011       if (local_p)
5012         {
5013           sec = elf_tdata (input_bfd)->local_stubs[r_symndx];
5014           value = 0;
5015         }
5016       else
5017         {
5018           BFD_ASSERT (h->need_fn_stub);
5019           if (h->la25_stub)
5020             {
5021               /* If a LA25 header for the stub itself exists, point to the
5022                  prepended LUI/ADDIU sequence.  */
5023               sec = h->la25_stub->stub_section;
5024               value = h->la25_stub->offset;
5025             }
5026           else
5027             {
5028               sec = h->fn_stub;
5029               value = 0;
5030             }
5031         }
5032
5033       symbol = sec->output_section->vma + sec->output_offset + value;
5034       /* The target is 16-bit, but the stub isn't.  */
5035       target_is_16_bit_code_p = FALSE;
5036     }
5037   /* If this is a 16-bit call to a 32- or 64-bit function with a stub, we
5038      need to redirect the call to the stub.  Note that we specifically
5039      exclude R_MIPS16_CALL16 from this behavior; indirect calls should
5040      use an indirect stub instead.  */
5041   else if (r_type == R_MIPS16_26 && !info->relocatable
5042            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5043                || (local_p
5044                    && elf_tdata (input_bfd)->local_call_stubs != NULL
5045                    && elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5046            && !target_is_16_bit_code_p)
5047     {
5048       if (local_p)
5049         sec = elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5050       else
5051         {
5052           /* If both call_stub and call_fp_stub are defined, we can figure
5053              out which one to use by checking which one appears in the input
5054              file.  */
5055           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5056             {
5057               asection *o;
5058
5059               sec = NULL;
5060               for (o = input_bfd->sections; o != NULL; o = o->next)
5061                 {
5062                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5063                     {
5064                       sec = h->call_fp_stub;
5065                       break;
5066                     }
5067                 }
5068               if (sec == NULL)
5069                 sec = h->call_stub;
5070             }
5071           else if (h->call_stub != NULL)
5072             sec = h->call_stub;
5073           else
5074             sec = h->call_fp_stub;
5075         }
5076
5077       BFD_ASSERT (sec->size > 0);
5078       symbol = sec->output_section->vma + sec->output_offset;
5079     }
5080   /* If this is a direct call to a PIC function, redirect to the
5081      non-PIC stub.  */
5082   else if (h != NULL && h->la25_stub
5083            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type,
5084                                                    target_is_16_bit_code_p))
5085     symbol = (h->la25_stub->stub_section->output_section->vma
5086               + h->la25_stub->stub_section->output_offset
5087               + h->la25_stub->offset);
5088
5089   /* Make sure MIPS16 and microMIPS are not used together.  */
5090   if ((r_type == R_MIPS16_26 && target_is_micromips_code_p)
5091       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5092    {
5093       (*_bfd_error_handler)
5094         (_("MIPS16 and microMIPS functions cannot call each other"));
5095       return bfd_reloc_notsupported;
5096    }
5097
5098   /* Calls from 16-bit code to 32-bit code and vice versa require the
5099      mode change.  However, we can ignore calls to undefined weak symbols,
5100      which should never be executed at runtime.  This exception is important
5101      because the assembly writer may have "known" that any definition of the
5102      symbol would be 16-bit code, and that direct jumps were therefore
5103      acceptable.  */
5104   *cross_mode_jump_p = (!info->relocatable
5105                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5106                         && ((r_type == R_MIPS16_26 && !target_is_16_bit_code_p)
5107                             || (r_type == R_MICROMIPS_26_S1
5108                                 && !target_is_micromips_code_p)
5109                             || ((r_type == R_MIPS_26 || r_type == R_MIPS_JALR)
5110                                 && (target_is_16_bit_code_p
5111                                     || target_is_micromips_code_p))));
5112
5113   local_p = (h == NULL
5114              || (h->got_only_for_calls
5115                  ? SYMBOL_CALLS_LOCAL (info, &h->root)
5116                  : SYMBOL_REFERENCES_LOCAL (info, &h->root)));
5117
5118   gp0 = _bfd_get_gp_value (input_bfd);
5119   gp = _bfd_get_gp_value (abfd);
5120   if (htab->got_info)
5121     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5122
5123   if (gnu_local_gp_p)
5124     symbol = gp;
5125
5126   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5127      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5128      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5129   if (got_page_reloc_p (r_type) && !local_p)
5130     {
5131       r_type = (micromips_reloc_p (r_type)
5132                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5133       addend = 0;
5134     }
5135
5136   /* If we haven't already determined the GOT offset, and we're going
5137      to need it, get it now.  */
5138   switch (r_type)
5139     {
5140     case R_MIPS16_CALL16:
5141     case R_MIPS16_GOT16:
5142     case R_MIPS_CALL16:
5143     case R_MIPS_GOT16:
5144     case R_MIPS_GOT_DISP:
5145     case R_MIPS_GOT_HI16:
5146     case R_MIPS_CALL_HI16:
5147     case R_MIPS_GOT_LO16:
5148     case R_MIPS_CALL_LO16:
5149     case R_MICROMIPS_CALL16:
5150     case R_MICROMIPS_GOT16:
5151     case R_MICROMIPS_GOT_DISP:
5152     case R_MICROMIPS_GOT_HI16:
5153     case R_MICROMIPS_CALL_HI16:
5154     case R_MICROMIPS_GOT_LO16:
5155     case R_MICROMIPS_CALL_LO16:
5156     case R_MIPS_TLS_GD:
5157     case R_MIPS_TLS_GOTTPREL:
5158     case R_MIPS_TLS_LDM:
5159     case R_MIPS16_TLS_GD:
5160     case R_MIPS16_TLS_GOTTPREL:
5161     case R_MIPS16_TLS_LDM:
5162     case R_MICROMIPS_TLS_GD:
5163     case R_MICROMIPS_TLS_GOTTPREL:
5164     case R_MICROMIPS_TLS_LDM:
5165       /* Find the index into the GOT where this value is located.  */
5166       if (tls_ldm_reloc_p (r_type))
5167         {
5168           g = mips_elf_local_got_index (abfd, input_bfd, info,
5169                                         0, 0, NULL, r_type);
5170           if (g == MINUS_ONE)
5171             return bfd_reloc_outofrange;
5172         }
5173       else if (!local_p)
5174         {
5175           /* On VxWorks, CALL relocations should refer to the .got.plt
5176              entry, which is initialized to point at the PLT stub.  */
5177           if (htab->is_vxworks
5178               && (call_hi16_reloc_p (r_type)
5179                   || call_lo16_reloc_p (r_type)
5180                   || call16_reloc_p (r_type)))
5181             {
5182               BFD_ASSERT (addend == 0);
5183               BFD_ASSERT (h->root.needs_plt);
5184               g = mips_elf_gotplt_index (info, &h->root);
5185             }
5186           else
5187             {
5188               BFD_ASSERT (addend == 0);
5189               g = mips_elf_global_got_index (abfd, info, input_bfd,
5190                                              &h->root, r_type);
5191               if (!TLS_RELOC_P (r_type)
5192                   && !elf_hash_table (info)->dynamic_sections_created)
5193                 /* This is a static link.  We must initialize the GOT entry.  */
5194                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->sgot->contents + g);
5195             }
5196         }
5197       else if (!htab->is_vxworks
5198                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5199         /* The calculation below does not involve "g".  */
5200         break;
5201       else
5202         {
5203           g = mips_elf_local_got_index (abfd, input_bfd, info,
5204                                         symbol + addend, r_symndx, h, r_type);
5205           if (g == MINUS_ONE)
5206             return bfd_reloc_outofrange;
5207         }
5208
5209       /* Convert GOT indices to actual offsets.  */
5210       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5211       break;
5212     }
5213
5214   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5215      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5216   if (h != NULL && is_gott_symbol (info, &h->root))
5217     {
5218       Elf_Internal_Rela outrel;
5219       bfd_byte *loc;
5220       asection *s;
5221
5222       s = mips_elf_rel_dyn_section (info, FALSE);
5223       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5224
5225       outrel.r_offset = (input_section->output_section->vma
5226                          + input_section->output_offset
5227                          + relocation->r_offset);
5228       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5229       outrel.r_addend = addend;
5230       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5231
5232       /* If we've written this relocation for a readonly section,
5233          we need to set DF_TEXTREL again, so that we do not delete the
5234          DT_TEXTREL tag.  */
5235       if (MIPS_ELF_READONLY_SECTION (input_section))
5236         info->flags |= DF_TEXTREL;
5237
5238       *valuep = 0;
5239       return bfd_reloc_ok;
5240     }
5241
5242   /* Figure out what kind of relocation is being performed.  */
5243   switch (r_type)
5244     {
5245     case R_MIPS_NONE:
5246       return bfd_reloc_continue;
5247
5248     case R_MIPS_16:
5249       value = symbol + _bfd_mips_elf_sign_extend (addend, 16);
5250       overflowed_p = mips_elf_overflow_p (value, 16);
5251       break;
5252
5253     case R_MIPS_32:
5254     case R_MIPS_REL32:
5255     case R_MIPS_64:
5256       if ((info->shared
5257            || (htab->root.dynamic_sections_created
5258                && h != NULL
5259                && h->root.def_dynamic
5260                && !h->root.def_regular
5261                && !h->has_static_relocs))
5262           && r_symndx != STN_UNDEF
5263           && (h == NULL
5264               || h->root.root.type != bfd_link_hash_undefweak
5265               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5266           && (input_section->flags & SEC_ALLOC) != 0)
5267         {
5268           /* If we're creating a shared library, then we can't know
5269              where the symbol will end up.  So, we create a relocation
5270              record in the output, and leave the job up to the dynamic
5271              linker.  We must do the same for executable references to
5272              shared library symbols, unless we've decided to use copy
5273              relocs or PLTs instead.  */
5274           value = addend;
5275           if (!mips_elf_create_dynamic_relocation (abfd,
5276                                                    info,
5277                                                    relocation,
5278                                                    h,
5279                                                    sec,
5280                                                    symbol,
5281                                                    &value,
5282                                                    input_section))
5283             return bfd_reloc_undefined;
5284         }
5285       else
5286         {
5287           if (r_type != R_MIPS_REL32)
5288             value = symbol + addend;
5289           else
5290             value = addend;
5291         }
5292       value &= howto->dst_mask;
5293       break;
5294
5295     case R_MIPS_PC32:
5296       value = symbol + addend - p;
5297       value &= howto->dst_mask;
5298       break;
5299
5300     case R_MIPS16_26:
5301       /* The calculation for R_MIPS16_26 is just the same as for an
5302          R_MIPS_26.  It's only the storage of the relocated field into
5303          the output file that's different.  That's handled in
5304          mips_elf_perform_relocation.  So, we just fall through to the
5305          R_MIPS_26 case here.  */
5306     case R_MIPS_26:
5307     case R_MICROMIPS_26_S1:
5308       {
5309         unsigned int shift;
5310
5311         /* Make sure the target of JALX is word-aligned.  Bit 0 must be
5312            the correct ISA mode selector and bit 1 must be 0.  */
5313         if (*cross_mode_jump_p && (symbol & 3) != (r_type == R_MIPS_26))
5314           return bfd_reloc_outofrange;
5315
5316         /* Shift is 2, unusually, for microMIPS JALX.  */
5317         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5318
5319         if (was_local_p)
5320           value = addend | ((p + 4) & (0xfc000000 << shift));
5321         else
5322           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5323         value = (value + symbol) >> shift;
5324         if (!was_local_p && h->root.root.type != bfd_link_hash_undefweak)
5325           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5326         value &= howto->dst_mask;
5327       }
5328       break;
5329
5330     case R_MIPS_TLS_DTPREL_HI16:
5331     case R_MIPS16_TLS_DTPREL_HI16:
5332     case R_MICROMIPS_TLS_DTPREL_HI16:
5333       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5334                & howto->dst_mask);
5335       break;
5336
5337     case R_MIPS_TLS_DTPREL_LO16:
5338     case R_MIPS_TLS_DTPREL32:
5339     case R_MIPS_TLS_DTPREL64:
5340     case R_MIPS16_TLS_DTPREL_LO16:
5341     case R_MICROMIPS_TLS_DTPREL_LO16:
5342       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5343       break;
5344
5345     case R_MIPS_TLS_TPREL_HI16:
5346     case R_MIPS16_TLS_TPREL_HI16:
5347     case R_MICROMIPS_TLS_TPREL_HI16:
5348       value = (mips_elf_high (addend + symbol - tprel_base (info))
5349                & howto->dst_mask);
5350       break;
5351
5352     case R_MIPS_TLS_TPREL_LO16:
5353     case R_MIPS_TLS_TPREL32:
5354     case R_MIPS_TLS_TPREL64:
5355     case R_MIPS16_TLS_TPREL_LO16:
5356     case R_MICROMIPS_TLS_TPREL_LO16:
5357       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5358       break;
5359
5360     case R_MIPS_HI16:
5361     case R_MIPS16_HI16:
5362     case R_MICROMIPS_HI16:
5363       if (!gp_disp_p)
5364         {
5365           value = mips_elf_high (addend + symbol);
5366           value &= howto->dst_mask;
5367         }
5368       else
5369         {
5370           /* For MIPS16 ABI code we generate this sequence
5371                 0: li      $v0,%hi(_gp_disp)
5372                 4: addiupc $v1,%lo(_gp_disp)
5373                 8: sll     $v0,16
5374                12: addu    $v0,$v1
5375                14: move    $gp,$v0
5376              So the offsets of hi and lo relocs are the same, but the
5377              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5378              ADDIUPC clears the low two bits of the instruction address,
5379              so the base is ($t9 + 4) & ~3.  */
5380           if (r_type == R_MIPS16_HI16)
5381             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5382           /* The microMIPS .cpload sequence uses the same assembly
5383              instructions as the traditional psABI version, but the
5384              incoming $t9 has the low bit set.  */
5385           else if (r_type == R_MICROMIPS_HI16)
5386             value = mips_elf_high (addend + gp - p - 1);
5387           else
5388             value = mips_elf_high (addend + gp - p);
5389           overflowed_p = mips_elf_overflow_p (value, 16);
5390         }
5391       break;
5392
5393     case R_MIPS_LO16:
5394     case R_MIPS16_LO16:
5395     case R_MICROMIPS_LO16:
5396     case R_MICROMIPS_HI0_LO16:
5397       if (!gp_disp_p)
5398         value = (symbol + addend) & howto->dst_mask;
5399       else
5400         {
5401           /* See the comment for R_MIPS16_HI16 above for the reason
5402              for this conditional.  */
5403           if (r_type == R_MIPS16_LO16)
5404             value = addend + gp - (p & ~(bfd_vma) 0x3);
5405           else if (r_type == R_MICROMIPS_LO16
5406                    || r_type == R_MICROMIPS_HI0_LO16)
5407             value = addend + gp - p + 3;
5408           else
5409             value = addend + gp - p + 4;
5410           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5411              for overflow.  But, on, say, IRIX5, relocations against
5412              _gp_disp are normally generated from the .cpload
5413              pseudo-op.  It generates code that normally looks like
5414              this:
5415
5416                lui    $gp,%hi(_gp_disp)
5417                addiu  $gp,$gp,%lo(_gp_disp)
5418                addu   $gp,$gp,$t9
5419
5420              Here $t9 holds the address of the function being called,
5421              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5422              relocation can easily overflow in this situation, but the
5423              R_MIPS_HI16 relocation will handle the overflow.
5424              Therefore, we consider this a bug in the MIPS ABI, and do
5425              not check for overflow here.  */
5426         }
5427       break;
5428
5429     case R_MIPS_LITERAL:
5430     case R_MICROMIPS_LITERAL:
5431       /* Because we don't merge literal sections, we can handle this
5432          just like R_MIPS_GPREL16.  In the long run, we should merge
5433          shared literals, and then we will need to additional work
5434          here.  */
5435
5436       /* Fall through.  */
5437
5438     case R_MIPS16_GPREL:
5439       /* The R_MIPS16_GPREL performs the same calculation as
5440          R_MIPS_GPREL16, but stores the relocated bits in a different
5441          order.  We don't need to do anything special here; the
5442          differences are handled in mips_elf_perform_relocation.  */
5443     case R_MIPS_GPREL16:
5444     case R_MICROMIPS_GPREL7_S2:
5445     case R_MICROMIPS_GPREL16:
5446       /* Only sign-extend the addend if it was extracted from the
5447          instruction.  If the addend was separate, leave it alone,
5448          otherwise we may lose significant bits.  */
5449       if (howto->partial_inplace)
5450         addend = _bfd_mips_elf_sign_extend (addend, 16);
5451       value = symbol + addend - gp;
5452       /* If the symbol was local, any earlier relocatable links will
5453          have adjusted its addend with the gp offset, so compensate
5454          for that now.  Don't do it for symbols forced local in this
5455          link, though, since they won't have had the gp offset applied
5456          to them before.  */
5457       if (was_local_p)
5458         value += gp0;
5459       overflowed_p = mips_elf_overflow_p (value, 16);
5460       break;
5461
5462     case R_MIPS16_GOT16:
5463     case R_MIPS16_CALL16:
5464     case R_MIPS_GOT16:
5465     case R_MIPS_CALL16:
5466     case R_MICROMIPS_GOT16:
5467     case R_MICROMIPS_CALL16:
5468       /* VxWorks does not have separate local and global semantics for
5469          R_MIPS*_GOT16; every relocation evaluates to "G".  */
5470       if (!htab->is_vxworks && local_p)
5471         {
5472           value = mips_elf_got16_entry (abfd, input_bfd, info,
5473                                         symbol + addend, !was_local_p);
5474           if (value == MINUS_ONE)
5475             return bfd_reloc_outofrange;
5476           value
5477             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5478           overflowed_p = mips_elf_overflow_p (value, 16);
5479           break;
5480         }
5481
5482       /* Fall through.  */
5483
5484     case R_MIPS_TLS_GD:
5485     case R_MIPS_TLS_GOTTPREL:
5486     case R_MIPS_TLS_LDM:
5487     case R_MIPS_GOT_DISP:
5488     case R_MIPS16_TLS_GD:
5489     case R_MIPS16_TLS_GOTTPREL:
5490     case R_MIPS16_TLS_LDM:
5491     case R_MICROMIPS_TLS_GD:
5492     case R_MICROMIPS_TLS_GOTTPREL:
5493     case R_MICROMIPS_TLS_LDM:
5494     case R_MICROMIPS_GOT_DISP:
5495       value = g;
5496       overflowed_p = mips_elf_overflow_p (value, 16);
5497       break;
5498
5499     case R_MIPS_GPREL32:
5500       value = (addend + symbol + gp0 - gp);
5501       if (!save_addend)
5502         value &= howto->dst_mask;
5503       break;
5504
5505     case R_MIPS_PC16:
5506     case R_MIPS_GNU_REL16_S2:
5507       value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p;
5508       overflowed_p = mips_elf_overflow_p (value, 18);
5509       value >>= howto->rightshift;
5510       value &= howto->dst_mask;
5511       break;
5512
5513     case R_MICROMIPS_PC7_S1:
5514       value = symbol + _bfd_mips_elf_sign_extend (addend, 8) - p;
5515       overflowed_p = mips_elf_overflow_p (value, 8);
5516       value >>= howto->rightshift;
5517       value &= howto->dst_mask;
5518       break;
5519
5520     case R_MICROMIPS_PC10_S1:
5521       value = symbol + _bfd_mips_elf_sign_extend (addend, 11) - p;
5522       overflowed_p = mips_elf_overflow_p (value, 11);
5523       value >>= howto->rightshift;
5524       value &= howto->dst_mask;
5525       break;
5526
5527     case R_MICROMIPS_PC16_S1:
5528       value = symbol + _bfd_mips_elf_sign_extend (addend, 17) - p;
5529       overflowed_p = mips_elf_overflow_p (value, 17);
5530       value >>= howto->rightshift;
5531       value &= howto->dst_mask;
5532       break;
5533
5534     case R_MICROMIPS_PC23_S2:
5535       value = symbol + _bfd_mips_elf_sign_extend (addend, 25) - ((p | 3) ^ 3);
5536       overflowed_p = mips_elf_overflow_p (value, 25);
5537       value >>= howto->rightshift;
5538       value &= howto->dst_mask;
5539       break;
5540
5541     case R_MIPS_GOT_HI16:
5542     case R_MIPS_CALL_HI16:
5543     case R_MICROMIPS_GOT_HI16:
5544     case R_MICROMIPS_CALL_HI16:
5545       /* We're allowed to handle these two relocations identically.
5546          The dynamic linker is allowed to handle the CALL relocations
5547          differently by creating a lazy evaluation stub.  */
5548       value = g;
5549       value = mips_elf_high (value);
5550       value &= howto->dst_mask;
5551       break;
5552
5553     case R_MIPS_GOT_LO16:
5554     case R_MIPS_CALL_LO16:
5555     case R_MICROMIPS_GOT_LO16:
5556     case R_MICROMIPS_CALL_LO16:
5557       value = g & howto->dst_mask;
5558       break;
5559
5560     case R_MIPS_GOT_PAGE:
5561     case R_MICROMIPS_GOT_PAGE:
5562       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
5563       if (value == MINUS_ONE)
5564         return bfd_reloc_outofrange;
5565       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5566       overflowed_p = mips_elf_overflow_p (value, 16);
5567       break;
5568
5569     case R_MIPS_GOT_OFST:
5570     case R_MICROMIPS_GOT_OFST:
5571       if (local_p)
5572         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
5573       else
5574         value = addend;
5575       overflowed_p = mips_elf_overflow_p (value, 16);
5576       break;
5577
5578     case R_MIPS_SUB:
5579     case R_MICROMIPS_SUB:
5580       value = symbol - addend;
5581       value &= howto->dst_mask;
5582       break;
5583
5584     case R_MIPS_HIGHER:
5585     case R_MICROMIPS_HIGHER:
5586       value = mips_elf_higher (addend + symbol);
5587       value &= howto->dst_mask;
5588       break;
5589
5590     case R_MIPS_HIGHEST:
5591     case R_MICROMIPS_HIGHEST:
5592       value = mips_elf_highest (addend + symbol);
5593       value &= howto->dst_mask;
5594       break;
5595
5596     case R_MIPS_SCN_DISP:
5597     case R_MICROMIPS_SCN_DISP:
5598       value = symbol + addend - sec->output_offset;
5599       value &= howto->dst_mask;
5600       break;
5601
5602     case R_MIPS_JALR:
5603     case R_MICROMIPS_JALR:
5604       /* This relocation is only a hint.  In some cases, we optimize
5605          it into a bal instruction.  But we don't try to optimize
5606          when the symbol does not resolve locally.  */
5607       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
5608         return bfd_reloc_continue;
5609       value = symbol + addend;
5610       break;
5611
5612     case R_MIPS_PJUMP:
5613     case R_MIPS_GNU_VTINHERIT:
5614     case R_MIPS_GNU_VTENTRY:
5615       /* We don't do anything with these at present.  */
5616       return bfd_reloc_continue;
5617
5618     default:
5619       /* An unrecognized relocation type.  */
5620       return bfd_reloc_notsupported;
5621     }
5622
5623   /* Store the VALUE for our caller.  */
5624   *valuep = value;
5625   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
5626 }
5627
5628 /* Obtain the field relocated by RELOCATION.  */
5629
5630 static bfd_vma
5631 mips_elf_obtain_contents (reloc_howto_type *howto,
5632                           const Elf_Internal_Rela *relocation,
5633                           bfd *input_bfd, bfd_byte *contents)
5634 {
5635   bfd_vma x;
5636   bfd_byte *location = contents + relocation->r_offset;
5637
5638   /* Obtain the bytes.  */
5639   x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location);
5640
5641   return x;
5642 }
5643
5644 /* It has been determined that the result of the RELOCATION is the
5645    VALUE.  Use HOWTO to place VALUE into the output file at the
5646    appropriate position.  The SECTION is the section to which the
5647    relocation applies.
5648    CROSS_MODE_JUMP_P is true if the relocation field
5649    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5650
5651    Returns FALSE if anything goes wrong.  */
5652
5653 static bfd_boolean
5654 mips_elf_perform_relocation (struct bfd_link_info *info,
5655                              reloc_howto_type *howto,
5656                              const Elf_Internal_Rela *relocation,
5657                              bfd_vma value, bfd *input_bfd,
5658                              asection *input_section, bfd_byte *contents,
5659                              bfd_boolean cross_mode_jump_p)
5660 {
5661   bfd_vma x;
5662   bfd_byte *location;
5663   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5664
5665   /* Figure out where the relocation is occurring.  */
5666   location = contents + relocation->r_offset;
5667
5668   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
5669
5670   /* Obtain the current value.  */
5671   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
5672
5673   /* Clear the field we are setting.  */
5674   x &= ~howto->dst_mask;
5675
5676   /* Set the field.  */
5677   x |= (value & howto->dst_mask);
5678
5679   /* If required, turn JAL into JALX.  */
5680   if (cross_mode_jump_p && jal_reloc_p (r_type))
5681     {
5682       bfd_boolean ok;
5683       bfd_vma opcode = x >> 26;
5684       bfd_vma jalx_opcode;
5685
5686       /* Check to see if the opcode is already JAL or JALX.  */
5687       if (r_type == R_MIPS16_26)
5688         {
5689           ok = ((opcode == 0x6) || (opcode == 0x7));
5690           jalx_opcode = 0x7;
5691         }
5692       else if (r_type == R_MICROMIPS_26_S1)
5693         {
5694           ok = ((opcode == 0x3d) || (opcode == 0x3c));
5695           jalx_opcode = 0x3c;
5696         }
5697       else
5698         {
5699           ok = ((opcode == 0x3) || (opcode == 0x1d));
5700           jalx_opcode = 0x1d;
5701         }
5702
5703       /* If the opcode is not JAL or JALX, there's a problem.  We cannot
5704          convert J or JALS to JALX.  */
5705       if (!ok)
5706         {
5707           (*_bfd_error_handler)
5708             (_("%B: %A+0x%lx: Unsupported jump between ISA modes; consider recompiling with interlinking enabled."),
5709              input_bfd,
5710              input_section,
5711              (unsigned long) relocation->r_offset);
5712           bfd_set_error (bfd_error_bad_value);
5713           return FALSE;
5714         }
5715
5716       /* Make this the JALX opcode.  */
5717       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
5718     }
5719
5720   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
5721      range.  */
5722   if (!info->relocatable
5723       && !cross_mode_jump_p
5724       && ((JAL_TO_BAL_P (input_bfd)
5725            && r_type == R_MIPS_26
5726            && (x >> 26) == 0x3)         /* jal addr */
5727           || (JALR_TO_BAL_P (input_bfd)
5728               && r_type == R_MIPS_JALR
5729               && x == 0x0320f809)       /* jalr t9 */
5730           || (JR_TO_B_P (input_bfd)
5731               && r_type == R_MIPS_JALR
5732               && x == 0x03200008)))     /* jr t9 */
5733     {
5734       bfd_vma addr;
5735       bfd_vma dest;
5736       bfd_signed_vma off;
5737
5738       addr = (input_section->output_section->vma
5739               + input_section->output_offset
5740               + relocation->r_offset
5741               + 4);
5742       if (r_type == R_MIPS_26)
5743         dest = (value << 2) | ((addr >> 28) << 28);
5744       else
5745         dest = value;
5746       off = dest - addr;
5747       if (off <= 0x1ffff && off >= -0x20000)
5748         {
5749           if (x == 0x03200008)  /* jr t9 */
5750             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
5751           else
5752             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
5753         }
5754     }
5755
5756   /* Put the value into the output.  */
5757   bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location);
5758
5759   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !info->relocatable,
5760                                location);
5761
5762   return TRUE;
5763 }
5764 \f
5765 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
5766    is the original relocation, which is now being transformed into a
5767    dynamic relocation.  The ADDENDP is adjusted if necessary; the
5768    caller should store the result in place of the original addend.  */
5769
5770 static bfd_boolean
5771 mips_elf_create_dynamic_relocation (bfd *output_bfd,
5772                                     struct bfd_link_info *info,
5773                                     const Elf_Internal_Rela *rel,
5774                                     struct mips_elf_link_hash_entry *h,
5775                                     asection *sec, bfd_vma symbol,
5776                                     bfd_vma *addendp, asection *input_section)
5777 {
5778   Elf_Internal_Rela outrel[3];
5779   asection *sreloc;
5780   bfd *dynobj;
5781   int r_type;
5782   long indx;
5783   bfd_boolean defined_p;
5784   struct mips_elf_link_hash_table *htab;
5785
5786   htab = mips_elf_hash_table (info);
5787   BFD_ASSERT (htab != NULL);
5788
5789   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
5790   dynobj = elf_hash_table (info)->dynobj;
5791   sreloc = mips_elf_rel_dyn_section (info, FALSE);
5792   BFD_ASSERT (sreloc != NULL);
5793   BFD_ASSERT (sreloc->contents != NULL);
5794   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
5795               < sreloc->size);
5796
5797   outrel[0].r_offset =
5798     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
5799   if (ABI_64_P (output_bfd))
5800     {
5801       outrel[1].r_offset =
5802         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
5803       outrel[2].r_offset =
5804         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
5805     }
5806
5807   if (outrel[0].r_offset == MINUS_ONE)
5808     /* The relocation field has been deleted.  */
5809     return TRUE;
5810
5811   if (outrel[0].r_offset == MINUS_TWO)
5812     {
5813       /* The relocation field has been converted into a relative value of
5814          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
5815          the field to be fully relocated, so add in the symbol's value.  */
5816       *addendp += symbol;
5817       return TRUE;
5818     }
5819
5820   /* We must now calculate the dynamic symbol table index to use
5821      in the relocation.  */
5822   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
5823     {
5824       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
5825       indx = h->root.dynindx;
5826       if (SGI_COMPAT (output_bfd))
5827         defined_p = h->root.def_regular;
5828       else
5829         /* ??? glibc's ld.so just adds the final GOT entry to the
5830            relocation field.  It therefore treats relocs against
5831            defined symbols in the same way as relocs against
5832            undefined symbols.  */
5833         defined_p = FALSE;
5834     }
5835   else
5836     {
5837       if (sec != NULL && bfd_is_abs_section (sec))
5838         indx = 0;
5839       else if (sec == NULL || sec->owner == NULL)
5840         {
5841           bfd_set_error (bfd_error_bad_value);
5842           return FALSE;
5843         }
5844       else
5845         {
5846           indx = elf_section_data (sec->output_section)->dynindx;
5847           if (indx == 0)
5848             {
5849               asection *osec = htab->root.text_index_section;
5850               indx = elf_section_data (osec)->dynindx;
5851             }
5852           if (indx == 0)
5853             abort ();
5854         }
5855
5856       /* Instead of generating a relocation using the section
5857          symbol, we may as well make it a fully relative
5858          relocation.  We want to avoid generating relocations to
5859          local symbols because we used to generate them
5860          incorrectly, without adding the original symbol value,
5861          which is mandated by the ABI for section symbols.  In
5862          order to give dynamic loaders and applications time to
5863          phase out the incorrect use, we refrain from emitting
5864          section-relative relocations.  It's not like they're
5865          useful, after all.  This should be a bit more efficient
5866          as well.  */
5867       /* ??? Although this behavior is compatible with glibc's ld.so,
5868          the ABI says that relocations against STN_UNDEF should have
5869          a symbol value of 0.  Irix rld honors this, so relocations
5870          against STN_UNDEF have no effect.  */
5871       if (!SGI_COMPAT (output_bfd))
5872         indx = 0;
5873       defined_p = TRUE;
5874     }
5875
5876   /* If the relocation was previously an absolute relocation and
5877      this symbol will not be referred to by the relocation, we must
5878      adjust it by the value we give it in the dynamic symbol table.
5879      Otherwise leave the job up to the dynamic linker.  */
5880   if (defined_p && r_type != R_MIPS_REL32)
5881     *addendp += symbol;
5882
5883   if (htab->is_vxworks)
5884     /* VxWorks uses non-relative relocations for this.  */
5885     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
5886   else
5887     /* The relocation is always an REL32 relocation because we don't
5888        know where the shared library will wind up at load-time.  */
5889     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
5890                                    R_MIPS_REL32);
5891
5892   /* For strict adherence to the ABI specification, we should
5893      generate a R_MIPS_64 relocation record by itself before the
5894      _REL32/_64 record as well, such that the addend is read in as
5895      a 64-bit value (REL32 is a 32-bit relocation, after all).
5896      However, since none of the existing ELF64 MIPS dynamic
5897      loaders seems to care, we don't waste space with these
5898      artificial relocations.  If this turns out to not be true,
5899      mips_elf_allocate_dynamic_relocation() should be tweaked so
5900      as to make room for a pair of dynamic relocations per
5901      invocation if ABI_64_P, and here we should generate an
5902      additional relocation record with R_MIPS_64 by itself for a
5903      NULL symbol before this relocation record.  */
5904   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
5905                                  ABI_64_P (output_bfd)
5906                                  ? R_MIPS_64
5907                                  : R_MIPS_NONE);
5908   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
5909
5910   /* Adjust the output offset of the relocation to reference the
5911      correct location in the output file.  */
5912   outrel[0].r_offset += (input_section->output_section->vma
5913                          + input_section->output_offset);
5914   outrel[1].r_offset += (input_section->output_section->vma
5915                          + input_section->output_offset);
5916   outrel[2].r_offset += (input_section->output_section->vma
5917                          + input_section->output_offset);
5918
5919   /* Put the relocation back out.  We have to use the special
5920      relocation outputter in the 64-bit case since the 64-bit
5921      relocation format is non-standard.  */
5922   if (ABI_64_P (output_bfd))
5923     {
5924       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
5925         (output_bfd, &outrel[0],
5926          (sreloc->contents
5927           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
5928     }
5929   else if (htab->is_vxworks)
5930     {
5931       /* VxWorks uses RELA rather than REL dynamic relocations.  */
5932       outrel[0].r_addend = *addendp;
5933       bfd_elf32_swap_reloca_out
5934         (output_bfd, &outrel[0],
5935          (sreloc->contents
5936           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
5937     }
5938   else
5939     bfd_elf32_swap_reloc_out
5940       (output_bfd, &outrel[0],
5941        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
5942
5943   /* We've now added another relocation.  */
5944   ++sreloc->reloc_count;
5945
5946   /* Make sure the output section is writable.  The dynamic linker
5947      will be writing to it.  */
5948   elf_section_data (input_section->output_section)->this_hdr.sh_flags
5949     |= SHF_WRITE;
5950
5951   /* On IRIX5, make an entry of compact relocation info.  */
5952   if (IRIX_COMPAT (output_bfd) == ict_irix5)
5953     {
5954       asection *scpt = bfd_get_linker_section (dynobj, ".compact_rel");
5955       bfd_byte *cr;
5956
5957       if (scpt)
5958         {
5959           Elf32_crinfo cptrel;
5960
5961           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
5962           cptrel.vaddr = (rel->r_offset
5963                           + input_section->output_section->vma
5964                           + input_section->output_offset);
5965           if (r_type == R_MIPS_REL32)
5966             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
5967           else
5968             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
5969           mips_elf_set_cr_dist2to (cptrel, 0);
5970           cptrel.konst = *addendp;
5971
5972           cr = (scpt->contents
5973                 + sizeof (Elf32_External_compact_rel));
5974           mips_elf_set_cr_relvaddr (cptrel, 0);
5975           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
5976                                      ((Elf32_External_crinfo *) cr
5977                                       + scpt->reloc_count));
5978           ++scpt->reloc_count;
5979         }
5980     }
5981
5982   /* If we've written this relocation for a readonly section,
5983      we need to set DF_TEXTREL again, so that we do not delete the
5984      DT_TEXTREL tag.  */
5985   if (MIPS_ELF_READONLY_SECTION (input_section))
5986     info->flags |= DF_TEXTREL;
5987
5988   return TRUE;
5989 }
5990 \f
5991 /* Return the MACH for a MIPS e_flags value.  */
5992
5993 unsigned long
5994 _bfd_elf_mips_mach (flagword flags)
5995 {
5996   switch (flags & EF_MIPS_MACH)
5997     {
5998     case E_MIPS_MACH_3900:
5999       return bfd_mach_mips3900;
6000
6001     case E_MIPS_MACH_4010:
6002       return bfd_mach_mips4010;
6003
6004     case E_MIPS_MACH_4100:
6005       return bfd_mach_mips4100;
6006
6007     case E_MIPS_MACH_4111:
6008       return bfd_mach_mips4111;
6009
6010     case E_MIPS_MACH_4120:
6011       return bfd_mach_mips4120;
6012
6013     case E_MIPS_MACH_4650:
6014       return bfd_mach_mips4650;
6015
6016     case E_MIPS_MACH_5400:
6017       return bfd_mach_mips5400;
6018
6019     case E_MIPS_MACH_5500:
6020       return bfd_mach_mips5500;
6021
6022     case E_MIPS_MACH_5900:
6023       return bfd_mach_mips5900;
6024
6025     case E_MIPS_MACH_9000:
6026       return bfd_mach_mips9000;
6027
6028     case E_MIPS_MACH_SB1:
6029       return bfd_mach_mips_sb1;
6030
6031     case E_MIPS_MACH_LS2E:
6032       return bfd_mach_mips_loongson_2e;
6033
6034     case E_MIPS_MACH_LS2F:
6035       return bfd_mach_mips_loongson_2f;
6036
6037     case E_MIPS_MACH_LS3A:
6038       return bfd_mach_mips_loongson_3a;
6039
6040     case E_MIPS_MACH_OCTEON2:
6041       return bfd_mach_mips_octeon2;
6042
6043     case E_MIPS_MACH_OCTEON:
6044       return bfd_mach_mips_octeon;
6045
6046     case E_MIPS_MACH_XLR:
6047       return bfd_mach_mips_xlr;
6048
6049     default:
6050       switch (flags & EF_MIPS_ARCH)
6051         {
6052         default:
6053         case E_MIPS_ARCH_1:
6054           return bfd_mach_mips3000;
6055
6056         case E_MIPS_ARCH_2:
6057           return bfd_mach_mips6000;
6058
6059         case E_MIPS_ARCH_3:
6060           return bfd_mach_mips4000;
6061
6062         case E_MIPS_ARCH_4:
6063           return bfd_mach_mips8000;
6064
6065         case E_MIPS_ARCH_5:
6066           return bfd_mach_mips5;
6067
6068         case E_MIPS_ARCH_32:
6069           return bfd_mach_mipsisa32;
6070
6071         case E_MIPS_ARCH_64:
6072           return bfd_mach_mipsisa64;
6073
6074         case E_MIPS_ARCH_32R2:
6075           return bfd_mach_mipsisa32r2;
6076
6077         case E_MIPS_ARCH_64R2:
6078           return bfd_mach_mipsisa64r2;
6079         }
6080     }
6081
6082   return 0;
6083 }
6084
6085 /* Return printable name for ABI.  */
6086
6087 static INLINE char *
6088 elf_mips_abi_name (bfd *abfd)
6089 {
6090   flagword flags;
6091
6092   flags = elf_elfheader (abfd)->e_flags;
6093   switch (flags & EF_MIPS_ABI)
6094     {
6095     case 0:
6096       if (ABI_N32_P (abfd))
6097         return "N32";
6098       else if (ABI_64_P (abfd))
6099         return "64";
6100       else
6101         return "none";
6102     case E_MIPS_ABI_O32:
6103       return "O32";
6104     case E_MIPS_ABI_O64:
6105       return "O64";
6106     case E_MIPS_ABI_EABI32:
6107       return "EABI32";
6108     case E_MIPS_ABI_EABI64:
6109       return "EABI64";
6110     default:
6111       return "unknown abi";
6112     }
6113 }
6114 \f
6115 /* MIPS ELF uses two common sections.  One is the usual one, and the
6116    other is for small objects.  All the small objects are kept
6117    together, and then referenced via the gp pointer, which yields
6118    faster assembler code.  This is what we use for the small common
6119    section.  This approach is copied from ecoff.c.  */
6120 static asection mips_elf_scom_section;
6121 static asymbol mips_elf_scom_symbol;
6122 static asymbol *mips_elf_scom_symbol_ptr;
6123
6124 /* MIPS ELF also uses an acommon section, which represents an
6125    allocated common symbol which may be overridden by a
6126    definition in a shared library.  */
6127 static asection mips_elf_acom_section;
6128 static asymbol mips_elf_acom_symbol;
6129 static asymbol *mips_elf_acom_symbol_ptr;
6130
6131 /* This is used for both the 32-bit and the 64-bit ABI.  */
6132
6133 void
6134 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6135 {
6136   elf_symbol_type *elfsym;
6137
6138   /* Handle the special MIPS section numbers that a symbol may use.  */
6139   elfsym = (elf_symbol_type *) asym;
6140   switch (elfsym->internal_elf_sym.st_shndx)
6141     {
6142     case SHN_MIPS_ACOMMON:
6143       /* This section is used in a dynamically linked executable file.
6144          It is an allocated common section.  The dynamic linker can
6145          either resolve these symbols to something in a shared
6146          library, or it can just leave them here.  For our purposes,
6147          we can consider these symbols to be in a new section.  */
6148       if (mips_elf_acom_section.name == NULL)
6149         {
6150           /* Initialize the acommon section.  */
6151           mips_elf_acom_section.name = ".acommon";
6152           mips_elf_acom_section.flags = SEC_ALLOC;
6153           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6154           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6155           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6156           mips_elf_acom_symbol.name = ".acommon";
6157           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6158           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6159           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6160         }
6161       asym->section = &mips_elf_acom_section;
6162       break;
6163
6164     case SHN_COMMON:
6165       /* Common symbols less than the GP size are automatically
6166          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6167       if (asym->value > elf_gp_size (abfd)
6168           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6169           || IRIX_COMPAT (abfd) == ict_irix6)
6170         break;
6171       /* Fall through.  */
6172     case SHN_MIPS_SCOMMON:
6173       if (mips_elf_scom_section.name == NULL)
6174         {
6175           /* Initialize the small common section.  */
6176           mips_elf_scom_section.name = ".scommon";
6177           mips_elf_scom_section.flags = SEC_IS_COMMON;
6178           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6179           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6180           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6181           mips_elf_scom_symbol.name = ".scommon";
6182           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6183           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6184           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6185         }
6186       asym->section = &mips_elf_scom_section;
6187       asym->value = elfsym->internal_elf_sym.st_size;
6188       break;
6189
6190     case SHN_MIPS_SUNDEFINED:
6191       asym->section = bfd_und_section_ptr;
6192       break;
6193
6194     case SHN_MIPS_TEXT:
6195       {
6196         asection *section = bfd_get_section_by_name (abfd, ".text");
6197
6198         if (section != NULL)
6199           {
6200             asym->section = section;
6201             /* MIPS_TEXT is a bit special, the address is not an offset
6202                to the base of the .text section.  So substract the section
6203                base address to make it an offset.  */
6204             asym->value -= section->vma;
6205           }
6206       }
6207       break;
6208
6209     case SHN_MIPS_DATA:
6210       {
6211         asection *section = bfd_get_section_by_name (abfd, ".data");
6212
6213         if (section != NULL)
6214           {
6215             asym->section = section;
6216             /* MIPS_DATA is a bit special, the address is not an offset
6217                to the base of the .data section.  So substract the section
6218                base address to make it an offset.  */
6219             asym->value -= section->vma;
6220           }
6221       }
6222       break;
6223     }
6224
6225   /* If this is an odd-valued function symbol, assume it's a MIPS16
6226      or microMIPS one.  */
6227   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6228       && (asym->value & 1) != 0)
6229     {
6230       asym->value--;
6231       if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
6232         elfsym->internal_elf_sym.st_other
6233           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6234       else
6235         elfsym->internal_elf_sym.st_other
6236           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6237     }
6238 }
6239 \f
6240 /* Implement elf_backend_eh_frame_address_size.  This differs from
6241    the default in the way it handles EABI64.
6242
6243    EABI64 was originally specified as an LP64 ABI, and that is what
6244    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6245    historically accepted the combination of -mabi=eabi and -mlong32,
6246    and this ILP32 variation has become semi-official over time.
6247    Both forms use elf32 and have pointer-sized FDE addresses.
6248
6249    If an EABI object was generated by GCC 4.0 or above, it will have
6250    an empty .gcc_compiled_longXX section, where XX is the size of longs
6251    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6252    have no special marking to distinguish them from LP64 objects.
6253
6254    We don't want users of the official LP64 ABI to be punished for the
6255    existence of the ILP32 variant, but at the same time, we don't want
6256    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6257    We therefore take the following approach:
6258
6259       - If ABFD contains a .gcc_compiled_longXX section, use it to
6260         determine the pointer size.
6261
6262       - Otherwise check the type of the first relocation.  Assume that
6263         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
6264
6265       - Otherwise punt.
6266
6267    The second check is enough to detect LP64 objects generated by pre-4.0
6268    compilers because, in the kind of output generated by those compilers,
6269    the first relocation will be associated with either a CIE personality
6270    routine or an FDE start address.  Furthermore, the compilers never
6271    used a special (non-pointer) encoding for this ABI.
6272
6273    Checking the relocation type should also be safe because there is no
6274    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
6275    did so.  */
6276
6277 unsigned int
6278 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
6279 {
6280   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
6281     return 8;
6282   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
6283     {
6284       bfd_boolean long32_p, long64_p;
6285
6286       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
6287       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
6288       if (long32_p && long64_p)
6289         return 0;
6290       if (long32_p)
6291         return 4;
6292       if (long64_p)
6293         return 8;
6294
6295       if (sec->reloc_count > 0
6296           && elf_section_data (sec)->relocs != NULL
6297           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
6298               == R_MIPS_64))
6299         return 8;
6300
6301       return 0;
6302     }
6303   return 4;
6304 }
6305 \f
6306 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
6307    relocations against two unnamed section symbols to resolve to the
6308    same address.  For example, if we have code like:
6309
6310         lw      $4,%got_disp(.data)($gp)
6311         lw      $25,%got_disp(.text)($gp)
6312         jalr    $25
6313
6314    then the linker will resolve both relocations to .data and the program
6315    will jump there rather than to .text.
6316
6317    We can work around this problem by giving names to local section symbols.
6318    This is also what the MIPSpro tools do.  */
6319
6320 bfd_boolean
6321 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
6322 {
6323   return SGI_COMPAT (abfd);
6324 }
6325 \f
6326 /* Work over a section just before writing it out.  This routine is
6327    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
6328    sections that need the SHF_MIPS_GPREL flag by name; there has to be
6329    a better way.  */
6330
6331 bfd_boolean
6332 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
6333 {
6334   if (hdr->sh_type == SHT_MIPS_REGINFO
6335       && hdr->sh_size > 0)
6336     {
6337       bfd_byte buf[4];
6338
6339       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
6340       BFD_ASSERT (hdr->contents == NULL);
6341
6342       if (bfd_seek (abfd,
6343                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
6344                     SEEK_SET) != 0)
6345         return FALSE;
6346       H_PUT_32 (abfd, elf_gp (abfd), buf);
6347       if (bfd_bwrite (buf, 4, abfd) != 4)
6348         return FALSE;
6349     }
6350
6351   if (hdr->sh_type == SHT_MIPS_OPTIONS
6352       && hdr->bfd_section != NULL
6353       && mips_elf_section_data (hdr->bfd_section) != NULL
6354       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
6355     {
6356       bfd_byte *contents, *l, *lend;
6357
6358       /* We stored the section contents in the tdata field in the
6359          set_section_contents routine.  We save the section contents
6360          so that we don't have to read them again.
6361          At this point we know that elf_gp is set, so we can look
6362          through the section contents to see if there is an
6363          ODK_REGINFO structure.  */
6364
6365       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
6366       l = contents;
6367       lend = contents + hdr->sh_size;
6368       while (l + sizeof (Elf_External_Options) <= lend)
6369         {
6370           Elf_Internal_Options intopt;
6371
6372           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6373                                         &intopt);
6374           if (intopt.size < sizeof (Elf_External_Options))
6375             {
6376               (*_bfd_error_handler)
6377                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6378                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6379               break;
6380             }
6381           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6382             {
6383               bfd_byte buf[8];
6384
6385               if (bfd_seek (abfd,
6386                             (hdr->sh_offset
6387                              + (l - contents)
6388                              + sizeof (Elf_External_Options)
6389                              + (sizeof (Elf64_External_RegInfo) - 8)),
6390                              SEEK_SET) != 0)
6391                 return FALSE;
6392               H_PUT_64 (abfd, elf_gp (abfd), buf);
6393               if (bfd_bwrite (buf, 8, abfd) != 8)
6394                 return FALSE;
6395             }
6396           else if (intopt.kind == ODK_REGINFO)
6397             {
6398               bfd_byte buf[4];
6399
6400               if (bfd_seek (abfd,
6401                             (hdr->sh_offset
6402                              + (l - contents)
6403                              + sizeof (Elf_External_Options)
6404                              + (sizeof (Elf32_External_RegInfo) - 4)),
6405                             SEEK_SET) != 0)
6406                 return FALSE;
6407               H_PUT_32 (abfd, elf_gp (abfd), buf);
6408               if (bfd_bwrite (buf, 4, abfd) != 4)
6409                 return FALSE;
6410             }
6411           l += intopt.size;
6412         }
6413     }
6414
6415   if (hdr->bfd_section != NULL)
6416     {
6417       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
6418
6419       /* .sbss is not handled specially here because the GNU/Linux
6420          prelinker can convert .sbss from NOBITS to PROGBITS and
6421          changing it back to NOBITS breaks the binary.  The entry in
6422          _bfd_mips_elf_special_sections will ensure the correct flags
6423          are set on .sbss if BFD creates it without reading it from an
6424          input file, and without special handling here the flags set
6425          on it in an input file will be followed.  */
6426       if (strcmp (name, ".sdata") == 0
6427           || strcmp (name, ".lit8") == 0
6428           || strcmp (name, ".lit4") == 0)
6429         {
6430           hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
6431           hdr->sh_type = SHT_PROGBITS;
6432         }
6433       else if (strcmp (name, ".srdata") == 0)
6434         {
6435           hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
6436           hdr->sh_type = SHT_PROGBITS;
6437         }
6438       else if (strcmp (name, ".compact_rel") == 0)
6439         {
6440           hdr->sh_flags = 0;
6441           hdr->sh_type = SHT_PROGBITS;
6442         }
6443       else if (strcmp (name, ".rtproc") == 0)
6444         {
6445           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
6446             {
6447               unsigned int adjust;
6448
6449               adjust = hdr->sh_size % hdr->sh_addralign;
6450               if (adjust != 0)
6451                 hdr->sh_size += hdr->sh_addralign - adjust;
6452             }
6453         }
6454     }
6455
6456   return TRUE;
6457 }
6458
6459 /* Handle a MIPS specific section when reading an object file.  This
6460    is called when elfcode.h finds a section with an unknown type.
6461    This routine supports both the 32-bit and 64-bit ELF ABI.
6462
6463    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
6464    how to.  */
6465
6466 bfd_boolean
6467 _bfd_mips_elf_section_from_shdr (bfd *abfd,
6468                                  Elf_Internal_Shdr *hdr,
6469                                  const char *name,
6470                                  int shindex)
6471 {
6472   flagword flags = 0;
6473
6474   /* There ought to be a place to keep ELF backend specific flags, but
6475      at the moment there isn't one.  We just keep track of the
6476      sections by their name, instead.  Fortunately, the ABI gives
6477      suggested names for all the MIPS specific sections, so we will
6478      probably get away with this.  */
6479   switch (hdr->sh_type)
6480     {
6481     case SHT_MIPS_LIBLIST:
6482       if (strcmp (name, ".liblist") != 0)
6483         return FALSE;
6484       break;
6485     case SHT_MIPS_MSYM:
6486       if (strcmp (name, ".msym") != 0)
6487         return FALSE;
6488       break;
6489     case SHT_MIPS_CONFLICT:
6490       if (strcmp (name, ".conflict") != 0)
6491         return FALSE;
6492       break;
6493     case SHT_MIPS_GPTAB:
6494       if (! CONST_STRNEQ (name, ".gptab."))
6495         return FALSE;
6496       break;
6497     case SHT_MIPS_UCODE:
6498       if (strcmp (name, ".ucode") != 0)
6499         return FALSE;
6500       break;
6501     case SHT_MIPS_DEBUG:
6502       if (strcmp (name, ".mdebug") != 0)
6503         return FALSE;
6504       flags = SEC_DEBUGGING;
6505       break;
6506     case SHT_MIPS_REGINFO:
6507       if (strcmp (name, ".reginfo") != 0
6508           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
6509         return FALSE;
6510       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6511       break;
6512     case SHT_MIPS_IFACE:
6513       if (strcmp (name, ".MIPS.interfaces") != 0)
6514         return FALSE;
6515       break;
6516     case SHT_MIPS_CONTENT:
6517       if (! CONST_STRNEQ (name, ".MIPS.content"))
6518         return FALSE;
6519       break;
6520     case SHT_MIPS_OPTIONS:
6521       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6522         return FALSE;
6523       break;
6524     case SHT_MIPS_DWARF:
6525       if (! CONST_STRNEQ (name, ".debug_")
6526           && ! CONST_STRNEQ (name, ".zdebug_"))
6527         return FALSE;
6528       break;
6529     case SHT_MIPS_SYMBOL_LIB:
6530       if (strcmp (name, ".MIPS.symlib") != 0)
6531         return FALSE;
6532       break;
6533     case SHT_MIPS_EVENTS:
6534       if (! CONST_STRNEQ (name, ".MIPS.events")
6535           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
6536         return FALSE;
6537       break;
6538     default:
6539       break;
6540     }
6541
6542   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
6543     return FALSE;
6544
6545   if (flags)
6546     {
6547       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
6548                                    (bfd_get_section_flags (abfd,
6549                                                            hdr->bfd_section)
6550                                     | flags)))
6551         return FALSE;
6552     }
6553
6554   /* FIXME: We should record sh_info for a .gptab section.  */
6555
6556   /* For a .reginfo section, set the gp value in the tdata information
6557      from the contents of this section.  We need the gp value while
6558      processing relocs, so we just get it now.  The .reginfo section
6559      is not used in the 64-bit MIPS ELF ABI.  */
6560   if (hdr->sh_type == SHT_MIPS_REGINFO)
6561     {
6562       Elf32_External_RegInfo ext;
6563       Elf32_RegInfo s;
6564
6565       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
6566                                       &ext, 0, sizeof ext))
6567         return FALSE;
6568       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
6569       elf_gp (abfd) = s.ri_gp_value;
6570     }
6571
6572   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
6573      set the gp value based on what we find.  We may see both
6574      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
6575      they should agree.  */
6576   if (hdr->sh_type == SHT_MIPS_OPTIONS)
6577     {
6578       bfd_byte *contents, *l, *lend;
6579
6580       contents = bfd_malloc (hdr->sh_size);
6581       if (contents == NULL)
6582         return FALSE;
6583       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
6584                                       0, hdr->sh_size))
6585         {
6586           free (contents);
6587           return FALSE;
6588         }
6589       l = contents;
6590       lend = contents + hdr->sh_size;
6591       while (l + sizeof (Elf_External_Options) <= lend)
6592         {
6593           Elf_Internal_Options intopt;
6594
6595           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6596                                         &intopt);
6597           if (intopt.size < sizeof (Elf_External_Options))
6598             {
6599               (*_bfd_error_handler)
6600                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6601                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6602               break;
6603             }
6604           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6605             {
6606               Elf64_Internal_RegInfo intreg;
6607
6608               bfd_mips_elf64_swap_reginfo_in
6609                 (abfd,
6610                  ((Elf64_External_RegInfo *)
6611                   (l + sizeof (Elf_External_Options))),
6612                  &intreg);
6613               elf_gp (abfd) = intreg.ri_gp_value;
6614             }
6615           else if (intopt.kind == ODK_REGINFO)
6616             {
6617               Elf32_RegInfo intreg;
6618
6619               bfd_mips_elf32_swap_reginfo_in
6620                 (abfd,
6621                  ((Elf32_External_RegInfo *)
6622                   (l + sizeof (Elf_External_Options))),
6623                  &intreg);
6624               elf_gp (abfd) = intreg.ri_gp_value;
6625             }
6626           l += intopt.size;
6627         }
6628       free (contents);
6629     }
6630
6631   return TRUE;
6632 }
6633
6634 /* Set the correct type for a MIPS ELF section.  We do this by the
6635    section name, which is a hack, but ought to work.  This routine is
6636    used by both the 32-bit and the 64-bit ABI.  */
6637
6638 bfd_boolean
6639 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
6640 {
6641   const char *name = bfd_get_section_name (abfd, sec);
6642
6643   if (strcmp (name, ".liblist") == 0)
6644     {
6645       hdr->sh_type = SHT_MIPS_LIBLIST;
6646       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
6647       /* The sh_link field is set in final_write_processing.  */
6648     }
6649   else if (strcmp (name, ".conflict") == 0)
6650     hdr->sh_type = SHT_MIPS_CONFLICT;
6651   else if (CONST_STRNEQ (name, ".gptab."))
6652     {
6653       hdr->sh_type = SHT_MIPS_GPTAB;
6654       hdr->sh_entsize = sizeof (Elf32_External_gptab);
6655       /* The sh_info field is set in final_write_processing.  */
6656     }
6657   else if (strcmp (name, ".ucode") == 0)
6658     hdr->sh_type = SHT_MIPS_UCODE;
6659   else if (strcmp (name, ".mdebug") == 0)
6660     {
6661       hdr->sh_type = SHT_MIPS_DEBUG;
6662       /* In a shared object on IRIX 5.3, the .mdebug section has an
6663          entsize of 0.  FIXME: Does this matter?  */
6664       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
6665         hdr->sh_entsize = 0;
6666       else
6667         hdr->sh_entsize = 1;
6668     }
6669   else if (strcmp (name, ".reginfo") == 0)
6670     {
6671       hdr->sh_type = SHT_MIPS_REGINFO;
6672       /* In a shared object on IRIX 5.3, the .reginfo section has an
6673          entsize of 0x18.  FIXME: Does this matter?  */
6674       if (SGI_COMPAT (abfd))
6675         {
6676           if ((abfd->flags & DYNAMIC) != 0)
6677             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6678           else
6679             hdr->sh_entsize = 1;
6680         }
6681       else
6682         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6683     }
6684   else if (SGI_COMPAT (abfd)
6685            && (strcmp (name, ".hash") == 0
6686                || strcmp (name, ".dynamic") == 0
6687                || strcmp (name, ".dynstr") == 0))
6688     {
6689       if (SGI_COMPAT (abfd))
6690         hdr->sh_entsize = 0;
6691 #if 0
6692       /* This isn't how the IRIX6 linker behaves.  */
6693       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
6694 #endif
6695     }
6696   else if (strcmp (name, ".got") == 0
6697            || strcmp (name, ".srdata") == 0
6698            || strcmp (name, ".sdata") == 0
6699            || strcmp (name, ".sbss") == 0
6700            || strcmp (name, ".lit4") == 0
6701            || strcmp (name, ".lit8") == 0)
6702     hdr->sh_flags |= SHF_MIPS_GPREL;
6703   else if (strcmp (name, ".MIPS.interfaces") == 0)
6704     {
6705       hdr->sh_type = SHT_MIPS_IFACE;
6706       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6707     }
6708   else if (CONST_STRNEQ (name, ".MIPS.content"))
6709     {
6710       hdr->sh_type = SHT_MIPS_CONTENT;
6711       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6712       /* The sh_info field is set in final_write_processing.  */
6713     }
6714   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6715     {
6716       hdr->sh_type = SHT_MIPS_OPTIONS;
6717       hdr->sh_entsize = 1;
6718       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6719     }
6720   else if (CONST_STRNEQ (name, ".debug_")
6721            || CONST_STRNEQ (name, ".zdebug_"))
6722     {
6723       hdr->sh_type = SHT_MIPS_DWARF;
6724
6725       /* Irix facilities such as libexc expect a single .debug_frame
6726          per executable, the system ones have NOSTRIP set and the linker
6727          doesn't merge sections with different flags so ...  */
6728       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
6729         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6730     }
6731   else if (strcmp (name, ".MIPS.symlib") == 0)
6732     {
6733       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
6734       /* The sh_link and sh_info fields are set in
6735          final_write_processing.  */
6736     }
6737   else if (CONST_STRNEQ (name, ".MIPS.events")
6738            || CONST_STRNEQ (name, ".MIPS.post_rel"))
6739     {
6740       hdr->sh_type = SHT_MIPS_EVENTS;
6741       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6742       /* The sh_link field is set in final_write_processing.  */
6743     }
6744   else if (strcmp (name, ".msym") == 0)
6745     {
6746       hdr->sh_type = SHT_MIPS_MSYM;
6747       hdr->sh_flags |= SHF_ALLOC;
6748       hdr->sh_entsize = 8;
6749     }
6750
6751   /* The generic elf_fake_sections will set up REL_HDR using the default
6752    kind of relocations.  We used to set up a second header for the
6753    non-default kind of relocations here, but only NewABI would use
6754    these, and the IRIX ld doesn't like resulting empty RELA sections.
6755    Thus we create those header only on demand now.  */
6756
6757   return TRUE;
6758 }
6759
6760 /* Given a BFD section, try to locate the corresponding ELF section
6761    index.  This is used by both the 32-bit and the 64-bit ABI.
6762    Actually, it's not clear to me that the 64-bit ABI supports these,
6763    but for non-PIC objects we will certainly want support for at least
6764    the .scommon section.  */
6765
6766 bfd_boolean
6767 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
6768                                         asection *sec, int *retval)
6769 {
6770   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
6771     {
6772       *retval = SHN_MIPS_SCOMMON;
6773       return TRUE;
6774     }
6775   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
6776     {
6777       *retval = SHN_MIPS_ACOMMON;
6778       return TRUE;
6779     }
6780   return FALSE;
6781 }
6782 \f
6783 /* Hook called by the linker routine which adds symbols from an object
6784    file.  We must handle the special MIPS section numbers here.  */
6785
6786 bfd_boolean
6787 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
6788                                Elf_Internal_Sym *sym, const char **namep,
6789                                flagword *flagsp ATTRIBUTE_UNUSED,
6790                                asection **secp, bfd_vma *valp)
6791 {
6792   if (SGI_COMPAT (abfd)
6793       && (abfd->flags & DYNAMIC) != 0
6794       && strcmp (*namep, "_rld_new_interface") == 0)
6795     {
6796       /* Skip IRIX5 rld entry name.  */
6797       *namep = NULL;
6798       return TRUE;
6799     }
6800
6801   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
6802      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
6803      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
6804      a magic symbol resolved by the linker, we ignore this bogus definition
6805      of _gp_disp.  New ABI objects do not suffer from this problem so this
6806      is not done for them. */
6807   if (!NEWABI_P(abfd)
6808       && (sym->st_shndx == SHN_ABS)
6809       && (strcmp (*namep, "_gp_disp") == 0))
6810     {
6811       *namep = NULL;
6812       return TRUE;
6813     }
6814
6815   switch (sym->st_shndx)
6816     {
6817     case SHN_COMMON:
6818       /* Common symbols less than the GP size are automatically
6819          treated as SHN_MIPS_SCOMMON symbols.  */
6820       if (sym->st_size > elf_gp_size (abfd)
6821           || ELF_ST_TYPE (sym->st_info) == STT_TLS
6822           || IRIX_COMPAT (abfd) == ict_irix6)
6823         break;
6824       /* Fall through.  */
6825     case SHN_MIPS_SCOMMON:
6826       *secp = bfd_make_section_old_way (abfd, ".scommon");
6827       (*secp)->flags |= SEC_IS_COMMON;
6828       *valp = sym->st_size;
6829       break;
6830
6831     case SHN_MIPS_TEXT:
6832       /* This section is used in a shared object.  */
6833       if (elf_tdata (abfd)->elf_text_section == NULL)
6834         {
6835           asymbol *elf_text_symbol;
6836           asection *elf_text_section;
6837           bfd_size_type amt = sizeof (asection);
6838
6839           elf_text_section = bfd_zalloc (abfd, amt);
6840           if (elf_text_section == NULL)
6841             return FALSE;
6842
6843           amt = sizeof (asymbol);
6844           elf_text_symbol = bfd_zalloc (abfd, amt);
6845           if (elf_text_symbol == NULL)
6846             return FALSE;
6847
6848           /* Initialize the section.  */
6849
6850           elf_tdata (abfd)->elf_text_section = elf_text_section;
6851           elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
6852
6853           elf_text_section->symbol = elf_text_symbol;
6854           elf_text_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_text_symbol;
6855
6856           elf_text_section->name = ".text";
6857           elf_text_section->flags = SEC_NO_FLAGS;
6858           elf_text_section->output_section = NULL;
6859           elf_text_section->owner = abfd;
6860           elf_text_symbol->name = ".text";
6861           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
6862           elf_text_symbol->section = elf_text_section;
6863         }
6864       /* This code used to do *secp = bfd_und_section_ptr if
6865          info->shared.  I don't know why, and that doesn't make sense,
6866          so I took it out.  */
6867       *secp = elf_tdata (abfd)->elf_text_section;
6868       break;
6869
6870     case SHN_MIPS_ACOMMON:
6871       /* Fall through. XXX Can we treat this as allocated data?  */
6872     case SHN_MIPS_DATA:
6873       /* This section is used in a shared object.  */
6874       if (elf_tdata (abfd)->elf_data_section == NULL)
6875         {
6876           asymbol *elf_data_symbol;
6877           asection *elf_data_section;
6878           bfd_size_type amt = sizeof (asection);
6879
6880           elf_data_section = bfd_zalloc (abfd, amt);
6881           if (elf_data_section == NULL)
6882             return FALSE;
6883
6884           amt = sizeof (asymbol);
6885           elf_data_symbol = bfd_zalloc (abfd, amt);
6886           if (elf_data_symbol == NULL)
6887             return FALSE;
6888
6889           /* Initialize the section.  */
6890
6891           elf_tdata (abfd)->elf_data_section = elf_data_section;
6892           elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
6893
6894           elf_data_section->symbol = elf_data_symbol;
6895           elf_data_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_data_symbol;
6896
6897           elf_data_section->name = ".data";
6898           elf_data_section->flags = SEC_NO_FLAGS;
6899           elf_data_section->output_section = NULL;
6900           elf_data_section->owner = abfd;
6901           elf_data_symbol->name = ".data";
6902           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
6903           elf_data_symbol->section = elf_data_section;
6904         }
6905       /* This code used to do *secp = bfd_und_section_ptr if
6906          info->shared.  I don't know why, and that doesn't make sense,
6907          so I took it out.  */
6908       *secp = elf_tdata (abfd)->elf_data_section;
6909       break;
6910
6911     case SHN_MIPS_SUNDEFINED:
6912       *secp = bfd_und_section_ptr;
6913       break;
6914     }
6915
6916   if (SGI_COMPAT (abfd)
6917       && ! info->shared
6918       && info->output_bfd->xvec == abfd->xvec
6919       && strcmp (*namep, "__rld_obj_head") == 0)
6920     {
6921       struct elf_link_hash_entry *h;
6922       struct bfd_link_hash_entry *bh;
6923
6924       /* Mark __rld_obj_head as dynamic.  */
6925       bh = NULL;
6926       if (! (_bfd_generic_link_add_one_symbol
6927              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
6928               get_elf_backend_data (abfd)->collect, &bh)))
6929         return FALSE;
6930
6931       h = (struct elf_link_hash_entry *) bh;
6932       h->non_elf = 0;
6933       h->def_regular = 1;
6934       h->type = STT_OBJECT;
6935
6936       if (! bfd_elf_link_record_dynamic_symbol (info, h))
6937         return FALSE;
6938
6939       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
6940       mips_elf_hash_table (info)->rld_symbol = h;
6941     }
6942
6943   /* If this is a mips16 text symbol, add 1 to the value to make it
6944      odd.  This will cause something like .word SYM to come up with
6945      the right value when it is loaded into the PC.  */
6946   if (ELF_ST_IS_COMPRESSED (sym->st_other))
6947     ++*valp;
6948
6949   return TRUE;
6950 }
6951
6952 /* This hook function is called before the linker writes out a global
6953    symbol.  We mark symbols as small common if appropriate.  This is
6954    also where we undo the increment of the value for a mips16 symbol.  */
6955
6956 int
6957 _bfd_mips_elf_link_output_symbol_hook
6958   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
6959    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
6960    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
6961 {
6962   /* If we see a common symbol, which implies a relocatable link, then
6963      if a symbol was small common in an input file, mark it as small
6964      common in the output file.  */
6965   if (sym->st_shndx == SHN_COMMON
6966       && strcmp (input_sec->name, ".scommon") == 0)
6967     sym->st_shndx = SHN_MIPS_SCOMMON;
6968
6969   if (ELF_ST_IS_COMPRESSED (sym->st_other))
6970     sym->st_value &= ~1;
6971
6972   return 1;
6973 }
6974 \f
6975 /* Functions for the dynamic linker.  */
6976
6977 /* Create dynamic sections when linking against a dynamic object.  */
6978
6979 bfd_boolean
6980 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
6981 {
6982   struct elf_link_hash_entry *h;
6983   struct bfd_link_hash_entry *bh;
6984   flagword flags;
6985   register asection *s;
6986   const char * const *namep;
6987   struct mips_elf_link_hash_table *htab;
6988
6989   htab = mips_elf_hash_table (info);
6990   BFD_ASSERT (htab != NULL);
6991
6992   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
6993            | SEC_LINKER_CREATED | SEC_READONLY);
6994
6995   /* The psABI requires a read-only .dynamic section, but the VxWorks
6996      EABI doesn't.  */
6997   if (!htab->is_vxworks)
6998     {
6999       s = bfd_get_linker_section (abfd, ".dynamic");
7000       if (s != NULL)
7001         {
7002           if (! bfd_set_section_flags (abfd, s, flags))
7003             return FALSE;
7004         }
7005     }
7006
7007   /* We need to create .got section.  */
7008   if (!mips_elf_create_got_section (abfd, info))
7009     return FALSE;
7010
7011   if (! mips_elf_rel_dyn_section (info, TRUE))
7012     return FALSE;
7013
7014   /* Create .stub section.  */
7015   s = bfd_make_section_anyway_with_flags (abfd,
7016                                           MIPS_ELF_STUB_SECTION_NAME (abfd),
7017                                           flags | SEC_CODE);
7018   if (s == NULL
7019       || ! bfd_set_section_alignment (abfd, s,
7020                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7021     return FALSE;
7022   htab->sstubs = s;
7023
7024   if (!mips_elf_hash_table (info)->use_rld_obj_head
7025       && !info->shared
7026       && bfd_get_linker_section (abfd, ".rld_map") == NULL)
7027     {
7028       s = bfd_make_section_anyway_with_flags (abfd, ".rld_map",
7029                                               flags &~ (flagword) SEC_READONLY);
7030       if (s == NULL
7031           || ! bfd_set_section_alignment (abfd, s,
7032                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7033         return FALSE;
7034     }
7035
7036   /* On IRIX5, we adjust add some additional symbols and change the
7037      alignments of several sections.  There is no ABI documentation
7038      indicating that this is necessary on IRIX6, nor any evidence that
7039      the linker takes such action.  */
7040   if (IRIX_COMPAT (abfd) == ict_irix5)
7041     {
7042       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7043         {
7044           bh = NULL;
7045           if (! (_bfd_generic_link_add_one_symbol
7046                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7047                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7048             return FALSE;
7049
7050           h = (struct elf_link_hash_entry *) bh;
7051           h->non_elf = 0;
7052           h->def_regular = 1;
7053           h->type = STT_SECTION;
7054
7055           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7056             return FALSE;
7057         }
7058
7059       /* We need to create a .compact_rel section.  */
7060       if (SGI_COMPAT (abfd))
7061         {
7062           if (!mips_elf_create_compact_rel_section (abfd, info))
7063             return FALSE;
7064         }
7065
7066       /* Change alignments of some sections.  */
7067       s = bfd_get_linker_section (abfd, ".hash");
7068       if (s != NULL)
7069         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7070       s = bfd_get_linker_section (abfd, ".dynsym");
7071       if (s != NULL)
7072         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7073       s = bfd_get_linker_section (abfd, ".dynstr");
7074       if (s != NULL)
7075         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7076       /* ??? */
7077       s = bfd_get_section_by_name (abfd, ".reginfo");
7078       if (s != NULL)
7079         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7080       s = bfd_get_linker_section (abfd, ".dynamic");
7081       if (s != NULL)
7082         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7083     }
7084
7085   if (!info->shared)
7086     {
7087       const char *name;
7088
7089       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7090       bh = NULL;
7091       if (!(_bfd_generic_link_add_one_symbol
7092             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7093              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7094         return FALSE;
7095
7096       h = (struct elf_link_hash_entry *) bh;
7097       h->non_elf = 0;
7098       h->def_regular = 1;
7099       h->type = STT_SECTION;
7100
7101       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7102         return FALSE;
7103
7104       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7105         {
7106           /* __rld_map is a four byte word located in the .data section
7107              and is filled in by the rtld to contain a pointer to
7108              the _r_debug structure. Its symbol value will be set in
7109              _bfd_mips_elf_finish_dynamic_symbol.  */
7110           s = bfd_get_linker_section (abfd, ".rld_map");
7111           BFD_ASSERT (s != NULL);
7112
7113           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7114           bh = NULL;
7115           if (!(_bfd_generic_link_add_one_symbol
7116                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7117                  get_elf_backend_data (abfd)->collect, &bh)))
7118             return FALSE;
7119
7120           h = (struct elf_link_hash_entry *) bh;
7121           h->non_elf = 0;
7122           h->def_regular = 1;
7123           h->type = STT_OBJECT;
7124
7125           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7126             return FALSE;
7127           mips_elf_hash_table (info)->rld_symbol = h;
7128         }
7129     }
7130
7131   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7132      Also create the _PROCEDURE_LINKAGE_TABLE symbol.  */
7133   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7134     return FALSE;
7135
7136   /* Cache the sections created above.  */
7137   htab->splt = bfd_get_linker_section (abfd, ".plt");
7138   htab->sdynbss = bfd_get_linker_section (abfd, ".dynbss");
7139   if (htab->is_vxworks)
7140     {
7141       htab->srelbss = bfd_get_linker_section (abfd, ".rela.bss");
7142       htab->srelplt = bfd_get_linker_section (abfd, ".rela.plt");
7143     }
7144   else
7145     htab->srelplt = bfd_get_linker_section (abfd, ".rel.plt");
7146   if (!htab->sdynbss
7147       || (htab->is_vxworks && !htab->srelbss && !info->shared)
7148       || !htab->srelplt
7149       || !htab->splt)
7150     abort ();
7151
7152   if (htab->is_vxworks)
7153     {
7154       /* Do the usual VxWorks handling.  */
7155       if (!elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7156         return FALSE;
7157
7158       /* Work out the PLT sizes.  */
7159       if (info->shared)
7160         {
7161           htab->plt_header_size
7162             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
7163           htab->plt_entry_size
7164             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
7165         }
7166       else
7167         {
7168           htab->plt_header_size
7169             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
7170           htab->plt_entry_size
7171             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
7172         }
7173     }
7174   else if (!info->shared)
7175     {
7176       /* All variants of the plt0 entry are the same size.  */
7177       htab->plt_header_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
7178       htab->plt_entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
7179     }
7180
7181   return TRUE;
7182 }
7183 \f
7184 /* Return true if relocation REL against section SEC is a REL rather than
7185    RELA relocation.  RELOCS is the first relocation in the section and
7186    ABFD is the bfd that contains SEC.  */
7187
7188 static bfd_boolean
7189 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7190                            const Elf_Internal_Rela *relocs,
7191                            const Elf_Internal_Rela *rel)
7192 {
7193   Elf_Internal_Shdr *rel_hdr;
7194   const struct elf_backend_data *bed;
7195
7196   /* To determine which flavor of relocation this is, we depend on the
7197      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7198   rel_hdr = elf_section_data (sec)->rel.hdr;
7199   if (rel_hdr == NULL)
7200     return FALSE;
7201   bed = get_elf_backend_data (abfd);
7202   return ((size_t) (rel - relocs)
7203           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7204 }
7205
7206 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7207    HOWTO is the relocation's howto and CONTENTS points to the contents
7208    of the section that REL is against.  */
7209
7210 static bfd_vma
7211 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7212                           reloc_howto_type *howto, bfd_byte *contents)
7213 {
7214   bfd_byte *location;
7215   unsigned int r_type;
7216   bfd_vma addend;
7217
7218   r_type = ELF_R_TYPE (abfd, rel->r_info);
7219   location = contents + rel->r_offset;
7220
7221   /* Get the addend, which is stored in the input file.  */
7222   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7223   addend = mips_elf_obtain_contents (howto, rel, abfd, contents);
7224   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7225
7226   return addend & howto->src_mask;
7227 }
7228
7229 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7230    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7231    and update *ADDEND with the final addend.  Return true on success
7232    or false if the LO16 could not be found.  RELEND is the exclusive
7233    upper bound on the relocations for REL's section.  */
7234
7235 static bfd_boolean
7236 mips_elf_add_lo16_rel_addend (bfd *abfd,
7237                               const Elf_Internal_Rela *rel,
7238                               const Elf_Internal_Rela *relend,
7239                               bfd_byte *contents, bfd_vma *addend)
7240 {
7241   unsigned int r_type, lo16_type;
7242   const Elf_Internal_Rela *lo16_relocation;
7243   reloc_howto_type *lo16_howto;
7244   bfd_vma l;
7245
7246   r_type = ELF_R_TYPE (abfd, rel->r_info);
7247   if (mips16_reloc_p (r_type))
7248     lo16_type = R_MIPS16_LO16;
7249   else if (micromips_reloc_p (r_type))
7250     lo16_type = R_MICROMIPS_LO16;
7251   else
7252     lo16_type = R_MIPS_LO16;
7253
7254   /* The combined value is the sum of the HI16 addend, left-shifted by
7255      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7256      code does a `lui' of the HI16 value, and then an `addiu' of the
7257      LO16 value.)
7258
7259      Scan ahead to find a matching LO16 relocation.
7260
7261      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7262      be immediately following.  However, for the IRIX6 ABI, the next
7263      relocation may be a composed relocation consisting of several
7264      relocations for the same address.  In that case, the R_MIPS_LO16
7265      relocation may occur as one of these.  We permit a similar
7266      extension in general, as that is useful for GCC.
7267
7268      In some cases GCC dead code elimination removes the LO16 but keeps
7269      the corresponding HI16.  This is strictly speaking a violation of
7270      the ABI but not immediately harmful.  */
7271   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
7272   if (lo16_relocation == NULL)
7273     return FALSE;
7274
7275   /* Obtain the addend kept there.  */
7276   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
7277   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
7278
7279   l <<= lo16_howto->rightshift;
7280   l = _bfd_mips_elf_sign_extend (l, 16);
7281
7282   *addend <<= 16;
7283   *addend += l;
7284   return TRUE;
7285 }
7286
7287 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
7288    store the contents in *CONTENTS on success.  Assume that *CONTENTS
7289    already holds the contents if it is nonull on entry.  */
7290
7291 static bfd_boolean
7292 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
7293 {
7294   if (*contents)
7295     return TRUE;
7296
7297   /* Get cached copy if it exists.  */
7298   if (elf_section_data (sec)->this_hdr.contents != NULL)
7299     {
7300       *contents = elf_section_data (sec)->this_hdr.contents;
7301       return TRUE;
7302     }
7303
7304   return bfd_malloc_and_get_section (abfd, sec, contents);
7305 }
7306
7307 /* Look through the relocs for a section during the first phase, and
7308    allocate space in the global offset table.  */
7309
7310 bfd_boolean
7311 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
7312                             asection *sec, const Elf_Internal_Rela *relocs)
7313 {
7314   const char *name;
7315   bfd *dynobj;
7316   Elf_Internal_Shdr *symtab_hdr;
7317   struct elf_link_hash_entry **sym_hashes;
7318   size_t extsymoff;
7319   const Elf_Internal_Rela *rel;
7320   const Elf_Internal_Rela *rel_end;
7321   asection *sreloc;
7322   const struct elf_backend_data *bed;
7323   struct mips_elf_link_hash_table *htab;
7324   bfd_byte *contents;
7325   bfd_vma addend;
7326   reloc_howto_type *howto;
7327
7328   if (info->relocatable)
7329     return TRUE;
7330
7331   htab = mips_elf_hash_table (info);
7332   BFD_ASSERT (htab != NULL);
7333
7334   dynobj = elf_hash_table (info)->dynobj;
7335   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7336   sym_hashes = elf_sym_hashes (abfd);
7337   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
7338
7339   bed = get_elf_backend_data (abfd);
7340   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
7341
7342   /* Check for the mips16 stub sections.  */
7343
7344   name = bfd_get_section_name (abfd, sec);
7345   if (FN_STUB_P (name))
7346     {
7347       unsigned long r_symndx;
7348
7349       /* Look at the relocation information to figure out which symbol
7350          this is for.  */
7351
7352       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7353       if (r_symndx == 0)
7354         {
7355           (*_bfd_error_handler)
7356             (_("%B: Warning: cannot determine the target function for"
7357                " stub section `%s'"),
7358              abfd, name);
7359           bfd_set_error (bfd_error_bad_value);
7360           return FALSE;
7361         }
7362
7363       if (r_symndx < extsymoff
7364           || sym_hashes[r_symndx - extsymoff] == NULL)
7365         {
7366           asection *o;
7367
7368           /* This stub is for a local symbol.  This stub will only be
7369              needed if there is some relocation in this BFD, other
7370              than a 16 bit function call, which refers to this symbol.  */
7371           for (o = abfd->sections; o != NULL; o = o->next)
7372             {
7373               Elf_Internal_Rela *sec_relocs;
7374               const Elf_Internal_Rela *r, *rend;
7375
7376               /* We can ignore stub sections when looking for relocs.  */
7377               if ((o->flags & SEC_RELOC) == 0
7378                   || o->reloc_count == 0
7379                   || section_allows_mips16_refs_p (o))
7380                 continue;
7381
7382               sec_relocs
7383                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7384                                              info->keep_memory);
7385               if (sec_relocs == NULL)
7386                 return FALSE;
7387
7388               rend = sec_relocs + o->reloc_count;
7389               for (r = sec_relocs; r < rend; r++)
7390                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7391                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
7392                   break;
7393
7394               if (elf_section_data (o)->relocs != sec_relocs)
7395                 free (sec_relocs);
7396
7397               if (r < rend)
7398                 break;
7399             }
7400
7401           if (o == NULL)
7402             {
7403               /* There is no non-call reloc for this stub, so we do
7404                  not need it.  Since this function is called before
7405                  the linker maps input sections to output sections, we
7406                  can easily discard it by setting the SEC_EXCLUDE
7407                  flag.  */
7408               sec->flags |= SEC_EXCLUDE;
7409               return TRUE;
7410             }
7411
7412           /* Record this stub in an array of local symbol stubs for
7413              this BFD.  */
7414           if (elf_tdata (abfd)->local_stubs == NULL)
7415             {
7416               unsigned long symcount;
7417               asection **n;
7418               bfd_size_type amt;
7419
7420               if (elf_bad_symtab (abfd))
7421                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7422               else
7423                 symcount = symtab_hdr->sh_info;
7424               amt = symcount * sizeof (asection *);
7425               n = bfd_zalloc (abfd, amt);
7426               if (n == NULL)
7427                 return FALSE;
7428               elf_tdata (abfd)->local_stubs = n;
7429             }
7430
7431           sec->flags |= SEC_KEEP;
7432           elf_tdata (abfd)->local_stubs[r_symndx] = sec;
7433
7434           /* We don't need to set mips16_stubs_seen in this case.
7435              That flag is used to see whether we need to look through
7436              the global symbol table for stubs.  We don't need to set
7437              it here, because we just have a local stub.  */
7438         }
7439       else
7440         {
7441           struct mips_elf_link_hash_entry *h;
7442
7443           h = ((struct mips_elf_link_hash_entry *)
7444                sym_hashes[r_symndx - extsymoff]);
7445
7446           while (h->root.root.type == bfd_link_hash_indirect
7447                  || h->root.root.type == bfd_link_hash_warning)
7448             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
7449
7450           /* H is the symbol this stub is for.  */
7451
7452           /* If we already have an appropriate stub for this function, we
7453              don't need another one, so we can discard this one.  Since
7454              this function is called before the linker maps input sections
7455              to output sections, we can easily discard it by setting the
7456              SEC_EXCLUDE flag.  */
7457           if (h->fn_stub != NULL)
7458             {
7459               sec->flags |= SEC_EXCLUDE;
7460               return TRUE;
7461             }
7462
7463           sec->flags |= SEC_KEEP;
7464           h->fn_stub = sec;
7465           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7466         }
7467     }
7468   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
7469     {
7470       unsigned long r_symndx;
7471       struct mips_elf_link_hash_entry *h;
7472       asection **loc;
7473
7474       /* Look at the relocation information to figure out which symbol
7475          this is for.  */
7476
7477       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7478       if (r_symndx == 0)
7479         {
7480           (*_bfd_error_handler)
7481             (_("%B: Warning: cannot determine the target function for"
7482                " stub section `%s'"),
7483              abfd, name);
7484           bfd_set_error (bfd_error_bad_value);
7485           return FALSE;
7486         }
7487
7488       if (r_symndx < extsymoff
7489           || sym_hashes[r_symndx - extsymoff] == NULL)
7490         {
7491           asection *o;
7492
7493           /* This stub is for a local symbol.  This stub will only be
7494              needed if there is some relocation (R_MIPS16_26) in this BFD
7495              that refers to this symbol.  */
7496           for (o = abfd->sections; o != NULL; o = o->next)
7497             {
7498               Elf_Internal_Rela *sec_relocs;
7499               const Elf_Internal_Rela *r, *rend;
7500
7501               /* We can ignore stub sections when looking for relocs.  */
7502               if ((o->flags & SEC_RELOC) == 0
7503                   || o->reloc_count == 0
7504                   || section_allows_mips16_refs_p (o))
7505                 continue;
7506
7507               sec_relocs
7508                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7509                                              info->keep_memory);
7510               if (sec_relocs == NULL)
7511                 return FALSE;
7512
7513               rend = sec_relocs + o->reloc_count;
7514               for (r = sec_relocs; r < rend; r++)
7515                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7516                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
7517                     break;
7518
7519               if (elf_section_data (o)->relocs != sec_relocs)
7520                 free (sec_relocs);
7521
7522               if (r < rend)
7523                 break;
7524             }
7525
7526           if (o == NULL)
7527             {
7528               /* There is no non-call reloc for this stub, so we do
7529                  not need it.  Since this function is called before
7530                  the linker maps input sections to output sections, we
7531                  can easily discard it by setting the SEC_EXCLUDE
7532                  flag.  */
7533               sec->flags |= SEC_EXCLUDE;
7534               return TRUE;
7535             }
7536
7537           /* Record this stub in an array of local symbol call_stubs for
7538              this BFD.  */
7539           if (elf_tdata (abfd)->local_call_stubs == NULL)
7540             {
7541               unsigned long symcount;
7542               asection **n;
7543               bfd_size_type amt;
7544
7545               if (elf_bad_symtab (abfd))
7546                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7547               else
7548                 symcount = symtab_hdr->sh_info;
7549               amt = symcount * sizeof (asection *);
7550               n = bfd_zalloc (abfd, amt);
7551               if (n == NULL)
7552                 return FALSE;
7553               elf_tdata (abfd)->local_call_stubs = n;
7554             }
7555
7556           sec->flags |= SEC_KEEP;
7557           elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
7558
7559           /* We don't need to set mips16_stubs_seen in this case.
7560              That flag is used to see whether we need to look through
7561              the global symbol table for stubs.  We don't need to set
7562              it here, because we just have a local stub.  */
7563         }
7564       else
7565         {
7566           h = ((struct mips_elf_link_hash_entry *)
7567                sym_hashes[r_symndx - extsymoff]);
7568
7569           /* H is the symbol this stub is for.  */
7570
7571           if (CALL_FP_STUB_P (name))
7572             loc = &h->call_fp_stub;
7573           else
7574             loc = &h->call_stub;
7575
7576           /* If we already have an appropriate stub for this function, we
7577              don't need another one, so we can discard this one.  Since
7578              this function is called before the linker maps input sections
7579              to output sections, we can easily discard it by setting the
7580              SEC_EXCLUDE flag.  */
7581           if (*loc != NULL)
7582             {
7583               sec->flags |= SEC_EXCLUDE;
7584               return TRUE;
7585             }
7586
7587           sec->flags |= SEC_KEEP;
7588           *loc = sec;
7589           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7590         }
7591     }
7592
7593   sreloc = NULL;
7594   contents = NULL;
7595   for (rel = relocs; rel < rel_end; ++rel)
7596     {
7597       unsigned long r_symndx;
7598       unsigned int r_type;
7599       struct elf_link_hash_entry *h;
7600       bfd_boolean can_make_dynamic_p;
7601
7602       r_symndx = ELF_R_SYM (abfd, rel->r_info);
7603       r_type = ELF_R_TYPE (abfd, rel->r_info);
7604
7605       if (r_symndx < extsymoff)
7606         h = NULL;
7607       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
7608         {
7609           (*_bfd_error_handler)
7610             (_("%B: Malformed reloc detected for section %s"),
7611              abfd, name);
7612           bfd_set_error (bfd_error_bad_value);
7613           return FALSE;
7614         }
7615       else
7616         {
7617           h = sym_hashes[r_symndx - extsymoff];
7618           while (h != NULL
7619                  && (h->root.type == bfd_link_hash_indirect
7620                      || h->root.type == bfd_link_hash_warning))
7621             h = (struct elf_link_hash_entry *) h->root.u.i.link;
7622         }
7623
7624       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
7625          relocation into a dynamic one.  */
7626       can_make_dynamic_p = FALSE;
7627       switch (r_type)
7628         {
7629         case R_MIPS_GOT16:
7630         case R_MIPS_CALL16:
7631         case R_MIPS_CALL_HI16:
7632         case R_MIPS_CALL_LO16:
7633         case R_MIPS_GOT_HI16:
7634         case R_MIPS_GOT_LO16:
7635         case R_MIPS_GOT_PAGE:
7636         case R_MIPS_GOT_OFST:
7637         case R_MIPS_GOT_DISP:
7638         case R_MIPS_TLS_GOTTPREL:
7639         case R_MIPS_TLS_GD:
7640         case R_MIPS_TLS_LDM:
7641         case R_MIPS16_GOT16:
7642         case R_MIPS16_CALL16:
7643         case R_MIPS16_TLS_GOTTPREL:
7644         case R_MIPS16_TLS_GD:
7645         case R_MIPS16_TLS_LDM:
7646         case R_MICROMIPS_GOT16:
7647         case R_MICROMIPS_CALL16:
7648         case R_MICROMIPS_CALL_HI16:
7649         case R_MICROMIPS_CALL_LO16:
7650         case R_MICROMIPS_GOT_HI16:
7651         case R_MICROMIPS_GOT_LO16:
7652         case R_MICROMIPS_GOT_PAGE:
7653         case R_MICROMIPS_GOT_OFST:
7654         case R_MICROMIPS_GOT_DISP:
7655         case R_MICROMIPS_TLS_GOTTPREL:
7656         case R_MICROMIPS_TLS_GD:
7657         case R_MICROMIPS_TLS_LDM:
7658           if (dynobj == NULL)
7659             elf_hash_table (info)->dynobj = dynobj = abfd;
7660           if (!mips_elf_create_got_section (dynobj, info))
7661             return FALSE;
7662           if (htab->is_vxworks && !info->shared)
7663             {
7664               (*_bfd_error_handler)
7665                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
7666                  abfd, (unsigned long) rel->r_offset);
7667               bfd_set_error (bfd_error_bad_value);
7668               return FALSE;
7669             }
7670           break;
7671
7672           /* This is just a hint; it can safely be ignored.  Don't set
7673              has_static_relocs for the corresponding symbol.  */
7674         case R_MIPS_JALR:
7675         case R_MICROMIPS_JALR:
7676           break;
7677
7678         case R_MIPS_32:
7679         case R_MIPS_REL32:
7680         case R_MIPS_64:
7681           /* In VxWorks executables, references to external symbols
7682              must be handled using copy relocs or PLT entries; it is not
7683              possible to convert this relocation into a dynamic one.
7684
7685              For executables that use PLTs and copy-relocs, we have a
7686              choice between converting the relocation into a dynamic
7687              one or using copy relocations or PLT entries.  It is
7688              usually better to do the former, unless the relocation is
7689              against a read-only section.  */
7690           if ((info->shared
7691                || (h != NULL
7692                    && !htab->is_vxworks
7693                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
7694                    && !(!info->nocopyreloc
7695                         && !PIC_OBJECT_P (abfd)
7696                         && MIPS_ELF_READONLY_SECTION (sec))))
7697               && (sec->flags & SEC_ALLOC) != 0)
7698             {
7699               can_make_dynamic_p = TRUE;
7700               if (dynobj == NULL)
7701                 elf_hash_table (info)->dynobj = dynobj = abfd;
7702               break;
7703             }
7704           /* For sections that are not SEC_ALLOC a copy reloc would be
7705              output if possible (implying questionable semantics for
7706              read-only data objects) or otherwise the final link would
7707              fail as ld.so will not process them and could not therefore
7708              handle any outstanding dynamic relocations.
7709
7710              For such sections that are also SEC_DEBUGGING, we can avoid
7711              these problems by simply ignoring any relocs as these
7712              sections have a predefined use and we know it is safe to do
7713              so.
7714
7715              This is needed in cases such as a global symbol definition
7716              in a shared library causing a common symbol from an object
7717              file to be converted to an undefined reference.  If that
7718              happens, then all the relocations against this symbol from
7719              SEC_DEBUGGING sections in the object file will resolve to
7720              nil.  */
7721           if ((sec->flags & SEC_DEBUGGING) != 0)
7722             break;
7723           /* Fall through.  */
7724
7725         default:
7726           /* Most static relocations require pointer equality, except
7727              for branches.  */
7728           if (h)
7729             h->pointer_equality_needed = TRUE;
7730           /* Fall through.  */
7731
7732         case R_MIPS_26:
7733         case R_MIPS_PC16:
7734         case R_MIPS16_26:
7735         case R_MICROMIPS_26_S1:
7736         case R_MICROMIPS_PC7_S1:
7737         case R_MICROMIPS_PC10_S1:
7738         case R_MICROMIPS_PC16_S1:
7739         case R_MICROMIPS_PC23_S2:
7740           if (h)
7741             ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = TRUE;
7742           break;
7743         }
7744
7745       if (h)
7746         {
7747           /* Relocations against the special VxWorks __GOTT_BASE__ and
7748              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
7749              room for them in .rela.dyn.  */
7750           if (is_gott_symbol (info, h))
7751             {
7752               if (sreloc == NULL)
7753                 {
7754                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
7755                   if (sreloc == NULL)
7756                     return FALSE;
7757                 }
7758               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
7759               if (MIPS_ELF_READONLY_SECTION (sec))
7760                 /* We tell the dynamic linker that there are
7761                    relocations against the text segment.  */
7762                 info->flags |= DF_TEXTREL;
7763             }
7764         }
7765       else if (call_lo16_reloc_p (r_type)
7766                || got_lo16_reloc_p (r_type)
7767                || got_disp_reloc_p (r_type)
7768                || (got16_reloc_p (r_type) && htab->is_vxworks))
7769         {
7770           /* We may need a local GOT entry for this relocation.  We
7771              don't count R_MIPS_GOT_PAGE because we can estimate the
7772              maximum number of pages needed by looking at the size of
7773              the segment.  Similar comments apply to R_MIPS*_GOT16 and
7774              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
7775              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
7776              R_MIPS_CALL_HI16 because these are always followed by an
7777              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
7778           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
7779                                                  rel->r_addend, info, r_type))
7780             return FALSE;
7781         }
7782
7783       if (h != NULL
7784           && mips_elf_relocation_needs_la25_stub (abfd, r_type,
7785                                                   ELF_ST_IS_MIPS16 (h->other)))
7786         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
7787
7788       switch (r_type)
7789         {
7790         case R_MIPS_CALL16:
7791         case R_MIPS16_CALL16:
7792         case R_MICROMIPS_CALL16:
7793           if (h == NULL)
7794             {
7795               (*_bfd_error_handler)
7796                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
7797                  abfd, (unsigned long) rel->r_offset);
7798               bfd_set_error (bfd_error_bad_value);
7799               return FALSE;
7800             }
7801           /* Fall through.  */
7802
7803         case R_MIPS_CALL_HI16:
7804         case R_MIPS_CALL_LO16:
7805         case R_MICROMIPS_CALL_HI16:
7806         case R_MICROMIPS_CALL_LO16:
7807           if (h != NULL)
7808             {
7809               /* Make sure there is room in the regular GOT to hold the
7810                  function's address.  We may eliminate it in favour of
7811                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
7812               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE,
7813                                                       r_type))
7814                 return FALSE;
7815
7816               /* We need a stub, not a plt entry for the undefined
7817                  function.  But we record it as if it needs plt.  See
7818                  _bfd_elf_adjust_dynamic_symbol.  */
7819               h->needs_plt = 1;
7820               h->type = STT_FUNC;
7821             }
7822           break;
7823
7824         case R_MIPS_GOT_PAGE:
7825         case R_MICROMIPS_GOT_PAGE:
7826           /* If this is a global, overridable symbol, GOT_PAGE will
7827              decay to GOT_DISP, so we'll need a GOT entry for it.  */
7828           if (h)
7829             {
7830               struct mips_elf_link_hash_entry *hmips =
7831                 (struct mips_elf_link_hash_entry *) h;
7832
7833               /* This symbol is definitely not overridable.  */
7834               if (hmips->root.def_regular
7835                   && ! (info->shared && ! info->symbolic
7836                         && ! hmips->root.forced_local))
7837                 h = NULL;
7838             }
7839           /* Fall through.  */
7840
7841         case R_MIPS16_GOT16:
7842         case R_MIPS_GOT16:
7843         case R_MIPS_GOT_HI16:
7844         case R_MIPS_GOT_LO16:
7845         case R_MICROMIPS_GOT16:
7846         case R_MICROMIPS_GOT_HI16:
7847         case R_MICROMIPS_GOT_LO16:
7848           if (!h || got_page_reloc_p (r_type))
7849             {
7850               /* This relocation needs (or may need, if h != NULL) a
7851                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
7852                  know for sure until we know whether the symbol is
7853                  preemptible.  */
7854               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
7855                 {
7856                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
7857                     return FALSE;
7858                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
7859                   addend = mips_elf_read_rel_addend (abfd, rel,
7860                                                      howto, contents);
7861                   if (got16_reloc_p (r_type))
7862                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
7863                                                   contents, &addend);
7864                   else
7865                     addend <<= howto->rightshift;
7866                 }
7867               else
7868                 addend = rel->r_addend;
7869               if (!mips_elf_record_got_page_entry (info, abfd, r_symndx,
7870                                                    addend))
7871                 return FALSE;
7872             }
7873           /* Fall through.  */
7874
7875         case R_MIPS_GOT_DISP:
7876         case R_MICROMIPS_GOT_DISP:
7877           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
7878                                                        FALSE, r_type))
7879             return FALSE;
7880           break;
7881
7882         case R_MIPS_TLS_GOTTPREL:
7883         case R_MIPS16_TLS_GOTTPREL:
7884         case R_MICROMIPS_TLS_GOTTPREL:
7885           if (info->shared)
7886             info->flags |= DF_STATIC_TLS;
7887           /* Fall through */
7888
7889         case R_MIPS_TLS_LDM:
7890         case R_MIPS16_TLS_LDM:
7891         case R_MICROMIPS_TLS_LDM:
7892           if (tls_ldm_reloc_p (r_type))
7893             {
7894               r_symndx = STN_UNDEF;
7895               h = NULL;
7896             }
7897           /* Fall through */
7898
7899         case R_MIPS_TLS_GD:
7900         case R_MIPS16_TLS_GD:
7901         case R_MICROMIPS_TLS_GD:
7902           /* This symbol requires a global offset table entry, or two
7903              for TLS GD relocations.  */
7904           if (h != NULL)
7905             {
7906               if (!mips_elf_record_global_got_symbol (h, abfd, info,
7907                                                       FALSE, r_type))
7908                 return FALSE;
7909             }
7910           else
7911             {
7912               if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
7913                                                      rel->r_addend,
7914                                                      info, r_type))
7915                 return FALSE;
7916             }
7917           break;
7918
7919         case R_MIPS_32:
7920         case R_MIPS_REL32:
7921         case R_MIPS_64:
7922           /* In VxWorks executables, references to external symbols
7923              are handled using copy relocs or PLT stubs, so there's
7924              no need to add a .rela.dyn entry for this relocation.  */
7925           if (can_make_dynamic_p)
7926             {
7927               if (sreloc == NULL)
7928                 {
7929                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
7930                   if (sreloc == NULL)
7931                     return FALSE;
7932                 }
7933               if (info->shared && h == NULL)
7934                 {
7935                   /* When creating a shared object, we must copy these
7936                      reloc types into the output file as R_MIPS_REL32
7937                      relocs.  Make room for this reloc in .rel(a).dyn.  */
7938                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
7939                   if (MIPS_ELF_READONLY_SECTION (sec))
7940                     /* We tell the dynamic linker that there are
7941                        relocations against the text segment.  */
7942                     info->flags |= DF_TEXTREL;
7943                 }
7944               else
7945                 {
7946                   struct mips_elf_link_hash_entry *hmips;
7947
7948                   /* For a shared object, we must copy this relocation
7949                      unless the symbol turns out to be undefined and
7950                      weak with non-default visibility, in which case
7951                      it will be left as zero.
7952
7953                      We could elide R_MIPS_REL32 for locally binding symbols
7954                      in shared libraries, but do not yet do so.
7955
7956                      For an executable, we only need to copy this
7957                      reloc if the symbol is defined in a dynamic
7958                      object.  */
7959                   hmips = (struct mips_elf_link_hash_entry *) h;
7960                   ++hmips->possibly_dynamic_relocs;
7961                   if (MIPS_ELF_READONLY_SECTION (sec))
7962                     /* We need it to tell the dynamic linker if there
7963                        are relocations against the text segment.  */
7964                     hmips->readonly_reloc = TRUE;
7965                 }
7966             }
7967
7968           if (SGI_COMPAT (abfd))
7969             mips_elf_hash_table (info)->compact_rel_size +=
7970               sizeof (Elf32_External_crinfo);
7971           break;
7972
7973         case R_MIPS_26:
7974         case R_MIPS_GPREL16:
7975         case R_MIPS_LITERAL:
7976         case R_MIPS_GPREL32:
7977         case R_MICROMIPS_26_S1:
7978         case R_MICROMIPS_GPREL16:
7979         case R_MICROMIPS_LITERAL:
7980         case R_MICROMIPS_GPREL7_S2:
7981           if (SGI_COMPAT (abfd))
7982             mips_elf_hash_table (info)->compact_rel_size +=
7983               sizeof (Elf32_External_crinfo);
7984           break;
7985
7986           /* This relocation describes the C++ object vtable hierarchy.
7987              Reconstruct it for later use during GC.  */
7988         case R_MIPS_GNU_VTINHERIT:
7989           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
7990             return FALSE;
7991           break;
7992
7993           /* This relocation describes which C++ vtable entries are actually
7994              used.  Record for later use during GC.  */
7995         case R_MIPS_GNU_VTENTRY:
7996           BFD_ASSERT (h != NULL);
7997           if (h != NULL
7998               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
7999             return FALSE;
8000           break;
8001
8002         default:
8003           break;
8004         }
8005
8006       /* We must not create a stub for a symbol that has relocations
8007          related to taking the function's address.  This doesn't apply to
8008          VxWorks, where CALL relocs refer to a .got.plt entry instead of
8009          a normal .got entry.  */
8010       if (!htab->is_vxworks && h != NULL)
8011         switch (r_type)
8012           {
8013           default:
8014             ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8015             break;
8016           case R_MIPS16_CALL16:
8017           case R_MIPS_CALL16:
8018           case R_MIPS_CALL_HI16:
8019           case R_MIPS_CALL_LO16:
8020           case R_MIPS_JALR:
8021           case R_MICROMIPS_CALL16:
8022           case R_MICROMIPS_CALL_HI16:
8023           case R_MICROMIPS_CALL_LO16:
8024           case R_MICROMIPS_JALR:
8025             break;
8026           }
8027
8028       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8029          if there is one.  We only need to handle global symbols here;
8030          we decide whether to keep or delete stubs for local symbols
8031          when processing the stub's relocations.  */
8032       if (h != NULL
8033           && !mips16_call_reloc_p (r_type)
8034           && !section_allows_mips16_refs_p (sec))
8035         {
8036           struct mips_elf_link_hash_entry *mh;
8037
8038           mh = (struct mips_elf_link_hash_entry *) h;
8039           mh->need_fn_stub = TRUE;
8040         }
8041
8042       /* Refuse some position-dependent relocations when creating a
8043          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8044          not PIC, but we can create dynamic relocations and the result
8045          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8046          combined with R_MIPS_GOT16.  */
8047       if (info->shared)
8048         {
8049           switch (r_type)
8050             {
8051             case R_MIPS16_HI16:
8052             case R_MIPS_HI16:
8053             case R_MIPS_HIGHER:
8054             case R_MIPS_HIGHEST:
8055             case R_MICROMIPS_HI16:
8056             case R_MICROMIPS_HIGHER:
8057             case R_MICROMIPS_HIGHEST:
8058               /* Don't refuse a high part relocation if it's against
8059                  no symbol (e.g. part of a compound relocation).  */
8060               if (r_symndx == STN_UNDEF)
8061                 break;
8062
8063               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8064                  and has a special meaning.  */
8065               if (!NEWABI_P (abfd) && h != NULL
8066                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8067                 break;
8068
8069               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8070               if (is_gott_symbol (info, h))
8071                 break;
8072
8073               /* FALLTHROUGH */
8074
8075             case R_MIPS16_26:
8076             case R_MIPS_26:
8077             case R_MICROMIPS_26_S1:
8078               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8079               (*_bfd_error_handler)
8080                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8081                  abfd, howto->name,
8082                  (h) ? h->root.root.string : "a local symbol");
8083               bfd_set_error (bfd_error_bad_value);
8084               return FALSE;
8085             default:
8086               break;
8087             }
8088         }
8089     }
8090
8091   return TRUE;
8092 }
8093 \f
8094 bfd_boolean
8095 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8096                          struct bfd_link_info *link_info,
8097                          bfd_boolean *again)
8098 {
8099   Elf_Internal_Rela *internal_relocs;
8100   Elf_Internal_Rela *irel, *irelend;
8101   Elf_Internal_Shdr *symtab_hdr;
8102   bfd_byte *contents = NULL;
8103   size_t extsymoff;
8104   bfd_boolean changed_contents = FALSE;
8105   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8106   Elf_Internal_Sym *isymbuf = NULL;
8107
8108   /* We are not currently changing any sizes, so only one pass.  */
8109   *again = FALSE;
8110
8111   if (link_info->relocatable)
8112     return TRUE;
8113
8114   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8115                                                link_info->keep_memory);
8116   if (internal_relocs == NULL)
8117     return TRUE;
8118
8119   irelend = internal_relocs + sec->reloc_count
8120     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8121   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8122   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8123
8124   for (irel = internal_relocs; irel < irelend; irel++)
8125     {
8126       bfd_vma symval;
8127       bfd_signed_vma sym_offset;
8128       unsigned int r_type;
8129       unsigned long r_symndx;
8130       asection *sym_sec;
8131       unsigned long instruction;
8132
8133       /* Turn jalr into bgezal, and jr into beq, if they're marked
8134          with a JALR relocation, that indicate where they jump to.
8135          This saves some pipeline bubbles.  */
8136       r_type = ELF_R_TYPE (abfd, irel->r_info);
8137       if (r_type != R_MIPS_JALR)
8138         continue;
8139
8140       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8141       /* Compute the address of the jump target.  */
8142       if (r_symndx >= extsymoff)
8143         {
8144           struct mips_elf_link_hash_entry *h
8145             = ((struct mips_elf_link_hash_entry *)
8146                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8147
8148           while (h->root.root.type == bfd_link_hash_indirect
8149                  || h->root.root.type == bfd_link_hash_warning)
8150             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8151
8152           /* If a symbol is undefined, or if it may be overridden,
8153              skip it.  */
8154           if (! ((h->root.root.type == bfd_link_hash_defined
8155                   || h->root.root.type == bfd_link_hash_defweak)
8156                  && h->root.root.u.def.section)
8157               || (link_info->shared && ! link_info->symbolic
8158                   && !h->root.forced_local))
8159             continue;
8160
8161           sym_sec = h->root.root.u.def.section;
8162           if (sym_sec->output_section)
8163             symval = (h->root.root.u.def.value
8164                       + sym_sec->output_section->vma
8165                       + sym_sec->output_offset);
8166           else
8167             symval = h->root.root.u.def.value;
8168         }
8169       else
8170         {
8171           Elf_Internal_Sym *isym;
8172
8173           /* Read this BFD's symbols if we haven't done so already.  */
8174           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8175             {
8176               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8177               if (isymbuf == NULL)
8178                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8179                                                 symtab_hdr->sh_info, 0,
8180                                                 NULL, NULL, NULL);
8181               if (isymbuf == NULL)
8182                 goto relax_return;
8183             }
8184
8185           isym = isymbuf + r_symndx;
8186           if (isym->st_shndx == SHN_UNDEF)
8187             continue;
8188           else if (isym->st_shndx == SHN_ABS)
8189             sym_sec = bfd_abs_section_ptr;
8190           else if (isym->st_shndx == SHN_COMMON)
8191             sym_sec = bfd_com_section_ptr;
8192           else
8193             sym_sec
8194               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8195           symval = isym->st_value
8196             + sym_sec->output_section->vma
8197             + sym_sec->output_offset;
8198         }
8199
8200       /* Compute branch offset, from delay slot of the jump to the
8201          branch target.  */
8202       sym_offset = (symval + irel->r_addend)
8203         - (sec_start + irel->r_offset + 4);
8204
8205       /* Branch offset must be properly aligned.  */
8206       if ((sym_offset & 3) != 0)
8207         continue;
8208
8209       sym_offset >>= 2;
8210
8211       /* Check that it's in range.  */
8212       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
8213         continue;
8214
8215       /* Get the section contents if we haven't done so already.  */
8216       if (!mips_elf_get_section_contents (abfd, sec, &contents))
8217         goto relax_return;
8218
8219       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
8220
8221       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
8222       if ((instruction & 0xfc1fffff) == 0x0000f809)
8223         instruction = 0x04110000;
8224       /* If it was jr <reg>, turn it into b <target>.  */
8225       else if ((instruction & 0xfc1fffff) == 0x00000008)
8226         instruction = 0x10000000;
8227       else
8228         continue;
8229
8230       instruction |= (sym_offset & 0xffff);
8231       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
8232       changed_contents = TRUE;
8233     }
8234
8235   if (contents != NULL
8236       && elf_section_data (sec)->this_hdr.contents != contents)
8237     {
8238       if (!changed_contents && !link_info->keep_memory)
8239         free (contents);
8240       else
8241         {
8242           /* Cache the section contents for elf_link_input_bfd.  */
8243           elf_section_data (sec)->this_hdr.contents = contents;
8244         }
8245     }
8246   return TRUE;
8247
8248  relax_return:
8249   if (contents != NULL
8250       && elf_section_data (sec)->this_hdr.contents != contents)
8251     free (contents);
8252   return FALSE;
8253 }
8254 \f
8255 /* Allocate space for global sym dynamic relocs.  */
8256
8257 static bfd_boolean
8258 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
8259 {
8260   struct bfd_link_info *info = inf;
8261   bfd *dynobj;
8262   struct mips_elf_link_hash_entry *hmips;
8263   struct mips_elf_link_hash_table *htab;
8264
8265   htab = mips_elf_hash_table (info);
8266   BFD_ASSERT (htab != NULL);
8267
8268   dynobj = elf_hash_table (info)->dynobj;
8269   hmips = (struct mips_elf_link_hash_entry *) h;
8270
8271   /* VxWorks executables are handled elsewhere; we only need to
8272      allocate relocations in shared objects.  */
8273   if (htab->is_vxworks && !info->shared)
8274     return TRUE;
8275
8276   /* Ignore indirect symbols.  All relocations against such symbols
8277      will be redirected to the target symbol.  */
8278   if (h->root.type == bfd_link_hash_indirect)
8279     return TRUE;
8280
8281   /* If this symbol is defined in a dynamic object, or we are creating
8282      a shared library, we will need to copy any R_MIPS_32 or
8283      R_MIPS_REL32 relocs against it into the output file.  */
8284   if (! info->relocatable
8285       && hmips->possibly_dynamic_relocs != 0
8286       && (h->root.type == bfd_link_hash_defweak
8287           || (!h->def_regular && !ELF_COMMON_DEF_P (h))
8288           || info->shared))
8289     {
8290       bfd_boolean do_copy = TRUE;
8291
8292       if (h->root.type == bfd_link_hash_undefweak)
8293         {
8294           /* Do not copy relocations for undefined weak symbols with
8295              non-default visibility.  */
8296           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
8297             do_copy = FALSE;
8298
8299           /* Make sure undefined weak symbols are output as a dynamic
8300              symbol in PIEs.  */
8301           else if (h->dynindx == -1 && !h->forced_local)
8302             {
8303               if (! bfd_elf_link_record_dynamic_symbol (info, h))
8304                 return FALSE;
8305             }
8306         }
8307
8308       if (do_copy)
8309         {
8310           /* Even though we don't directly need a GOT entry for this symbol,
8311              the SVR4 psABI requires it to have a dynamic symbol table
8312              index greater that DT_MIPS_GOTSYM if there are dynamic
8313              relocations against it.
8314
8315              VxWorks does not enforce the same mapping between the GOT
8316              and the symbol table, so the same requirement does not
8317              apply there.  */
8318           if (!htab->is_vxworks)
8319             {
8320               if (hmips->global_got_area > GGA_RELOC_ONLY)
8321                 hmips->global_got_area = GGA_RELOC_ONLY;
8322               hmips->got_only_for_calls = FALSE;
8323             }
8324
8325           mips_elf_allocate_dynamic_relocations
8326             (dynobj, info, hmips->possibly_dynamic_relocs);
8327           if (hmips->readonly_reloc)
8328             /* We tell the dynamic linker that there are relocations
8329                against the text segment.  */
8330             info->flags |= DF_TEXTREL;
8331         }
8332     }
8333
8334   return TRUE;
8335 }
8336
8337 /* Adjust a symbol defined by a dynamic object and referenced by a
8338    regular object.  The current definition is in some section of the
8339    dynamic object, but we're not including those sections.  We have to
8340    change the definition to something the rest of the link can
8341    understand.  */
8342
8343 bfd_boolean
8344 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
8345                                      struct elf_link_hash_entry *h)
8346 {
8347   bfd *dynobj;
8348   struct mips_elf_link_hash_entry *hmips;
8349   struct mips_elf_link_hash_table *htab;
8350
8351   htab = mips_elf_hash_table (info);
8352   BFD_ASSERT (htab != NULL);
8353
8354   dynobj = elf_hash_table (info)->dynobj;
8355   hmips = (struct mips_elf_link_hash_entry *) h;
8356
8357   /* Make sure we know what is going on here.  */
8358   BFD_ASSERT (dynobj != NULL
8359               && (h->needs_plt
8360                   || h->u.weakdef != NULL
8361                   || (h->def_dynamic
8362                       && h->ref_regular
8363                       && !h->def_regular)));
8364
8365   hmips = (struct mips_elf_link_hash_entry *) h;
8366
8367   /* If there are call relocations against an externally-defined symbol,
8368      see whether we can create a MIPS lazy-binding stub for it.  We can
8369      only do this if all references to the function are through call
8370      relocations, and in that case, the traditional lazy-binding stubs
8371      are much more efficient than PLT entries.
8372
8373      Traditional stubs are only available on SVR4 psABI-based systems;
8374      VxWorks always uses PLTs instead.  */
8375   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
8376     {
8377       if (! elf_hash_table (info)->dynamic_sections_created)
8378         return TRUE;
8379
8380       /* If this symbol is not defined in a regular file, then set
8381          the symbol to the stub location.  This is required to make
8382          function pointers compare as equal between the normal
8383          executable and the shared library.  */
8384       if (!h->def_regular)
8385         {
8386           hmips->needs_lazy_stub = TRUE;
8387           htab->lazy_stub_count++;
8388           return TRUE;
8389         }
8390     }
8391   /* As above, VxWorks requires PLT entries for externally-defined
8392      functions that are only accessed through call relocations.
8393
8394      Both VxWorks and non-VxWorks targets also need PLT entries if there
8395      are static-only relocations against an externally-defined function.
8396      This can technically occur for shared libraries if there are
8397      branches to the symbol, although it is unlikely that this will be
8398      used in practice due to the short ranges involved.  It can occur
8399      for any relative or absolute relocation in executables; in that
8400      case, the PLT entry becomes the function's canonical address.  */
8401   else if (((h->needs_plt && !hmips->no_fn_stub)
8402             || (h->type == STT_FUNC && hmips->has_static_relocs))
8403            && htab->use_plts_and_copy_relocs
8404            && !SYMBOL_CALLS_LOCAL (info, h)
8405            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
8406                 && h->root.type == bfd_link_hash_undefweak))
8407     {
8408       /* If this is the first symbol to need a PLT entry, allocate room
8409          for the header.  */
8410       if (htab->splt->size == 0)
8411         {
8412           BFD_ASSERT (htab->sgotplt->size == 0);
8413
8414           /* If we're using the PLT additions to the psABI, each PLT
8415              entry is 16 bytes and the PLT0 entry is 32 bytes.
8416              Encourage better cache usage by aligning.  We do this
8417              lazily to avoid pessimizing traditional objects.  */
8418           if (!htab->is_vxworks
8419               && !bfd_set_section_alignment (dynobj, htab->splt, 5))
8420             return FALSE;
8421
8422           /* Make sure that .got.plt is word-aligned.  We do this lazily
8423              for the same reason as above.  */
8424           if (!bfd_set_section_alignment (dynobj, htab->sgotplt,
8425                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
8426             return FALSE;
8427
8428           htab->splt->size += htab->plt_header_size;
8429
8430           /* On non-VxWorks targets, the first two entries in .got.plt
8431              are reserved.  */
8432           if (!htab->is_vxworks)
8433             htab->sgotplt->size
8434               += get_elf_backend_data (dynobj)->got_header_size;
8435
8436           /* On VxWorks, also allocate room for the header's
8437              .rela.plt.unloaded entries.  */
8438           if (htab->is_vxworks && !info->shared)
8439             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
8440         }
8441
8442       /* Assign the next .plt entry to this symbol.  */
8443       h->plt.offset = htab->splt->size;
8444       htab->splt->size += htab->plt_entry_size;
8445
8446       /* If the output file has no definition of the symbol, set the
8447          symbol's value to the address of the stub.  */
8448       if (!info->shared && !h->def_regular)
8449         {
8450           h->root.u.def.section = htab->splt;
8451           h->root.u.def.value = h->plt.offset;
8452           /* For VxWorks, point at the PLT load stub rather than the
8453              lazy resolution stub; this stub will become the canonical
8454              function address.  */
8455           if (htab->is_vxworks)
8456             h->root.u.def.value += 8;
8457         }
8458
8459       /* Make room for the .got.plt entry and the R_MIPS_JUMP_SLOT
8460          relocation.  */
8461       htab->sgotplt->size += MIPS_ELF_GOT_SIZE (dynobj);
8462       htab->srelplt->size += (htab->is_vxworks
8463                               ? MIPS_ELF_RELA_SIZE (dynobj)
8464                               : MIPS_ELF_REL_SIZE (dynobj));
8465
8466       /* Make room for the .rela.plt.unloaded relocations.  */
8467       if (htab->is_vxworks && !info->shared)
8468         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
8469
8470       /* All relocations against this symbol that could have been made
8471          dynamic will now refer to the PLT entry instead.  */
8472       hmips->possibly_dynamic_relocs = 0;
8473
8474       return TRUE;
8475     }
8476
8477   /* If this is a weak symbol, and there is a real definition, the
8478      processor independent code will have arranged for us to see the
8479      real definition first, and we can just use the same value.  */
8480   if (h->u.weakdef != NULL)
8481     {
8482       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
8483                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
8484       h->root.u.def.section = h->u.weakdef->root.u.def.section;
8485       h->root.u.def.value = h->u.weakdef->root.u.def.value;
8486       return TRUE;
8487     }
8488
8489   /* Otherwise, there is nothing further to do for symbols defined
8490      in regular objects.  */
8491   if (h->def_regular)
8492     return TRUE;
8493
8494   /* There's also nothing more to do if we'll convert all relocations
8495      against this symbol into dynamic relocations.  */
8496   if (!hmips->has_static_relocs)
8497     return TRUE;
8498
8499   /* We're now relying on copy relocations.  Complain if we have
8500      some that we can't convert.  */
8501   if (!htab->use_plts_and_copy_relocs || info->shared)
8502     {
8503       (*_bfd_error_handler) (_("non-dynamic relocations refer to "
8504                                "dynamic symbol %s"),
8505                              h->root.root.string);
8506       bfd_set_error (bfd_error_bad_value);
8507       return FALSE;
8508     }
8509
8510   /* We must allocate the symbol in our .dynbss section, which will
8511      become part of the .bss section of the executable.  There will be
8512      an entry for this symbol in the .dynsym section.  The dynamic
8513      object will contain position independent code, so all references
8514      from the dynamic object to this symbol will go through the global
8515      offset table.  The dynamic linker will use the .dynsym entry to
8516      determine the address it must put in the global offset table, so
8517      both the dynamic object and the regular object will refer to the
8518      same memory location for the variable.  */
8519
8520   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
8521     {
8522       if (htab->is_vxworks)
8523         htab->srelbss->size += sizeof (Elf32_External_Rela);
8524       else
8525         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8526       h->needs_copy = 1;
8527     }
8528
8529   /* All relocations against this symbol that could have been made
8530      dynamic will now refer to the local copy instead.  */
8531   hmips->possibly_dynamic_relocs = 0;
8532
8533   return _bfd_elf_adjust_dynamic_copy (h, htab->sdynbss);
8534 }
8535 \f
8536 /* This function is called after all the input files have been read,
8537    and the input sections have been assigned to output sections.  We
8538    check for any mips16 stub sections that we can discard.  */
8539
8540 bfd_boolean
8541 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
8542                                     struct bfd_link_info *info)
8543 {
8544   asection *ri;
8545   struct mips_elf_link_hash_table *htab;
8546   struct mips_htab_traverse_info hti;
8547
8548   htab = mips_elf_hash_table (info);
8549   BFD_ASSERT (htab != NULL);
8550
8551   /* The .reginfo section has a fixed size.  */
8552   ri = bfd_get_section_by_name (output_bfd, ".reginfo");
8553   if (ri != NULL)
8554     bfd_set_section_size (output_bfd, ri, sizeof (Elf32_External_RegInfo));
8555
8556   hti.info = info;
8557   hti.output_bfd = output_bfd;
8558   hti.error = FALSE;
8559   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
8560                                mips_elf_check_symbols, &hti);
8561   if (hti.error)
8562     return FALSE;
8563
8564   return TRUE;
8565 }
8566
8567 /* If the link uses a GOT, lay it out and work out its size.  */
8568
8569 static bfd_boolean
8570 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
8571 {
8572   bfd *dynobj;
8573   asection *s;
8574   struct mips_got_info *g;
8575   bfd_size_type loadable_size = 0;
8576   bfd_size_type page_gotno;
8577   bfd *ibfd;
8578   struct mips_elf_traverse_got_arg tga;
8579   struct mips_elf_link_hash_table *htab;
8580
8581   htab = mips_elf_hash_table (info);
8582   BFD_ASSERT (htab != NULL);
8583
8584   s = htab->sgot;
8585   if (s == NULL)
8586     return TRUE;
8587
8588   dynobj = elf_hash_table (info)->dynobj;
8589   g = htab->got_info;
8590
8591   /* Allocate room for the reserved entries.  VxWorks always reserves
8592      3 entries; other objects only reserve 2 entries.  */
8593   BFD_ASSERT (g->assigned_gotno == 0);
8594   if (htab->is_vxworks)
8595     htab->reserved_gotno = 3;
8596   else
8597     htab->reserved_gotno = 2;
8598   g->local_gotno += htab->reserved_gotno;
8599   g->assigned_gotno = htab->reserved_gotno;
8600
8601   /* Decide which symbols need to go in the global part of the GOT and
8602      count the number of reloc-only GOT symbols.  */
8603   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
8604
8605   /* Calculate the total loadable size of the output.  That
8606      will give us the maximum number of GOT_PAGE entries
8607      required.  */
8608   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
8609     {
8610       asection *subsection;
8611
8612       for (subsection = ibfd->sections;
8613            subsection;
8614            subsection = subsection->next)
8615         {
8616           if ((subsection->flags & SEC_ALLOC) == 0)
8617             continue;
8618           loadable_size += ((subsection->size + 0xf)
8619                             &~ (bfd_size_type) 0xf);
8620         }
8621     }
8622
8623   if (htab->is_vxworks)
8624     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
8625        relocations against local symbols evaluate to "G", and the EABI does
8626        not include R_MIPS_GOT_PAGE.  */
8627     page_gotno = 0;
8628   else
8629     /* Assume there are two loadable segments consisting of contiguous
8630        sections.  Is 5 enough?  */
8631     page_gotno = (loadable_size >> 16) + 5;
8632
8633   /* Choose the smaller of the two estimates; both are intended to be
8634      conservative.  */
8635   if (page_gotno > g->page_gotno)
8636     page_gotno = g->page_gotno;
8637
8638   g->local_gotno += page_gotno;
8639
8640   /* Replace entries for indirect and warning symbols with entries for
8641      the target symbol.  Count the number of GOT entries and TLS relocs.  */
8642   if (!mips_elf_resolve_final_got_entries (info, g))
8643     return FALSE;
8644
8645   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8646   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8647   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8648
8649   /* VxWorks does not support multiple GOTs.  It initializes $gp to
8650      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
8651      dynamic loader.  */
8652   if (htab->is_vxworks)
8653     {
8654       /* VxWorks executables do not need a GOT.  */
8655       if (info->shared)
8656         {
8657           /* Each VxWorks GOT entry needs an explicit relocation.  */
8658           unsigned int count;
8659
8660           count = g->global_gotno + g->local_gotno - htab->reserved_gotno;
8661           if (count)
8662             mips_elf_allocate_dynamic_relocations (dynobj, info, count);
8663         }
8664     }
8665   else if (s->size > MIPS_ELF_GOT_MAX_SIZE (info))
8666     {
8667       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
8668         return FALSE;
8669     }
8670   else
8671     {
8672       /* Record that all bfds use G.  This also has the effect of freeing
8673          the per-bfd GOTs, which we no longer need.  */
8674       for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
8675         if (mips_elf_bfd_got (ibfd, FALSE))
8676           mips_elf_replace_bfd_got (ibfd, g);
8677       mips_elf_replace_bfd_got (output_bfd, g);
8678
8679       /* Set up TLS entries.  */
8680       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
8681       tga.info = info;
8682       tga.g = g;
8683       tga.value = MIPS_ELF_GOT_SIZE (output_bfd);
8684       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
8685       if (!tga.g)
8686         return FALSE;
8687       BFD_ASSERT (g->tls_assigned_gotno
8688                   == g->global_gotno + g->local_gotno + g->tls_gotno);
8689
8690       /* Allocate room for the TLS relocations.  */
8691       if (g->relocs)
8692         mips_elf_allocate_dynamic_relocations (dynobj, info, g->relocs);
8693     }
8694
8695   return TRUE;
8696 }
8697
8698 /* Estimate the size of the .MIPS.stubs section.  */
8699
8700 static void
8701 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
8702 {
8703   struct mips_elf_link_hash_table *htab;
8704   bfd_size_type dynsymcount;
8705
8706   htab = mips_elf_hash_table (info);
8707   BFD_ASSERT (htab != NULL);
8708
8709   if (htab->lazy_stub_count == 0)
8710     return;
8711
8712   /* IRIX rld assumes that a function stub isn't at the end of the .text
8713      section, so add a dummy entry to the end.  */
8714   htab->lazy_stub_count++;
8715
8716   /* Get a worst-case estimate of the number of dynamic symbols needed.
8717      At this point, dynsymcount does not account for section symbols
8718      and count_section_dynsyms may overestimate the number that will
8719      be needed.  */
8720   dynsymcount = (elf_hash_table (info)->dynsymcount
8721                  + count_section_dynsyms (output_bfd, info));
8722
8723   /* Determine the size of one stub entry.  */
8724   htab->function_stub_size = (dynsymcount > 0x10000
8725                               ? MIPS_FUNCTION_STUB_BIG_SIZE
8726                               : MIPS_FUNCTION_STUB_NORMAL_SIZE);
8727
8728   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
8729 }
8730
8731 /* A mips_elf_link_hash_traverse callback for which DATA points to the
8732    MIPS hash table.  If H needs a traditional MIPS lazy-binding stub,
8733    allocate an entry in the stubs section.  */
8734
8735 static bfd_boolean
8736 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void **data)
8737 {
8738   struct mips_elf_link_hash_table *htab;
8739
8740   htab = (struct mips_elf_link_hash_table *) data;
8741   if (h->needs_lazy_stub)
8742     {
8743       h->root.root.u.def.section = htab->sstubs;
8744       h->root.root.u.def.value = htab->sstubs->size;
8745       h->root.plt.offset = htab->sstubs->size;
8746       htab->sstubs->size += htab->function_stub_size;
8747     }
8748   return TRUE;
8749 }
8750
8751 /* Allocate offsets in the stubs section to each symbol that needs one.
8752    Set the final size of the .MIPS.stub section.  */
8753
8754 static void
8755 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
8756 {
8757   struct mips_elf_link_hash_table *htab;
8758
8759   htab = mips_elf_hash_table (info);
8760   BFD_ASSERT (htab != NULL);
8761
8762   if (htab->lazy_stub_count == 0)
8763     return;
8764
8765   htab->sstubs->size = 0;
8766   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, htab);
8767   htab->sstubs->size += htab->function_stub_size;
8768   BFD_ASSERT (htab->sstubs->size
8769               == htab->lazy_stub_count * htab->function_stub_size);
8770 }
8771
8772 /* Set the sizes of the dynamic sections.  */
8773
8774 bfd_boolean
8775 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
8776                                      struct bfd_link_info *info)
8777 {
8778   bfd *dynobj;
8779   asection *s, *sreldyn;
8780   bfd_boolean reltext;
8781   struct mips_elf_link_hash_table *htab;
8782
8783   htab = mips_elf_hash_table (info);
8784   BFD_ASSERT (htab != NULL);
8785   dynobj = elf_hash_table (info)->dynobj;
8786   BFD_ASSERT (dynobj != NULL);
8787
8788   if (elf_hash_table (info)->dynamic_sections_created)
8789     {
8790       /* Set the contents of the .interp section to the interpreter.  */
8791       if (info->executable)
8792         {
8793           s = bfd_get_linker_section (dynobj, ".interp");
8794           BFD_ASSERT (s != NULL);
8795           s->size
8796             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
8797           s->contents
8798             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
8799         }
8800
8801       /* Create a symbol for the PLT, if we know that we are using it.  */
8802       if (htab->splt && htab->splt->size > 0 && htab->root.hplt == NULL)
8803         {
8804           struct elf_link_hash_entry *h;
8805
8806           BFD_ASSERT (htab->use_plts_and_copy_relocs);
8807
8808           h = _bfd_elf_define_linkage_sym (dynobj, info, htab->splt,
8809                                            "_PROCEDURE_LINKAGE_TABLE_");
8810           htab->root.hplt = h;
8811           if (h == NULL)
8812             return FALSE;
8813           h->type = STT_FUNC;
8814         }
8815     }
8816
8817   /* Allocate space for global sym dynamic relocs.  */
8818   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, info);
8819
8820   mips_elf_estimate_stub_size (output_bfd, info);
8821
8822   if (!mips_elf_lay_out_got (output_bfd, info))
8823     return FALSE;
8824
8825   mips_elf_lay_out_lazy_stubs (info);
8826
8827   /* The check_relocs and adjust_dynamic_symbol entry points have
8828      determined the sizes of the various dynamic sections.  Allocate
8829      memory for them.  */
8830   reltext = FALSE;
8831   for (s = dynobj->sections; s != NULL; s = s->next)
8832     {
8833       const char *name;
8834
8835       /* It's OK to base decisions on the section name, because none
8836          of the dynobj section names depend upon the input files.  */
8837       name = bfd_get_section_name (dynobj, s);
8838
8839       if ((s->flags & SEC_LINKER_CREATED) == 0)
8840         continue;
8841
8842       if (CONST_STRNEQ (name, ".rel"))
8843         {
8844           if (s->size != 0)
8845             {
8846               const char *outname;
8847               asection *target;
8848
8849               /* If this relocation section applies to a read only
8850                  section, then we probably need a DT_TEXTREL entry.
8851                  If the relocation section is .rel(a).dyn, we always
8852                  assert a DT_TEXTREL entry rather than testing whether
8853                  there exists a relocation to a read only section or
8854                  not.  */
8855               outname = bfd_get_section_name (output_bfd,
8856                                               s->output_section);
8857               target = bfd_get_section_by_name (output_bfd, outname + 4);
8858               if ((target != NULL
8859                    && (target->flags & SEC_READONLY) != 0
8860                    && (target->flags & SEC_ALLOC) != 0)
8861                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
8862                 reltext = TRUE;
8863
8864               /* We use the reloc_count field as a counter if we need
8865                  to copy relocs into the output file.  */
8866               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
8867                 s->reloc_count = 0;
8868
8869               /* If combreloc is enabled, elf_link_sort_relocs() will
8870                  sort relocations, but in a different way than we do,
8871                  and before we're done creating relocations.  Also, it
8872                  will move them around between input sections'
8873                  relocation's contents, so our sorting would be
8874                  broken, so don't let it run.  */
8875               info->combreloc = 0;
8876             }
8877         }
8878       else if (! info->shared
8879                && ! mips_elf_hash_table (info)->use_rld_obj_head
8880                && CONST_STRNEQ (name, ".rld_map"))
8881         {
8882           /* We add a room for __rld_map.  It will be filled in by the
8883              rtld to contain a pointer to the _r_debug structure.  */
8884           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
8885         }
8886       else if (SGI_COMPAT (output_bfd)
8887                && CONST_STRNEQ (name, ".compact_rel"))
8888         s->size += mips_elf_hash_table (info)->compact_rel_size;
8889       else if (s == htab->splt)
8890         {
8891           /* If the last PLT entry has a branch delay slot, allocate
8892              room for an extra nop to fill the delay slot.  This is
8893              for CPUs without load interlocking.  */
8894           if (! LOAD_INTERLOCKS_P (output_bfd)
8895               && ! htab->is_vxworks && s->size > 0)
8896             s->size += 4;
8897         }
8898       else if (! CONST_STRNEQ (name, ".init")
8899                && s != htab->sgot
8900                && s != htab->sgotplt
8901                && s != htab->sstubs
8902                && s != htab->sdynbss)
8903         {
8904           /* It's not one of our sections, so don't allocate space.  */
8905           continue;
8906         }
8907
8908       if (s->size == 0)
8909         {
8910           s->flags |= SEC_EXCLUDE;
8911           continue;
8912         }
8913
8914       if ((s->flags & SEC_HAS_CONTENTS) == 0)
8915         continue;
8916
8917       /* Allocate memory for the section contents.  */
8918       s->contents = bfd_zalloc (dynobj, s->size);
8919       if (s->contents == NULL)
8920         {
8921           bfd_set_error (bfd_error_no_memory);
8922           return FALSE;
8923         }
8924     }
8925
8926   if (elf_hash_table (info)->dynamic_sections_created)
8927     {
8928       /* Add some entries to the .dynamic section.  We fill in the
8929          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
8930          must add the entries now so that we get the correct size for
8931          the .dynamic section.  */
8932
8933       /* SGI object has the equivalence of DT_DEBUG in the
8934          DT_MIPS_RLD_MAP entry.  This must come first because glibc
8935          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and some tools
8936          may only look at the first one they see.  */
8937       if (!info->shared
8938           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
8939         return FALSE;
8940
8941       /* The DT_DEBUG entry may be filled in by the dynamic linker and
8942          used by the debugger.  */
8943       if (info->executable
8944           && !SGI_COMPAT (output_bfd)
8945           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
8946         return FALSE;
8947
8948       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
8949         info->flags |= DF_TEXTREL;
8950
8951       if ((info->flags & DF_TEXTREL) != 0)
8952         {
8953           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
8954             return FALSE;
8955
8956           /* Clear the DF_TEXTREL flag.  It will be set again if we
8957              write out an actual text relocation; we may not, because
8958              at this point we do not know whether e.g. any .eh_frame
8959              absolute relocations have been converted to PC-relative.  */
8960           info->flags &= ~DF_TEXTREL;
8961         }
8962
8963       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
8964         return FALSE;
8965
8966       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
8967       if (htab->is_vxworks)
8968         {
8969           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
8970              use any of the DT_MIPS_* tags.  */
8971           if (sreldyn && sreldyn->size > 0)
8972             {
8973               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
8974                 return FALSE;
8975
8976               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
8977                 return FALSE;
8978
8979               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
8980                 return FALSE;
8981             }
8982         }
8983       else
8984         {
8985           if (sreldyn && sreldyn->size > 0)
8986             {
8987               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
8988                 return FALSE;
8989
8990               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
8991                 return FALSE;
8992
8993               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
8994                 return FALSE;
8995             }
8996
8997           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
8998             return FALSE;
8999
9000           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
9001             return FALSE;
9002
9003           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
9004             return FALSE;
9005
9006           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
9007             return FALSE;
9008
9009           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
9010             return FALSE;
9011
9012           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
9013             return FALSE;
9014
9015           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
9016             return FALSE;
9017
9018           if (IRIX_COMPAT (dynobj) == ict_irix5
9019               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
9020             return FALSE;
9021
9022           if (IRIX_COMPAT (dynobj) == ict_irix6
9023               && (bfd_get_section_by_name
9024                   (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
9025               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
9026             return FALSE;
9027         }
9028       if (htab->splt->size > 0)
9029         {
9030           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
9031             return FALSE;
9032
9033           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
9034             return FALSE;
9035
9036           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
9037             return FALSE;
9038
9039           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
9040             return FALSE;
9041         }
9042       if (htab->is_vxworks
9043           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
9044         return FALSE;
9045     }
9046
9047   return TRUE;
9048 }
9049 \f
9050 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
9051    Adjust its R_ADDEND field so that it is correct for the output file.
9052    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
9053    and sections respectively; both use symbol indexes.  */
9054
9055 static void
9056 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
9057                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
9058                         asection **local_sections, Elf_Internal_Rela *rel)
9059 {
9060   unsigned int r_type, r_symndx;
9061   Elf_Internal_Sym *sym;
9062   asection *sec;
9063
9064   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9065     {
9066       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9067       if (gprel16_reloc_p (r_type)
9068           || r_type == R_MIPS_GPREL32
9069           || literal_reloc_p (r_type))
9070         {
9071           rel->r_addend += _bfd_get_gp_value (input_bfd);
9072           rel->r_addend -= _bfd_get_gp_value (output_bfd);
9073         }
9074
9075       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
9076       sym = local_syms + r_symndx;
9077
9078       /* Adjust REL's addend to account for section merging.  */
9079       if (!info->relocatable)
9080         {
9081           sec = local_sections[r_symndx];
9082           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
9083         }
9084
9085       /* This would normally be done by the rela_normal code in elflink.c.  */
9086       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
9087         rel->r_addend += local_sections[r_symndx]->output_offset;
9088     }
9089 }
9090
9091 /* Handle relocations against symbols from removed linkonce sections,
9092    or sections discarded by a linker script.  We use this wrapper around
9093    RELOC_AGAINST_DISCARDED_SECTION to handle triplets of compound relocs
9094    on 64-bit ELF targets.  In this case for any relocation handled, which
9095    always be the first in a triplet, the remaining two have to be processed
9096    together with the first, even if they are R_MIPS_NONE.  It is the symbol
9097    index referred by the first reloc that applies to all the three and the
9098    remaining two never refer to an object symbol.  And it is the final
9099    relocation (the last non-null one) that determines the output field of
9100    the whole relocation so retrieve the corresponding howto structure for
9101    the relocatable field to be cleared by RELOC_AGAINST_DISCARDED_SECTION.
9102
9103    Note that RELOC_AGAINST_DISCARDED_SECTION is a macro that uses "continue"
9104    and therefore requires to be pasted in a loop.  It also defines a block
9105    and does not protect any of its arguments, hence the extra brackets.  */
9106
9107 static void
9108 mips_reloc_against_discarded_section (bfd *output_bfd,
9109                                       struct bfd_link_info *info,
9110                                       bfd *input_bfd, asection *input_section,
9111                                       Elf_Internal_Rela **rel,
9112                                       const Elf_Internal_Rela **relend,
9113                                       bfd_boolean rel_reloc,
9114                                       reloc_howto_type *howto,
9115                                       bfd_byte *contents)
9116 {
9117   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
9118   int count = bed->s->int_rels_per_ext_rel;
9119   unsigned int r_type;
9120   int i;
9121
9122   for (i = count - 1; i > 0; i--)
9123     {
9124       r_type = ELF_R_TYPE (output_bfd, (*rel)[i].r_info);
9125       if (r_type != R_MIPS_NONE)
9126         {
9127           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9128           break;
9129         }
9130     }
9131   do
9132     {
9133        RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
9134                                         (*rel), count, (*relend),
9135                                         howto, i, contents);
9136     }
9137   while (0);
9138 }
9139
9140 /* Relocate a MIPS ELF section.  */
9141
9142 bfd_boolean
9143 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
9144                                 bfd *input_bfd, asection *input_section,
9145                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
9146                                 Elf_Internal_Sym *local_syms,
9147                                 asection **local_sections)
9148 {
9149   Elf_Internal_Rela *rel;
9150   const Elf_Internal_Rela *relend;
9151   bfd_vma addend = 0;
9152   bfd_boolean use_saved_addend_p = FALSE;
9153   const struct elf_backend_data *bed;
9154
9155   bed = get_elf_backend_data (output_bfd);
9156   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
9157   for (rel = relocs; rel < relend; ++rel)
9158     {
9159       const char *name;
9160       bfd_vma value = 0;
9161       reloc_howto_type *howto;
9162       bfd_boolean cross_mode_jump_p;
9163       /* TRUE if the relocation is a RELA relocation, rather than a
9164          REL relocation.  */
9165       bfd_boolean rela_relocation_p = TRUE;
9166       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9167       const char *msg;
9168       unsigned long r_symndx;
9169       asection *sec;
9170       Elf_Internal_Shdr *symtab_hdr;
9171       struct elf_link_hash_entry *h;
9172       bfd_boolean rel_reloc;
9173
9174       rel_reloc = (NEWABI_P (input_bfd)
9175                    && mips_elf_rel_relocation_p (input_bfd, input_section,
9176                                                  relocs, rel));
9177       /* Find the relocation howto for this relocation.  */
9178       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9179
9180       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
9181       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9182       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9183         {
9184           sec = local_sections[r_symndx];
9185           h = NULL;
9186         }
9187       else
9188         {
9189           unsigned long extsymoff;
9190
9191           extsymoff = 0;
9192           if (!elf_bad_symtab (input_bfd))
9193             extsymoff = symtab_hdr->sh_info;
9194           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
9195           while (h->root.type == bfd_link_hash_indirect
9196                  || h->root.type == bfd_link_hash_warning)
9197             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9198
9199           sec = NULL;
9200           if (h->root.type == bfd_link_hash_defined
9201               || h->root.type == bfd_link_hash_defweak)
9202             sec = h->root.u.def.section;
9203         }
9204
9205       if (sec != NULL && discarded_section (sec))
9206         {
9207           mips_reloc_against_discarded_section (output_bfd, info, input_bfd,
9208                                                 input_section, &rel, &relend,
9209                                                 rel_reloc, howto, contents);
9210           continue;
9211         }
9212
9213       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
9214         {
9215           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
9216              64-bit code, but make sure all their addresses are in the
9217              lowermost or uppermost 32-bit section of the 64-bit address
9218              space.  Thus, when they use an R_MIPS_64 they mean what is
9219              usually meant by R_MIPS_32, with the exception that the
9220              stored value is sign-extended to 64 bits.  */
9221           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
9222
9223           /* On big-endian systems, we need to lie about the position
9224              of the reloc.  */
9225           if (bfd_big_endian (input_bfd))
9226             rel->r_offset += 4;
9227         }
9228
9229       if (!use_saved_addend_p)
9230         {
9231           /* If these relocations were originally of the REL variety,
9232              we must pull the addend out of the field that will be
9233              relocated.  Otherwise, we simply use the contents of the
9234              RELA relocation.  */
9235           if (mips_elf_rel_relocation_p (input_bfd, input_section,
9236                                          relocs, rel))
9237             {
9238               rela_relocation_p = FALSE;
9239               addend = mips_elf_read_rel_addend (input_bfd, rel,
9240                                                  howto, contents);
9241               if (hi16_reloc_p (r_type)
9242                   || (got16_reloc_p (r_type)
9243                       && mips_elf_local_relocation_p (input_bfd, rel,
9244                                                       local_sections)))
9245                 {
9246                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
9247                                                      contents, &addend))
9248                     {
9249                       if (h)
9250                         name = h->root.root.string;
9251                       else
9252                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9253                                                  local_syms + r_symndx,
9254                                                  sec);
9255                       (*_bfd_error_handler)
9256                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
9257                          input_bfd, input_section, name, howto->name,
9258                          rel->r_offset);
9259                     }
9260                 }
9261               else
9262                 addend <<= howto->rightshift;
9263             }
9264           else
9265             addend = rel->r_addend;
9266           mips_elf_adjust_addend (output_bfd, info, input_bfd,
9267                                   local_syms, local_sections, rel);
9268         }
9269
9270       if (info->relocatable)
9271         {
9272           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
9273               && bfd_big_endian (input_bfd))
9274             rel->r_offset -= 4;
9275
9276           if (!rela_relocation_p && rel->r_addend)
9277             {
9278               addend += rel->r_addend;
9279               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
9280                 addend = mips_elf_high (addend);
9281               else if (r_type == R_MIPS_HIGHER)
9282                 addend = mips_elf_higher (addend);
9283               else if (r_type == R_MIPS_HIGHEST)
9284                 addend = mips_elf_highest (addend);
9285               else
9286                 addend >>= howto->rightshift;
9287
9288               /* We use the source mask, rather than the destination
9289                  mask because the place to which we are writing will be
9290                  source of the addend in the final link.  */
9291               addend &= howto->src_mask;
9292
9293               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9294                 /* See the comment above about using R_MIPS_64 in the 32-bit
9295                    ABI.  Here, we need to update the addend.  It would be
9296                    possible to get away with just using the R_MIPS_32 reloc
9297                    but for endianness.  */
9298                 {
9299                   bfd_vma sign_bits;
9300                   bfd_vma low_bits;
9301                   bfd_vma high_bits;
9302
9303                   if (addend & ((bfd_vma) 1 << 31))
9304 #ifdef BFD64
9305                     sign_bits = ((bfd_vma) 1 << 32) - 1;
9306 #else
9307                     sign_bits = -1;
9308 #endif
9309                   else
9310                     sign_bits = 0;
9311
9312                   /* If we don't know that we have a 64-bit type,
9313                      do two separate stores.  */
9314                   if (bfd_big_endian (input_bfd))
9315                     {
9316                       /* Store the sign-bits (which are most significant)
9317                          first.  */
9318                       low_bits = sign_bits;
9319                       high_bits = addend;
9320                     }
9321                   else
9322                     {
9323                       low_bits = addend;
9324                       high_bits = sign_bits;
9325                     }
9326                   bfd_put_32 (input_bfd, low_bits,
9327                               contents + rel->r_offset);
9328                   bfd_put_32 (input_bfd, high_bits,
9329                               contents + rel->r_offset + 4);
9330                   continue;
9331                 }
9332
9333               if (! mips_elf_perform_relocation (info, howto, rel, addend,
9334                                                  input_bfd, input_section,
9335                                                  contents, FALSE))
9336                 return FALSE;
9337             }
9338
9339           /* Go on to the next relocation.  */
9340           continue;
9341         }
9342
9343       /* In the N32 and 64-bit ABIs there may be multiple consecutive
9344          relocations for the same offset.  In that case we are
9345          supposed to treat the output of each relocation as the addend
9346          for the next.  */
9347       if (rel + 1 < relend
9348           && rel->r_offset == rel[1].r_offset
9349           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
9350         use_saved_addend_p = TRUE;
9351       else
9352         use_saved_addend_p = FALSE;
9353
9354       /* Figure out what value we are supposed to relocate.  */
9355       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
9356                                              input_section, info, rel,
9357                                              addend, howto, local_syms,
9358                                              local_sections, &value,
9359                                              &name, &cross_mode_jump_p,
9360                                              use_saved_addend_p))
9361         {
9362         case bfd_reloc_continue:
9363           /* There's nothing to do.  */
9364           continue;
9365
9366         case bfd_reloc_undefined:
9367           /* mips_elf_calculate_relocation already called the
9368              undefined_symbol callback.  There's no real point in
9369              trying to perform the relocation at this point, so we
9370              just skip ahead to the next relocation.  */
9371           continue;
9372
9373         case bfd_reloc_notsupported:
9374           msg = _("internal error: unsupported relocation error");
9375           info->callbacks->warning
9376             (info, msg, name, input_bfd, input_section, rel->r_offset);
9377           return FALSE;
9378
9379         case bfd_reloc_overflow:
9380           if (use_saved_addend_p)
9381             /* Ignore overflow until we reach the last relocation for
9382                a given location.  */
9383             ;
9384           else
9385             {
9386               struct mips_elf_link_hash_table *htab;
9387
9388               htab = mips_elf_hash_table (info);
9389               BFD_ASSERT (htab != NULL);
9390               BFD_ASSERT (name != NULL);
9391               if (!htab->small_data_overflow_reported
9392                   && (gprel16_reloc_p (howto->type)
9393                       || literal_reloc_p (howto->type)))
9394                 {
9395                   msg = _("small-data section exceeds 64KB;"
9396                           " lower small-data size limit (see option -G)");
9397
9398                   htab->small_data_overflow_reported = TRUE;
9399                   (*info->callbacks->einfo) ("%P: %s\n", msg);
9400                 }
9401               if (! ((*info->callbacks->reloc_overflow)
9402                      (info, NULL, name, howto->name, (bfd_vma) 0,
9403                       input_bfd, input_section, rel->r_offset)))
9404                 return FALSE;
9405             }
9406           break;
9407
9408         case bfd_reloc_ok:
9409           break;
9410
9411         case bfd_reloc_outofrange:
9412           if (jal_reloc_p (howto->type))
9413             {
9414               msg = _("JALX to a non-word-aligned address");
9415               info->callbacks->warning
9416                 (info, msg, name, input_bfd, input_section, rel->r_offset);
9417               return FALSE;
9418             }
9419           /* Fall through.  */
9420
9421         default:
9422           abort ();
9423           break;
9424         }
9425
9426       /* If we've got another relocation for the address, keep going
9427          until we reach the last one.  */
9428       if (use_saved_addend_p)
9429         {
9430           addend = value;
9431           continue;
9432         }
9433
9434       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9435         /* See the comment above about using R_MIPS_64 in the 32-bit
9436            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
9437            that calculated the right value.  Now, however, we
9438            sign-extend the 32-bit result to 64-bits, and store it as a
9439            64-bit value.  We are especially generous here in that we
9440            go to extreme lengths to support this usage on systems with
9441            only a 32-bit VMA.  */
9442         {
9443           bfd_vma sign_bits;
9444           bfd_vma low_bits;
9445           bfd_vma high_bits;
9446
9447           if (value & ((bfd_vma) 1 << 31))
9448 #ifdef BFD64
9449             sign_bits = ((bfd_vma) 1 << 32) - 1;
9450 #else
9451             sign_bits = -1;
9452 #endif
9453           else
9454             sign_bits = 0;
9455
9456           /* If we don't know that we have a 64-bit type,
9457              do two separate stores.  */
9458           if (bfd_big_endian (input_bfd))
9459             {
9460               /* Undo what we did above.  */
9461               rel->r_offset -= 4;
9462               /* Store the sign-bits (which are most significant)
9463                  first.  */
9464               low_bits = sign_bits;
9465               high_bits = value;
9466             }
9467           else
9468             {
9469               low_bits = value;
9470               high_bits = sign_bits;
9471             }
9472           bfd_put_32 (input_bfd, low_bits,
9473                       contents + rel->r_offset);
9474           bfd_put_32 (input_bfd, high_bits,
9475                       contents + rel->r_offset + 4);
9476           continue;
9477         }
9478
9479       /* Actually perform the relocation.  */
9480       if (! mips_elf_perform_relocation (info, howto, rel, value,
9481                                          input_bfd, input_section,
9482                                          contents, cross_mode_jump_p))
9483         return FALSE;
9484     }
9485
9486   return TRUE;
9487 }
9488 \f
9489 /* A function that iterates over each entry in la25_stubs and fills
9490    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
9491
9492 static int
9493 mips_elf_create_la25_stub (void **slot, void *data)
9494 {
9495   struct mips_htab_traverse_info *hti;
9496   struct mips_elf_link_hash_table *htab;
9497   struct mips_elf_la25_stub *stub;
9498   asection *s;
9499   bfd_byte *loc;
9500   bfd_vma offset, target, target_high, target_low;
9501
9502   stub = (struct mips_elf_la25_stub *) *slot;
9503   hti = (struct mips_htab_traverse_info *) data;
9504   htab = mips_elf_hash_table (hti->info);
9505   BFD_ASSERT (htab != NULL);
9506
9507   /* Create the section contents, if we haven't already.  */
9508   s = stub->stub_section;
9509   loc = s->contents;
9510   if (loc == NULL)
9511     {
9512       loc = bfd_malloc (s->size);
9513       if (loc == NULL)
9514         {
9515           hti->error = TRUE;
9516           return FALSE;
9517         }
9518       s->contents = loc;
9519     }
9520
9521   /* Work out where in the section this stub should go.  */
9522   offset = stub->offset;
9523
9524   /* Work out the target address.  */
9525   target = mips_elf_get_la25_target (stub, &s);
9526   target += s->output_section->vma + s->output_offset;
9527
9528   target_high = ((target + 0x8000) >> 16) & 0xffff;
9529   target_low = (target & 0xffff);
9530
9531   if (stub->stub_section != htab->strampoline)
9532     {
9533       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
9534          of the section and write the two instructions at the end.  */
9535       memset (loc, 0, offset);
9536       loc += offset;
9537       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9538         {
9539           bfd_put_micromips_32 (hti->output_bfd,
9540                                 LA25_LUI_MICROMIPS (target_high),
9541                                 loc);
9542           bfd_put_micromips_32 (hti->output_bfd,
9543                                 LA25_ADDIU_MICROMIPS (target_low),
9544                                 loc + 4);
9545         }
9546       else
9547         {
9548           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9549           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
9550         }
9551     }
9552   else
9553     {
9554       /* This is trampoline.  */
9555       loc += offset;
9556       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9557         {
9558           bfd_put_micromips_32 (hti->output_bfd,
9559                                 LA25_LUI_MICROMIPS (target_high), loc);
9560           bfd_put_micromips_32 (hti->output_bfd,
9561                                 LA25_J_MICROMIPS (target), loc + 4);
9562           bfd_put_micromips_32 (hti->output_bfd,
9563                                 LA25_ADDIU_MICROMIPS (target_low), loc + 8);
9564           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9565         }
9566       else
9567         {
9568           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9569           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
9570           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
9571           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9572         }
9573     }
9574   return TRUE;
9575 }
9576
9577 /* If NAME is one of the special IRIX6 symbols defined by the linker,
9578    adjust it appropriately now.  */
9579
9580 static void
9581 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
9582                                       const char *name, Elf_Internal_Sym *sym)
9583 {
9584   /* The linker script takes care of providing names and values for
9585      these, but we must place them into the right sections.  */
9586   static const char* const text_section_symbols[] = {
9587     "_ftext",
9588     "_etext",
9589     "__dso_displacement",
9590     "__elf_header",
9591     "__program_header_table",
9592     NULL
9593   };
9594
9595   static const char* const data_section_symbols[] = {
9596     "_fdata",
9597     "_edata",
9598     "_end",
9599     "_fbss",
9600     NULL
9601   };
9602
9603   const char* const *p;
9604   int i;
9605
9606   for (i = 0; i < 2; ++i)
9607     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
9608          *p;
9609          ++p)
9610       if (strcmp (*p, name) == 0)
9611         {
9612           /* All of these symbols are given type STT_SECTION by the
9613              IRIX6 linker.  */
9614           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9615           sym->st_other = STO_PROTECTED;
9616
9617           /* The IRIX linker puts these symbols in special sections.  */
9618           if (i == 0)
9619             sym->st_shndx = SHN_MIPS_TEXT;
9620           else
9621             sym->st_shndx = SHN_MIPS_DATA;
9622
9623           break;
9624         }
9625 }
9626
9627 /* Finish up dynamic symbol handling.  We set the contents of various
9628    dynamic sections here.  */
9629
9630 bfd_boolean
9631 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
9632                                      struct bfd_link_info *info,
9633                                      struct elf_link_hash_entry *h,
9634                                      Elf_Internal_Sym *sym)
9635 {
9636   bfd *dynobj;
9637   asection *sgot;
9638   struct mips_got_info *g, *gg;
9639   const char *name;
9640   int idx;
9641   struct mips_elf_link_hash_table *htab;
9642   struct mips_elf_link_hash_entry *hmips;
9643
9644   htab = mips_elf_hash_table (info);
9645   BFD_ASSERT (htab != NULL);
9646   dynobj = elf_hash_table (info)->dynobj;
9647   hmips = (struct mips_elf_link_hash_entry *) h;
9648
9649   BFD_ASSERT (!htab->is_vxworks);
9650
9651   if (h->plt.offset != MINUS_ONE && hmips->no_fn_stub)
9652     {
9653       /* We've decided to create a PLT entry for this symbol.  */
9654       bfd_byte *loc;
9655       bfd_vma header_address, plt_index, got_address;
9656       bfd_vma got_address_high, got_address_low, load;
9657       const bfd_vma *plt_entry;
9658
9659       BFD_ASSERT (htab->use_plts_and_copy_relocs);
9660       BFD_ASSERT (h->dynindx != -1);
9661       BFD_ASSERT (htab->splt != NULL);
9662       BFD_ASSERT (h->plt.offset <= htab->splt->size);
9663       BFD_ASSERT (!h->def_regular);
9664
9665       /* Calculate the address of the PLT header.  */
9666       header_address = (htab->splt->output_section->vma
9667                         + htab->splt->output_offset);
9668
9669       /* Calculate the index of the entry.  */
9670       plt_index = ((h->plt.offset - htab->plt_header_size)
9671                    / htab->plt_entry_size);
9672
9673       /* Calculate the address of the .got.plt entry.  */
9674       got_address = (htab->sgotplt->output_section->vma
9675                      + htab->sgotplt->output_offset
9676                      + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9677       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
9678       got_address_low = got_address & 0xffff;
9679
9680       /* Initially point the .got.plt entry at the PLT header.  */
9681       loc = (htab->sgotplt->contents
9682              + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9683       if (ABI_64_P (output_bfd))
9684         bfd_put_64 (output_bfd, header_address, loc);
9685       else
9686         bfd_put_32 (output_bfd, header_address, loc);
9687
9688       /* Find out where the .plt entry should go.  */
9689       loc = htab->splt->contents + h->plt.offset;
9690
9691       /* Pick the load opcode.  */
9692       load = MIPS_ELF_LOAD_WORD (output_bfd);
9693
9694       /* Fill in the PLT entry itself.  */
9695       plt_entry = mips_exec_plt_entry;
9696       bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
9697       bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load, loc + 4);
9698
9699       if (! LOAD_INTERLOCKS_P (output_bfd))
9700         {
9701           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
9702           bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
9703         }
9704       else
9705         {
9706           bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
9707           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 12);
9708         }
9709
9710       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
9711       mips_elf_output_dynamic_relocation (output_bfd, htab->srelplt,
9712                                           plt_index, h->dynindx,
9713                                           R_MIPS_JUMP_SLOT, got_address);
9714
9715       /* We distinguish between PLT entries and lazy-binding stubs by
9716          giving the former an st_other value of STO_MIPS_PLT.  Set the
9717          flag and leave the value if there are any relocations in the
9718          binary where pointer equality matters.  */
9719       sym->st_shndx = SHN_UNDEF;
9720       if (h->pointer_equality_needed)
9721         sym->st_other = STO_MIPS_PLT;
9722       else
9723         sym->st_value = 0;
9724     }
9725   else if (h->plt.offset != MINUS_ONE)
9726     {
9727       /* We've decided to create a lazy-binding stub.  */
9728       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
9729
9730       /* This symbol has a stub.  Set it up.  */
9731
9732       BFD_ASSERT (h->dynindx != -1);
9733
9734       BFD_ASSERT ((htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9735                   || (h->dynindx <= 0xffff));
9736
9737       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
9738          sign extension at runtime in the stub, resulting in a negative
9739          index value.  */
9740       if (h->dynindx & ~0x7fffffff)
9741         return FALSE;
9742
9743       /* Fill the stub.  */
9744       idx = 0;
9745       bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
9746       idx += 4;
9747       bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + idx);
9748       idx += 4;
9749       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9750         {
9751           bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
9752                       stub + idx);
9753           idx += 4;
9754         }
9755       bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
9756       idx += 4;
9757
9758       /* If a large stub is not required and sign extension is not a
9759          problem, then use legacy code in the stub.  */
9760       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9761         bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff), stub + idx);
9762       else if (h->dynindx & ~0x7fff)
9763         bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff), stub + idx);
9764       else
9765         bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
9766                     stub + idx);
9767
9768       BFD_ASSERT (h->plt.offset <= htab->sstubs->size);
9769       memcpy (htab->sstubs->contents + h->plt.offset,
9770               stub, htab->function_stub_size);
9771
9772       /* Mark the symbol as undefined.  plt.offset != -1 occurs
9773          only for the referenced symbol.  */
9774       sym->st_shndx = SHN_UNDEF;
9775
9776       /* The run-time linker uses the st_value field of the symbol
9777          to reset the global offset table entry for this external
9778          to its stub address when unlinking a shared object.  */
9779       sym->st_value = (htab->sstubs->output_section->vma
9780                        + htab->sstubs->output_offset
9781                        + h->plt.offset);
9782     }
9783
9784   /* If we have a MIPS16 function with a stub, the dynamic symbol must
9785      refer to the stub, since only the stub uses the standard calling
9786      conventions.  */
9787   if (h->dynindx != -1 && hmips->fn_stub != NULL)
9788     {
9789       BFD_ASSERT (hmips->need_fn_stub);
9790       sym->st_value = (hmips->fn_stub->output_section->vma
9791                        + hmips->fn_stub->output_offset);
9792       sym->st_size = hmips->fn_stub->size;
9793       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
9794     }
9795
9796   BFD_ASSERT (h->dynindx != -1
9797               || h->forced_local);
9798
9799   sgot = htab->sgot;
9800   g = htab->got_info;
9801   BFD_ASSERT (g != NULL);
9802
9803   /* Run through the global symbol table, creating GOT entries for all
9804      the symbols that need them.  */
9805   if (hmips->global_got_area != GGA_NONE)
9806     {
9807       bfd_vma offset;
9808       bfd_vma value;
9809
9810       value = sym->st_value;
9811       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
9812       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
9813     }
9814
9815   if (hmips->global_got_area != GGA_NONE && g->next)
9816     {
9817       struct mips_got_entry e, *p;
9818       bfd_vma entry;
9819       bfd_vma offset;
9820
9821       gg = g;
9822
9823       e.abfd = output_bfd;
9824       e.symndx = -1;
9825       e.d.h = hmips;
9826       e.tls_type = GOT_TLS_NONE;
9827
9828       for (g = g->next; g->next != gg; g = g->next)
9829         {
9830           if (g->got_entries
9831               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
9832                                                            &e)))
9833             {
9834               offset = p->gotidx;
9835               BFD_ASSERT (offset > 0 && offset < htab->sgot->size);
9836               if (info->shared
9837                   || (elf_hash_table (info)->dynamic_sections_created
9838                       && p->d.h != NULL
9839                       && p->d.h->root.def_dynamic
9840                       && !p->d.h->root.def_regular))
9841                 {
9842                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
9843                      the various compatibility problems, it's easier to mock
9844                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
9845                      mips_elf_create_dynamic_relocation to calculate the
9846                      appropriate addend.  */
9847                   Elf_Internal_Rela rel[3];
9848
9849                   memset (rel, 0, sizeof (rel));
9850                   if (ABI_64_P (output_bfd))
9851                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
9852                   else
9853                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
9854                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
9855
9856                   entry = 0;
9857                   if (! (mips_elf_create_dynamic_relocation
9858                          (output_bfd, info, rel,
9859                           e.d.h, NULL, sym->st_value, &entry, sgot)))
9860                     return FALSE;
9861                 }
9862               else
9863                 entry = sym->st_value;
9864               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
9865             }
9866         }
9867     }
9868
9869   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
9870   name = h->root.root.string;
9871   if (h == elf_hash_table (info)->hdynamic
9872       || h == elf_hash_table (info)->hgot)
9873     sym->st_shndx = SHN_ABS;
9874   else if (strcmp (name, "_DYNAMIC_LINK") == 0
9875            || strcmp (name, "_DYNAMIC_LINKING") == 0)
9876     {
9877       sym->st_shndx = SHN_ABS;
9878       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9879       sym->st_value = 1;
9880     }
9881   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
9882     {
9883       sym->st_shndx = SHN_ABS;
9884       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9885       sym->st_value = elf_gp (output_bfd);
9886     }
9887   else if (SGI_COMPAT (output_bfd))
9888     {
9889       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
9890           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
9891         {
9892           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9893           sym->st_other = STO_PROTECTED;
9894           sym->st_value = 0;
9895           sym->st_shndx = SHN_MIPS_DATA;
9896         }
9897       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
9898         {
9899           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9900           sym->st_other = STO_PROTECTED;
9901           sym->st_value = mips_elf_hash_table (info)->procedure_count;
9902           sym->st_shndx = SHN_ABS;
9903         }
9904       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
9905         {
9906           if (h->type == STT_FUNC)
9907             sym->st_shndx = SHN_MIPS_TEXT;
9908           else if (h->type == STT_OBJECT)
9909             sym->st_shndx = SHN_MIPS_DATA;
9910         }
9911     }
9912
9913   /* Emit a copy reloc, if needed.  */
9914   if (h->needs_copy)
9915     {
9916       asection *s;
9917       bfd_vma symval;
9918
9919       BFD_ASSERT (h->dynindx != -1);
9920       BFD_ASSERT (htab->use_plts_and_copy_relocs);
9921
9922       s = mips_elf_rel_dyn_section (info, FALSE);
9923       symval = (h->root.u.def.section->output_section->vma
9924                 + h->root.u.def.section->output_offset
9925                 + h->root.u.def.value);
9926       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
9927                                           h->dynindx, R_MIPS_COPY, symval);
9928     }
9929
9930   /* Handle the IRIX6-specific symbols.  */
9931   if (IRIX_COMPAT (output_bfd) == ict_irix6)
9932     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
9933
9934   /* Keep dynamic MIPS16 symbols odd.  This allows the dynamic linker to
9935      treat MIPS16 symbols like any other.  */
9936   if (ELF_ST_IS_MIPS16 (sym->st_other))
9937     {
9938       BFD_ASSERT (sym->st_value & 1);
9939       sym->st_other -= STO_MIPS16;
9940     }
9941
9942   return TRUE;
9943 }
9944
9945 /* Likewise, for VxWorks.  */
9946
9947 bfd_boolean
9948 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
9949                                          struct bfd_link_info *info,
9950                                          struct elf_link_hash_entry *h,
9951                                          Elf_Internal_Sym *sym)
9952 {
9953   bfd *dynobj;
9954   asection *sgot;
9955   struct mips_got_info *g;
9956   struct mips_elf_link_hash_table *htab;
9957   struct mips_elf_link_hash_entry *hmips;
9958
9959   htab = mips_elf_hash_table (info);
9960   BFD_ASSERT (htab != NULL);
9961   dynobj = elf_hash_table (info)->dynobj;
9962   hmips = (struct mips_elf_link_hash_entry *) h;
9963
9964   if (h->plt.offset != (bfd_vma) -1)
9965     {
9966       bfd_byte *loc;
9967       bfd_vma plt_address, plt_index, got_address, got_offset, branch_offset;
9968       Elf_Internal_Rela rel;
9969       static const bfd_vma *plt_entry;
9970
9971       BFD_ASSERT (h->dynindx != -1);
9972       BFD_ASSERT (htab->splt != NULL);
9973       BFD_ASSERT (h->plt.offset <= htab->splt->size);
9974
9975       /* Calculate the address of the .plt entry.  */
9976       plt_address = (htab->splt->output_section->vma
9977                      + htab->splt->output_offset
9978                      + h->plt.offset);
9979
9980       /* Calculate the index of the entry.  */
9981       plt_index = ((h->plt.offset - htab->plt_header_size)
9982                    / htab->plt_entry_size);
9983
9984       /* Calculate the address of the .got.plt entry.  */
9985       got_address = (htab->sgotplt->output_section->vma
9986                      + htab->sgotplt->output_offset
9987                      + plt_index * 4);
9988
9989       /* Calculate the offset of the .got.plt entry from
9990          _GLOBAL_OFFSET_TABLE_.  */
9991       got_offset = mips_elf_gotplt_index (info, h);
9992
9993       /* Calculate the offset for the branch at the start of the PLT
9994          entry.  The branch jumps to the beginning of .plt.  */
9995       branch_offset = -(h->plt.offset / 4 + 1) & 0xffff;
9996
9997       /* Fill in the initial value of the .got.plt entry.  */
9998       bfd_put_32 (output_bfd, plt_address,
9999                   htab->sgotplt->contents + plt_index * 4);
10000
10001       /* Find out where the .plt entry should go.  */
10002       loc = htab->splt->contents + h->plt.offset;
10003
10004       if (info->shared)
10005         {
10006           plt_entry = mips_vxworks_shared_plt_entry;
10007           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10008           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10009         }
10010       else
10011         {
10012           bfd_vma got_address_high, got_address_low;
10013
10014           plt_entry = mips_vxworks_exec_plt_entry;
10015           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10016           got_address_low = got_address & 0xffff;
10017
10018           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10019           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10020           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
10021           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
10022           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10023           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10024           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10025           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10026
10027           loc = (htab->srelplt2->contents
10028                  + (plt_index * 3 + 2) * sizeof (Elf32_External_Rela));
10029
10030           /* Emit a relocation for the .got.plt entry.  */
10031           rel.r_offset = got_address;
10032           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10033           rel.r_addend = h->plt.offset;
10034           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10035
10036           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
10037           loc += sizeof (Elf32_External_Rela);
10038           rel.r_offset = plt_address + 8;
10039           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10040           rel.r_addend = got_offset;
10041           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10042
10043           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
10044           loc += sizeof (Elf32_External_Rela);
10045           rel.r_offset += 4;
10046           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10047           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10048         }
10049
10050       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10051       loc = htab->srelplt->contents + plt_index * sizeof (Elf32_External_Rela);
10052       rel.r_offset = got_address;
10053       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
10054       rel.r_addend = 0;
10055       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10056
10057       if (!h->def_regular)
10058         sym->st_shndx = SHN_UNDEF;
10059     }
10060
10061   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
10062
10063   sgot = htab->sgot;
10064   g = htab->got_info;
10065   BFD_ASSERT (g != NULL);
10066
10067   /* See if this symbol has an entry in the GOT.  */
10068   if (hmips->global_got_area != GGA_NONE)
10069     {
10070       bfd_vma offset;
10071       Elf_Internal_Rela outrel;
10072       bfd_byte *loc;
10073       asection *s;
10074
10075       /* Install the symbol value in the GOT.   */
10076       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
10077       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
10078
10079       /* Add a dynamic relocation for it.  */
10080       s = mips_elf_rel_dyn_section (info, FALSE);
10081       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
10082       outrel.r_offset = (sgot->output_section->vma
10083                          + sgot->output_offset
10084                          + offset);
10085       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
10086       outrel.r_addend = 0;
10087       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
10088     }
10089
10090   /* Emit a copy reloc, if needed.  */
10091   if (h->needs_copy)
10092     {
10093       Elf_Internal_Rela rel;
10094
10095       BFD_ASSERT (h->dynindx != -1);
10096
10097       rel.r_offset = (h->root.u.def.section->output_section->vma
10098                       + h->root.u.def.section->output_offset
10099                       + h->root.u.def.value);
10100       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
10101       rel.r_addend = 0;
10102       bfd_elf32_swap_reloca_out (output_bfd, &rel,
10103                                  htab->srelbss->contents
10104                                  + (htab->srelbss->reloc_count
10105                                     * sizeof (Elf32_External_Rela)));
10106       ++htab->srelbss->reloc_count;
10107     }
10108
10109   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
10110   if (ELF_ST_IS_COMPRESSED (sym->st_other))
10111     sym->st_value &= ~1;
10112
10113   return TRUE;
10114 }
10115
10116 /* Write out a plt0 entry to the beginning of .plt.  */
10117
10118 static void
10119 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10120 {
10121   bfd_byte *loc;
10122   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
10123   static const bfd_vma *plt_entry;
10124   struct mips_elf_link_hash_table *htab;
10125
10126   htab = mips_elf_hash_table (info);
10127   BFD_ASSERT (htab != NULL);
10128
10129   if (ABI_64_P (output_bfd))
10130     plt_entry = mips_n64_exec_plt0_entry;
10131   else if (ABI_N32_P (output_bfd))
10132     plt_entry = mips_n32_exec_plt0_entry;
10133   else
10134     plt_entry = mips_o32_exec_plt0_entry;
10135
10136   /* Calculate the value of .got.plt.  */
10137   gotplt_value = (htab->sgotplt->output_section->vma
10138                   + htab->sgotplt->output_offset);
10139   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
10140   gotplt_value_low = gotplt_value & 0xffff;
10141
10142   /* The PLT sequence is not safe for N64 if .got.plt's address can
10143      not be loaded in two instructions.  */
10144   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
10145               || ~(gotplt_value | 0x7fffffff) == 0);
10146
10147   /* Install the PLT header.  */
10148   loc = htab->splt->contents;
10149   bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
10150   bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
10151   bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
10152   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10153   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10154   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10155   bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10156   bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10157 }
10158
10159 /* Install the PLT header for a VxWorks executable and finalize the
10160    contents of .rela.plt.unloaded.  */
10161
10162 static void
10163 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10164 {
10165   Elf_Internal_Rela rela;
10166   bfd_byte *loc;
10167   bfd_vma got_value, got_value_high, got_value_low, plt_address;
10168   static const bfd_vma *plt_entry;
10169   struct mips_elf_link_hash_table *htab;
10170
10171   htab = mips_elf_hash_table (info);
10172   BFD_ASSERT (htab != NULL);
10173
10174   plt_entry = mips_vxworks_exec_plt0_entry;
10175
10176   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
10177   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
10178                + htab->root.hgot->root.u.def.section->output_offset
10179                + htab->root.hgot->root.u.def.value);
10180
10181   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
10182   got_value_low = got_value & 0xffff;
10183
10184   /* Calculate the address of the PLT header.  */
10185   plt_address = htab->splt->output_section->vma + htab->splt->output_offset;
10186
10187   /* Install the PLT header.  */
10188   loc = htab->splt->contents;
10189   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
10190   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
10191   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
10192   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10193   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10194   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10195
10196   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
10197   loc = htab->srelplt2->contents;
10198   rela.r_offset = plt_address;
10199   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10200   rela.r_addend = 0;
10201   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10202   loc += sizeof (Elf32_External_Rela);
10203
10204   /* Output the relocation for the following addiu of
10205      %lo(_GLOBAL_OFFSET_TABLE_).  */
10206   rela.r_offset += 4;
10207   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10208   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10209   loc += sizeof (Elf32_External_Rela);
10210
10211   /* Fix up the remaining relocations.  They may have the wrong
10212      symbol index for _G_O_T_ or _P_L_T_ depending on the order
10213      in which symbols were output.  */
10214   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
10215     {
10216       Elf_Internal_Rela rel;
10217
10218       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10219       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10220       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10221       loc += sizeof (Elf32_External_Rela);
10222
10223       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10224       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10225       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10226       loc += sizeof (Elf32_External_Rela);
10227
10228       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10229       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10230       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10231       loc += sizeof (Elf32_External_Rela);
10232     }
10233 }
10234
10235 /* Install the PLT header for a VxWorks shared library.  */
10236
10237 static void
10238 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
10239 {
10240   unsigned int i;
10241   struct mips_elf_link_hash_table *htab;
10242
10243   htab = mips_elf_hash_table (info);
10244   BFD_ASSERT (htab != NULL);
10245
10246   /* We just need to copy the entry byte-by-byte.  */
10247   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
10248     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
10249                 htab->splt->contents + i * 4);
10250 }
10251
10252 /* Finish up the dynamic sections.  */
10253
10254 bfd_boolean
10255 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
10256                                        struct bfd_link_info *info)
10257 {
10258   bfd *dynobj;
10259   asection *sdyn;
10260   asection *sgot;
10261   struct mips_got_info *gg, *g;
10262   struct mips_elf_link_hash_table *htab;
10263
10264   htab = mips_elf_hash_table (info);
10265   BFD_ASSERT (htab != NULL);
10266
10267   dynobj = elf_hash_table (info)->dynobj;
10268
10269   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
10270
10271   sgot = htab->sgot;
10272   gg = htab->got_info;
10273
10274   if (elf_hash_table (info)->dynamic_sections_created)
10275     {
10276       bfd_byte *b;
10277       int dyn_to_skip = 0, dyn_skipped = 0;
10278
10279       BFD_ASSERT (sdyn != NULL);
10280       BFD_ASSERT (gg != NULL);
10281
10282       g = mips_elf_bfd_got (output_bfd, FALSE);
10283       BFD_ASSERT (g != NULL);
10284
10285       for (b = sdyn->contents;
10286            b < sdyn->contents + sdyn->size;
10287            b += MIPS_ELF_DYN_SIZE (dynobj))
10288         {
10289           Elf_Internal_Dyn dyn;
10290           const char *name;
10291           size_t elemsize;
10292           asection *s;
10293           bfd_boolean swap_out_p;
10294
10295           /* Read in the current dynamic entry.  */
10296           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10297
10298           /* Assume that we're going to modify it and write it out.  */
10299           swap_out_p = TRUE;
10300
10301           switch (dyn.d_tag)
10302             {
10303             case DT_RELENT:
10304               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
10305               break;
10306
10307             case DT_RELAENT:
10308               BFD_ASSERT (htab->is_vxworks);
10309               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
10310               break;
10311
10312             case DT_STRSZ:
10313               /* Rewrite DT_STRSZ.  */
10314               dyn.d_un.d_val =
10315                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
10316               break;
10317
10318             case DT_PLTGOT:
10319               s = htab->sgot;
10320               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10321               break;
10322
10323             case DT_MIPS_PLTGOT:
10324               s = htab->sgotplt;
10325               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10326               break;
10327
10328             case DT_MIPS_RLD_VERSION:
10329               dyn.d_un.d_val = 1; /* XXX */
10330               break;
10331
10332             case DT_MIPS_FLAGS:
10333               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
10334               break;
10335
10336             case DT_MIPS_TIME_STAMP:
10337               {
10338                 time_t t;
10339                 time (&t);
10340                 dyn.d_un.d_val = t;
10341               }
10342               break;
10343
10344             case DT_MIPS_ICHECKSUM:
10345               /* XXX FIXME: */
10346               swap_out_p = FALSE;
10347               break;
10348
10349             case DT_MIPS_IVERSION:
10350               /* XXX FIXME: */
10351               swap_out_p = FALSE;
10352               break;
10353
10354             case DT_MIPS_BASE_ADDRESS:
10355               s = output_bfd->sections;
10356               BFD_ASSERT (s != NULL);
10357               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
10358               break;
10359
10360             case DT_MIPS_LOCAL_GOTNO:
10361               dyn.d_un.d_val = g->local_gotno;
10362               break;
10363
10364             case DT_MIPS_UNREFEXTNO:
10365               /* The index into the dynamic symbol table which is the
10366                  entry of the first external symbol that is not
10367                  referenced within the same object.  */
10368               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
10369               break;
10370
10371             case DT_MIPS_GOTSYM:
10372               if (htab->global_gotsym)
10373                 {
10374                   dyn.d_un.d_val = htab->global_gotsym->dynindx;
10375                   break;
10376                 }
10377               /* In case if we don't have global got symbols we default
10378                  to setting DT_MIPS_GOTSYM to the same value as
10379                  DT_MIPS_SYMTABNO, so we just fall through.  */
10380
10381             case DT_MIPS_SYMTABNO:
10382               name = ".dynsym";
10383               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
10384               s = bfd_get_section_by_name (output_bfd, name);
10385               BFD_ASSERT (s != NULL);
10386
10387               dyn.d_un.d_val = s->size / elemsize;
10388               break;
10389
10390             case DT_MIPS_HIPAGENO:
10391               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
10392               break;
10393
10394             case DT_MIPS_RLD_MAP:
10395               {
10396                 struct elf_link_hash_entry *h;
10397                 h = mips_elf_hash_table (info)->rld_symbol;
10398                 if (!h)
10399                   {
10400                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10401                     swap_out_p = FALSE;
10402                     break;
10403                   }
10404                 s = h->root.u.def.section;
10405                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
10406                                   + h->root.u.def.value);
10407               }
10408               break;
10409
10410             case DT_MIPS_OPTIONS:
10411               s = (bfd_get_section_by_name
10412                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
10413               dyn.d_un.d_ptr = s->vma;
10414               break;
10415
10416             case DT_RELASZ:
10417               BFD_ASSERT (htab->is_vxworks);
10418               /* The count does not include the JUMP_SLOT relocations.  */
10419               if (htab->srelplt)
10420                 dyn.d_un.d_val -= htab->srelplt->size;
10421               break;
10422
10423             case DT_PLTREL:
10424               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10425               if (htab->is_vxworks)
10426                 dyn.d_un.d_val = DT_RELA;
10427               else
10428                 dyn.d_un.d_val = DT_REL;
10429               break;
10430
10431             case DT_PLTRELSZ:
10432               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10433               dyn.d_un.d_val = htab->srelplt->size;
10434               break;
10435
10436             case DT_JMPREL:
10437               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10438               dyn.d_un.d_ptr = (htab->srelplt->output_section->vma
10439                                 + htab->srelplt->output_offset);
10440               break;
10441
10442             case DT_TEXTREL:
10443               /* If we didn't need any text relocations after all, delete
10444                  the dynamic tag.  */
10445               if (!(info->flags & DF_TEXTREL))
10446                 {
10447                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10448                   swap_out_p = FALSE;
10449                 }
10450               break;
10451
10452             case DT_FLAGS:
10453               /* If we didn't need any text relocations after all, clear
10454                  DF_TEXTREL from DT_FLAGS.  */
10455               if (!(info->flags & DF_TEXTREL))
10456                 dyn.d_un.d_val &= ~DF_TEXTREL;
10457               else
10458                 swap_out_p = FALSE;
10459               break;
10460
10461             default:
10462               swap_out_p = FALSE;
10463               if (htab->is_vxworks
10464                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
10465                 swap_out_p = TRUE;
10466               break;
10467             }
10468
10469           if (swap_out_p || dyn_skipped)
10470             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10471               (dynobj, &dyn, b - dyn_skipped);
10472
10473           if (dyn_to_skip)
10474             {
10475               dyn_skipped += dyn_to_skip;
10476               dyn_to_skip = 0;
10477             }
10478         }
10479
10480       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
10481       if (dyn_skipped > 0)
10482         memset (b - dyn_skipped, 0, dyn_skipped);
10483     }
10484
10485   if (sgot != NULL && sgot->size > 0
10486       && !bfd_is_abs_section (sgot->output_section))
10487     {
10488       if (htab->is_vxworks)
10489         {
10490           /* The first entry of the global offset table points to the
10491              ".dynamic" section.  The second is initialized by the
10492              loader and contains the shared library identifier.
10493              The third is also initialized by the loader and points
10494              to the lazy resolution stub.  */
10495           MIPS_ELF_PUT_WORD (output_bfd,
10496                              sdyn->output_offset + sdyn->output_section->vma,
10497                              sgot->contents);
10498           MIPS_ELF_PUT_WORD (output_bfd, 0,
10499                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10500           MIPS_ELF_PUT_WORD (output_bfd, 0,
10501                              sgot->contents
10502                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
10503         }
10504       else
10505         {
10506           /* The first entry of the global offset table will be filled at
10507              runtime. The second entry will be used by some runtime loaders.
10508              This isn't the case of IRIX rld.  */
10509           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
10510           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10511                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10512         }
10513
10514       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
10515          = MIPS_ELF_GOT_SIZE (output_bfd);
10516     }
10517
10518   /* Generate dynamic relocations for the non-primary gots.  */
10519   if (gg != NULL && gg->next)
10520     {
10521       Elf_Internal_Rela rel[3];
10522       bfd_vma addend = 0;
10523
10524       memset (rel, 0, sizeof (rel));
10525       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
10526
10527       for (g = gg->next; g->next != gg; g = g->next)
10528         {
10529           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
10530             + g->next->tls_gotno;
10531
10532           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
10533                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10534           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10535                              sgot->contents
10536                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10537
10538           if (! info->shared)
10539             continue;
10540
10541           while (got_index < g->assigned_gotno)
10542             {
10543               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
10544                 = got_index++ * MIPS_ELF_GOT_SIZE (output_bfd);
10545               if (!(mips_elf_create_dynamic_relocation
10546                     (output_bfd, info, rel, NULL,
10547                      bfd_abs_section_ptr,
10548                      0, &addend, sgot)))
10549                 return FALSE;
10550               BFD_ASSERT (addend == 0);
10551             }
10552         }
10553     }
10554
10555   /* The generation of dynamic relocations for the non-primary gots
10556      adds more dynamic relocations.  We cannot count them until
10557      here.  */
10558
10559   if (elf_hash_table (info)->dynamic_sections_created)
10560     {
10561       bfd_byte *b;
10562       bfd_boolean swap_out_p;
10563
10564       BFD_ASSERT (sdyn != NULL);
10565
10566       for (b = sdyn->contents;
10567            b < sdyn->contents + sdyn->size;
10568            b += MIPS_ELF_DYN_SIZE (dynobj))
10569         {
10570           Elf_Internal_Dyn dyn;
10571           asection *s;
10572
10573           /* Read in the current dynamic entry.  */
10574           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10575
10576           /* Assume that we're going to modify it and write it out.  */
10577           swap_out_p = TRUE;
10578
10579           switch (dyn.d_tag)
10580             {
10581             case DT_RELSZ:
10582               /* Reduce DT_RELSZ to account for any relocations we
10583                  decided not to make.  This is for the n64 irix rld,
10584                  which doesn't seem to apply any relocations if there
10585                  are trailing null entries.  */
10586               s = mips_elf_rel_dyn_section (info, FALSE);
10587               dyn.d_un.d_val = (s->reloc_count
10588                                 * (ABI_64_P (output_bfd)
10589                                    ? sizeof (Elf64_Mips_External_Rel)
10590                                    : sizeof (Elf32_External_Rel)));
10591               /* Adjust the section size too.  Tools like the prelinker
10592                  can reasonably expect the values to the same.  */
10593               elf_section_data (s->output_section)->this_hdr.sh_size
10594                 = dyn.d_un.d_val;
10595               break;
10596
10597             default:
10598               swap_out_p = FALSE;
10599               break;
10600             }
10601
10602           if (swap_out_p)
10603             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10604               (dynobj, &dyn, b);
10605         }
10606     }
10607
10608   {
10609     asection *s;
10610     Elf32_compact_rel cpt;
10611
10612     if (SGI_COMPAT (output_bfd))
10613       {
10614         /* Write .compact_rel section out.  */
10615         s = bfd_get_linker_section (dynobj, ".compact_rel");
10616         if (s != NULL)
10617           {
10618             cpt.id1 = 1;
10619             cpt.num = s->reloc_count;
10620             cpt.id2 = 2;
10621             cpt.offset = (s->output_section->filepos
10622                           + sizeof (Elf32_External_compact_rel));
10623             cpt.reserved0 = 0;
10624             cpt.reserved1 = 0;
10625             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
10626                                             ((Elf32_External_compact_rel *)
10627                                              s->contents));
10628
10629             /* Clean up a dummy stub function entry in .text.  */
10630             if (htab->sstubs != NULL)
10631               {
10632                 file_ptr dummy_offset;
10633
10634                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
10635                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
10636                 memset (htab->sstubs->contents + dummy_offset, 0,
10637                         htab->function_stub_size);
10638               }
10639           }
10640       }
10641
10642     /* The psABI says that the dynamic relocations must be sorted in
10643        increasing order of r_symndx.  The VxWorks EABI doesn't require
10644        this, and because the code below handles REL rather than RELA
10645        relocations, using it for VxWorks would be outright harmful.  */
10646     if (!htab->is_vxworks)
10647       {
10648         s = mips_elf_rel_dyn_section (info, FALSE);
10649         if (s != NULL
10650             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
10651           {
10652             reldyn_sorting_bfd = output_bfd;
10653
10654             if (ABI_64_P (output_bfd))
10655               qsort ((Elf64_External_Rel *) s->contents + 1,
10656                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
10657                      sort_dynamic_relocs_64);
10658             else
10659               qsort ((Elf32_External_Rel *) s->contents + 1,
10660                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
10661                      sort_dynamic_relocs);
10662           }
10663       }
10664   }
10665
10666   if (htab->splt && htab->splt->size > 0)
10667     {
10668       if (htab->is_vxworks)
10669         {
10670           if (info->shared)
10671             mips_vxworks_finish_shared_plt (output_bfd, info);
10672           else
10673             mips_vxworks_finish_exec_plt (output_bfd, info);
10674         }
10675       else
10676         {
10677           BFD_ASSERT (!info->shared);
10678           mips_finish_exec_plt (output_bfd, info);
10679         }
10680     }
10681   return TRUE;
10682 }
10683
10684
10685 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
10686
10687 static void
10688 mips_set_isa_flags (bfd *abfd)
10689 {
10690   flagword val;
10691
10692   switch (bfd_get_mach (abfd))
10693     {
10694     default:
10695     case bfd_mach_mips3000:
10696       val = E_MIPS_ARCH_1;
10697       break;
10698
10699     case bfd_mach_mips3900:
10700       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
10701       break;
10702
10703     case bfd_mach_mips6000:
10704       val = E_MIPS_ARCH_2;
10705       break;
10706
10707     case bfd_mach_mips4000:
10708     case bfd_mach_mips4300:
10709     case bfd_mach_mips4400:
10710     case bfd_mach_mips4600:
10711       val = E_MIPS_ARCH_3;
10712       break;
10713
10714     case bfd_mach_mips4010:
10715       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
10716       break;
10717
10718     case bfd_mach_mips4100:
10719       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
10720       break;
10721
10722     case bfd_mach_mips4111:
10723       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
10724       break;
10725
10726     case bfd_mach_mips4120:
10727       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
10728       break;
10729
10730     case bfd_mach_mips4650:
10731       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
10732       break;
10733
10734     case bfd_mach_mips5400:
10735       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
10736       break;
10737
10738     case bfd_mach_mips5500:
10739       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
10740       break;
10741
10742     case bfd_mach_mips5900:
10743       val = E_MIPS_ARCH_3 | E_MIPS_MACH_5900;
10744       break;
10745
10746     case bfd_mach_mips9000:
10747       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
10748       break;
10749
10750     case bfd_mach_mips5000:
10751     case bfd_mach_mips7000:
10752     case bfd_mach_mips8000:
10753     case bfd_mach_mips10000:
10754     case bfd_mach_mips12000:
10755     case bfd_mach_mips14000:
10756     case bfd_mach_mips16000:
10757       val = E_MIPS_ARCH_4;
10758       break;
10759
10760     case bfd_mach_mips5:
10761       val = E_MIPS_ARCH_5;
10762       break;
10763
10764     case bfd_mach_mips_loongson_2e:
10765       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
10766       break;
10767
10768     case bfd_mach_mips_loongson_2f:
10769       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
10770       break;
10771
10772     case bfd_mach_mips_sb1:
10773       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
10774       break;
10775
10776     case bfd_mach_mips_loongson_3a:
10777       val = E_MIPS_ARCH_64 | E_MIPS_MACH_LS3A;
10778       break;
10779
10780     case bfd_mach_mips_octeon:
10781     case bfd_mach_mips_octeonp:
10782       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
10783       break;
10784
10785     case bfd_mach_mips_xlr:
10786       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
10787       break;
10788
10789     case bfd_mach_mips_octeon2:
10790       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
10791       break;
10792
10793     case bfd_mach_mipsisa32:
10794       val = E_MIPS_ARCH_32;
10795       break;
10796
10797     case bfd_mach_mipsisa64:
10798       val = E_MIPS_ARCH_64;
10799       break;
10800
10801     case bfd_mach_mipsisa32r2:
10802       val = E_MIPS_ARCH_32R2;
10803       break;
10804
10805     case bfd_mach_mipsisa64r2:
10806       val = E_MIPS_ARCH_64R2;
10807       break;
10808     }
10809   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
10810   elf_elfheader (abfd)->e_flags |= val;
10811
10812 }
10813
10814
10815 /* The final processing done just before writing out a MIPS ELF object
10816    file.  This gets the MIPS architecture right based on the machine
10817    number.  This is used by both the 32-bit and the 64-bit ABI.  */
10818
10819 void
10820 _bfd_mips_elf_final_write_processing (bfd *abfd,
10821                                       bfd_boolean linker ATTRIBUTE_UNUSED)
10822 {
10823   unsigned int i;
10824   Elf_Internal_Shdr **hdrpp;
10825   const char *name;
10826   asection *sec;
10827
10828   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
10829      is nonzero.  This is for compatibility with old objects, which used
10830      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
10831   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
10832     mips_set_isa_flags (abfd);
10833
10834   /* Set the sh_info field for .gptab sections and other appropriate
10835      info for each special section.  */
10836   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
10837        i < elf_numsections (abfd);
10838        i++, hdrpp++)
10839     {
10840       switch ((*hdrpp)->sh_type)
10841         {
10842         case SHT_MIPS_MSYM:
10843         case SHT_MIPS_LIBLIST:
10844           sec = bfd_get_section_by_name (abfd, ".dynstr");
10845           if (sec != NULL)
10846             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
10847           break;
10848
10849         case SHT_MIPS_GPTAB:
10850           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
10851           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
10852           BFD_ASSERT (name != NULL
10853                       && CONST_STRNEQ (name, ".gptab."));
10854           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
10855           BFD_ASSERT (sec != NULL);
10856           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
10857           break;
10858
10859         case SHT_MIPS_CONTENT:
10860           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
10861           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
10862           BFD_ASSERT (name != NULL
10863                       && CONST_STRNEQ (name, ".MIPS.content"));
10864           sec = bfd_get_section_by_name (abfd,
10865                                          name + sizeof ".MIPS.content" - 1);
10866           BFD_ASSERT (sec != NULL);
10867           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
10868           break;
10869
10870         case SHT_MIPS_SYMBOL_LIB:
10871           sec = bfd_get_section_by_name (abfd, ".dynsym");
10872           if (sec != NULL)
10873             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
10874           sec = bfd_get_section_by_name (abfd, ".liblist");
10875           if (sec != NULL)
10876             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
10877           break;
10878
10879         case SHT_MIPS_EVENTS:
10880           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
10881           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
10882           BFD_ASSERT (name != NULL);
10883           if (CONST_STRNEQ (name, ".MIPS.events"))
10884             sec = bfd_get_section_by_name (abfd,
10885                                            name + sizeof ".MIPS.events" - 1);
10886           else
10887             {
10888               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
10889               sec = bfd_get_section_by_name (abfd,
10890                                              (name
10891                                               + sizeof ".MIPS.post_rel" - 1));
10892             }
10893           BFD_ASSERT (sec != NULL);
10894           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
10895           break;
10896
10897         }
10898     }
10899 }
10900 \f
10901 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
10902    segments.  */
10903
10904 int
10905 _bfd_mips_elf_additional_program_headers (bfd *abfd,
10906                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
10907 {
10908   asection *s;
10909   int ret = 0;
10910
10911   /* See if we need a PT_MIPS_REGINFO segment.  */
10912   s = bfd_get_section_by_name (abfd, ".reginfo");
10913   if (s && (s->flags & SEC_LOAD))
10914     ++ret;
10915
10916   /* See if we need a PT_MIPS_OPTIONS segment.  */
10917   if (IRIX_COMPAT (abfd) == ict_irix6
10918       && bfd_get_section_by_name (abfd,
10919                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
10920     ++ret;
10921
10922   /* See if we need a PT_MIPS_RTPROC segment.  */
10923   if (IRIX_COMPAT (abfd) == ict_irix5
10924       && bfd_get_section_by_name (abfd, ".dynamic")
10925       && bfd_get_section_by_name (abfd, ".mdebug"))
10926     ++ret;
10927
10928   /* Allocate a PT_NULL header in dynamic objects.  See
10929      _bfd_mips_elf_modify_segment_map for details.  */
10930   if (!SGI_COMPAT (abfd)
10931       && bfd_get_section_by_name (abfd, ".dynamic"))
10932     ++ret;
10933
10934   return ret;
10935 }
10936
10937 /* Modify the segment map for an IRIX5 executable.  */
10938
10939 bfd_boolean
10940 _bfd_mips_elf_modify_segment_map (bfd *abfd,
10941                                   struct bfd_link_info *info)
10942 {
10943   asection *s;
10944   struct elf_segment_map *m, **pm;
10945   bfd_size_type amt;
10946
10947   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
10948      segment.  */
10949   s = bfd_get_section_by_name (abfd, ".reginfo");
10950   if (s != NULL && (s->flags & SEC_LOAD) != 0)
10951     {
10952       for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
10953         if (m->p_type == PT_MIPS_REGINFO)
10954           break;
10955       if (m == NULL)
10956         {
10957           amt = sizeof *m;
10958           m = bfd_zalloc (abfd, amt);
10959           if (m == NULL)
10960             return FALSE;
10961
10962           m->p_type = PT_MIPS_REGINFO;
10963           m->count = 1;
10964           m->sections[0] = s;
10965
10966           /* We want to put it after the PHDR and INTERP segments.  */
10967           pm = &elf_tdata (abfd)->segment_map;
10968           while (*pm != NULL
10969                  && ((*pm)->p_type == PT_PHDR
10970                      || (*pm)->p_type == PT_INTERP))
10971             pm = &(*pm)->next;
10972
10973           m->next = *pm;
10974           *pm = m;
10975         }
10976     }
10977
10978   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
10979      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
10980      PT_MIPS_OPTIONS segment immediately following the program header
10981      table.  */
10982   if (NEWABI_P (abfd)
10983       /* On non-IRIX6 new abi, we'll have already created a segment
10984          for this section, so don't create another.  I'm not sure this
10985          is not also the case for IRIX 6, but I can't test it right
10986          now.  */
10987       && IRIX_COMPAT (abfd) == ict_irix6)
10988     {
10989       for (s = abfd->sections; s; s = s->next)
10990         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
10991           break;
10992
10993       if (s)
10994         {
10995           struct elf_segment_map *options_segment;
10996
10997           pm = &elf_tdata (abfd)->segment_map;
10998           while (*pm != NULL
10999                  && ((*pm)->p_type == PT_PHDR
11000                      || (*pm)->p_type == PT_INTERP))
11001             pm = &(*pm)->next;
11002
11003           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
11004             {
11005               amt = sizeof (struct elf_segment_map);
11006               options_segment = bfd_zalloc (abfd, amt);
11007               options_segment->next = *pm;
11008               options_segment->p_type = PT_MIPS_OPTIONS;
11009               options_segment->p_flags = PF_R;
11010               options_segment->p_flags_valid = TRUE;
11011               options_segment->count = 1;
11012               options_segment->sections[0] = s;
11013               *pm = options_segment;
11014             }
11015         }
11016     }
11017   else
11018     {
11019       if (IRIX_COMPAT (abfd) == ict_irix5)
11020         {
11021           /* If there are .dynamic and .mdebug sections, we make a room
11022              for the RTPROC header.  FIXME: Rewrite without section names.  */
11023           if (bfd_get_section_by_name (abfd, ".interp") == NULL
11024               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
11025               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
11026             {
11027               for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11028                 if (m->p_type == PT_MIPS_RTPROC)
11029                   break;
11030               if (m == NULL)
11031                 {
11032                   amt = sizeof *m;
11033                   m = bfd_zalloc (abfd, amt);
11034                   if (m == NULL)
11035                     return FALSE;
11036
11037                   m->p_type = PT_MIPS_RTPROC;
11038
11039                   s = bfd_get_section_by_name (abfd, ".rtproc");
11040                   if (s == NULL)
11041                     {
11042                       m->count = 0;
11043                       m->p_flags = 0;
11044                       m->p_flags_valid = 1;
11045                     }
11046                   else
11047                     {
11048                       m->count = 1;
11049                       m->sections[0] = s;
11050                     }
11051
11052                   /* We want to put it after the DYNAMIC segment.  */
11053                   pm = &elf_tdata (abfd)->segment_map;
11054                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
11055                     pm = &(*pm)->next;
11056                   if (*pm != NULL)
11057                     pm = &(*pm)->next;
11058
11059                   m->next = *pm;
11060                   *pm = m;
11061                 }
11062             }
11063         }
11064       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
11065          .dynstr, .dynsym, and .hash sections, and everything in
11066          between.  */
11067       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL;
11068            pm = &(*pm)->next)
11069         if ((*pm)->p_type == PT_DYNAMIC)
11070           break;
11071       m = *pm;
11072       if (m != NULL && IRIX_COMPAT (abfd) == ict_none)
11073         {
11074           /* For a normal mips executable the permissions for the PT_DYNAMIC
11075              segment are read, write and execute. We do that here since
11076              the code in elf.c sets only the read permission. This matters
11077              sometimes for the dynamic linker.  */
11078           if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
11079             {
11080               m->p_flags = PF_R | PF_W | PF_X;
11081               m->p_flags_valid = 1;
11082             }
11083         }
11084       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
11085          glibc's dynamic linker has traditionally derived the number of
11086          tags from the p_filesz field, and sometimes allocates stack
11087          arrays of that size.  An overly-big PT_DYNAMIC segment can
11088          be actively harmful in such cases.  Making PT_DYNAMIC contain
11089          other sections can also make life hard for the prelinker,
11090          which might move one of the other sections to a different
11091          PT_LOAD segment.  */
11092       if (SGI_COMPAT (abfd)
11093           && m != NULL
11094           && m->count == 1
11095           && strcmp (m->sections[0]->name, ".dynamic") == 0)
11096         {
11097           static const char *sec_names[] =
11098           {
11099             ".dynamic", ".dynstr", ".dynsym", ".hash"
11100           };
11101           bfd_vma low, high;
11102           unsigned int i, c;
11103           struct elf_segment_map *n;
11104
11105           low = ~(bfd_vma) 0;
11106           high = 0;
11107           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
11108             {
11109               s = bfd_get_section_by_name (abfd, sec_names[i]);
11110               if (s != NULL && (s->flags & SEC_LOAD) != 0)
11111                 {
11112                   bfd_size_type sz;
11113
11114                   if (low > s->vma)
11115                     low = s->vma;
11116                   sz = s->size;
11117                   if (high < s->vma + sz)
11118                     high = s->vma + sz;
11119                 }
11120             }
11121
11122           c = 0;
11123           for (s = abfd->sections; s != NULL; s = s->next)
11124             if ((s->flags & SEC_LOAD) != 0
11125                 && s->vma >= low
11126                 && s->vma + s->size <= high)
11127               ++c;
11128
11129           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
11130           n = bfd_zalloc (abfd, amt);
11131           if (n == NULL)
11132             return FALSE;
11133           *n = *m;
11134           n->count = c;
11135
11136           i = 0;
11137           for (s = abfd->sections; s != NULL; s = s->next)
11138             {
11139               if ((s->flags & SEC_LOAD) != 0
11140                   && s->vma >= low
11141                   && s->vma + s->size <= high)
11142                 {
11143                   n->sections[i] = s;
11144                   ++i;
11145                 }
11146             }
11147
11148           *pm = n;
11149         }
11150     }
11151
11152   /* Allocate a spare program header in dynamic objects so that tools
11153      like the prelinker can add an extra PT_LOAD entry.
11154
11155      If the prelinker needs to make room for a new PT_LOAD entry, its
11156      standard procedure is to move the first (read-only) sections into
11157      the new (writable) segment.  However, the MIPS ABI requires
11158      .dynamic to be in a read-only segment, and the section will often
11159      start within sizeof (ElfNN_Phdr) bytes of the last program header.
11160
11161      Although the prelinker could in principle move .dynamic to a
11162      writable segment, it seems better to allocate a spare program
11163      header instead, and avoid the need to move any sections.
11164      There is a long tradition of allocating spare dynamic tags,
11165      so allocating a spare program header seems like a natural
11166      extension.
11167
11168      If INFO is NULL, we may be copying an already prelinked binary
11169      with objcopy or strip, so do not add this header.  */
11170   if (info != NULL
11171       && !SGI_COMPAT (abfd)
11172       && bfd_get_section_by_name (abfd, ".dynamic"))
11173     {
11174       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL; pm = &(*pm)->next)
11175         if ((*pm)->p_type == PT_NULL)
11176           break;
11177       if (*pm == NULL)
11178         {
11179           m = bfd_zalloc (abfd, sizeof (*m));
11180           if (m == NULL)
11181             return FALSE;
11182
11183           m->p_type = PT_NULL;
11184           *pm = m;
11185         }
11186     }
11187
11188   return TRUE;
11189 }
11190 \f
11191 /* Return the section that should be marked against GC for a given
11192    relocation.  */
11193
11194 asection *
11195 _bfd_mips_elf_gc_mark_hook (asection *sec,
11196                             struct bfd_link_info *info,
11197                             Elf_Internal_Rela *rel,
11198                             struct elf_link_hash_entry *h,
11199                             Elf_Internal_Sym *sym)
11200 {
11201   /* ??? Do mips16 stub sections need to be handled special?  */
11202
11203   if (h != NULL)
11204     switch (ELF_R_TYPE (sec->owner, rel->r_info))
11205       {
11206       case R_MIPS_GNU_VTINHERIT:
11207       case R_MIPS_GNU_VTENTRY:
11208         return NULL;
11209       }
11210
11211   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
11212 }
11213
11214 /* Update the got entry reference counts for the section being removed.  */
11215
11216 bfd_boolean
11217 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
11218                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
11219                              asection *sec ATTRIBUTE_UNUSED,
11220                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
11221 {
11222 #if 0
11223   Elf_Internal_Shdr *symtab_hdr;
11224   struct elf_link_hash_entry **sym_hashes;
11225   bfd_signed_vma *local_got_refcounts;
11226   const Elf_Internal_Rela *rel, *relend;
11227   unsigned long r_symndx;
11228   struct elf_link_hash_entry *h;
11229
11230   if (info->relocatable)
11231     return TRUE;
11232
11233   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11234   sym_hashes = elf_sym_hashes (abfd);
11235   local_got_refcounts = elf_local_got_refcounts (abfd);
11236
11237   relend = relocs + sec->reloc_count;
11238   for (rel = relocs; rel < relend; rel++)
11239     switch (ELF_R_TYPE (abfd, rel->r_info))
11240       {
11241       case R_MIPS16_GOT16:
11242       case R_MIPS16_CALL16:
11243       case R_MIPS_GOT16:
11244       case R_MIPS_CALL16:
11245       case R_MIPS_CALL_HI16:
11246       case R_MIPS_CALL_LO16:
11247       case R_MIPS_GOT_HI16:
11248       case R_MIPS_GOT_LO16:
11249       case R_MIPS_GOT_DISP:
11250       case R_MIPS_GOT_PAGE:
11251       case R_MIPS_GOT_OFST:
11252       case R_MICROMIPS_GOT16:
11253       case R_MICROMIPS_CALL16:
11254       case R_MICROMIPS_CALL_HI16:
11255       case R_MICROMIPS_CALL_LO16:
11256       case R_MICROMIPS_GOT_HI16:
11257       case R_MICROMIPS_GOT_LO16:
11258       case R_MICROMIPS_GOT_DISP:
11259       case R_MICROMIPS_GOT_PAGE:
11260       case R_MICROMIPS_GOT_OFST:
11261         /* ??? It would seem that the existing MIPS code does no sort
11262            of reference counting or whatnot on its GOT and PLT entries,
11263            so it is not possible to garbage collect them at this time.  */
11264         break;
11265
11266       default:
11267         break;
11268       }
11269 #endif
11270
11271   return TRUE;
11272 }
11273 \f
11274 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
11275    hiding the old indirect symbol.  Process additional relocation
11276    information.  Also called for weakdefs, in which case we just let
11277    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
11278
11279 void
11280 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
11281                                     struct elf_link_hash_entry *dir,
11282                                     struct elf_link_hash_entry *ind)
11283 {
11284   struct mips_elf_link_hash_entry *dirmips, *indmips;
11285
11286   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
11287
11288   dirmips = (struct mips_elf_link_hash_entry *) dir;
11289   indmips = (struct mips_elf_link_hash_entry *) ind;
11290   /* Any absolute non-dynamic relocations against an indirect or weak
11291      definition will be against the target symbol.  */
11292   if (indmips->has_static_relocs)
11293     dirmips->has_static_relocs = TRUE;
11294
11295   if (ind->root.type != bfd_link_hash_indirect)
11296     return;
11297
11298   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
11299   if (indmips->readonly_reloc)
11300     dirmips->readonly_reloc = TRUE;
11301   if (indmips->no_fn_stub)
11302     dirmips->no_fn_stub = TRUE;
11303   if (indmips->fn_stub)
11304     {
11305       dirmips->fn_stub = indmips->fn_stub;
11306       indmips->fn_stub = NULL;
11307     }
11308   if (indmips->need_fn_stub)
11309     {
11310       dirmips->need_fn_stub = TRUE;
11311       indmips->need_fn_stub = FALSE;
11312     }
11313   if (indmips->call_stub)
11314     {
11315       dirmips->call_stub = indmips->call_stub;
11316       indmips->call_stub = NULL;
11317     }
11318   if (indmips->call_fp_stub)
11319     {
11320       dirmips->call_fp_stub = indmips->call_fp_stub;
11321       indmips->call_fp_stub = NULL;
11322     }
11323   if (indmips->global_got_area < dirmips->global_got_area)
11324     dirmips->global_got_area = indmips->global_got_area;
11325   if (indmips->global_got_area < GGA_NONE)
11326     indmips->global_got_area = GGA_NONE;
11327   if (indmips->has_nonpic_branches)
11328     dirmips->has_nonpic_branches = TRUE;
11329 }
11330 \f
11331 #define PDR_SIZE 32
11332
11333 bfd_boolean
11334 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
11335                             struct bfd_link_info *info)
11336 {
11337   asection *o;
11338   bfd_boolean ret = FALSE;
11339   unsigned char *tdata;
11340   size_t i, skip;
11341
11342   o = bfd_get_section_by_name (abfd, ".pdr");
11343   if (! o)
11344     return FALSE;
11345   if (o->size == 0)
11346     return FALSE;
11347   if (o->size % PDR_SIZE != 0)
11348     return FALSE;
11349   if (o->output_section != NULL
11350       && bfd_is_abs_section (o->output_section))
11351     return FALSE;
11352
11353   tdata = bfd_zmalloc (o->size / PDR_SIZE);
11354   if (! tdata)
11355     return FALSE;
11356
11357   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
11358                                             info->keep_memory);
11359   if (!cookie->rels)
11360     {
11361       free (tdata);
11362       return FALSE;
11363     }
11364
11365   cookie->rel = cookie->rels;
11366   cookie->relend = cookie->rels + o->reloc_count;
11367
11368   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
11369     {
11370       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
11371         {
11372           tdata[i] = 1;
11373           skip ++;
11374         }
11375     }
11376
11377   if (skip != 0)
11378     {
11379       mips_elf_section_data (o)->u.tdata = tdata;
11380       o->size -= skip * PDR_SIZE;
11381       ret = TRUE;
11382     }
11383   else
11384     free (tdata);
11385
11386   if (! info->keep_memory)
11387     free (cookie->rels);
11388
11389   return ret;
11390 }
11391
11392 bfd_boolean
11393 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
11394 {
11395   if (strcmp (sec->name, ".pdr") == 0)
11396     return TRUE;
11397   return FALSE;
11398 }
11399
11400 bfd_boolean
11401 _bfd_mips_elf_write_section (bfd *output_bfd,
11402                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
11403                              asection *sec, bfd_byte *contents)
11404 {
11405   bfd_byte *to, *from, *end;
11406   int i;
11407
11408   if (strcmp (sec->name, ".pdr") != 0)
11409     return FALSE;
11410
11411   if (mips_elf_section_data (sec)->u.tdata == NULL)
11412     return FALSE;
11413
11414   to = contents;
11415   end = contents + sec->size;
11416   for (from = contents, i = 0;
11417        from < end;
11418        from += PDR_SIZE, i++)
11419     {
11420       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
11421         continue;
11422       if (to != from)
11423         memcpy (to, from, PDR_SIZE);
11424       to += PDR_SIZE;
11425     }
11426   bfd_set_section_contents (output_bfd, sec->output_section, contents,
11427                             sec->output_offset, sec->size);
11428   return TRUE;
11429 }
11430 \f
11431 /* microMIPS code retains local labels for linker relaxation.  Omit them
11432    from output by default for clarity.  */
11433
11434 bfd_boolean
11435 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
11436 {
11437   return _bfd_elf_is_local_label_name (abfd, sym->name);
11438 }
11439
11440 /* MIPS ELF uses a special find_nearest_line routine in order the
11441    handle the ECOFF debugging information.  */
11442
11443 struct mips_elf_find_line
11444 {
11445   struct ecoff_debug_info d;
11446   struct ecoff_find_line i;
11447 };
11448
11449 bfd_boolean
11450 _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section,
11451                                  asymbol **symbols, bfd_vma offset,
11452                                  const char **filename_ptr,
11453                                  const char **functionname_ptr,
11454                                  unsigned int *line_ptr)
11455 {
11456   asection *msec;
11457
11458   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
11459                                      filename_ptr, functionname_ptr,
11460                                      line_ptr))
11461     return TRUE;
11462
11463   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
11464                                      section, symbols, offset,
11465                                      filename_ptr, functionname_ptr,
11466                                      line_ptr, NULL, ABI_64_P (abfd) ? 8 : 0,
11467                                      &elf_tdata (abfd)->dwarf2_find_line_info))
11468     return TRUE;
11469
11470   msec = bfd_get_section_by_name (abfd, ".mdebug");
11471   if (msec != NULL)
11472     {
11473       flagword origflags;
11474       struct mips_elf_find_line *fi;
11475       const struct ecoff_debug_swap * const swap =
11476         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
11477
11478       /* If we are called during a link, mips_elf_final_link may have
11479          cleared the SEC_HAS_CONTENTS field.  We force it back on here
11480          if appropriate (which it normally will be).  */
11481       origflags = msec->flags;
11482       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
11483         msec->flags |= SEC_HAS_CONTENTS;
11484
11485       fi = elf_tdata (abfd)->find_line_info;
11486       if (fi == NULL)
11487         {
11488           bfd_size_type external_fdr_size;
11489           char *fraw_src;
11490           char *fraw_end;
11491           struct fdr *fdr_ptr;
11492           bfd_size_type amt = sizeof (struct mips_elf_find_line);
11493
11494           fi = bfd_zalloc (abfd, amt);
11495           if (fi == NULL)
11496             {
11497               msec->flags = origflags;
11498               return FALSE;
11499             }
11500
11501           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
11502             {
11503               msec->flags = origflags;
11504               return FALSE;
11505             }
11506
11507           /* Swap in the FDR information.  */
11508           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
11509           fi->d.fdr = bfd_alloc (abfd, amt);
11510           if (fi->d.fdr == NULL)
11511             {
11512               msec->flags = origflags;
11513               return FALSE;
11514             }
11515           external_fdr_size = swap->external_fdr_size;
11516           fdr_ptr = fi->d.fdr;
11517           fraw_src = (char *) fi->d.external_fdr;
11518           fraw_end = (fraw_src
11519                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
11520           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
11521             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
11522
11523           elf_tdata (abfd)->find_line_info = fi;
11524
11525           /* Note that we don't bother to ever free this information.
11526              find_nearest_line is either called all the time, as in
11527              objdump -l, so the information should be saved, or it is
11528              rarely called, as in ld error messages, so the memory
11529              wasted is unimportant.  Still, it would probably be a
11530              good idea for free_cached_info to throw it away.  */
11531         }
11532
11533       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
11534                                   &fi->i, filename_ptr, functionname_ptr,
11535                                   line_ptr))
11536         {
11537           msec->flags = origflags;
11538           return TRUE;
11539         }
11540
11541       msec->flags = origflags;
11542     }
11543
11544   /* Fall back on the generic ELF find_nearest_line routine.  */
11545
11546   return _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
11547                                      filename_ptr, functionname_ptr,
11548                                      line_ptr);
11549 }
11550
11551 bfd_boolean
11552 _bfd_mips_elf_find_inliner_info (bfd *abfd,
11553                                  const char **filename_ptr,
11554                                  const char **functionname_ptr,
11555                                  unsigned int *line_ptr)
11556 {
11557   bfd_boolean found;
11558   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
11559                                          functionname_ptr, line_ptr,
11560                                          & elf_tdata (abfd)->dwarf2_find_line_info);
11561   return found;
11562 }
11563
11564 \f
11565 /* When are writing out the .options or .MIPS.options section,
11566    remember the bytes we are writing out, so that we can install the
11567    GP value in the section_processing routine.  */
11568
11569 bfd_boolean
11570 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
11571                                     const void *location,
11572                                     file_ptr offset, bfd_size_type count)
11573 {
11574   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
11575     {
11576       bfd_byte *c;
11577
11578       if (elf_section_data (section) == NULL)
11579         {
11580           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
11581           section->used_by_bfd = bfd_zalloc (abfd, amt);
11582           if (elf_section_data (section) == NULL)
11583             return FALSE;
11584         }
11585       c = mips_elf_section_data (section)->u.tdata;
11586       if (c == NULL)
11587         {
11588           c = bfd_zalloc (abfd, section->size);
11589           if (c == NULL)
11590             return FALSE;
11591           mips_elf_section_data (section)->u.tdata = c;
11592         }
11593
11594       memcpy (c + offset, location, count);
11595     }
11596
11597   return _bfd_elf_set_section_contents (abfd, section, location, offset,
11598                                         count);
11599 }
11600
11601 /* This is almost identical to bfd_generic_get_... except that some
11602    MIPS relocations need to be handled specially.  Sigh.  */
11603
11604 bfd_byte *
11605 _bfd_elf_mips_get_relocated_section_contents
11606   (bfd *abfd,
11607    struct bfd_link_info *link_info,
11608    struct bfd_link_order *link_order,
11609    bfd_byte *data,
11610    bfd_boolean relocatable,
11611    asymbol **symbols)
11612 {
11613   /* Get enough memory to hold the stuff */
11614   bfd *input_bfd = link_order->u.indirect.section->owner;
11615   asection *input_section = link_order->u.indirect.section;
11616   bfd_size_type sz;
11617
11618   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
11619   arelent **reloc_vector = NULL;
11620   long reloc_count;
11621
11622   if (reloc_size < 0)
11623     goto error_return;
11624
11625   reloc_vector = bfd_malloc (reloc_size);
11626   if (reloc_vector == NULL && reloc_size != 0)
11627     goto error_return;
11628
11629   /* read in the section */
11630   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
11631   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
11632     goto error_return;
11633
11634   reloc_count = bfd_canonicalize_reloc (input_bfd,
11635                                         input_section,
11636                                         reloc_vector,
11637                                         symbols);
11638   if (reloc_count < 0)
11639     goto error_return;
11640
11641   if (reloc_count > 0)
11642     {
11643       arelent **parent;
11644       /* for mips */
11645       int gp_found;
11646       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
11647
11648       {
11649         struct bfd_hash_entry *h;
11650         struct bfd_link_hash_entry *lh;
11651         /* Skip all this stuff if we aren't mixing formats.  */
11652         if (abfd && input_bfd
11653             && abfd->xvec == input_bfd->xvec)
11654           lh = 0;
11655         else
11656           {
11657             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
11658             lh = (struct bfd_link_hash_entry *) h;
11659           }
11660       lookup:
11661         if (lh)
11662           {
11663             switch (lh->type)
11664               {
11665               case bfd_link_hash_undefined:
11666               case bfd_link_hash_undefweak:
11667               case bfd_link_hash_common:
11668                 gp_found = 0;
11669                 break;
11670               case bfd_link_hash_defined:
11671               case bfd_link_hash_defweak:
11672                 gp_found = 1;
11673                 gp = lh->u.def.value;
11674                 break;
11675               case bfd_link_hash_indirect:
11676               case bfd_link_hash_warning:
11677                 lh = lh->u.i.link;
11678                 /* @@FIXME  ignoring warning for now */
11679                 goto lookup;
11680               case bfd_link_hash_new:
11681               default:
11682                 abort ();
11683               }
11684           }
11685         else
11686           gp_found = 0;
11687       }
11688       /* end mips */
11689       for (parent = reloc_vector; *parent != NULL; parent++)
11690         {
11691           char *error_message = NULL;
11692           bfd_reloc_status_type r;
11693
11694           /* Specific to MIPS: Deal with relocation types that require
11695              knowing the gp of the output bfd.  */
11696           asymbol *sym = *(*parent)->sym_ptr_ptr;
11697
11698           /* If we've managed to find the gp and have a special
11699              function for the relocation then go ahead, else default
11700              to the generic handling.  */
11701           if (gp_found
11702               && (*parent)->howto->special_function
11703               == _bfd_mips_elf32_gprel16_reloc)
11704             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
11705                                                input_section, relocatable,
11706                                                data, gp);
11707           else
11708             r = bfd_perform_relocation (input_bfd, *parent, data,
11709                                         input_section,
11710                                         relocatable ? abfd : NULL,
11711                                         &error_message);
11712
11713           if (relocatable)
11714             {
11715               asection *os = input_section->output_section;
11716
11717               /* A partial link, so keep the relocs */
11718               os->orelocation[os->reloc_count] = *parent;
11719               os->reloc_count++;
11720             }
11721
11722           if (r != bfd_reloc_ok)
11723             {
11724               switch (r)
11725                 {
11726                 case bfd_reloc_undefined:
11727                   if (!((*link_info->callbacks->undefined_symbol)
11728                         (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11729                          input_bfd, input_section, (*parent)->address, TRUE)))
11730                     goto error_return;
11731                   break;
11732                 case bfd_reloc_dangerous:
11733                   BFD_ASSERT (error_message != NULL);
11734                   if (!((*link_info->callbacks->reloc_dangerous)
11735                         (link_info, error_message, input_bfd, input_section,
11736                          (*parent)->address)))
11737                     goto error_return;
11738                   break;
11739                 case bfd_reloc_overflow:
11740                   if (!((*link_info->callbacks->reloc_overflow)
11741                         (link_info, NULL,
11742                          bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11743                          (*parent)->howto->name, (*parent)->addend,
11744                          input_bfd, input_section, (*parent)->address)))
11745                     goto error_return;
11746                   break;
11747                 case bfd_reloc_outofrange:
11748                 default:
11749                   abort ();
11750                   break;
11751                 }
11752
11753             }
11754         }
11755     }
11756   if (reloc_vector != NULL)
11757     free (reloc_vector);
11758   return data;
11759
11760 error_return:
11761   if (reloc_vector != NULL)
11762     free (reloc_vector);
11763   return NULL;
11764 }
11765 \f
11766 static bfd_boolean
11767 mips_elf_relax_delete_bytes (bfd *abfd,
11768                              asection *sec, bfd_vma addr, int count)
11769 {
11770   Elf_Internal_Shdr *symtab_hdr;
11771   unsigned int sec_shndx;
11772   bfd_byte *contents;
11773   Elf_Internal_Rela *irel, *irelend;
11774   Elf_Internal_Sym *isym;
11775   Elf_Internal_Sym *isymend;
11776   struct elf_link_hash_entry **sym_hashes;
11777   struct elf_link_hash_entry **end_hashes;
11778   struct elf_link_hash_entry **start_hashes;
11779   unsigned int symcount;
11780
11781   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
11782   contents = elf_section_data (sec)->this_hdr.contents;
11783
11784   irel = elf_section_data (sec)->relocs;
11785   irelend = irel + sec->reloc_count;
11786
11787   /* Actually delete the bytes.  */
11788   memmove (contents + addr, contents + addr + count,
11789            (size_t) (sec->size - addr - count));
11790   sec->size -= count;
11791
11792   /* Adjust all the relocs.  */
11793   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
11794     {
11795       /* Get the new reloc address.  */
11796       if (irel->r_offset > addr)
11797         irel->r_offset -= count;
11798     }
11799
11800   BFD_ASSERT (addr % 2 == 0);
11801   BFD_ASSERT (count % 2 == 0);
11802
11803   /* Adjust the local symbols defined in this section.  */
11804   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11805   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
11806   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
11807     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
11808       isym->st_value -= count;
11809
11810   /* Now adjust the global symbols defined in this section.  */
11811   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
11812               - symtab_hdr->sh_info);
11813   sym_hashes = start_hashes = elf_sym_hashes (abfd);
11814   end_hashes = sym_hashes + symcount;
11815
11816   for (; sym_hashes < end_hashes; sym_hashes++)
11817     {
11818       struct elf_link_hash_entry *sym_hash = *sym_hashes;
11819
11820       if ((sym_hash->root.type == bfd_link_hash_defined
11821            || sym_hash->root.type == bfd_link_hash_defweak)
11822           && sym_hash->root.u.def.section == sec)
11823         {
11824           bfd_vma value = sym_hash->root.u.def.value;
11825
11826           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
11827             value &= MINUS_TWO;
11828           if (value > addr)
11829             sym_hash->root.u.def.value -= count;
11830         }
11831     }
11832
11833   return TRUE;
11834 }
11835
11836
11837 /* Opcodes needed for microMIPS relaxation as found in
11838    opcodes/micromips-opc.c.  */
11839
11840 struct opcode_descriptor {
11841   unsigned long match;
11842   unsigned long mask;
11843 };
11844
11845 /* The $ra register aka $31.  */
11846
11847 #define RA 31
11848
11849 /* 32-bit instruction format register fields.  */
11850
11851 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
11852 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
11853
11854 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
11855
11856 #define OP16_VALID_REG(r) \
11857   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
11858
11859
11860 /* 32-bit and 16-bit branches.  */
11861
11862 static const struct opcode_descriptor b_insns_32[] = {
11863   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
11864   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
11865   { 0, 0 }  /* End marker for find_match().  */
11866 };
11867
11868 static const struct opcode_descriptor bc_insn_32 =
11869   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
11870
11871 static const struct opcode_descriptor bz_insn_32 =
11872   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
11873
11874 static const struct opcode_descriptor bzal_insn_32 =
11875   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
11876
11877 static const struct opcode_descriptor beq_insn_32 =
11878   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
11879
11880 static const struct opcode_descriptor b_insn_16 =
11881   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
11882
11883 static const struct opcode_descriptor bz_insn_16 =
11884   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
11885
11886
11887 /* 32-bit and 16-bit branch EQ and NE zero.  */
11888
11889 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
11890    eq and second the ne.  This convention is used when replacing a
11891    32-bit BEQ/BNE with the 16-bit version.  */
11892
11893 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
11894
11895 static const struct opcode_descriptor bz_rs_insns_32[] = {
11896   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
11897   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
11898   { 0, 0 }  /* End marker for find_match().  */
11899 };
11900
11901 static const struct opcode_descriptor bz_rt_insns_32[] = {
11902   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
11903   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
11904   { 0, 0 }  /* End marker for find_match().  */
11905 };
11906
11907 static const struct opcode_descriptor bzc_insns_32[] = {
11908   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
11909   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
11910   { 0, 0 }  /* End marker for find_match().  */
11911 };
11912
11913 static const struct opcode_descriptor bz_insns_16[] = {
11914   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
11915   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
11916   { 0, 0 }  /* End marker for find_match().  */
11917 };
11918
11919 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
11920
11921 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0x17) + 2)
11922 #define BZ16_REG_FIELD(r) \
11923   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 7)
11924
11925
11926 /* 32-bit instructions with a delay slot.  */
11927
11928 static const struct opcode_descriptor jal_insn_32_bd16 =
11929   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
11930
11931 static const struct opcode_descriptor jal_insn_32_bd32 =
11932   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
11933
11934 static const struct opcode_descriptor jal_x_insn_32_bd32 =
11935   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
11936
11937 static const struct opcode_descriptor j_insn_32 =
11938   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
11939
11940 static const struct opcode_descriptor jalr_insn_32 =
11941   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
11942
11943 /* This table can be compacted, because no opcode replacement is made.  */
11944
11945 static const struct opcode_descriptor ds_insns_32_bd16[] = {
11946   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
11947
11948   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
11949   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
11950
11951   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
11952   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
11953   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
11954   { 0, 0 }  /* End marker for find_match().  */
11955 };
11956
11957 /* This table can be compacted, because no opcode replacement is made.  */
11958
11959 static const struct opcode_descriptor ds_insns_32_bd32[] = {
11960   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
11961
11962   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
11963   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
11964   { 0, 0 }  /* End marker for find_match().  */
11965 };
11966
11967
11968 /* 16-bit instructions with a delay slot.  */
11969
11970 static const struct opcode_descriptor jalr_insn_16_bd16 =
11971   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
11972
11973 static const struct opcode_descriptor jalr_insn_16_bd32 =
11974   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
11975
11976 static const struct opcode_descriptor jr_insn_16 =
11977   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
11978
11979 #define JR16_REG(opcode) ((opcode) & 0x1f)
11980
11981 /* This table can be compacted, because no opcode replacement is made.  */
11982
11983 static const struct opcode_descriptor ds_insns_16_bd16[] = {
11984   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
11985
11986   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
11987   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
11988   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
11989   { 0, 0 }  /* End marker for find_match().  */
11990 };
11991
11992
11993 /* LUI instruction.  */
11994
11995 static const struct opcode_descriptor lui_insn =
11996  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
11997
11998
11999 /* ADDIU instruction.  */
12000
12001 static const struct opcode_descriptor addiu_insn =
12002   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
12003
12004 static const struct opcode_descriptor addiupc_insn =
12005   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
12006
12007 #define ADDIUPC_REG_FIELD(r) \
12008   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
12009
12010
12011 /* Relaxable instructions in a JAL delay slot: MOVE.  */
12012
12013 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
12014    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
12015 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
12016 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
12017
12018 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
12019 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
12020
12021 static const struct opcode_descriptor move_insns_32[] = {
12022   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
12023   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
12024   { 0, 0 }  /* End marker for find_match().  */
12025 };
12026
12027 static const struct opcode_descriptor move_insn_16 =
12028   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
12029
12030
12031 /* NOP instructions.  */
12032
12033 static const struct opcode_descriptor nop_insn_32 =
12034   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
12035
12036 static const struct opcode_descriptor nop_insn_16 =
12037   { /* "nop",   "",             */ 0x0c00,     0xffff };
12038
12039
12040 /* Instruction match support.  */
12041
12042 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
12043
12044 static int
12045 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
12046 {
12047   unsigned long indx;
12048
12049   for (indx = 0; insn[indx].mask != 0; indx++)
12050     if (MATCH (opcode, insn[indx]))
12051       return indx;
12052
12053   return -1;
12054 }
12055
12056
12057 /* Branch and delay slot decoding support.  */
12058
12059 /* If PTR points to what *might* be a 16-bit branch or jump, then
12060    return the minimum length of its delay slot, otherwise return 0.
12061    Non-zero results are not definitive as we might be checking against
12062    the second half of another instruction.  */
12063
12064 static int
12065 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
12066 {
12067   unsigned long opcode;
12068   int bdsize;
12069
12070   opcode = bfd_get_16 (abfd, ptr);
12071   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
12072     /* 16-bit branch/jump with a 32-bit delay slot.  */
12073     bdsize = 4;
12074   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
12075            || find_match (opcode, ds_insns_16_bd16) >= 0)
12076     /* 16-bit branch/jump with a 16-bit delay slot.  */
12077     bdsize = 2;
12078   else
12079     /* No delay slot.  */
12080     bdsize = 0;
12081
12082   return bdsize;
12083 }
12084
12085 /* If PTR points to what *might* be a 32-bit branch or jump, then
12086    return the minimum length of its delay slot, otherwise return 0.
12087    Non-zero results are not definitive as we might be checking against
12088    the second half of another instruction.  */
12089
12090 static int
12091 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
12092 {
12093   unsigned long opcode;
12094   int bdsize;
12095
12096   opcode = bfd_get_micromips_32 (abfd, ptr);
12097   if (find_match (opcode, ds_insns_32_bd32) >= 0)
12098     /* 32-bit branch/jump with a 32-bit delay slot.  */
12099     bdsize = 4;
12100   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
12101     /* 32-bit branch/jump with a 16-bit delay slot.  */
12102     bdsize = 2;
12103   else
12104     /* No delay slot.  */
12105     bdsize = 0;
12106
12107   return bdsize;
12108 }
12109
12110 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
12111    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
12112
12113 static bfd_boolean
12114 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12115 {
12116   unsigned long opcode;
12117
12118   opcode = bfd_get_16 (abfd, ptr);
12119   if (MATCH (opcode, b_insn_16)
12120                                                 /* B16  */
12121       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
12122                                                 /* JR16  */
12123       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
12124                                                 /* BEQZ16, BNEZ16  */
12125       || (MATCH (opcode, jalr_insn_16_bd32)
12126                                                 /* JALR16  */
12127           && reg != JR16_REG (opcode) && reg != RA))
12128     return TRUE;
12129
12130   return FALSE;
12131 }
12132
12133 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
12134    then return TRUE, otherwise FALSE.  */
12135
12136 static bfd_boolean
12137 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12138 {
12139   unsigned long opcode;
12140
12141   opcode = bfd_get_micromips_32 (abfd, ptr);
12142   if (MATCH (opcode, j_insn_32)
12143                                                 /* J  */
12144       || MATCH (opcode, bc_insn_32)
12145                                                 /* BC1F, BC1T, BC2F, BC2T  */
12146       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
12147                                                 /* JAL, JALX  */
12148       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
12149                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
12150       || (MATCH (opcode, bzal_insn_32)
12151                                                 /* BGEZAL, BLTZAL  */
12152           && reg != OP32_SREG (opcode) && reg != RA)
12153       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
12154                                                 /* JALR, JALR.HB, BEQ, BNE  */
12155           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
12156     return TRUE;
12157
12158   return FALSE;
12159 }
12160
12161 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
12162    IRELEND) at OFFSET indicate that there must be a compact branch there,
12163    then return TRUE, otherwise FALSE.  */
12164
12165 static bfd_boolean
12166 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
12167                      const Elf_Internal_Rela *internal_relocs,
12168                      const Elf_Internal_Rela *irelend)
12169 {
12170   const Elf_Internal_Rela *irel;
12171   unsigned long opcode;
12172
12173   opcode = bfd_get_micromips_32 (abfd, ptr);
12174   if (find_match (opcode, bzc_insns_32) < 0)
12175     return FALSE;
12176
12177   for (irel = internal_relocs; irel < irelend; irel++)
12178     if (irel->r_offset == offset
12179         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
12180       return TRUE;
12181
12182   return FALSE;
12183 }
12184
12185 /* Bitsize checking.  */
12186 #define IS_BITSIZE(val, N)                                              \
12187   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
12188     - (1ULL << ((N) - 1))) == (val))
12189
12190 \f
12191 bfd_boolean
12192 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
12193                              struct bfd_link_info *link_info,
12194                              bfd_boolean *again)
12195 {
12196   Elf_Internal_Shdr *symtab_hdr;
12197   Elf_Internal_Rela *internal_relocs;
12198   Elf_Internal_Rela *irel, *irelend;
12199   bfd_byte *contents = NULL;
12200   Elf_Internal_Sym *isymbuf = NULL;
12201
12202   /* Assume nothing changes.  */
12203   *again = FALSE;
12204
12205   /* We don't have to do anything for a relocatable link, if
12206      this section does not have relocs, or if this is not a
12207      code section.  */
12208
12209   if (link_info->relocatable
12210       || (sec->flags & SEC_RELOC) == 0
12211       || sec->reloc_count == 0
12212       || (sec->flags & SEC_CODE) == 0)
12213     return TRUE;
12214
12215   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12216
12217   /* Get a copy of the native relocations.  */
12218   internal_relocs = (_bfd_elf_link_read_relocs
12219                      (abfd, sec, NULL, (Elf_Internal_Rela *) NULL,
12220                       link_info->keep_memory));
12221   if (internal_relocs == NULL)
12222     goto error_return;
12223
12224   /* Walk through them looking for relaxing opportunities.  */
12225   irelend = internal_relocs + sec->reloc_count;
12226   for (irel = internal_relocs; irel < irelend; irel++)
12227     {
12228       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
12229       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
12230       bfd_boolean target_is_micromips_code_p;
12231       unsigned long opcode;
12232       bfd_vma symval;
12233       bfd_vma pcrval;
12234       bfd_byte *ptr;
12235       int fndopc;
12236
12237       /* The number of bytes to delete for relaxation and from where
12238          to delete these bytes starting at irel->r_offset.  */
12239       int delcnt = 0;
12240       int deloff = 0;
12241
12242       /* If this isn't something that can be relaxed, then ignore
12243          this reloc.  */
12244       if (r_type != R_MICROMIPS_HI16
12245           && r_type != R_MICROMIPS_PC16_S1
12246           && r_type != R_MICROMIPS_26_S1)
12247         continue;
12248
12249       /* Get the section contents if we haven't done so already.  */
12250       if (contents == NULL)
12251         {
12252           /* Get cached copy if it exists.  */
12253           if (elf_section_data (sec)->this_hdr.contents != NULL)
12254             contents = elf_section_data (sec)->this_hdr.contents;
12255           /* Go get them off disk.  */
12256           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
12257             goto error_return;
12258         }
12259       ptr = contents + irel->r_offset;
12260
12261       /* Read this BFD's local symbols if we haven't done so already.  */
12262       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
12263         {
12264           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
12265           if (isymbuf == NULL)
12266             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12267                                             symtab_hdr->sh_info, 0,
12268                                             NULL, NULL, NULL);
12269           if (isymbuf == NULL)
12270             goto error_return;
12271         }
12272
12273       /* Get the value of the symbol referred to by the reloc.  */
12274       if (r_symndx < symtab_hdr->sh_info)
12275         {
12276           /* A local symbol.  */
12277           Elf_Internal_Sym *isym;
12278           asection *sym_sec;
12279
12280           isym = isymbuf + r_symndx;
12281           if (isym->st_shndx == SHN_UNDEF)
12282             sym_sec = bfd_und_section_ptr;
12283           else if (isym->st_shndx == SHN_ABS)
12284             sym_sec = bfd_abs_section_ptr;
12285           else if (isym->st_shndx == SHN_COMMON)
12286             sym_sec = bfd_com_section_ptr;
12287           else
12288             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
12289           symval = (isym->st_value
12290                     + sym_sec->output_section->vma
12291                     + sym_sec->output_offset);
12292           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
12293         }
12294       else
12295         {
12296           unsigned long indx;
12297           struct elf_link_hash_entry *h;
12298
12299           /* An external symbol.  */
12300           indx = r_symndx - symtab_hdr->sh_info;
12301           h = elf_sym_hashes (abfd)[indx];
12302           BFD_ASSERT (h != NULL);
12303
12304           if (h->root.type != bfd_link_hash_defined
12305               && h->root.type != bfd_link_hash_defweak)
12306             /* This appears to be a reference to an undefined
12307                symbol.  Just ignore it -- it will be caught by the
12308                regular reloc processing.  */
12309             continue;
12310
12311           symval = (h->root.u.def.value
12312                     + h->root.u.def.section->output_section->vma
12313                     + h->root.u.def.section->output_offset);
12314           target_is_micromips_code_p = (!h->needs_plt
12315                                         && ELF_ST_IS_MICROMIPS (h->other));
12316         }
12317
12318
12319       /* For simplicity of coding, we are going to modify the
12320          section contents, the section relocs, and the BFD symbol
12321          table.  We must tell the rest of the code not to free up this
12322          information.  It would be possible to instead create a table
12323          of changes which have to be made, as is done in coff-mips.c;
12324          that would be more work, but would require less memory when
12325          the linker is run.  */
12326
12327       /* Only 32-bit instructions relaxed.  */
12328       if (irel->r_offset + 4 > sec->size)
12329         continue;
12330
12331       opcode = bfd_get_micromips_32 (abfd, ptr);
12332
12333       /* This is the pc-relative distance from the instruction the
12334          relocation is applied to, to the symbol referred.  */
12335       pcrval = (symval
12336                 - (sec->output_section->vma + sec->output_offset)
12337                 - irel->r_offset);
12338
12339       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
12340          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
12341          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
12342
12343            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
12344
12345          where pcrval has first to be adjusted to apply against the LO16
12346          location (we make the adjustment later on, when we have figured
12347          out the offset).  */
12348       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
12349         {
12350           bfd_boolean bzc = FALSE;
12351           unsigned long nextopc;
12352           unsigned long reg;
12353           bfd_vma offset;
12354
12355           /* Give up if the previous reloc was a HI16 against this symbol
12356              too.  */
12357           if (irel > internal_relocs
12358               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
12359               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
12360             continue;
12361
12362           /* Or if the next reloc is not a LO16 against this symbol.  */
12363           if (irel + 1 >= irelend
12364               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
12365               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
12366             continue;
12367
12368           /* Or if the second next reloc is a LO16 against this symbol too.  */
12369           if (irel + 2 >= irelend
12370               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
12371               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
12372             continue;
12373
12374           /* See if the LUI instruction *might* be in a branch delay slot.
12375              We check whether what looks like a 16-bit branch or jump is
12376              actually an immediate argument to a compact branch, and let
12377              it through if so.  */
12378           if (irel->r_offset >= 2
12379               && check_br16_dslot (abfd, ptr - 2)
12380               && !(irel->r_offset >= 4
12381                    && (bzc = check_relocated_bzc (abfd,
12382                                                   ptr - 4, irel->r_offset - 4,
12383                                                   internal_relocs, irelend))))
12384             continue;
12385           if (irel->r_offset >= 4
12386               && !bzc
12387               && check_br32_dslot (abfd, ptr - 4))
12388             continue;
12389
12390           reg = OP32_SREG (opcode);
12391
12392           /* We only relax adjacent instructions or ones separated with
12393              a branch or jump that has a delay slot.  The branch or jump
12394              must not fiddle with the register used to hold the address.
12395              Subtract 4 for the LUI itself.  */
12396           offset = irel[1].r_offset - irel[0].r_offset;
12397           switch (offset - 4)
12398             {
12399             case 0:
12400               break;
12401             case 2:
12402               if (check_br16 (abfd, ptr + 4, reg))
12403                 break;
12404               continue;
12405             case 4:
12406               if (check_br32 (abfd, ptr + 4, reg))
12407                 break;
12408               continue;
12409             default:
12410               continue;
12411             }
12412
12413           nextopc = bfd_get_micromips_32 (abfd, contents + irel[1].r_offset);
12414
12415           /* Give up unless the same register is used with both
12416              relocations.  */
12417           if (OP32_SREG (nextopc) != reg)
12418             continue;
12419
12420           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
12421              and rounding up to take masking of the two LSBs into account.  */
12422           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
12423
12424           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
12425           if (IS_BITSIZE (symval, 16))
12426             {
12427               /* Fix the relocation's type.  */
12428               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
12429
12430               /* Instructions using R_MICROMIPS_LO16 have the base or
12431                  source register in bits 20:16.  This register becomes $0
12432                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
12433               nextopc &= ~0x001f0000;
12434               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
12435                           contents + irel[1].r_offset);
12436             }
12437
12438           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
12439              We add 4 to take LUI deletion into account while checking
12440              the PC-relative distance.  */
12441           else if (symval % 4 == 0
12442                    && IS_BITSIZE (pcrval + 4, 25)
12443                    && MATCH (nextopc, addiu_insn)
12444                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
12445                    && OP16_VALID_REG (OP32_TREG (nextopc)))
12446             {
12447               /* Fix the relocation's type.  */
12448               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
12449
12450               /* Replace ADDIU with the ADDIUPC version.  */
12451               nextopc = (addiupc_insn.match
12452                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
12453
12454               bfd_put_micromips_32 (abfd, nextopc,
12455                                     contents + irel[1].r_offset);
12456             }
12457
12458           /* Can't do anything, give up, sigh...  */
12459           else
12460             continue;
12461
12462           /* Fix the relocation's type.  */
12463           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
12464
12465           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
12466           delcnt = 4;
12467           deloff = 0;
12468         }
12469
12470       /* Compact branch relaxation -- due to the multitude of macros
12471          employed by the compiler/assembler, compact branches are not
12472          always generated.  Obviously, this can/will be fixed elsewhere,
12473          but there is no drawback in double checking it here.  */
12474       else if (r_type == R_MICROMIPS_PC16_S1
12475                && irel->r_offset + 5 < sec->size
12476                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12477                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
12478                && MATCH (bfd_get_16 (abfd, ptr + 4), nop_insn_16))
12479         {
12480           unsigned long reg;
12481
12482           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12483
12484           /* Replace BEQZ/BNEZ with the compact version.  */
12485           opcode = (bzc_insns_32[fndopc].match
12486                     | BZC32_REG_FIELD (reg)
12487                     | (opcode & 0xffff));               /* Addend value.  */
12488
12489           bfd_put_micromips_32 (abfd, opcode, ptr);
12490
12491           /* Delete the 16-bit delay slot NOP: two bytes from
12492              irel->offset + 4.  */
12493           delcnt = 2;
12494           deloff = 4;
12495         }
12496
12497       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
12498          to check the distance from the next instruction, so subtract 2.  */
12499       else if (r_type == R_MICROMIPS_PC16_S1
12500                && IS_BITSIZE (pcrval - 2, 11)
12501                && find_match (opcode, b_insns_32) >= 0)
12502         {
12503           /* Fix the relocation's type.  */
12504           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
12505
12506           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12507           bfd_put_16 (abfd,
12508                       (b_insn_16.match
12509                        | (opcode & 0x3ff)),             /* Addend value.  */
12510                       ptr);
12511
12512           /* Delete 2 bytes from irel->r_offset + 2.  */
12513           delcnt = 2;
12514           deloff = 2;
12515         }
12516
12517       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
12518          to check the distance from the next instruction, so subtract 2.  */
12519       else if (r_type == R_MICROMIPS_PC16_S1
12520                && IS_BITSIZE (pcrval - 2, 8)
12521                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12522                     && OP16_VALID_REG (OP32_SREG (opcode)))
12523                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
12524                        && OP16_VALID_REG (OP32_TREG (opcode)))))
12525         {
12526           unsigned long reg;
12527
12528           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12529
12530           /* Fix the relocation's type.  */
12531           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
12532
12533           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12534           bfd_put_16 (abfd,
12535                       (bz_insns_16[fndopc].match
12536                        | BZ16_REG_FIELD (reg)
12537                        | (opcode & 0x7f)),              /* Addend value.  */
12538                       ptr);
12539
12540           /* Delete 2 bytes from irel->r_offset + 2.  */
12541           delcnt = 2;
12542           deloff = 2;
12543         }
12544
12545       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
12546       else if (r_type == R_MICROMIPS_26_S1
12547                && target_is_micromips_code_p
12548                && irel->r_offset + 7 < sec->size
12549                && MATCH (opcode, jal_insn_32_bd32))
12550         {
12551           unsigned long n32opc;
12552           bfd_boolean relaxed = FALSE;
12553
12554           n32opc = bfd_get_micromips_32 (abfd, ptr + 4);
12555
12556           if (MATCH (n32opc, nop_insn_32))
12557             {
12558               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
12559               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
12560
12561               relaxed = TRUE;
12562             }
12563           else if (find_match (n32opc, move_insns_32) >= 0)
12564             {
12565               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
12566               bfd_put_16 (abfd,
12567                           (move_insn_16.match
12568                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
12569                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
12570                           ptr + 4);
12571
12572               relaxed = TRUE;
12573             }
12574           /* Other 32-bit instructions relaxable to 16-bit
12575              instructions will be handled here later.  */
12576
12577           if (relaxed)
12578             {
12579               /* JAL with 32-bit delay slot that is changed to a JALS
12580                  with 16-bit delay slot.  */
12581               bfd_put_micromips_32 (abfd, jal_insn_32_bd16.match, ptr);
12582
12583               /* Delete 2 bytes from irel->r_offset + 6.  */
12584               delcnt = 2;
12585               deloff = 6;
12586             }
12587         }
12588
12589       if (delcnt != 0)
12590         {
12591           /* Note that we've changed the relocs, section contents, etc.  */
12592           elf_section_data (sec)->relocs = internal_relocs;
12593           elf_section_data (sec)->this_hdr.contents = contents;
12594           symtab_hdr->contents = (unsigned char *) isymbuf;
12595
12596           /* Delete bytes depending on the delcnt and deloff.  */
12597           if (!mips_elf_relax_delete_bytes (abfd, sec,
12598                                             irel->r_offset + deloff, delcnt))
12599             goto error_return;
12600
12601           /* That will change things, so we should relax again.
12602              Note that this is not required, and it may be slow.  */
12603           *again = TRUE;
12604         }
12605     }
12606
12607   if (isymbuf != NULL
12608       && symtab_hdr->contents != (unsigned char *) isymbuf)
12609     {
12610       if (! link_info->keep_memory)
12611         free (isymbuf);
12612       else
12613         {
12614           /* Cache the symbols for elf_link_input_bfd.  */
12615           symtab_hdr->contents = (unsigned char *) isymbuf;
12616         }
12617     }
12618
12619   if (contents != NULL
12620       && elf_section_data (sec)->this_hdr.contents != contents)
12621     {
12622       if (! link_info->keep_memory)
12623         free (contents);
12624       else
12625         {
12626           /* Cache the section contents for elf_link_input_bfd.  */
12627           elf_section_data (sec)->this_hdr.contents = contents;
12628         }
12629     }
12630
12631   if (internal_relocs != NULL
12632       && elf_section_data (sec)->relocs != internal_relocs)
12633     free (internal_relocs);
12634
12635   return TRUE;
12636
12637  error_return:
12638   if (isymbuf != NULL
12639       && symtab_hdr->contents != (unsigned char *) isymbuf)
12640     free (isymbuf);
12641   if (contents != NULL
12642       && elf_section_data (sec)->this_hdr.contents != contents)
12643     free (contents);
12644   if (internal_relocs != NULL
12645       && elf_section_data (sec)->relocs != internal_relocs)
12646     free (internal_relocs);
12647
12648   return FALSE;
12649 }
12650 \f
12651 /* Create a MIPS ELF linker hash table.  */
12652
12653 struct bfd_link_hash_table *
12654 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
12655 {
12656   struct mips_elf_link_hash_table *ret;
12657   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
12658
12659   ret = bfd_zmalloc (amt);
12660   if (ret == NULL)
12661     return NULL;
12662
12663   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
12664                                       mips_elf_link_hash_newfunc,
12665                                       sizeof (struct mips_elf_link_hash_entry),
12666                                       MIPS_ELF_DATA))
12667     {
12668       free (ret);
12669       return NULL;
12670     }
12671
12672   return &ret->root.root;
12673 }
12674
12675 /* Likewise, but indicate that the target is VxWorks.  */
12676
12677 struct bfd_link_hash_table *
12678 _bfd_mips_vxworks_link_hash_table_create (bfd *abfd)
12679 {
12680   struct bfd_link_hash_table *ret;
12681
12682   ret = _bfd_mips_elf_link_hash_table_create (abfd);
12683   if (ret)
12684     {
12685       struct mips_elf_link_hash_table *htab;
12686
12687       htab = (struct mips_elf_link_hash_table *) ret;
12688       htab->use_plts_and_copy_relocs = TRUE;
12689       htab->is_vxworks = TRUE;
12690     }
12691   return ret;
12692 }
12693
12694 /* A function that the linker calls if we are allowed to use PLTs
12695    and copy relocs.  */
12696
12697 void
12698 _bfd_mips_elf_use_plts_and_copy_relocs (struct bfd_link_info *info)
12699 {
12700   mips_elf_hash_table (info)->use_plts_and_copy_relocs = TRUE;
12701 }
12702 \f
12703 /* We need to use a special link routine to handle the .reginfo and
12704    the .mdebug sections.  We need to merge all instances of these
12705    sections together, not write them all out sequentially.  */
12706
12707 bfd_boolean
12708 _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info)
12709 {
12710   asection *o;
12711   struct bfd_link_order *p;
12712   asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec;
12713   asection *rtproc_sec;
12714   Elf32_RegInfo reginfo;
12715   struct ecoff_debug_info debug;
12716   struct mips_htab_traverse_info hti;
12717   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12718   const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap;
12719   HDRR *symhdr = &debug.symbolic_header;
12720   void *mdebug_handle = NULL;
12721   asection *s;
12722   EXTR esym;
12723   unsigned int i;
12724   bfd_size_type amt;
12725   struct mips_elf_link_hash_table *htab;
12726
12727   static const char * const secname[] =
12728   {
12729     ".text", ".init", ".fini", ".data",
12730     ".rodata", ".sdata", ".sbss", ".bss"
12731   };
12732   static const int sc[] =
12733   {
12734     scText, scInit, scFini, scData,
12735     scRData, scSData, scSBss, scBss
12736   };
12737
12738   /* Sort the dynamic symbols so that those with GOT entries come after
12739      those without.  */
12740   htab = mips_elf_hash_table (info);
12741   BFD_ASSERT (htab != NULL);
12742
12743   if (!mips_elf_sort_hash_table (abfd, info))
12744     return FALSE;
12745
12746   /* Create any scheduled LA25 stubs.  */
12747   hti.info = info;
12748   hti.output_bfd = abfd;
12749   hti.error = FALSE;
12750   htab_traverse (htab->la25_stubs, mips_elf_create_la25_stub, &hti);
12751   if (hti.error)
12752     return FALSE;
12753
12754   /* Get a value for the GP register.  */
12755   if (elf_gp (abfd) == 0)
12756     {
12757       struct bfd_link_hash_entry *h;
12758
12759       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
12760       if (h != NULL && h->type == bfd_link_hash_defined)
12761         elf_gp (abfd) = (h->u.def.value
12762                          + h->u.def.section->output_section->vma
12763                          + h->u.def.section->output_offset);
12764       else if (htab->is_vxworks
12765                && (h = bfd_link_hash_lookup (info->hash,
12766                                              "_GLOBAL_OFFSET_TABLE_",
12767                                              FALSE, FALSE, TRUE))
12768                && h->type == bfd_link_hash_defined)
12769         elf_gp (abfd) = (h->u.def.section->output_section->vma
12770                          + h->u.def.section->output_offset
12771                          + h->u.def.value);
12772       else if (info->relocatable)
12773         {
12774           bfd_vma lo = MINUS_ONE;
12775
12776           /* Find the GP-relative section with the lowest offset.  */
12777           for (o = abfd->sections; o != NULL; o = o->next)
12778             if (o->vma < lo
12779                 && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL))
12780               lo = o->vma;
12781
12782           /* And calculate GP relative to that.  */
12783           elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (info);
12784         }
12785       else
12786         {
12787           /* If the relocate_section function needs to do a reloc
12788              involving the GP value, it should make a reloc_dangerous
12789              callback to warn that GP is not defined.  */
12790         }
12791     }
12792
12793   /* Go through the sections and collect the .reginfo and .mdebug
12794      information.  */
12795   reginfo_sec = NULL;
12796   mdebug_sec = NULL;
12797   gptab_data_sec = NULL;
12798   gptab_bss_sec = NULL;
12799   for (o = abfd->sections; o != NULL; o = o->next)
12800     {
12801       if (strcmp (o->name, ".reginfo") == 0)
12802         {
12803           memset (&reginfo, 0, sizeof reginfo);
12804
12805           /* We have found the .reginfo section in the output file.
12806              Look through all the link_orders comprising it and merge
12807              the information together.  */
12808           for (p = o->map_head.link_order; p != NULL; p = p->next)
12809             {
12810               asection *input_section;
12811               bfd *input_bfd;
12812               Elf32_External_RegInfo ext;
12813               Elf32_RegInfo sub;
12814
12815               if (p->type != bfd_indirect_link_order)
12816                 {
12817                   if (p->type == bfd_data_link_order)
12818                     continue;
12819                   abort ();
12820                 }
12821
12822               input_section = p->u.indirect.section;
12823               input_bfd = input_section->owner;
12824
12825               if (! bfd_get_section_contents (input_bfd, input_section,
12826                                               &ext, 0, sizeof ext))
12827                 return FALSE;
12828
12829               bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub);
12830
12831               reginfo.ri_gprmask |= sub.ri_gprmask;
12832               reginfo.ri_cprmask[0] |= sub.ri_cprmask[0];
12833               reginfo.ri_cprmask[1] |= sub.ri_cprmask[1];
12834               reginfo.ri_cprmask[2] |= sub.ri_cprmask[2];
12835               reginfo.ri_cprmask[3] |= sub.ri_cprmask[3];
12836
12837               /* ri_gp_value is set by the function
12838                  mips_elf32_section_processing when the section is
12839                  finally written out.  */
12840
12841               /* Hack: reset the SEC_HAS_CONTENTS flag so that
12842                  elf_link_input_bfd ignores this section.  */
12843               input_section->flags &= ~SEC_HAS_CONTENTS;
12844             }
12845
12846           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
12847           BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo));
12848
12849           /* Skip this section later on (I don't think this currently
12850              matters, but someday it might).  */
12851           o->map_head.link_order = NULL;
12852
12853           reginfo_sec = o;
12854         }
12855
12856       if (strcmp (o->name, ".mdebug") == 0)
12857         {
12858           struct extsym_info einfo;
12859           bfd_vma last;
12860
12861           /* We have found the .mdebug section in the output file.
12862              Look through all the link_orders comprising it and merge
12863              the information together.  */
12864           symhdr->magic = swap->sym_magic;
12865           /* FIXME: What should the version stamp be?  */
12866           symhdr->vstamp = 0;
12867           symhdr->ilineMax = 0;
12868           symhdr->cbLine = 0;
12869           symhdr->idnMax = 0;
12870           symhdr->ipdMax = 0;
12871           symhdr->isymMax = 0;
12872           symhdr->ioptMax = 0;
12873           symhdr->iauxMax = 0;
12874           symhdr->issMax = 0;
12875           symhdr->issExtMax = 0;
12876           symhdr->ifdMax = 0;
12877           symhdr->crfd = 0;
12878           symhdr->iextMax = 0;
12879
12880           /* We accumulate the debugging information itself in the
12881              debug_info structure.  */
12882           debug.line = NULL;
12883           debug.external_dnr = NULL;
12884           debug.external_pdr = NULL;
12885           debug.external_sym = NULL;
12886           debug.external_opt = NULL;
12887           debug.external_aux = NULL;
12888           debug.ss = NULL;
12889           debug.ssext = debug.ssext_end = NULL;
12890           debug.external_fdr = NULL;
12891           debug.external_rfd = NULL;
12892           debug.external_ext = debug.external_ext_end = NULL;
12893
12894           mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info);
12895           if (mdebug_handle == NULL)
12896             return FALSE;
12897
12898           esym.jmptbl = 0;
12899           esym.cobol_main = 0;
12900           esym.weakext = 0;
12901           esym.reserved = 0;
12902           esym.ifd = ifdNil;
12903           esym.asym.iss = issNil;
12904           esym.asym.st = stLocal;
12905           esym.asym.reserved = 0;
12906           esym.asym.index = indexNil;
12907           last = 0;
12908           for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++)
12909             {
12910               esym.asym.sc = sc[i];
12911               s = bfd_get_section_by_name (abfd, secname[i]);
12912               if (s != NULL)
12913                 {
12914                   esym.asym.value = s->vma;
12915                   last = s->vma + s->size;
12916                 }
12917               else
12918                 esym.asym.value = last;
12919               if (!bfd_ecoff_debug_one_external (abfd, &debug, swap,
12920                                                  secname[i], &esym))
12921                 return FALSE;
12922             }
12923
12924           for (p = o->map_head.link_order; p != NULL; p = p->next)
12925             {
12926               asection *input_section;
12927               bfd *input_bfd;
12928               const struct ecoff_debug_swap *input_swap;
12929               struct ecoff_debug_info input_debug;
12930               char *eraw_src;
12931               char *eraw_end;
12932
12933               if (p->type != bfd_indirect_link_order)
12934                 {
12935                   if (p->type == bfd_data_link_order)
12936                     continue;
12937                   abort ();
12938                 }
12939
12940               input_section = p->u.indirect.section;
12941               input_bfd = input_section->owner;
12942
12943               if (!is_mips_elf (input_bfd))
12944                 {
12945                   /* I don't know what a non MIPS ELF bfd would be
12946                      doing with a .mdebug section, but I don't really
12947                      want to deal with it.  */
12948                   continue;
12949                 }
12950
12951               input_swap = (get_elf_backend_data (input_bfd)
12952                             ->elf_backend_ecoff_debug_swap);
12953
12954               BFD_ASSERT (p->size == input_section->size);
12955
12956               /* The ECOFF linking code expects that we have already
12957                  read in the debugging information and set up an
12958                  ecoff_debug_info structure, so we do that now.  */
12959               if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section,
12960                                                    &input_debug))
12961                 return FALSE;
12962
12963               if (! (bfd_ecoff_debug_accumulate
12964                      (mdebug_handle, abfd, &debug, swap, input_bfd,
12965                       &input_debug, input_swap, info)))
12966                 return FALSE;
12967
12968               /* Loop through the external symbols.  For each one with
12969                  interesting information, try to find the symbol in
12970                  the linker global hash table and save the information
12971                  for the output external symbols.  */
12972               eraw_src = input_debug.external_ext;
12973               eraw_end = (eraw_src
12974                           + (input_debug.symbolic_header.iextMax
12975                              * input_swap->external_ext_size));
12976               for (;
12977                    eraw_src < eraw_end;
12978                    eraw_src += input_swap->external_ext_size)
12979                 {
12980                   EXTR ext;
12981                   const char *name;
12982                   struct mips_elf_link_hash_entry *h;
12983
12984                   (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext);
12985                   if (ext.asym.sc == scNil
12986                       || ext.asym.sc == scUndefined
12987                       || ext.asym.sc == scSUndefined)
12988                     continue;
12989
12990                   name = input_debug.ssext + ext.asym.iss;
12991                   h = mips_elf_link_hash_lookup (mips_elf_hash_table (info),
12992                                                  name, FALSE, FALSE, TRUE);
12993                   if (h == NULL || h->esym.ifd != -2)
12994                     continue;
12995
12996                   if (ext.ifd != -1)
12997                     {
12998                       BFD_ASSERT (ext.ifd
12999                                   < input_debug.symbolic_header.ifdMax);
13000                       ext.ifd = input_debug.ifdmap[ext.ifd];
13001                     }
13002
13003                   h->esym = ext;
13004                 }
13005
13006               /* Free up the information we just read.  */
13007               free (input_debug.line);
13008               free (input_debug.external_dnr);
13009               free (input_debug.external_pdr);
13010               free (input_debug.external_sym);
13011               free (input_debug.external_opt);
13012               free (input_debug.external_aux);
13013               free (input_debug.ss);
13014               free (input_debug.ssext);
13015               free (input_debug.external_fdr);
13016               free (input_debug.external_rfd);
13017               free (input_debug.external_ext);
13018
13019               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13020                  elf_link_input_bfd ignores this section.  */
13021               input_section->flags &= ~SEC_HAS_CONTENTS;
13022             }
13023
13024           if (SGI_COMPAT (abfd) && info->shared)
13025             {
13026               /* Create .rtproc section.  */
13027               rtproc_sec = bfd_get_linker_section (abfd, ".rtproc");
13028               if (rtproc_sec == NULL)
13029                 {
13030                   flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
13031                                     | SEC_LINKER_CREATED | SEC_READONLY);
13032
13033                   rtproc_sec = bfd_make_section_anyway_with_flags (abfd,
13034                                                                    ".rtproc",
13035                                                                    flags);
13036                   if (rtproc_sec == NULL
13037                       || ! bfd_set_section_alignment (abfd, rtproc_sec, 4))
13038                     return FALSE;
13039                 }
13040
13041               if (! mips_elf_create_procedure_table (mdebug_handle, abfd,
13042                                                      info, rtproc_sec,
13043                                                      &debug))
13044                 return FALSE;
13045             }
13046
13047           /* Build the external symbol information.  */
13048           einfo.abfd = abfd;
13049           einfo.info = info;
13050           einfo.debug = &debug;
13051           einfo.swap = swap;
13052           einfo.failed = FALSE;
13053           mips_elf_link_hash_traverse (mips_elf_hash_table (info),
13054                                        mips_elf_output_extsym, &einfo);
13055           if (einfo.failed)
13056             return FALSE;
13057
13058           /* Set the size of the .mdebug section.  */
13059           o->size = bfd_ecoff_debug_size (abfd, &debug, swap);
13060
13061           /* Skip this section later on (I don't think this currently
13062              matters, but someday it might).  */
13063           o->map_head.link_order = NULL;
13064
13065           mdebug_sec = o;
13066         }
13067
13068       if (CONST_STRNEQ (o->name, ".gptab."))
13069         {
13070           const char *subname;
13071           unsigned int c;
13072           Elf32_gptab *tab;
13073           Elf32_External_gptab *ext_tab;
13074           unsigned int j;
13075
13076           /* The .gptab.sdata and .gptab.sbss sections hold
13077              information describing how the small data area would
13078              change depending upon the -G switch.  These sections
13079              not used in executables files.  */
13080           if (! info->relocatable)
13081             {
13082               for (p = o->map_head.link_order; p != NULL; p = p->next)
13083                 {
13084                   asection *input_section;
13085
13086                   if (p->type != bfd_indirect_link_order)
13087                     {
13088                       if (p->type == bfd_data_link_order)
13089                         continue;
13090                       abort ();
13091                     }
13092
13093                   input_section = p->u.indirect.section;
13094
13095                   /* Hack: reset the SEC_HAS_CONTENTS flag so that
13096                      elf_link_input_bfd ignores this section.  */
13097                   input_section->flags &= ~SEC_HAS_CONTENTS;
13098                 }
13099
13100               /* Skip this section later on (I don't think this
13101                  currently matters, but someday it might).  */
13102               o->map_head.link_order = NULL;
13103
13104               /* Really remove the section.  */
13105               bfd_section_list_remove (abfd, o);
13106               --abfd->section_count;
13107
13108               continue;
13109             }
13110
13111           /* There is one gptab for initialized data, and one for
13112              uninitialized data.  */
13113           if (strcmp (o->name, ".gptab.sdata") == 0)
13114             gptab_data_sec = o;
13115           else if (strcmp (o->name, ".gptab.sbss") == 0)
13116             gptab_bss_sec = o;
13117           else
13118             {
13119               (*_bfd_error_handler)
13120                 (_("%s: illegal section name `%s'"),
13121                  bfd_get_filename (abfd), o->name);
13122               bfd_set_error (bfd_error_nonrepresentable_section);
13123               return FALSE;
13124             }
13125
13126           /* The linker script always combines .gptab.data and
13127              .gptab.sdata into .gptab.sdata, and likewise for
13128              .gptab.bss and .gptab.sbss.  It is possible that there is
13129              no .sdata or .sbss section in the output file, in which
13130              case we must change the name of the output section.  */
13131           subname = o->name + sizeof ".gptab" - 1;
13132           if (bfd_get_section_by_name (abfd, subname) == NULL)
13133             {
13134               if (o == gptab_data_sec)
13135                 o->name = ".gptab.data";
13136               else
13137                 o->name = ".gptab.bss";
13138               subname = o->name + sizeof ".gptab" - 1;
13139               BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL);
13140             }
13141
13142           /* Set up the first entry.  */
13143           c = 1;
13144           amt = c * sizeof (Elf32_gptab);
13145           tab = bfd_malloc (amt);
13146           if (tab == NULL)
13147             return FALSE;
13148           tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd);
13149           tab[0].gt_header.gt_unused = 0;
13150
13151           /* Combine the input sections.  */
13152           for (p = o->map_head.link_order; p != NULL; p = p->next)
13153             {
13154               asection *input_section;
13155               bfd *input_bfd;
13156               bfd_size_type size;
13157               unsigned long last;
13158               bfd_size_type gpentry;
13159
13160               if (p->type != bfd_indirect_link_order)
13161                 {
13162                   if (p->type == bfd_data_link_order)
13163                     continue;
13164                   abort ();
13165                 }
13166
13167               input_section = p->u.indirect.section;
13168               input_bfd = input_section->owner;
13169
13170               /* Combine the gptab entries for this input section one
13171                  by one.  We know that the input gptab entries are
13172                  sorted by ascending -G value.  */
13173               size = input_section->size;
13174               last = 0;
13175               for (gpentry = sizeof (Elf32_External_gptab);
13176                    gpentry < size;
13177                    gpentry += sizeof (Elf32_External_gptab))
13178                 {
13179                   Elf32_External_gptab ext_gptab;
13180                   Elf32_gptab int_gptab;
13181                   unsigned long val;
13182                   unsigned long add;
13183                   bfd_boolean exact;
13184                   unsigned int look;
13185
13186                   if (! (bfd_get_section_contents
13187                          (input_bfd, input_section, &ext_gptab, gpentry,
13188                           sizeof (Elf32_External_gptab))))
13189                     {
13190                       free (tab);
13191                       return FALSE;
13192                     }
13193
13194                   bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab,
13195                                                 &int_gptab);
13196                   val = int_gptab.gt_entry.gt_g_value;
13197                   add = int_gptab.gt_entry.gt_bytes - last;
13198
13199                   exact = FALSE;
13200                   for (look = 1; look < c; look++)
13201                     {
13202                       if (tab[look].gt_entry.gt_g_value >= val)
13203                         tab[look].gt_entry.gt_bytes += add;
13204
13205                       if (tab[look].gt_entry.gt_g_value == val)
13206                         exact = TRUE;
13207                     }
13208
13209                   if (! exact)
13210                     {
13211                       Elf32_gptab *new_tab;
13212                       unsigned int max;
13213
13214                       /* We need a new table entry.  */
13215                       amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab);
13216                       new_tab = bfd_realloc (tab, amt);
13217                       if (new_tab == NULL)
13218                         {
13219                           free (tab);
13220                           return FALSE;
13221                         }
13222                       tab = new_tab;
13223                       tab[c].gt_entry.gt_g_value = val;
13224                       tab[c].gt_entry.gt_bytes = add;
13225
13226                       /* Merge in the size for the next smallest -G
13227                          value, since that will be implied by this new
13228                          value.  */
13229                       max = 0;
13230                       for (look = 1; look < c; look++)
13231                         {
13232                           if (tab[look].gt_entry.gt_g_value < val
13233                               && (max == 0
13234                                   || (tab[look].gt_entry.gt_g_value
13235                                       > tab[max].gt_entry.gt_g_value)))
13236                             max = look;
13237                         }
13238                       if (max != 0)
13239                         tab[c].gt_entry.gt_bytes +=
13240                           tab[max].gt_entry.gt_bytes;
13241
13242                       ++c;
13243                     }
13244
13245                   last = int_gptab.gt_entry.gt_bytes;
13246                 }
13247
13248               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13249                  elf_link_input_bfd ignores this section.  */
13250               input_section->flags &= ~SEC_HAS_CONTENTS;
13251             }
13252
13253           /* The table must be sorted by -G value.  */
13254           if (c > 2)
13255             qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare);
13256
13257           /* Swap out the table.  */
13258           amt = (bfd_size_type) c * sizeof (Elf32_External_gptab);
13259           ext_tab = bfd_alloc (abfd, amt);
13260           if (ext_tab == NULL)
13261             {
13262               free (tab);
13263               return FALSE;
13264             }
13265
13266           for (j = 0; j < c; j++)
13267             bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j);
13268           free (tab);
13269
13270           o->size = c * sizeof (Elf32_External_gptab);
13271           o->contents = (bfd_byte *) ext_tab;
13272
13273           /* Skip this section later on (I don't think this currently
13274              matters, but someday it might).  */
13275           o->map_head.link_order = NULL;
13276         }
13277     }
13278
13279   /* Invoke the regular ELF backend linker to do all the work.  */
13280   if (!bfd_elf_final_link (abfd, info))
13281     return FALSE;
13282
13283   /* Now write out the computed sections.  */
13284
13285   if (reginfo_sec != NULL)
13286     {
13287       Elf32_External_RegInfo ext;
13288
13289       bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext);
13290       if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext))
13291         return FALSE;
13292     }
13293
13294   if (mdebug_sec != NULL)
13295     {
13296       BFD_ASSERT (abfd->output_has_begun);
13297       if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug,
13298                                                swap, info,
13299                                                mdebug_sec->filepos))
13300         return FALSE;
13301
13302       bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info);
13303     }
13304
13305   if (gptab_data_sec != NULL)
13306     {
13307       if (! bfd_set_section_contents (abfd, gptab_data_sec,
13308                                       gptab_data_sec->contents,
13309                                       0, gptab_data_sec->size))
13310         return FALSE;
13311     }
13312
13313   if (gptab_bss_sec != NULL)
13314     {
13315       if (! bfd_set_section_contents (abfd, gptab_bss_sec,
13316                                       gptab_bss_sec->contents,
13317                                       0, gptab_bss_sec->size))
13318         return FALSE;
13319     }
13320
13321   if (SGI_COMPAT (abfd))
13322     {
13323       rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
13324       if (rtproc_sec != NULL)
13325         {
13326           if (! bfd_set_section_contents (abfd, rtproc_sec,
13327                                           rtproc_sec->contents,
13328                                           0, rtproc_sec->size))
13329             return FALSE;
13330         }
13331     }
13332
13333   return TRUE;
13334 }
13335 \f
13336 /* Structure for saying that BFD machine EXTENSION extends BASE.  */
13337
13338 struct mips_mach_extension {
13339   unsigned long extension, base;
13340 };
13341
13342
13343 /* An array describing how BFD machines relate to one another.  The entries
13344    are ordered topologically with MIPS I extensions listed last.  */
13345
13346 static const struct mips_mach_extension mips_mach_extensions[] = {
13347   /* MIPS64r2 extensions.  */
13348   { bfd_mach_mips_octeon2, bfd_mach_mips_octeonp },
13349   { bfd_mach_mips_octeonp, bfd_mach_mips_octeon },
13350   { bfd_mach_mips_octeon, bfd_mach_mipsisa64r2 },
13351
13352   /* MIPS64 extensions.  */
13353   { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 },
13354   { bfd_mach_mips_sb1, bfd_mach_mipsisa64 },
13355   { bfd_mach_mips_xlr, bfd_mach_mipsisa64 },
13356   { bfd_mach_mips_loongson_3a, bfd_mach_mipsisa64 },
13357
13358   /* MIPS V extensions.  */
13359   { bfd_mach_mipsisa64, bfd_mach_mips5 },
13360
13361   /* R10000 extensions.  */
13362   { bfd_mach_mips12000, bfd_mach_mips10000 },
13363   { bfd_mach_mips14000, bfd_mach_mips10000 },
13364   { bfd_mach_mips16000, bfd_mach_mips10000 },
13365
13366   /* R5000 extensions.  Note: the vr5500 ISA is an extension of the core
13367      vr5400 ISA, but doesn't include the multimedia stuff.  It seems
13368      better to allow vr5400 and vr5500 code to be merged anyway, since
13369      many libraries will just use the core ISA.  Perhaps we could add
13370      some sort of ASE flag if this ever proves a problem.  */
13371   { bfd_mach_mips5500, bfd_mach_mips5400 },
13372   { bfd_mach_mips5400, bfd_mach_mips5000 },
13373
13374   /* MIPS IV extensions.  */
13375   { bfd_mach_mips5, bfd_mach_mips8000 },
13376   { bfd_mach_mips10000, bfd_mach_mips8000 },
13377   { bfd_mach_mips5000, bfd_mach_mips8000 },
13378   { bfd_mach_mips7000, bfd_mach_mips8000 },
13379   { bfd_mach_mips9000, bfd_mach_mips8000 },
13380
13381   /* VR4100 extensions.  */
13382   { bfd_mach_mips4120, bfd_mach_mips4100 },
13383   { bfd_mach_mips4111, bfd_mach_mips4100 },
13384
13385   /* MIPS III extensions.  */
13386   { bfd_mach_mips_loongson_2e, bfd_mach_mips4000 },
13387   { bfd_mach_mips_loongson_2f, bfd_mach_mips4000 },
13388   { bfd_mach_mips8000, bfd_mach_mips4000 },
13389   { bfd_mach_mips4650, bfd_mach_mips4000 },
13390   { bfd_mach_mips4600, bfd_mach_mips4000 },
13391   { bfd_mach_mips4400, bfd_mach_mips4000 },
13392   { bfd_mach_mips4300, bfd_mach_mips4000 },
13393   { bfd_mach_mips4100, bfd_mach_mips4000 },
13394   { bfd_mach_mips4010, bfd_mach_mips4000 },
13395   { bfd_mach_mips5900, bfd_mach_mips4000 },
13396
13397   /* MIPS32 extensions.  */
13398   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
13399
13400   /* MIPS II extensions.  */
13401   { bfd_mach_mips4000, bfd_mach_mips6000 },
13402   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
13403
13404   /* MIPS I extensions.  */
13405   { bfd_mach_mips6000, bfd_mach_mips3000 },
13406   { bfd_mach_mips3900, bfd_mach_mips3000 }
13407 };
13408
13409
13410 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
13411
13412 static bfd_boolean
13413 mips_mach_extends_p (unsigned long base, unsigned long extension)
13414 {
13415   size_t i;
13416
13417   if (extension == base)
13418     return TRUE;
13419
13420   if (base == bfd_mach_mipsisa32
13421       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
13422     return TRUE;
13423
13424   if (base == bfd_mach_mipsisa32r2
13425       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
13426     return TRUE;
13427
13428   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
13429     if (extension == mips_mach_extensions[i].extension)
13430       {
13431         extension = mips_mach_extensions[i].base;
13432         if (extension == base)
13433           return TRUE;
13434       }
13435
13436   return FALSE;
13437 }
13438
13439
13440 /* Return true if the given ELF header flags describe a 32-bit binary.  */
13441
13442 static bfd_boolean
13443 mips_32bit_flags_p (flagword flags)
13444 {
13445   return ((flags & EF_MIPS_32BITMODE) != 0
13446           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
13447           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
13448           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
13449           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
13450           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
13451           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2);
13452 }
13453
13454
13455 /* Merge object attributes from IBFD into OBFD.  Raise an error if
13456    there are conflicting attributes.  */
13457 static bfd_boolean
13458 mips_elf_merge_obj_attributes (bfd *ibfd, bfd *obfd)
13459 {
13460   obj_attribute *in_attr;
13461   obj_attribute *out_attr;
13462   bfd *abi_fp_bfd;
13463
13464   abi_fp_bfd = mips_elf_tdata (obfd)->abi_fp_bfd;
13465   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
13466   if (!abi_fp_bfd && in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13467     mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
13468
13469   if (!elf_known_obj_attributes_proc (obfd)[0].i)
13470     {
13471       /* This is the first object.  Copy the attributes.  */
13472       _bfd_elf_copy_obj_attributes (ibfd, obfd);
13473
13474       /* Use the Tag_null value to indicate the attributes have been
13475          initialized.  */
13476       elf_known_obj_attributes_proc (obfd)[0].i = 1;
13477
13478       return TRUE;
13479     }
13480
13481   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
13482      non-conflicting ones.  */
13483   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
13484   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
13485     {
13486       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
13487       if (out_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
13488         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
13489       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13490         switch (out_attr[Tag_GNU_MIPS_ABI_FP].i)
13491           {
13492           case 1:
13493             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13494               {
13495               case 2:
13496                 _bfd_error_handler
13497                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13498                    obfd, abi_fp_bfd, ibfd, "-mdouble-float", "-msingle-float");
13499                 break;
13500
13501               case 3:
13502                 _bfd_error_handler
13503                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13504                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13505                 break;
13506
13507               case 4:
13508                 _bfd_error_handler
13509                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13510                    obfd, abi_fp_bfd, ibfd,
13511                    "-mdouble-float", "-mips32r2 -mfp64");
13512                 break;
13513
13514               default:
13515                 _bfd_error_handler
13516                   (_("Warning: %B uses %s (set by %B), "
13517                      "%B uses unknown floating point ABI %d"),
13518                    obfd, abi_fp_bfd, ibfd,
13519                    "-mdouble-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13520                 break;
13521               }
13522             break;
13523
13524           case 2:
13525             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13526               {
13527               case 1:
13528                 _bfd_error_handler
13529                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13530                    obfd, abi_fp_bfd, ibfd, "-msingle-float", "-mdouble-float");
13531                 break;
13532
13533               case 3:
13534                 _bfd_error_handler
13535                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13536                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13537                 break;
13538
13539               case 4:
13540                 _bfd_error_handler
13541                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13542                    obfd, abi_fp_bfd, ibfd,
13543                    "-msingle-float", "-mips32r2 -mfp64");
13544                 break;
13545
13546               default:
13547                 _bfd_error_handler
13548                   (_("Warning: %B uses %s (set by %B), "
13549                      "%B uses unknown floating point ABI %d"),
13550                    obfd, abi_fp_bfd, ibfd,
13551                    "-msingle-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13552                 break;
13553               }
13554             break;
13555
13556           case 3:
13557             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13558               {
13559               case 1:
13560               case 2:
13561               case 4:
13562                 _bfd_error_handler
13563                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13564                    obfd, abi_fp_bfd, ibfd, "-msoft-float", "-mhard-float");
13565                 break;
13566
13567               default:
13568                 _bfd_error_handler
13569                   (_("Warning: %B uses %s (set by %B), "
13570                      "%B uses unknown floating point ABI %d"),
13571                    obfd, abi_fp_bfd, ibfd,
13572                    "-msoft-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13573                 break;
13574               }
13575             break;
13576
13577           case 4:
13578             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13579               {
13580               case 1:
13581                 _bfd_error_handler
13582                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13583                    obfd, abi_fp_bfd, ibfd,
13584                    "-mips32r2 -mfp64", "-mdouble-float");
13585                 break;
13586
13587               case 2:
13588                 _bfd_error_handler
13589                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13590                    obfd, abi_fp_bfd, ibfd,
13591                    "-mips32r2 -mfp64", "-msingle-float");
13592                 break;
13593
13594               case 3:
13595                 _bfd_error_handler
13596                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13597                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13598                 break;
13599
13600               default:
13601                 _bfd_error_handler
13602                   (_("Warning: %B uses %s (set by %B), "
13603                      "%B uses unknown floating point ABI %d"),
13604                    obfd, abi_fp_bfd, ibfd,
13605                    "-mips32r2 -mfp64", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13606                 break;
13607               }
13608             break;
13609
13610           default:
13611             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13612               {
13613               case 1:
13614                 _bfd_error_handler
13615                   (_("Warning: %B uses unknown floating point ABI %d "
13616                      "(set by %B), %B uses %s"),
13617                    obfd, abi_fp_bfd, ibfd,
13618                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mdouble-float");
13619                 break;
13620
13621               case 2:
13622                 _bfd_error_handler
13623                   (_("Warning: %B uses unknown floating point ABI %d "
13624                      "(set by %B), %B uses %s"),
13625                    obfd, abi_fp_bfd, ibfd,
13626                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msingle-float");
13627                 break;
13628
13629               case 3:
13630                 _bfd_error_handler
13631                   (_("Warning: %B uses unknown floating point ABI %d "
13632                      "(set by %B), %B uses %s"),
13633                    obfd, abi_fp_bfd, ibfd,
13634                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msoft-float");
13635                 break;
13636
13637               case 4:
13638                 _bfd_error_handler
13639                   (_("Warning: %B uses unknown floating point ABI %d "
13640                      "(set by %B), %B uses %s"),
13641                    obfd, abi_fp_bfd, ibfd,
13642                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mips32r2 -mfp64");
13643                 break;
13644
13645               default:
13646                 _bfd_error_handler
13647                   (_("Warning: %B uses unknown floating point ABI %d "
13648                      "(set by %B), %B uses unknown floating point ABI %d"),
13649                    obfd, abi_fp_bfd, ibfd,
13650                    out_attr[Tag_GNU_MIPS_ABI_FP].i,
13651                    in_attr[Tag_GNU_MIPS_ABI_FP].i);
13652                 break;
13653               }
13654             break;
13655           }
13656     }
13657
13658   /* Merge Tag_compatibility attributes and any common GNU ones.  */
13659   _bfd_elf_merge_object_attributes (ibfd, obfd);
13660
13661   return TRUE;
13662 }
13663
13664 /* Merge backend specific data from an object file to the output
13665    object file when linking.  */
13666
13667 bfd_boolean
13668 _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
13669 {
13670   flagword old_flags;
13671   flagword new_flags;
13672   bfd_boolean ok;
13673   bfd_boolean null_input_bfd = TRUE;
13674   asection *sec;
13675
13676   /* Check if we have the same endianness.  */
13677   if (! _bfd_generic_verify_endian_match (ibfd, obfd))
13678     {
13679       (*_bfd_error_handler)
13680         (_("%B: endianness incompatible with that of the selected emulation"),
13681          ibfd);
13682       return FALSE;
13683     }
13684
13685   if (!is_mips_elf (ibfd) || !is_mips_elf (obfd))
13686     return TRUE;
13687
13688   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
13689     {
13690       (*_bfd_error_handler)
13691         (_("%B: ABI is incompatible with that of the selected emulation"),
13692          ibfd);
13693       return FALSE;
13694     }
13695
13696   if (!mips_elf_merge_obj_attributes (ibfd, obfd))
13697     return FALSE;
13698
13699   new_flags = elf_elfheader (ibfd)->e_flags;
13700   elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER;
13701   old_flags = elf_elfheader (obfd)->e_flags;
13702
13703   if (! elf_flags_init (obfd))
13704     {
13705       elf_flags_init (obfd) = TRUE;
13706       elf_elfheader (obfd)->e_flags = new_flags;
13707       elf_elfheader (obfd)->e_ident[EI_CLASS]
13708         = elf_elfheader (ibfd)->e_ident[EI_CLASS];
13709
13710       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
13711           && (bfd_get_arch_info (obfd)->the_default
13712               || mips_mach_extends_p (bfd_get_mach (obfd),
13713                                       bfd_get_mach (ibfd))))
13714         {
13715           if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
13716                                    bfd_get_mach (ibfd)))
13717             return FALSE;
13718         }
13719
13720       return TRUE;
13721     }
13722
13723   /* Check flag compatibility.  */
13724
13725   new_flags &= ~EF_MIPS_NOREORDER;
13726   old_flags &= ~EF_MIPS_NOREORDER;
13727
13728   /* Some IRIX 6 BSD-compatibility objects have this bit set.  It
13729      doesn't seem to matter.  */
13730   new_flags &= ~EF_MIPS_XGOT;
13731   old_flags &= ~EF_MIPS_XGOT;
13732
13733   /* MIPSpro generates ucode info in n64 objects.  Again, we should
13734      just be able to ignore this.  */
13735   new_flags &= ~EF_MIPS_UCODE;
13736   old_flags &= ~EF_MIPS_UCODE;
13737
13738   /* DSOs should only be linked with CPIC code.  */
13739   if ((ibfd->flags & DYNAMIC) != 0)
13740     new_flags |= EF_MIPS_PIC | EF_MIPS_CPIC;
13741
13742   if (new_flags == old_flags)
13743     return TRUE;
13744
13745   /* Check to see if the input BFD actually contains any sections.
13746      If not, its flags may not have been initialised either, but it cannot
13747      actually cause any incompatibility.  */
13748   for (sec = ibfd->sections; sec != NULL; sec = sec->next)
13749     {
13750       /* Ignore synthetic sections and empty .text, .data and .bss sections
13751          which are automatically generated by gas.  Also ignore fake
13752          (s)common sections, since merely defining a common symbol does
13753          not affect compatibility.  */
13754       if ((sec->flags & SEC_IS_COMMON) == 0
13755           && strcmp (sec->name, ".reginfo")
13756           && strcmp (sec->name, ".mdebug")
13757           && (sec->size != 0
13758               || (strcmp (sec->name, ".text")
13759                   && strcmp (sec->name, ".data")
13760                   && strcmp (sec->name, ".bss"))))
13761         {
13762           null_input_bfd = FALSE;
13763           break;
13764         }
13765     }
13766   if (null_input_bfd)
13767     return TRUE;
13768
13769   ok = TRUE;
13770
13771   if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)
13772       != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0))
13773     {
13774       (*_bfd_error_handler)
13775         (_("%B: warning: linking abicalls files with non-abicalls files"),
13776          ibfd);
13777       ok = TRUE;
13778     }
13779
13780   if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC))
13781     elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC;
13782   if (! (new_flags & EF_MIPS_PIC))
13783     elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC;
13784
13785   new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13786   old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13787
13788   /* Compare the ISAs.  */
13789   if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags))
13790     {
13791       (*_bfd_error_handler)
13792         (_("%B: linking 32-bit code with 64-bit code"),
13793          ibfd);
13794       ok = FALSE;
13795     }
13796   else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd)))
13797     {
13798       /* OBFD's ISA isn't the same as, or an extension of, IBFD's.  */
13799       if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd)))
13800         {
13801           /* Copy the architecture info from IBFD to OBFD.  Also copy
13802              the 32-bit flag (if set) so that we continue to recognise
13803              OBFD as a 32-bit binary.  */
13804           bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd));
13805           elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
13806           elf_elfheader (obfd)->e_flags
13807             |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13808
13809           /* Copy across the ABI flags if OBFD doesn't use them
13810              and if that was what caused us to treat IBFD as 32-bit.  */
13811           if ((old_flags & EF_MIPS_ABI) == 0
13812               && mips_32bit_flags_p (new_flags)
13813               && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI))
13814             elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI;
13815         }
13816       else
13817         {
13818           /* The ISAs aren't compatible.  */
13819           (*_bfd_error_handler)
13820             (_("%B: linking %s module with previous %s modules"),
13821              ibfd,
13822              bfd_printable_name (ibfd),
13823              bfd_printable_name (obfd));
13824           ok = FALSE;
13825         }
13826     }
13827
13828   new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13829   old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13830
13831   /* Compare ABIs.  The 64-bit ABI does not use EF_MIPS_ABI.  But, it
13832      does set EI_CLASS differently from any 32-bit ABI.  */
13833   if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI)
13834       || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
13835           != elf_elfheader (obfd)->e_ident[EI_CLASS]))
13836     {
13837       /* Only error if both are set (to different values).  */
13838       if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI))
13839           || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
13840               != elf_elfheader (obfd)->e_ident[EI_CLASS]))
13841         {
13842           (*_bfd_error_handler)
13843             (_("%B: ABI mismatch: linking %s module with previous %s modules"),
13844              ibfd,
13845              elf_mips_abi_name (ibfd),
13846              elf_mips_abi_name (obfd));
13847           ok = FALSE;
13848         }
13849       new_flags &= ~EF_MIPS_ABI;
13850       old_flags &= ~EF_MIPS_ABI;
13851     }
13852
13853   /* Compare ASEs.  Forbid linking MIPS16 and microMIPS ASE modules together
13854      and allow arbitrary mixing of the remaining ASEs (retain the union).  */
13855   if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE))
13856     {
13857       int old_micro = old_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
13858       int new_micro = new_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
13859       int old_m16 = old_flags & EF_MIPS_ARCH_ASE_M16;
13860       int new_m16 = new_flags & EF_MIPS_ARCH_ASE_M16;
13861       int micro_mis = old_m16 && new_micro;
13862       int m16_mis = old_micro && new_m16;
13863
13864       if (m16_mis || micro_mis)
13865         {
13866           (*_bfd_error_handler)
13867             (_("%B: ASE mismatch: linking %s module with previous %s modules"),
13868              ibfd,
13869              m16_mis ? "MIPS16" : "microMIPS",
13870              m16_mis ? "microMIPS" : "MIPS16");
13871           ok = FALSE;
13872         }
13873
13874       elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE;
13875
13876       new_flags &= ~ EF_MIPS_ARCH_ASE;
13877       old_flags &= ~ EF_MIPS_ARCH_ASE;
13878     }
13879
13880   /* Warn about any other mismatches */
13881   if (new_flags != old_flags)
13882     {
13883       (*_bfd_error_handler)
13884         (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"),
13885          ibfd, (unsigned long) new_flags,
13886          (unsigned long) old_flags);
13887       ok = FALSE;
13888     }
13889
13890   if (! ok)
13891     {
13892       bfd_set_error (bfd_error_bad_value);
13893       return FALSE;
13894     }
13895
13896   return TRUE;
13897 }
13898
13899 /* Function to keep MIPS specific file flags like as EF_MIPS_PIC.  */
13900
13901 bfd_boolean
13902 _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags)
13903 {
13904   BFD_ASSERT (!elf_flags_init (abfd)
13905               || elf_elfheader (abfd)->e_flags == flags);
13906
13907   elf_elfheader (abfd)->e_flags = flags;
13908   elf_flags_init (abfd) = TRUE;
13909   return TRUE;
13910 }
13911
13912 char *
13913 _bfd_mips_elf_get_target_dtag (bfd_vma dtag)
13914 {
13915   switch (dtag)
13916     {
13917     default: return "";
13918     case DT_MIPS_RLD_VERSION:
13919       return "MIPS_RLD_VERSION";
13920     case DT_MIPS_TIME_STAMP:
13921       return "MIPS_TIME_STAMP";
13922     case DT_MIPS_ICHECKSUM:
13923       return "MIPS_ICHECKSUM";
13924     case DT_MIPS_IVERSION:
13925       return "MIPS_IVERSION";
13926     case DT_MIPS_FLAGS:
13927       return "MIPS_FLAGS";
13928     case DT_MIPS_BASE_ADDRESS:
13929       return "MIPS_BASE_ADDRESS";
13930     case DT_MIPS_MSYM:
13931       return "MIPS_MSYM";
13932     case DT_MIPS_CONFLICT:
13933       return "MIPS_CONFLICT";
13934     case DT_MIPS_LIBLIST:
13935       return "MIPS_LIBLIST";
13936     case DT_MIPS_LOCAL_GOTNO:
13937       return "MIPS_LOCAL_GOTNO";
13938     case DT_MIPS_CONFLICTNO:
13939       return "MIPS_CONFLICTNO";
13940     case DT_MIPS_LIBLISTNO:
13941       return "MIPS_LIBLISTNO";
13942     case DT_MIPS_SYMTABNO:
13943       return "MIPS_SYMTABNO";
13944     case DT_MIPS_UNREFEXTNO:
13945       return "MIPS_UNREFEXTNO";
13946     case DT_MIPS_GOTSYM:
13947       return "MIPS_GOTSYM";
13948     case DT_MIPS_HIPAGENO:
13949       return "MIPS_HIPAGENO";
13950     case DT_MIPS_RLD_MAP:
13951       return "MIPS_RLD_MAP";
13952     case DT_MIPS_DELTA_CLASS:
13953       return "MIPS_DELTA_CLASS";
13954     case DT_MIPS_DELTA_CLASS_NO:
13955       return "MIPS_DELTA_CLASS_NO";
13956     case DT_MIPS_DELTA_INSTANCE:
13957       return "MIPS_DELTA_INSTANCE";
13958     case DT_MIPS_DELTA_INSTANCE_NO:
13959       return "MIPS_DELTA_INSTANCE_NO";
13960     case DT_MIPS_DELTA_RELOC:
13961       return "MIPS_DELTA_RELOC";
13962     case DT_MIPS_DELTA_RELOC_NO:
13963       return "MIPS_DELTA_RELOC_NO";
13964     case DT_MIPS_DELTA_SYM:
13965       return "MIPS_DELTA_SYM";
13966     case DT_MIPS_DELTA_SYM_NO:
13967       return "MIPS_DELTA_SYM_NO";
13968     case DT_MIPS_DELTA_CLASSSYM:
13969       return "MIPS_DELTA_CLASSSYM";
13970     case DT_MIPS_DELTA_CLASSSYM_NO:
13971       return "MIPS_DELTA_CLASSSYM_NO";
13972     case DT_MIPS_CXX_FLAGS:
13973       return "MIPS_CXX_FLAGS";
13974     case DT_MIPS_PIXIE_INIT:
13975       return "MIPS_PIXIE_INIT";
13976     case DT_MIPS_SYMBOL_LIB:
13977       return "MIPS_SYMBOL_LIB";
13978     case DT_MIPS_LOCALPAGE_GOTIDX:
13979       return "MIPS_LOCALPAGE_GOTIDX";
13980     case DT_MIPS_LOCAL_GOTIDX:
13981       return "MIPS_LOCAL_GOTIDX";
13982     case DT_MIPS_HIDDEN_GOTIDX:
13983       return "MIPS_HIDDEN_GOTIDX";
13984     case DT_MIPS_PROTECTED_GOTIDX:
13985       return "MIPS_PROTECTED_GOT_IDX";
13986     case DT_MIPS_OPTIONS:
13987       return "MIPS_OPTIONS";
13988     case DT_MIPS_INTERFACE:
13989       return "MIPS_INTERFACE";
13990     case DT_MIPS_DYNSTR_ALIGN:
13991       return "DT_MIPS_DYNSTR_ALIGN";
13992     case DT_MIPS_INTERFACE_SIZE:
13993       return "DT_MIPS_INTERFACE_SIZE";
13994     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
13995       return "DT_MIPS_RLD_TEXT_RESOLVE_ADDR";
13996     case DT_MIPS_PERF_SUFFIX:
13997       return "DT_MIPS_PERF_SUFFIX";
13998     case DT_MIPS_COMPACT_SIZE:
13999       return "DT_MIPS_COMPACT_SIZE";
14000     case DT_MIPS_GP_VALUE:
14001       return "DT_MIPS_GP_VALUE";
14002     case DT_MIPS_AUX_DYNAMIC:
14003       return "DT_MIPS_AUX_DYNAMIC";
14004     case DT_MIPS_PLTGOT:
14005       return "DT_MIPS_PLTGOT";
14006     case DT_MIPS_RWPLT:
14007       return "DT_MIPS_RWPLT";
14008     }
14009 }
14010
14011 bfd_boolean
14012 _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr)
14013 {
14014   FILE *file = ptr;
14015
14016   BFD_ASSERT (abfd != NULL && ptr != NULL);
14017
14018   /* Print normal ELF private data.  */
14019   _bfd_elf_print_private_bfd_data (abfd, ptr);
14020
14021   /* xgettext:c-format */
14022   fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
14023
14024   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
14025     fprintf (file, _(" [abi=O32]"));
14026   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64)
14027     fprintf (file, _(" [abi=O64]"));
14028   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32)
14029     fprintf (file, _(" [abi=EABI32]"));
14030   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
14031     fprintf (file, _(" [abi=EABI64]"));
14032   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI))
14033     fprintf (file, _(" [abi unknown]"));
14034   else if (ABI_N32_P (abfd))
14035     fprintf (file, _(" [abi=N32]"));
14036   else if (ABI_64_P (abfd))
14037     fprintf (file, _(" [abi=64]"));
14038   else
14039     fprintf (file, _(" [no abi set]"));
14040
14041   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1)
14042     fprintf (file, " [mips1]");
14043   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2)
14044     fprintf (file, " [mips2]");
14045   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3)
14046     fprintf (file, " [mips3]");
14047   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4)
14048     fprintf (file, " [mips4]");
14049   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5)
14050     fprintf (file, " [mips5]");
14051   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32)
14052     fprintf (file, " [mips32]");
14053   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64)
14054     fprintf (file, " [mips64]");
14055   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2)
14056     fprintf (file, " [mips32r2]");
14057   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2)
14058     fprintf (file, " [mips64r2]");
14059   else
14060     fprintf (file, _(" [unknown ISA]"));
14061
14062   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
14063     fprintf (file, " [mdmx]");
14064
14065   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
14066     fprintf (file, " [mips16]");
14067
14068   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
14069     fprintf (file, " [micromips]");
14070
14071   if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE)
14072     fprintf (file, " [32bitmode]");
14073   else
14074     fprintf (file, _(" [not 32bitmode]"));
14075
14076   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NOREORDER)
14077     fprintf (file, " [noreorder]");
14078
14079   if (elf_elfheader (abfd)->e_flags & EF_MIPS_PIC)
14080     fprintf (file, " [PIC]");
14081
14082   if (elf_elfheader (abfd)->e_flags & EF_MIPS_CPIC)
14083     fprintf (file, " [CPIC]");
14084
14085   if (elf_elfheader (abfd)->e_flags & EF_MIPS_XGOT)
14086     fprintf (file, " [XGOT]");
14087
14088   if (elf_elfheader (abfd)->e_flags & EF_MIPS_UCODE)
14089     fprintf (file, " [UCODE]");
14090
14091   fputc ('\n', file);
14092
14093   return TRUE;
14094 }
14095
14096 const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] =
14097 {
14098   { STRING_COMMA_LEN (".lit4"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14099   { STRING_COMMA_LEN (".lit8"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14100   { STRING_COMMA_LEN (".mdebug"), 0, SHT_MIPS_DEBUG, 0 },
14101   { STRING_COMMA_LEN (".sbss"),  -2, SHT_NOBITS,     SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14102   { STRING_COMMA_LEN (".sdata"), -2, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14103   { STRING_COMMA_LEN (".ucode"),  0, SHT_MIPS_UCODE, 0 },
14104   { NULL,                     0,  0, 0,              0 }
14105 };
14106
14107 /* Merge non visibility st_other attributes.  Ensure that the
14108    STO_OPTIONAL flag is copied into h->other, even if this is not a
14109    definiton of the symbol.  */
14110 void
14111 _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
14112                                       const Elf_Internal_Sym *isym,
14113                                       bfd_boolean definition,
14114                                       bfd_boolean dynamic ATTRIBUTE_UNUSED)
14115 {
14116   if ((isym->st_other & ~ELF_ST_VISIBILITY (-1)) != 0)
14117     {
14118       unsigned char other;
14119
14120       other = (definition ? isym->st_other : h->other);
14121       other &= ~ELF_ST_VISIBILITY (-1);
14122       h->other = other | ELF_ST_VISIBILITY (h->other);
14123     }
14124
14125   if (!definition
14126       && ELF_MIPS_IS_OPTIONAL (isym->st_other))
14127     h->other |= STO_OPTIONAL;
14128 }
14129
14130 /* Decide whether an undefined symbol is special and can be ignored.
14131    This is the case for OPTIONAL symbols on IRIX.  */
14132 bfd_boolean
14133 _bfd_mips_elf_ignore_undef_symbol (struct elf_link_hash_entry *h)
14134 {
14135   return ELF_MIPS_IS_OPTIONAL (h->other) ? TRUE : FALSE;
14136 }
14137
14138 bfd_boolean
14139 _bfd_mips_elf_common_definition (Elf_Internal_Sym *sym)
14140 {
14141   return (sym->st_shndx == SHN_COMMON
14142           || sym->st_shndx == SHN_MIPS_ACOMMON
14143           || sym->st_shndx == SHN_MIPS_SCOMMON);
14144 }
14145
14146 /* Return address for Ith PLT stub in section PLT, for relocation REL
14147    or (bfd_vma) -1 if it should not be included.  */
14148
14149 bfd_vma
14150 _bfd_mips_elf_plt_sym_val (bfd_vma i, const asection *plt,
14151                            const arelent *rel ATTRIBUTE_UNUSED)
14152 {
14153   return (plt->vma
14154           + 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry)
14155           + i * 4 * ARRAY_SIZE (mips_exec_plt_entry));
14156 }
14157
14158 void
14159 _bfd_mips_post_process_headers (bfd *abfd, struct bfd_link_info *link_info)
14160 {
14161   struct mips_elf_link_hash_table *htab;
14162   Elf_Internal_Ehdr *i_ehdrp;
14163
14164   i_ehdrp = elf_elfheader (abfd);
14165   if (link_info)
14166     {
14167       htab = mips_elf_hash_table (link_info);
14168       BFD_ASSERT (htab != NULL);
14169
14170       if (htab->use_plts_and_copy_relocs && !htab->is_vxworks)
14171         i_ehdrp->e_ident[EI_ABIVERSION] = 1;
14172     }
14173 }