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