MIPS/BFD: Fix assertion in `mips_elf_sort_hash_table'
[external/binutils.git] / bfd / elfxx-mips.c
1 /* MIPS-specific support for ELF
2    Copyright (C) 1993-2017 Free Software Foundation, Inc.
3
4    Most of the information added by Ian Lance Taylor, Cygnus Support,
5    <ian@cygnus.com>.
6    N32/64 ABI support added by Mark Mitchell, CodeSourcery, LLC.
7    <mark@codesourcery.com>
8    Traditional MIPS targets support added by Koundinya.K, Dansk Data
9    Elektronik & Operations Research Group. <kk@ddeorg.soft.net>
10
11    This file is part of BFD, the Binary File Descriptor library.
12
13    This program is free software; you can redistribute it and/or modify
14    it under the terms of the GNU General Public License as published by
15    the Free Software Foundation; either version 3 of the License, or
16    (at your option) any later version.
17
18    This program is distributed in the hope that it will be useful,
19    but WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21    GNU General Public License for more details.
22
23    You should have received a copy of the GNU General Public License
24    along with this program; if not, write to the Free Software
25    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
26    MA 02110-1301, USA.  */
27
28
29 /* This file handles functionality common to the different MIPS ABI's.  */
30
31 #include "sysdep.h"
32 #include "bfd.h"
33 #include "libbfd.h"
34 #include "libiberty.h"
35 #include "elf-bfd.h"
36 #include "elfxx-mips.h"
37 #include "elf/mips.h"
38 #include "elf-vxworks.h"
39 #include "dwarf2.h"
40
41 /* Get the ECOFF swapping routines.  */
42 #include "coff/sym.h"
43 #include "coff/symconst.h"
44 #include "coff/ecoff.h"
45 #include "coff/mips.h"
46
47 #include "hashtab.h"
48
49 /* Types of TLS GOT entry.  */
50 enum mips_got_tls_type {
51   GOT_TLS_NONE,
52   GOT_TLS_GD,
53   GOT_TLS_LDM,
54   GOT_TLS_IE
55 };
56
57 /* This structure is used to hold information about one GOT entry.
58    There are four types of entry:
59
60       (1) an absolute address
61             requires: abfd == NULL
62             fields: d.address
63
64       (2) a SYMBOL + OFFSET address, where SYMBOL is local to an input bfd
65             requires: abfd != NULL, symndx >= 0, tls_type != GOT_TLS_LDM
66             fields: abfd, symndx, d.addend, tls_type
67
68       (3) a SYMBOL address, where SYMBOL is not local to an input bfd
69             requires: abfd != NULL, symndx == -1
70             fields: d.h, tls_type
71
72       (4) a TLS LDM slot
73             requires: abfd != NULL, symndx == 0, tls_type == GOT_TLS_LDM
74             fields: none; there's only one of these per GOT.  */
75 struct mips_got_entry
76 {
77   /* One input bfd that needs the GOT entry.  */
78   bfd *abfd;
79   /* The index of the symbol, as stored in the relocation r_info, if
80      we have a local symbol; -1 otherwise.  */
81   long symndx;
82   union
83   {
84     /* If abfd == NULL, an address that must be stored in the got.  */
85     bfd_vma address;
86     /* If abfd != NULL && symndx != -1, the addend of the relocation
87        that should be added to the symbol value.  */
88     bfd_vma addend;
89     /* If abfd != NULL && symndx == -1, the hash table entry
90        corresponding to a symbol in the GOT.  The symbol's entry
91        is in the local area if h->global_got_area is GGA_NONE,
92        otherwise it is in the global area.  */
93     struct mips_elf_link_hash_entry *h;
94   } d;
95
96   /* The TLS type of this GOT entry.  An LDM GOT entry will be a local
97      symbol entry with r_symndx == 0.  */
98   unsigned char tls_type;
99
100   /* True if we have filled in the GOT contents for a TLS entry,
101      and created the associated relocations.  */
102   unsigned char tls_initialized;
103
104   /* The offset from the beginning of the .got section to the entry
105      corresponding to this symbol+addend.  If it's a global symbol
106      whose offset is yet to be decided, it's going to be -1.  */
107   long gotidx;
108 };
109
110 /* This structure represents a GOT page reference from an input bfd.
111    Each instance represents a symbol + ADDEND, where the representation
112    of the symbol depends on whether it is local to the input bfd.
113    If it is, then SYMNDX >= 0, and the symbol has index SYMNDX in U.ABFD.
114    Otherwise, SYMNDX < 0 and U.H points to the symbol's hash table entry.
115
116    Page references with SYMNDX >= 0 always become page references
117    in the output.  Page references with SYMNDX < 0 only become page
118    references if the symbol binds locally; in other cases, the page
119    reference decays to a global GOT reference.  */
120 struct mips_got_page_ref
121 {
122   long symndx;
123   union
124   {
125     struct mips_elf_link_hash_entry *h;
126     bfd *abfd;
127   } u;
128   bfd_vma addend;
129 };
130
131 /* This structure describes a range of addends: [MIN_ADDEND, MAX_ADDEND].
132    The structures form a non-overlapping list that is sorted by increasing
133    MIN_ADDEND.  */
134 struct mips_got_page_range
135 {
136   struct mips_got_page_range *next;
137   bfd_signed_vma min_addend;
138   bfd_signed_vma max_addend;
139 };
140
141 /* This structure describes the range of addends that are applied to page
142    relocations against a given section.  */
143 struct mips_got_page_entry
144 {
145   /* The section that these entries are based on.  */
146   asection *sec;
147   /* The ranges for this page entry.  */
148   struct mips_got_page_range *ranges;
149   /* The maximum number of page entries needed for RANGES.  */
150   bfd_vma num_pages;
151 };
152
153 /* This structure is used to hold .got information when linking.  */
154
155 struct mips_got_info
156 {
157   /* The number of global .got entries.  */
158   unsigned int global_gotno;
159   /* The number of global .got entries that are in the GGA_RELOC_ONLY area.  */
160   unsigned int reloc_only_gotno;
161   /* The number of .got slots used for TLS.  */
162   unsigned int tls_gotno;
163   /* The first unused TLS .got entry.  Used only during
164      mips_elf_initialize_tls_index.  */
165   unsigned int tls_assigned_gotno;
166   /* The number of local .got entries, eventually including page entries.  */
167   unsigned int local_gotno;
168   /* The maximum number of page entries needed.  */
169   unsigned int page_gotno;
170   /* The number of relocations needed for the GOT entries.  */
171   unsigned int relocs;
172   /* The first unused local .got entry.  */
173   unsigned int assigned_low_gotno;
174   /* The last unused local .got entry.  */
175   unsigned int assigned_high_gotno;
176   /* A hash table holding members of the got.  */
177   struct htab *got_entries;
178   /* A hash table holding mips_got_page_ref structures.  */
179   struct htab *got_page_refs;
180   /* A hash table of mips_got_page_entry structures.  */
181   struct htab *got_page_entries;
182   /* In multi-got links, a pointer to the next got (err, rather, most
183      of the time, it points to the previous got).  */
184   struct mips_got_info *next;
185 };
186
187 /* Structure passed when merging bfds' gots.  */
188
189 struct mips_elf_got_per_bfd_arg
190 {
191   /* The output bfd.  */
192   bfd *obfd;
193   /* The link information.  */
194   struct bfd_link_info *info;
195   /* A pointer to the primary got, i.e., the one that's going to get
196      the implicit relocations from DT_MIPS_LOCAL_GOTNO and
197      DT_MIPS_GOTSYM.  */
198   struct mips_got_info *primary;
199   /* A non-primary got we're trying to merge with other input bfd's
200      gots.  */
201   struct mips_got_info *current;
202   /* The maximum number of got entries that can be addressed with a
203      16-bit offset.  */
204   unsigned int max_count;
205   /* The maximum number of page entries needed by each got.  */
206   unsigned int max_pages;
207   /* The total number of global entries which will live in the
208      primary got and be automatically relocated.  This includes
209      those not referenced by the primary GOT but included in
210      the "master" GOT.  */
211   unsigned int global_count;
212 };
213
214 /* A structure used to pass information to htab_traverse callbacks
215    when laying out the GOT.  */
216
217 struct mips_elf_traverse_got_arg
218 {
219   struct bfd_link_info *info;
220   struct mips_got_info *g;
221   int value;
222 };
223
224 struct _mips_elf_section_data
225 {
226   struct bfd_elf_section_data elf;
227   union
228   {
229     bfd_byte *tdata;
230   } u;
231 };
232
233 #define mips_elf_section_data(sec) \
234   ((struct _mips_elf_section_data *) elf_section_data (sec))
235
236 #define is_mips_elf(bfd)                                \
237   (bfd_get_flavour (bfd) == bfd_target_elf_flavour      \
238    && elf_tdata (bfd) != NULL                           \
239    && elf_object_id (bfd) == MIPS_ELF_DATA)
240
241 /* The ABI says that every symbol used by dynamic relocations must have
242    a global GOT entry.  Among other things, this provides the dynamic
243    linker with a free, directly-indexed cache.  The GOT can therefore
244    contain symbols that are not referenced by GOT relocations themselves
245    (in other words, it may have symbols that are not referenced by things
246    like R_MIPS_GOT16 and R_MIPS_GOT_PAGE).
247
248    GOT relocations are less likely to overflow if we put the associated
249    GOT entries towards the beginning.  We therefore divide the global
250    GOT entries into two areas: "normal" and "reloc-only".  Entries in
251    the first area can be used for both dynamic relocations and GP-relative
252    accesses, while those in the "reloc-only" area are for dynamic
253    relocations only.
254
255    These GGA_* ("Global GOT Area") values are organised so that lower
256    values are more general than higher values.  Also, non-GGA_NONE
257    values are ordered by the position of the area in the GOT.  */
258 #define GGA_NORMAL 0
259 #define GGA_RELOC_ONLY 1
260 #define GGA_NONE 2
261
262 /* Information about a non-PIC interface to a PIC function.  There are
263    two ways of creating these interfaces.  The first is to add:
264
265         lui     $25,%hi(func)
266         addiu   $25,$25,%lo(func)
267
268    immediately before a PIC function "func".  The second is to add:
269
270         lui     $25,%hi(func)
271         j       func
272         addiu   $25,$25,%lo(func)
273
274    to a separate trampoline section.
275
276    Stubs of the first kind go in a new section immediately before the
277    target function.  Stubs of the second kind go in a single section
278    pointed to by the hash table's "strampoline" field.  */
279 struct mips_elf_la25_stub {
280   /* The generated section that contains this stub.  */
281   asection *stub_section;
282
283   /* The offset of the stub from the start of STUB_SECTION.  */
284   bfd_vma offset;
285
286   /* One symbol for the original function.  Its location is available
287      in H->root.root.u.def.  */
288   struct mips_elf_link_hash_entry *h;
289 };
290
291 /* Macros for populating a mips_elf_la25_stub.  */
292
293 #define LA25_LUI(VAL) (0x3c190000 | (VAL))      /* lui t9,VAL */
294 #define LA25_J(VAL) (0x08000000 | (((VAL) >> 2) & 0x3ffffff)) /* j VAL */
295 #define LA25_ADDIU(VAL) (0x27390000 | (VAL))    /* addiu t9,t9,VAL */
296 #define LA25_LUI_MICROMIPS(VAL)                                         \
297   (0x41b90000 | (VAL))                          /* lui t9,VAL */
298 #define LA25_J_MICROMIPS(VAL)                                           \
299   (0xd4000000 | (((VAL) >> 1) & 0x3ffffff))     /* j VAL */
300 #define LA25_ADDIU_MICROMIPS(VAL)                                       \
301   (0x33390000 | (VAL))                          /* addiu t9,t9,VAL */
302
303 /* This structure is passed to mips_elf_sort_hash_table_f when sorting
304    the dynamic symbols.  */
305
306 struct mips_elf_hash_sort_data
307 {
308   /* The symbol in the global GOT with the lowest dynamic symbol table
309      index.  */
310   struct elf_link_hash_entry *low;
311   /* The least dynamic symbol table index corresponding to a non-TLS
312      symbol with a GOT entry.  */
313   long min_got_dynindx;
314   /* The greatest dynamic symbol table index corresponding to a symbol
315      with a GOT entry that is not referenced (e.g., a dynamic symbol
316      with dynamic relocations pointing to it from non-primary GOTs).  */
317   long max_unref_got_dynindx;
318   /* The greatest dynamic symbol table index not corresponding to a
319      symbol without a GOT entry.  */
320   long max_non_got_dynindx;
321 };
322
323 /* We make up to two PLT entries if needed, one for standard MIPS code
324    and one for compressed code, either a MIPS16 or microMIPS one.  We
325    keep a separate record of traditional lazy-binding stubs, for easier
326    processing.  */
327
328 struct plt_entry
329 {
330   /* Traditional SVR4 stub offset, or -1 if none.  */
331   bfd_vma stub_offset;
332
333   /* Standard PLT entry offset, or -1 if none.  */
334   bfd_vma mips_offset;
335
336   /* Compressed PLT entry offset, or -1 if none.  */
337   bfd_vma comp_offset;
338
339   /* The corresponding .got.plt index, or -1 if none.  */
340   bfd_vma gotplt_index;
341
342   /* Whether we need a standard PLT entry.  */
343   unsigned int need_mips : 1;
344
345   /* Whether we need a compressed PLT entry.  */
346   unsigned int need_comp : 1;
347 };
348
349 /* The MIPS ELF linker needs additional information for each symbol in
350    the global hash table.  */
351
352 struct mips_elf_link_hash_entry
353 {
354   struct elf_link_hash_entry root;
355
356   /* External symbol information.  */
357   EXTR esym;
358
359   /* The la25 stub we have created for ths symbol, if any.  */
360   struct mips_elf_la25_stub *la25_stub;
361
362   /* Number of R_MIPS_32, R_MIPS_REL32, or R_MIPS_64 relocs against
363      this symbol.  */
364   unsigned int possibly_dynamic_relocs;
365
366   /* If there is a stub that 32 bit functions should use to call this
367      16 bit function, this points to the section containing the stub.  */
368   asection *fn_stub;
369
370   /* If there is a stub that 16 bit functions should use to call this
371      32 bit function, this points to the section containing the stub.  */
372   asection *call_stub;
373
374   /* This is like the call_stub field, but it is used if the function
375      being called returns a floating point value.  */
376   asection *call_fp_stub;
377
378   /* The highest GGA_* value that satisfies all references to this symbol.  */
379   unsigned int global_got_area : 2;
380
381   /* True if all GOT relocations against this symbol are for calls.  This is
382      a looser condition than no_fn_stub below, because there may be other
383      non-call non-GOT relocations against the symbol.  */
384   unsigned int got_only_for_calls : 1;
385
386   /* True if one of the relocations described by possibly_dynamic_relocs
387      is against a readonly section.  */
388   unsigned int readonly_reloc : 1;
389
390   /* True if there is a relocation against this symbol that must be
391      resolved by the static linker (in other words, if the relocation
392      cannot possibly be made dynamic).  */
393   unsigned int has_static_relocs : 1;
394
395   /* True if we must not create a .MIPS.stubs entry for this symbol.
396      This is set, for example, if there are relocations related to
397      taking the function's address, i.e. any but R_MIPS_CALL*16 ones.
398      See "MIPS ABI Supplement, 3rd Edition", p. 4-20.  */
399   unsigned int no_fn_stub : 1;
400
401   /* Whether we need the fn_stub; this is true if this symbol appears
402      in any relocs other than a 16 bit call.  */
403   unsigned int need_fn_stub : 1;
404
405   /* True if this symbol is referenced by branch relocations from
406      any non-PIC input file.  This is used to determine whether an
407      la25 stub is required.  */
408   unsigned int has_nonpic_branches : 1;
409
410   /* Does this symbol need a traditional MIPS lazy-binding stub
411      (as opposed to a PLT entry)?  */
412   unsigned int needs_lazy_stub : 1;
413
414   /* Does this symbol resolve to a PLT entry?  */
415   unsigned int use_plt_entry : 1;
416 };
417
418 /* MIPS ELF linker hash table.  */
419
420 struct mips_elf_link_hash_table
421 {
422   struct elf_link_hash_table root;
423
424   /* The number of .rtproc entries.  */
425   bfd_size_type procedure_count;
426
427   /* The size of the .compact_rel section (if SGI_COMPAT).  */
428   bfd_size_type compact_rel_size;
429
430   /* This flag indicates that the value of DT_MIPS_RLD_MAP dynamic entry
431      is set to the address of __rld_obj_head as in IRIX5 and IRIX6.  */
432   bfd_boolean use_rld_obj_head;
433
434   /* The  __rld_map or __rld_obj_head symbol. */
435   struct elf_link_hash_entry *rld_symbol;
436
437   /* This is set if we see any mips16 stub sections.  */
438   bfd_boolean mips16_stubs_seen;
439
440   /* True if we can generate copy relocs and PLTs.  */
441   bfd_boolean use_plts_and_copy_relocs;
442
443   /* True if we can only use 32-bit microMIPS instructions.  */
444   bfd_boolean insn32;
445
446   /* True if we suppress checks for invalid branches between ISA modes.  */
447   bfd_boolean ignore_branch_isa;
448
449   /* True if we're generating code for VxWorks.  */
450   bfd_boolean is_vxworks;
451
452   /* True if we already reported the small-data section overflow.  */
453   bfd_boolean small_data_overflow_reported;
454
455   /* Shortcuts to some dynamic sections, or NULL if they are not
456      being used.  */
457   asection *srelplt2;
458   asection *sstubs;
459
460   /* The master GOT information.  */
461   struct mips_got_info *got_info;
462
463   /* The global symbol in the GOT with the lowest index in the dynamic
464      symbol table.  */
465   struct elf_link_hash_entry *global_gotsym;
466
467   /* The size of the PLT header in bytes.  */
468   bfd_vma plt_header_size;
469
470   /* The size of a standard PLT entry in bytes.  */
471   bfd_vma plt_mips_entry_size;
472
473   /* The size of a compressed PLT entry in bytes.  */
474   bfd_vma plt_comp_entry_size;
475
476   /* The offset of the next standard PLT entry to create.  */
477   bfd_vma plt_mips_offset;
478
479   /* The offset of the next compressed PLT entry to create.  */
480   bfd_vma plt_comp_offset;
481
482   /* The index of the next .got.plt entry to create.  */
483   bfd_vma plt_got_index;
484
485   /* The number of functions that need a lazy-binding stub.  */
486   bfd_vma lazy_stub_count;
487
488   /* The size of a function stub entry in bytes.  */
489   bfd_vma function_stub_size;
490
491   /* The number of reserved entries at the beginning of the GOT.  */
492   unsigned int reserved_gotno;
493
494   /* The section used for mips_elf_la25_stub trampolines.
495      See the comment above that structure for details.  */
496   asection *strampoline;
497
498   /* A table of mips_elf_la25_stubs, indexed by (input_section, offset)
499      pairs.  */
500   htab_t la25_stubs;
501
502   /* A function FN (NAME, IS, OS) that creates a new input section
503      called NAME and links it to output section OS.  If IS is nonnull,
504      the new section should go immediately before it, otherwise it
505      should go at the (current) beginning of OS.
506
507      The function returns the new section on success, otherwise it
508      returns null.  */
509   asection *(*add_stub_section) (const char *, asection *, asection *);
510
511   /* Small local sym cache.  */
512   struct sym_cache sym_cache;
513
514   /* Is the PLT header compressed?  */
515   unsigned int plt_header_is_comp : 1;
516 };
517
518 /* Get the MIPS ELF linker hash table from a link_info structure.  */
519
520 #define mips_elf_hash_table(p) \
521   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
522   == MIPS_ELF_DATA ? ((struct mips_elf_link_hash_table *) ((p)->hash)) : NULL)
523
524 /* A structure used to communicate with htab_traverse callbacks.  */
525 struct mips_htab_traverse_info
526 {
527   /* The usual link-wide information.  */
528   struct bfd_link_info *info;
529   bfd *output_bfd;
530
531   /* Starts off FALSE and is set to TRUE if the link should be aborted.  */
532   bfd_boolean error;
533 };
534
535 /* MIPS ELF private object data.  */
536
537 struct mips_elf_obj_tdata
538 {
539   /* Generic ELF private object data.  */
540   struct elf_obj_tdata root;
541
542   /* Input BFD providing Tag_GNU_MIPS_ABI_FP attribute for output.  */
543   bfd *abi_fp_bfd;
544
545   /* Input BFD providing Tag_GNU_MIPS_ABI_MSA attribute for output.  */
546   bfd *abi_msa_bfd;
547
548   /* The abiflags for this object.  */
549   Elf_Internal_ABIFlags_v0 abiflags;
550   bfd_boolean abiflags_valid;
551
552   /* The GOT requirements of input bfds.  */
553   struct mips_got_info *got;
554
555   /* Used by _bfd_mips_elf_find_nearest_line.  The structure could be
556      included directly in this one, but there's no point to wasting
557      the memory just for the infrequently called find_nearest_line.  */
558   struct mips_elf_find_line *find_line_info;
559
560   /* An array of stub sections indexed by symbol number.  */
561   asection **local_stubs;
562   asection **local_call_stubs;
563
564   /* The Irix 5 support uses two virtual sections, which represent
565      text/data symbols defined in dynamic objects.  */
566   asymbol *elf_data_symbol;
567   asymbol *elf_text_symbol;
568   asection *elf_data_section;
569   asection *elf_text_section;
570 };
571
572 /* Get MIPS ELF private object data from BFD's tdata.  */
573
574 #define mips_elf_tdata(bfd) \
575   ((struct mips_elf_obj_tdata *) (bfd)->tdata.any)
576
577 #define TLS_RELOC_P(r_type) \
578   (r_type == R_MIPS_TLS_DTPMOD32                \
579    || r_type == R_MIPS_TLS_DTPMOD64             \
580    || r_type == R_MIPS_TLS_DTPREL32             \
581    || r_type == R_MIPS_TLS_DTPREL64             \
582    || r_type == R_MIPS_TLS_GD                   \
583    || r_type == R_MIPS_TLS_LDM                  \
584    || r_type == R_MIPS_TLS_DTPREL_HI16          \
585    || r_type == R_MIPS_TLS_DTPREL_LO16          \
586    || r_type == R_MIPS_TLS_GOTTPREL             \
587    || r_type == R_MIPS_TLS_TPREL32              \
588    || r_type == R_MIPS_TLS_TPREL64              \
589    || r_type == R_MIPS_TLS_TPREL_HI16           \
590    || r_type == R_MIPS_TLS_TPREL_LO16           \
591    || r_type == R_MIPS16_TLS_GD                 \
592    || r_type == R_MIPS16_TLS_LDM                \
593    || r_type == R_MIPS16_TLS_DTPREL_HI16        \
594    || r_type == R_MIPS16_TLS_DTPREL_LO16        \
595    || r_type == R_MIPS16_TLS_GOTTPREL           \
596    || r_type == R_MIPS16_TLS_TPREL_HI16         \
597    || r_type == R_MIPS16_TLS_TPREL_LO16         \
598    || r_type == R_MICROMIPS_TLS_GD              \
599    || r_type == R_MICROMIPS_TLS_LDM             \
600    || r_type == R_MICROMIPS_TLS_DTPREL_HI16     \
601    || r_type == R_MICROMIPS_TLS_DTPREL_LO16     \
602    || r_type == R_MICROMIPS_TLS_GOTTPREL        \
603    || r_type == R_MICROMIPS_TLS_TPREL_HI16      \
604    || r_type == R_MICROMIPS_TLS_TPREL_LO16)
605
606 /* Structure used to pass information to mips_elf_output_extsym.  */
607
608 struct extsym_info
609 {
610   bfd *abfd;
611   struct bfd_link_info *info;
612   struct ecoff_debug_info *debug;
613   const struct ecoff_debug_swap *swap;
614   bfd_boolean failed;
615 };
616
617 /* The names of the runtime procedure table symbols used on IRIX5.  */
618
619 static const char * const mips_elf_dynsym_rtproc_names[] =
620 {
621   "_procedure_table",
622   "_procedure_string_table",
623   "_procedure_table_size",
624   NULL
625 };
626
627 /* These structures are used to generate the .compact_rel section on
628    IRIX5.  */
629
630 typedef struct
631 {
632   unsigned long id1;            /* Always one?  */
633   unsigned long num;            /* Number of compact relocation entries.  */
634   unsigned long id2;            /* Always two?  */
635   unsigned long offset;         /* The file offset of the first relocation.  */
636   unsigned long reserved0;      /* Zero?  */
637   unsigned long reserved1;      /* Zero?  */
638 } Elf32_compact_rel;
639
640 typedef struct
641 {
642   bfd_byte id1[4];
643   bfd_byte num[4];
644   bfd_byte id2[4];
645   bfd_byte offset[4];
646   bfd_byte reserved0[4];
647   bfd_byte reserved1[4];
648 } Elf32_External_compact_rel;
649
650 typedef struct
651 {
652   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
653   unsigned int rtype : 4;       /* Relocation types. See below.  */
654   unsigned int dist2to : 8;
655   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
656   unsigned long konst;          /* KONST field. See below.  */
657   unsigned long vaddr;          /* VADDR to be relocated.  */
658 } Elf32_crinfo;
659
660 typedef struct
661 {
662   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
663   unsigned int rtype : 4;       /* Relocation types. See below.  */
664   unsigned int dist2to : 8;
665   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
666   unsigned long konst;          /* KONST field. See below.  */
667 } Elf32_crinfo2;
668
669 typedef struct
670 {
671   bfd_byte info[4];
672   bfd_byte konst[4];
673   bfd_byte vaddr[4];
674 } Elf32_External_crinfo;
675
676 typedef struct
677 {
678   bfd_byte info[4];
679   bfd_byte konst[4];
680 } Elf32_External_crinfo2;
681
682 /* These are the constants used to swap the bitfields in a crinfo.  */
683
684 #define CRINFO_CTYPE (0x1)
685 #define CRINFO_CTYPE_SH (31)
686 #define CRINFO_RTYPE (0xf)
687 #define CRINFO_RTYPE_SH (27)
688 #define CRINFO_DIST2TO (0xff)
689 #define CRINFO_DIST2TO_SH (19)
690 #define CRINFO_RELVADDR (0x7ffff)
691 #define CRINFO_RELVADDR_SH (0)
692
693 /* A compact relocation info has long (3 words) or short (2 words)
694    formats.  A short format doesn't have VADDR field and relvaddr
695    fields contains ((VADDR - vaddr of the previous entry) >> 2).  */
696 #define CRF_MIPS_LONG                   1
697 #define CRF_MIPS_SHORT                  0
698
699 /* There are 4 types of compact relocation at least. The value KONST
700    has different meaning for each type:
701
702    (type)               (konst)
703    CT_MIPS_REL32        Address in data
704    CT_MIPS_WORD         Address in word (XXX)
705    CT_MIPS_GPHI_LO      GP - vaddr
706    CT_MIPS_JMPAD        Address to jump
707    */
708
709 #define CRT_MIPS_REL32                  0xa
710 #define CRT_MIPS_WORD                   0xb
711 #define CRT_MIPS_GPHI_LO                0xc
712 #define CRT_MIPS_JMPAD                  0xd
713
714 #define mips_elf_set_cr_format(x,format)        ((x).ctype = (format))
715 #define mips_elf_set_cr_type(x,type)            ((x).rtype = (type))
716 #define mips_elf_set_cr_dist2to(x,v)            ((x).dist2to = (v))
717 #define mips_elf_set_cr_relvaddr(x,d)           ((x).relvaddr = (d)<<2)
718 \f
719 /* The structure of the runtime procedure descriptor created by the
720    loader for use by the static exception system.  */
721
722 typedef struct runtime_pdr {
723         bfd_vma adr;            /* Memory address of start of procedure.  */
724         long    regmask;        /* Save register mask.  */
725         long    regoffset;      /* Save register offset.  */
726         long    fregmask;       /* Save floating point register mask.  */
727         long    fregoffset;     /* Save floating point register offset.  */
728         long    frameoffset;    /* Frame size.  */
729         short   framereg;       /* Frame pointer register.  */
730         short   pcreg;          /* Offset or reg of return pc.  */
731         long    irpss;          /* Index into the runtime string table.  */
732         long    reserved;
733         struct exception_info *exception_info;/* Pointer to exception array.  */
734 } RPDR, *pRPDR;
735 #define cbRPDR sizeof (RPDR)
736 #define rpdNil ((pRPDR) 0)
737 \f
738 static struct mips_got_entry *mips_elf_create_local_got_entry
739   (bfd *, struct bfd_link_info *, bfd *, bfd_vma, unsigned long,
740    struct mips_elf_link_hash_entry *, int);
741 static bfd_boolean mips_elf_sort_hash_table_f
742   (struct mips_elf_link_hash_entry *, void *);
743 static bfd_vma mips_elf_high
744   (bfd_vma);
745 static bfd_boolean mips_elf_create_dynamic_relocation
746   (bfd *, struct bfd_link_info *, const Elf_Internal_Rela *,
747    struct mips_elf_link_hash_entry *, asection *, bfd_vma,
748    bfd_vma *, asection *);
749 static bfd_vma mips_elf_adjust_gp
750   (bfd *, struct mips_got_info *, bfd *);
751
752 /* This will be used when we sort the dynamic relocation records.  */
753 static bfd *reldyn_sorting_bfd;
754
755 /* True if ABFD is for CPUs with load interlocking that include
756    non-MIPS1 CPUs and R3900.  */
757 #define LOAD_INTERLOCKS_P(abfd) \
758   (   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) != E_MIPS_ARCH_1) \
759    || ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_3900))
760
761 /* True if ABFD is for CPUs that are faster if JAL is converted to BAL.
762    This should be safe for all architectures.  We enable this predicate
763    for RM9000 for now.  */
764 #define JAL_TO_BAL_P(abfd) \
765   ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_9000)
766
767 /* True if ABFD is for CPUs that are faster if JALR is converted to BAL.
768    This should be safe for all architectures.  We enable this predicate for
769    all CPUs.  */
770 #define JALR_TO_BAL_P(abfd) 1
771
772 /* True if ABFD is for CPUs that are faster if JR is converted to B.
773    This should be safe for all architectures.  We enable this predicate for
774    all CPUs.  */
775 #define JR_TO_B_P(abfd) 1
776
777 /* True if ABFD is a PIC object.  */
778 #define PIC_OBJECT_P(abfd) \
779   ((elf_elfheader (abfd)->e_flags & EF_MIPS_PIC) != 0)
780
781 /* Nonzero if ABFD is using the O32 ABI.  */
782 #define ABI_O32_P(abfd) \
783   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
784
785 /* Nonzero if ABFD is using the N32 ABI.  */
786 #define ABI_N32_P(abfd) \
787   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI2) != 0)
788
789 /* Nonzero if ABFD is using the N64 ABI.  */
790 #define ABI_64_P(abfd) \
791   (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS64)
792
793 /* Nonzero if ABFD is using NewABI conventions.  */
794 #define NEWABI_P(abfd) (ABI_N32_P (abfd) || ABI_64_P (abfd))
795
796 /* Nonzero if ABFD has microMIPS code.  */
797 #define MICROMIPS_P(abfd) \
798   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS) != 0)
799
800 /* Nonzero if ABFD is MIPS R6.  */
801 #define MIPSR6_P(abfd) \
802   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R6 \
803     || (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R6)
804
805 /* The IRIX compatibility level we are striving for.  */
806 #define IRIX_COMPAT(abfd) \
807   (get_elf_backend_data (abfd)->elf_backend_mips_irix_compat (abfd))
808
809 /* Whether we are trying to be compatible with IRIX at all.  */
810 #define SGI_COMPAT(abfd) \
811   (IRIX_COMPAT (abfd) != ict_none)
812
813 /* The name of the options section.  */
814 #define MIPS_ELF_OPTIONS_SECTION_NAME(abfd) \
815   (NEWABI_P (abfd) ? ".MIPS.options" : ".options")
816
817 /* True if NAME is the recognized name of any SHT_MIPS_OPTIONS section.
818    Some IRIX system files do not use MIPS_ELF_OPTIONS_SECTION_NAME.  */
819 #define MIPS_ELF_OPTIONS_SECTION_NAME_P(NAME) \
820   (strcmp (NAME, ".MIPS.options") == 0 || strcmp (NAME, ".options") == 0)
821
822 /* True if NAME is the recognized name of any SHT_MIPS_ABIFLAGS section.  */
823 #define MIPS_ELF_ABIFLAGS_SECTION_NAME_P(NAME) \
824   (strcmp (NAME, ".MIPS.abiflags") == 0)
825
826 /* Whether the section is readonly.  */
827 #define MIPS_ELF_READONLY_SECTION(sec) \
828   ((sec->flags & (SEC_ALLOC | SEC_LOAD | SEC_READONLY))         \
829    == (SEC_ALLOC | SEC_LOAD | SEC_READONLY))
830
831 /* The name of the stub section.  */
832 #define MIPS_ELF_STUB_SECTION_NAME(abfd) ".MIPS.stubs"
833
834 /* The size of an external REL relocation.  */
835 #define MIPS_ELF_REL_SIZE(abfd) \
836   (get_elf_backend_data (abfd)->s->sizeof_rel)
837
838 /* The size of an external RELA relocation.  */
839 #define MIPS_ELF_RELA_SIZE(abfd) \
840   (get_elf_backend_data (abfd)->s->sizeof_rela)
841
842 /* The size of an external dynamic table entry.  */
843 #define MIPS_ELF_DYN_SIZE(abfd) \
844   (get_elf_backend_data (abfd)->s->sizeof_dyn)
845
846 /* The size of a GOT entry.  */
847 #define MIPS_ELF_GOT_SIZE(abfd) \
848   (get_elf_backend_data (abfd)->s->arch_size / 8)
849
850 /* The size of the .rld_map section. */
851 #define MIPS_ELF_RLD_MAP_SIZE(abfd) \
852   (get_elf_backend_data (abfd)->s->arch_size / 8)
853
854 /* The size of a symbol-table entry.  */
855 #define MIPS_ELF_SYM_SIZE(abfd) \
856   (get_elf_backend_data (abfd)->s->sizeof_sym)
857
858 /* The default alignment for sections, as a power of two.  */
859 #define MIPS_ELF_LOG_FILE_ALIGN(abfd)                           \
860   (get_elf_backend_data (abfd)->s->log_file_align)
861
862 /* Get word-sized data.  */
863 #define MIPS_ELF_GET_WORD(abfd, ptr) \
864   (ABI_64_P (abfd) ? bfd_get_64 (abfd, ptr) : bfd_get_32 (abfd, ptr))
865
866 /* Put out word-sized data.  */
867 #define MIPS_ELF_PUT_WORD(abfd, val, ptr)       \
868   (ABI_64_P (abfd)                              \
869    ? bfd_put_64 (abfd, val, ptr)                \
870    : bfd_put_32 (abfd, val, ptr))
871
872 /* The opcode for word-sized loads (LW or LD).  */
873 #define MIPS_ELF_LOAD_WORD(abfd) \
874   (ABI_64_P (abfd) ? 0xdc000000 : 0x8c000000)
875
876 /* Add a dynamic symbol table-entry.  */
877 #define MIPS_ELF_ADD_DYNAMIC_ENTRY(info, tag, val)      \
878   _bfd_elf_add_dynamic_entry (info, tag, val)
879
880 #define MIPS_ELF_RTYPE_TO_HOWTO(abfd, rtype, rela)                      \
881   (get_elf_backend_data (abfd)->elf_backend_mips_rtype_to_howto (rtype, rela))
882
883 /* The name of the dynamic relocation section.  */
884 #define MIPS_ELF_REL_DYN_NAME(INFO) \
885   (mips_elf_hash_table (INFO)->is_vxworks ? ".rela.dyn" : ".rel.dyn")
886
887 /* In case we're on a 32-bit machine, construct a 64-bit "-1" value
888    from smaller values.  Start with zero, widen, *then* decrement.  */
889 #define MINUS_ONE       (((bfd_vma)0) - 1)
890 #define MINUS_TWO       (((bfd_vma)0) - 2)
891
892 /* The value to write into got[1] for SVR4 targets, to identify it is
893    a GNU object.  The dynamic linker can then use got[1] to store the
894    module pointer.  */
895 #define MIPS_ELF_GNU_GOT1_MASK(abfd) \
896   ((bfd_vma) 1 << (ABI_64_P (abfd) ? 63 : 31))
897
898 /* The offset of $gp from the beginning of the .got section.  */
899 #define ELF_MIPS_GP_OFFSET(INFO) \
900   (mips_elf_hash_table (INFO)->is_vxworks ? 0x0 : 0x7ff0)
901
902 /* The maximum size of the GOT for it to be addressable using 16-bit
903    offsets from $gp.  */
904 #define MIPS_ELF_GOT_MAX_SIZE(INFO) (ELF_MIPS_GP_OFFSET (INFO) + 0x7fff)
905
906 /* Instructions which appear in a stub.  */
907 #define STUB_LW(abfd)                                                   \
908   ((ABI_64_P (abfd)                                                     \
909     ? 0xdf998010                                /* ld t9,0x8010(gp) */  \
910     : 0x8f998010))                              /* lw t9,0x8010(gp) */
911 #define STUB_MOVE 0x03e07825                    /* or t7,ra,zero */
912 #define STUB_LUI(VAL) (0x3c180000 + (VAL))      /* lui t8,VAL */
913 #define STUB_JALR 0x0320f809                    /* jalr ra,t9 */
914 #define STUB_ORI(VAL) (0x37180000 + (VAL))      /* ori t8,t8,VAL */
915 #define STUB_LI16U(VAL) (0x34180000 + (VAL))    /* ori t8,zero,VAL unsigned */
916 #define STUB_LI16S(abfd, VAL)                                           \
917    ((ABI_64_P (abfd)                                                    \
918     ? (0x64180000 + (VAL))      /* daddiu t8,zero,VAL sign extended */  \
919     : (0x24180000 + (VAL))))    /* addiu t8,zero,VAL sign extended */
920
921 /* Likewise for the microMIPS ASE.  */
922 #define STUB_LW_MICROMIPS(abfd)                                         \
923   (ABI_64_P (abfd)                                                      \
924    ? 0xdf3c8010                                 /* ld t9,0x8010(gp) */  \
925    : 0xff3c8010)                                /* lw t9,0x8010(gp) */
926 #define STUB_MOVE_MICROMIPS 0x0dff              /* move t7,ra */
927 #define STUB_MOVE32_MICROMIPS 0x001f7a90        /* or t7,ra,zero */
928 #define STUB_LUI_MICROMIPS(VAL)                                         \
929    (0x41b80000 + (VAL))                         /* lui t8,VAL */
930 #define STUB_JALR_MICROMIPS 0x45d9              /* jalr t9 */
931 #define STUB_JALR32_MICROMIPS 0x03f90f3c        /* jalr ra,t9 */
932 #define STUB_ORI_MICROMIPS(VAL)                                         \
933   (0x53180000 + (VAL))                          /* ori t8,t8,VAL */
934 #define STUB_LI16U_MICROMIPS(VAL)                                       \
935   (0x53000000 + (VAL))                          /* ori t8,zero,VAL unsigned */
936 #define STUB_LI16S_MICROMIPS(abfd, VAL)                                 \
937    (ABI_64_P (abfd)                                                     \
938     ? 0x5f000000 + (VAL)        /* daddiu t8,zero,VAL sign extended */  \
939     : 0x33000000 + (VAL))       /* addiu t8,zero,VAL sign extended */
940
941 #define MIPS_FUNCTION_STUB_NORMAL_SIZE 16
942 #define MIPS_FUNCTION_STUB_BIG_SIZE 20
943 #define MICROMIPS_FUNCTION_STUB_NORMAL_SIZE 12
944 #define MICROMIPS_FUNCTION_STUB_BIG_SIZE 16
945 #define MICROMIPS_INSN32_FUNCTION_STUB_NORMAL_SIZE 16
946 #define MICROMIPS_INSN32_FUNCTION_STUB_BIG_SIZE 20
947
948 /* The name of the dynamic interpreter.  This is put in the .interp
949    section.  */
950
951 #define ELF_DYNAMIC_INTERPRETER(abfd)           \
952    (ABI_N32_P (abfd) ? "/usr/lib32/libc.so.1"   \
953     : ABI_64_P (abfd) ? "/usr/lib64/libc.so.1"  \
954     : "/usr/lib/libc.so.1")
955
956 #ifdef BFD64
957 #define MNAME(bfd,pre,pos) \
958   (ABI_64_P (bfd) ? CONCAT4 (pre,64,_,pos) : CONCAT4 (pre,32,_,pos))
959 #define ELF_R_SYM(bfd, i)                                       \
960   (ABI_64_P (bfd) ? ELF64_R_SYM (i) : ELF32_R_SYM (i))
961 #define ELF_R_TYPE(bfd, i)                                      \
962   (ABI_64_P (bfd) ? ELF64_MIPS_R_TYPE (i) : ELF32_R_TYPE (i))
963 #define ELF_R_INFO(bfd, s, t)                                   \
964   (ABI_64_P (bfd) ? ELF64_R_INFO (s, t) : ELF32_R_INFO (s, t))
965 #else
966 #define MNAME(bfd,pre,pos) CONCAT4 (pre,32,_,pos)
967 #define ELF_R_SYM(bfd, i)                                       \
968   (ELF32_R_SYM (i))
969 #define ELF_R_TYPE(bfd, i)                                      \
970   (ELF32_R_TYPE (i))
971 #define ELF_R_INFO(bfd, s, t)                                   \
972   (ELF32_R_INFO (s, t))
973 #endif
974 \f
975   /* The mips16 compiler uses a couple of special sections to handle
976      floating point arguments.
977
978      Section names that look like .mips16.fn.FNNAME contain stubs that
979      copy floating point arguments from the fp regs to the gp regs and
980      then jump to FNNAME.  If any 32 bit function calls FNNAME, the
981      call should be redirected to the stub instead.  If no 32 bit
982      function calls FNNAME, the stub should be discarded.  We need to
983      consider any reference to the function, not just a call, because
984      if the address of the function is taken we will need the stub,
985      since the address might be passed to a 32 bit function.
986
987      Section names that look like .mips16.call.FNNAME contain stubs
988      that copy floating point arguments from the gp regs to the fp
989      regs and then jump to FNNAME.  If FNNAME is a 32 bit function,
990      then any 16 bit function that calls FNNAME should be redirected
991      to the stub instead.  If FNNAME is not a 32 bit function, the
992      stub should be discarded.
993
994      .mips16.call.fp.FNNAME sections are similar, but contain stubs
995      which call FNNAME and then copy the return value from the fp regs
996      to the gp regs.  These stubs store the return value in $18 while
997      calling FNNAME; any function which might call one of these stubs
998      must arrange to save $18 around the call.  (This case is not
999      needed for 32 bit functions that call 16 bit functions, because
1000      16 bit functions always return floating point values in both
1001      $f0/$f1 and $2/$3.)
1002
1003      Note that in all cases FNNAME might be defined statically.
1004      Therefore, FNNAME is not used literally.  Instead, the relocation
1005      information will indicate which symbol the section is for.
1006
1007      We record any stubs that we find in the symbol table.  */
1008
1009 #define FN_STUB ".mips16.fn."
1010 #define CALL_STUB ".mips16.call."
1011 #define CALL_FP_STUB ".mips16.call.fp."
1012
1013 #define FN_STUB_P(name) CONST_STRNEQ (name, FN_STUB)
1014 #define CALL_STUB_P(name) CONST_STRNEQ (name, CALL_STUB)
1015 #define CALL_FP_STUB_P(name) CONST_STRNEQ (name, CALL_FP_STUB)
1016 \f
1017 /* The format of the first PLT entry in an O32 executable.  */
1018 static const bfd_vma mips_o32_exec_plt0_entry[] =
1019 {
1020   0x3c1c0000,   /* lui $28, %hi(&GOTPLT[0])                             */
1021   0x8f990000,   /* lw $25, %lo(&GOTPLT[0])($28)                         */
1022   0x279c0000,   /* addiu $28, $28, %lo(&GOTPLT[0])                      */
1023   0x031cc023,   /* subu $24, $24, $28                                   */
1024   0x03e07825,   /* or t7, ra, zero                                      */
1025   0x0018c082,   /* srl $24, $24, 2                                      */
1026   0x0320f809,   /* jalr $25                                             */
1027   0x2718fffe    /* subu $24, $24, 2                                     */
1028 };
1029
1030 /* The format of the first PLT entry in an N32 executable.  Different
1031    because gp ($28) is not available; we use t2 ($14) instead.  */
1032 static const bfd_vma mips_n32_exec_plt0_entry[] =
1033 {
1034   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
1035   0x8dd90000,   /* lw $25, %lo(&GOTPLT[0])($14)                         */
1036   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
1037   0x030ec023,   /* subu $24, $24, $14                                   */
1038   0x03e07825,   /* or t7, ra, zero                                      */
1039   0x0018c082,   /* srl $24, $24, 2                                      */
1040   0x0320f809,   /* jalr $25                                             */
1041   0x2718fffe    /* subu $24, $24, 2                                     */
1042 };
1043
1044 /* The format of the first PLT entry in an N64 executable.  Different
1045    from N32 because of the increased size of GOT entries.  */
1046 static const bfd_vma mips_n64_exec_plt0_entry[] =
1047 {
1048   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
1049   0xddd90000,   /* ld $25, %lo(&GOTPLT[0])($14)                         */
1050   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
1051   0x030ec023,   /* subu $24, $24, $14                                   */
1052   0x03e07825,   /* or t7, ra, zero                                      */
1053   0x0018c0c2,   /* srl $24, $24, 3                                      */
1054   0x0320f809,   /* jalr $25                                             */
1055   0x2718fffe    /* subu $24, $24, 2                                     */
1056 };
1057
1058 /* The format of the microMIPS first PLT entry in an O32 executable.
1059    We rely on v0 ($2) rather than t8 ($24) to contain the address
1060    of the GOTPLT entry handled, so this stub may only be used when
1061    all the subsequent PLT entries are microMIPS code too.
1062
1063    The trailing NOP is for alignment and correct disassembly only.  */
1064 static const bfd_vma micromips_o32_exec_plt0_entry[] =
1065 {
1066   0x7980, 0x0000,       /* addiupc $3, (&GOTPLT[0]) - .                 */
1067   0xff23, 0x0000,       /* lw $25, 0($3)                                */
1068   0x0535,               /* subu $2, $2, $3                              */
1069   0x2525,               /* srl $2, $2, 2                                */
1070   0x3302, 0xfffe,       /* subu $24, $2, 2                              */
1071   0x0dff,               /* move $15, $31                                */
1072   0x45f9,               /* jalrs $25                                    */
1073   0x0f83,               /* move $28, $3                                 */
1074   0x0c00                /* nop                                          */
1075 };
1076
1077 /* The format of the microMIPS first PLT entry in an O32 executable
1078    in the insn32 mode.  */
1079 static const bfd_vma micromips_insn32_o32_exec_plt0_entry[] =
1080 {
1081   0x41bc, 0x0000,       /* lui $28, %hi(&GOTPLT[0])                     */
1082   0xff3c, 0x0000,       /* lw $25, %lo(&GOTPLT[0])($28)                 */
1083   0x339c, 0x0000,       /* addiu $28, $28, %lo(&GOTPLT[0])              */
1084   0x0398, 0xc1d0,       /* subu $24, $24, $28                           */
1085   0x001f, 0x7a90,       /* or $15, $31, zero                            */
1086   0x0318, 0x1040,       /* srl $24, $24, 2                              */
1087   0x03f9, 0x0f3c,       /* jalr $25                                     */
1088   0x3318, 0xfffe        /* subu $24, $24, 2                             */
1089 };
1090
1091 /* The format of subsequent standard PLT entries.  */
1092 static const bfd_vma mips_exec_plt_entry[] =
1093 {
1094   0x3c0f0000,   /* lui $15, %hi(.got.plt entry)                 */
1095   0x01f90000,   /* l[wd] $25, %lo(.got.plt entry)($15)          */
1096   0x25f80000,   /* addiu $24, $15, %lo(.got.plt entry)          */
1097   0x03200008    /* jr $25                                       */
1098 };
1099
1100 /* In the following PLT entry the JR and ADDIU instructions will
1101    be swapped in _bfd_mips_elf_finish_dynamic_symbol because
1102    LOAD_INTERLOCKS_P will be true for MIPS R6.  */
1103 static const bfd_vma mipsr6_exec_plt_entry[] =
1104 {
1105   0x3c0f0000,   /* lui $15, %hi(.got.plt entry)                 */
1106   0x01f90000,   /* l[wd] $25, %lo(.got.plt entry)($15)          */
1107   0x25f80000,   /* addiu $24, $15, %lo(.got.plt entry)          */
1108   0x03200009    /* jr $25                                       */
1109 };
1110
1111 /* The format of subsequent MIPS16 o32 PLT entries.  We use v0 ($2)
1112    and v1 ($3) as temporaries because t8 ($24) and t9 ($25) are not
1113    directly addressable.  */
1114 static const bfd_vma mips16_o32_exec_plt_entry[] =
1115 {
1116   0xb203,               /* lw $2, 12($pc)                       */
1117   0x9a60,               /* lw $3, 0($2)                         */
1118   0x651a,               /* move $24, $2                         */
1119   0xeb00,               /* jr $3                                */
1120   0x653b,               /* move $25, $3                         */
1121   0x6500,               /* nop                                  */
1122   0x0000, 0x0000        /* .word (.got.plt entry)               */
1123 };
1124
1125 /* The format of subsequent microMIPS o32 PLT entries.  We use v0 ($2)
1126    as a temporary because t8 ($24) is not addressable with ADDIUPC.  */
1127 static const bfd_vma micromips_o32_exec_plt_entry[] =
1128 {
1129   0x7900, 0x0000,       /* addiupc $2, (.got.plt entry) - .     */
1130   0xff22, 0x0000,       /* lw $25, 0($2)                        */
1131   0x4599,               /* jr $25                               */
1132   0x0f02                /* move $24, $2                         */
1133 };
1134
1135 /* The format of subsequent microMIPS o32 PLT entries in the insn32 mode.  */
1136 static const bfd_vma micromips_insn32_o32_exec_plt_entry[] =
1137 {
1138   0x41af, 0x0000,       /* lui $15, %hi(.got.plt entry)         */
1139   0xff2f, 0x0000,       /* lw $25, %lo(.got.plt entry)($15)     */
1140   0x0019, 0x0f3c,       /* jr $25                               */
1141   0x330f, 0x0000        /* addiu $24, $15, %lo(.got.plt entry)  */
1142 };
1143
1144 /* The format of the first PLT entry in a VxWorks executable.  */
1145 static const bfd_vma mips_vxworks_exec_plt0_entry[] =
1146 {
1147   0x3c190000,   /* lui t9, %hi(_GLOBAL_OFFSET_TABLE_)           */
1148   0x27390000,   /* addiu t9, t9, %lo(_GLOBAL_OFFSET_TABLE_)     */
1149   0x8f390008,   /* lw t9, 8(t9)                                 */
1150   0x00000000,   /* nop                                          */
1151   0x03200008,   /* jr t9                                        */
1152   0x00000000    /* nop                                          */
1153 };
1154
1155 /* The format of subsequent PLT entries.  */
1156 static const bfd_vma mips_vxworks_exec_plt_entry[] =
1157 {
1158   0x10000000,   /* b .PLT_resolver                      */
1159   0x24180000,   /* li t8, <pltindex>                    */
1160   0x3c190000,   /* lui t9, %hi(<.got.plt slot>)         */
1161   0x27390000,   /* addiu t9, t9, %lo(<.got.plt slot>)   */
1162   0x8f390000,   /* lw t9, 0(t9)                         */
1163   0x00000000,   /* nop                                  */
1164   0x03200008,   /* jr t9                                */
1165   0x00000000    /* nop                                  */
1166 };
1167
1168 /* The format of the first PLT entry in a VxWorks shared object.  */
1169 static const bfd_vma mips_vxworks_shared_plt0_entry[] =
1170 {
1171   0x8f990008,   /* lw t9, 8(gp)         */
1172   0x00000000,   /* nop                  */
1173   0x03200008,   /* jr t9                */
1174   0x00000000,   /* nop                  */
1175   0x00000000,   /* nop                  */
1176   0x00000000    /* nop                  */
1177 };
1178
1179 /* The format of subsequent PLT entries.  */
1180 static const bfd_vma mips_vxworks_shared_plt_entry[] =
1181 {
1182   0x10000000,   /* b .PLT_resolver      */
1183   0x24180000    /* li t8, <pltindex>    */
1184 };
1185 \f
1186 /* microMIPS 32-bit opcode helper installer.  */
1187
1188 static void
1189 bfd_put_micromips_32 (const bfd *abfd, bfd_vma opcode, bfd_byte *ptr)
1190 {
1191   bfd_put_16 (abfd, (opcode >> 16) & 0xffff, ptr);
1192   bfd_put_16 (abfd,  opcode        & 0xffff, ptr + 2);
1193 }
1194
1195 /* microMIPS 32-bit opcode helper retriever.  */
1196
1197 static bfd_vma
1198 bfd_get_micromips_32 (const bfd *abfd, const bfd_byte *ptr)
1199 {
1200   return (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
1201 }
1202 \f
1203 /* Look up an entry in a MIPS ELF linker hash table.  */
1204
1205 #define mips_elf_link_hash_lookup(table, string, create, copy, follow)  \
1206   ((struct mips_elf_link_hash_entry *)                                  \
1207    elf_link_hash_lookup (&(table)->root, (string), (create),            \
1208                          (copy), (follow)))
1209
1210 /* Traverse a MIPS ELF linker hash table.  */
1211
1212 #define mips_elf_link_hash_traverse(table, func, info)                  \
1213   (elf_link_hash_traverse                                               \
1214    (&(table)->root,                                                     \
1215     (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func),    \
1216     (info)))
1217
1218 /* Find the base offsets for thread-local storage in this object,
1219    for GD/LD and IE/LE respectively.  */
1220
1221 #define TP_OFFSET 0x7000
1222 #define DTP_OFFSET 0x8000
1223
1224 static bfd_vma
1225 dtprel_base (struct bfd_link_info *info)
1226 {
1227   /* If tls_sec is NULL, we should have signalled an error already.  */
1228   if (elf_hash_table (info)->tls_sec == NULL)
1229     return 0;
1230   return elf_hash_table (info)->tls_sec->vma + DTP_OFFSET;
1231 }
1232
1233 static bfd_vma
1234 tprel_base (struct bfd_link_info *info)
1235 {
1236   /* If tls_sec is NULL, we should have signalled an error already.  */
1237   if (elf_hash_table (info)->tls_sec == NULL)
1238     return 0;
1239   return elf_hash_table (info)->tls_sec->vma + TP_OFFSET;
1240 }
1241
1242 /* Create an entry in a MIPS ELF linker hash table.  */
1243
1244 static struct bfd_hash_entry *
1245 mips_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
1246                             struct bfd_hash_table *table, const char *string)
1247 {
1248   struct mips_elf_link_hash_entry *ret =
1249     (struct mips_elf_link_hash_entry *) entry;
1250
1251   /* Allocate the structure if it has not already been allocated by a
1252      subclass.  */
1253   if (ret == NULL)
1254     ret = bfd_hash_allocate (table, sizeof (struct mips_elf_link_hash_entry));
1255   if (ret == NULL)
1256     return (struct bfd_hash_entry *) ret;
1257
1258   /* Call the allocation method of the superclass.  */
1259   ret = ((struct mips_elf_link_hash_entry *)
1260          _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret,
1261                                      table, string));
1262   if (ret != NULL)
1263     {
1264       /* Set local fields.  */
1265       memset (&ret->esym, 0, sizeof (EXTR));
1266       /* We use -2 as a marker to indicate that the information has
1267          not been set.  -1 means there is no associated ifd.  */
1268       ret->esym.ifd = -2;
1269       ret->la25_stub = 0;
1270       ret->possibly_dynamic_relocs = 0;
1271       ret->fn_stub = NULL;
1272       ret->call_stub = NULL;
1273       ret->call_fp_stub = NULL;
1274       ret->global_got_area = GGA_NONE;
1275       ret->got_only_for_calls = TRUE;
1276       ret->readonly_reloc = FALSE;
1277       ret->has_static_relocs = FALSE;
1278       ret->no_fn_stub = FALSE;
1279       ret->need_fn_stub = FALSE;
1280       ret->has_nonpic_branches = FALSE;
1281       ret->needs_lazy_stub = FALSE;
1282       ret->use_plt_entry = FALSE;
1283     }
1284
1285   return (struct bfd_hash_entry *) ret;
1286 }
1287
1288 /* Allocate MIPS ELF private object data.  */
1289
1290 bfd_boolean
1291 _bfd_mips_elf_mkobject (bfd *abfd)
1292 {
1293   return bfd_elf_allocate_object (abfd, sizeof (struct mips_elf_obj_tdata),
1294                                   MIPS_ELF_DATA);
1295 }
1296
1297 bfd_boolean
1298 _bfd_mips_elf_new_section_hook (bfd *abfd, asection *sec)
1299 {
1300   if (!sec->used_by_bfd)
1301     {
1302       struct _mips_elf_section_data *sdata;
1303       bfd_size_type amt = sizeof (*sdata);
1304
1305       sdata = bfd_zalloc (abfd, amt);
1306       if (sdata == NULL)
1307         return FALSE;
1308       sec->used_by_bfd = sdata;
1309     }
1310
1311   return _bfd_elf_new_section_hook (abfd, sec);
1312 }
1313 \f
1314 /* Read ECOFF debugging information from a .mdebug section into a
1315    ecoff_debug_info structure.  */
1316
1317 bfd_boolean
1318 _bfd_mips_elf_read_ecoff_info (bfd *abfd, asection *section,
1319                                struct ecoff_debug_info *debug)
1320 {
1321   HDRR *symhdr;
1322   const struct ecoff_debug_swap *swap;
1323   char *ext_hdr;
1324
1325   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1326   memset (debug, 0, sizeof (*debug));
1327
1328   ext_hdr = bfd_malloc (swap->external_hdr_size);
1329   if (ext_hdr == NULL && swap->external_hdr_size != 0)
1330     goto error_return;
1331
1332   if (! bfd_get_section_contents (abfd, section, ext_hdr, 0,
1333                                   swap->external_hdr_size))
1334     goto error_return;
1335
1336   symhdr = &debug->symbolic_header;
1337   (*swap->swap_hdr_in) (abfd, ext_hdr, symhdr);
1338
1339   /* The symbolic header contains absolute file offsets and sizes to
1340      read.  */
1341 #define READ(ptr, offset, count, size, type)                            \
1342   if (symhdr->count == 0)                                               \
1343     debug->ptr = NULL;                                                  \
1344   else                                                                  \
1345     {                                                                   \
1346       bfd_size_type amt = (bfd_size_type) size * symhdr->count;         \
1347       debug->ptr = bfd_malloc (amt);                                    \
1348       if (debug->ptr == NULL)                                           \
1349         goto error_return;                                              \
1350       if (bfd_seek (abfd, symhdr->offset, SEEK_SET) != 0                \
1351           || bfd_bread (debug->ptr, amt, abfd) != amt)                  \
1352         goto error_return;                                              \
1353     }
1354
1355   READ (line, cbLineOffset, cbLine, sizeof (unsigned char), unsigned char *);
1356   READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *);
1357   READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *);
1358   READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *);
1359   READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *);
1360   READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext),
1361         union aux_ext *);
1362   READ (ss, cbSsOffset, issMax, sizeof (char), char *);
1363   READ (ssext, cbSsExtOffset, issExtMax, sizeof (char), char *);
1364   READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *);
1365   READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *);
1366   READ (external_ext, cbExtOffset, iextMax, swap->external_ext_size, void *);
1367 #undef READ
1368
1369   debug->fdr = NULL;
1370
1371   return TRUE;
1372
1373  error_return:
1374   if (ext_hdr != NULL)
1375     free (ext_hdr);
1376   if (debug->line != NULL)
1377     free (debug->line);
1378   if (debug->external_dnr != NULL)
1379     free (debug->external_dnr);
1380   if (debug->external_pdr != NULL)
1381     free (debug->external_pdr);
1382   if (debug->external_sym != NULL)
1383     free (debug->external_sym);
1384   if (debug->external_opt != NULL)
1385     free (debug->external_opt);
1386   if (debug->external_aux != NULL)
1387     free (debug->external_aux);
1388   if (debug->ss != NULL)
1389     free (debug->ss);
1390   if (debug->ssext != NULL)
1391     free (debug->ssext);
1392   if (debug->external_fdr != NULL)
1393     free (debug->external_fdr);
1394   if (debug->external_rfd != NULL)
1395     free (debug->external_rfd);
1396   if (debug->external_ext != NULL)
1397     free (debug->external_ext);
1398   return FALSE;
1399 }
1400 \f
1401 /* Swap RPDR (runtime procedure table entry) for output.  */
1402
1403 static void
1404 ecoff_swap_rpdr_out (bfd *abfd, const RPDR *in, struct rpdr_ext *ex)
1405 {
1406   H_PUT_S32 (abfd, in->adr, ex->p_adr);
1407   H_PUT_32 (abfd, in->regmask, ex->p_regmask);
1408   H_PUT_32 (abfd, in->regoffset, ex->p_regoffset);
1409   H_PUT_32 (abfd, in->fregmask, ex->p_fregmask);
1410   H_PUT_32 (abfd, in->fregoffset, ex->p_fregoffset);
1411   H_PUT_32 (abfd, in->frameoffset, ex->p_frameoffset);
1412
1413   H_PUT_16 (abfd, in->framereg, ex->p_framereg);
1414   H_PUT_16 (abfd, in->pcreg, ex->p_pcreg);
1415
1416   H_PUT_32 (abfd, in->irpss, ex->p_irpss);
1417 }
1418
1419 /* Create a runtime procedure table from the .mdebug section.  */
1420
1421 static bfd_boolean
1422 mips_elf_create_procedure_table (void *handle, bfd *abfd,
1423                                  struct bfd_link_info *info, asection *s,
1424                                  struct ecoff_debug_info *debug)
1425 {
1426   const struct ecoff_debug_swap *swap;
1427   HDRR *hdr = &debug->symbolic_header;
1428   RPDR *rpdr, *rp;
1429   struct rpdr_ext *erp;
1430   void *rtproc;
1431   struct pdr_ext *epdr;
1432   struct sym_ext *esym;
1433   char *ss, **sv;
1434   char *str;
1435   bfd_size_type size;
1436   bfd_size_type count;
1437   unsigned long sindex;
1438   unsigned long i;
1439   PDR pdr;
1440   SYMR sym;
1441   const char *no_name_func = _("static procedure (no name)");
1442
1443   epdr = NULL;
1444   rpdr = NULL;
1445   esym = NULL;
1446   ss = NULL;
1447   sv = NULL;
1448
1449   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1450
1451   sindex = strlen (no_name_func) + 1;
1452   count = hdr->ipdMax;
1453   if (count > 0)
1454     {
1455       size = swap->external_pdr_size;
1456
1457       epdr = bfd_malloc (size * count);
1458       if (epdr == NULL)
1459         goto error_return;
1460
1461       if (! _bfd_ecoff_get_accumulated_pdr (handle, (bfd_byte *) epdr))
1462         goto error_return;
1463
1464       size = sizeof (RPDR);
1465       rp = rpdr = bfd_malloc (size * count);
1466       if (rpdr == NULL)
1467         goto error_return;
1468
1469       size = sizeof (char *);
1470       sv = bfd_malloc (size * count);
1471       if (sv == NULL)
1472         goto error_return;
1473
1474       count = hdr->isymMax;
1475       size = swap->external_sym_size;
1476       esym = bfd_malloc (size * count);
1477       if (esym == NULL)
1478         goto error_return;
1479
1480       if (! _bfd_ecoff_get_accumulated_sym (handle, (bfd_byte *) esym))
1481         goto error_return;
1482
1483       count = hdr->issMax;
1484       ss = bfd_malloc (count);
1485       if (ss == NULL)
1486         goto error_return;
1487       if (! _bfd_ecoff_get_accumulated_ss (handle, (bfd_byte *) ss))
1488         goto error_return;
1489
1490       count = hdr->ipdMax;
1491       for (i = 0; i < (unsigned long) count; i++, rp++)
1492         {
1493           (*swap->swap_pdr_in) (abfd, epdr + i, &pdr);
1494           (*swap->swap_sym_in) (abfd, &esym[pdr.isym], &sym);
1495           rp->adr = sym.value;
1496           rp->regmask = pdr.regmask;
1497           rp->regoffset = pdr.regoffset;
1498           rp->fregmask = pdr.fregmask;
1499           rp->fregoffset = pdr.fregoffset;
1500           rp->frameoffset = pdr.frameoffset;
1501           rp->framereg = pdr.framereg;
1502           rp->pcreg = pdr.pcreg;
1503           rp->irpss = sindex;
1504           sv[i] = ss + sym.iss;
1505           sindex += strlen (sv[i]) + 1;
1506         }
1507     }
1508
1509   size = sizeof (struct rpdr_ext) * (count + 2) + sindex;
1510   size = BFD_ALIGN (size, 16);
1511   rtproc = bfd_alloc (abfd, size);
1512   if (rtproc == NULL)
1513     {
1514       mips_elf_hash_table (info)->procedure_count = 0;
1515       goto error_return;
1516     }
1517
1518   mips_elf_hash_table (info)->procedure_count = count + 2;
1519
1520   erp = rtproc;
1521   memset (erp, 0, sizeof (struct rpdr_ext));
1522   erp++;
1523   str = (char *) rtproc + sizeof (struct rpdr_ext) * (count + 2);
1524   strcpy (str, no_name_func);
1525   str += strlen (no_name_func) + 1;
1526   for (i = 0; i < count; i++)
1527     {
1528       ecoff_swap_rpdr_out (abfd, rpdr + i, erp + i);
1529       strcpy (str, sv[i]);
1530       str += strlen (sv[i]) + 1;
1531     }
1532   H_PUT_S32 (abfd, -1, (erp + count)->p_adr);
1533
1534   /* Set the size and contents of .rtproc section.  */
1535   s->size = size;
1536   s->contents = rtproc;
1537
1538   /* Skip this section later on (I don't think this currently
1539      matters, but someday it might).  */
1540   s->map_head.link_order = NULL;
1541
1542   if (epdr != NULL)
1543     free (epdr);
1544   if (rpdr != NULL)
1545     free (rpdr);
1546   if (esym != NULL)
1547     free (esym);
1548   if (ss != NULL)
1549     free (ss);
1550   if (sv != NULL)
1551     free (sv);
1552
1553   return TRUE;
1554
1555  error_return:
1556   if (epdr != NULL)
1557     free (epdr);
1558   if (rpdr != NULL)
1559     free (rpdr);
1560   if (esym != NULL)
1561     free (esym);
1562   if (ss != NULL)
1563     free (ss);
1564   if (sv != NULL)
1565     free (sv);
1566   return FALSE;
1567 }
1568 \f
1569 /* We're going to create a stub for H.  Create a symbol for the stub's
1570    value and size, to help make the disassembly easier to read.  */
1571
1572 static bfd_boolean
1573 mips_elf_create_stub_symbol (struct bfd_link_info *info,
1574                              struct mips_elf_link_hash_entry *h,
1575                              const char *prefix, asection *s, bfd_vma value,
1576                              bfd_vma size)
1577 {
1578   bfd_boolean micromips_p = ELF_ST_IS_MICROMIPS (h->root.other);
1579   struct bfd_link_hash_entry *bh;
1580   struct elf_link_hash_entry *elfh;
1581   char *name;
1582   bfd_boolean res;
1583
1584   if (micromips_p)
1585     value |= 1;
1586
1587   /* Create a new symbol.  */
1588   name = concat (prefix, h->root.root.root.string, NULL);
1589   bh = NULL;
1590   res = _bfd_generic_link_add_one_symbol (info, s->owner, name,
1591                                           BSF_LOCAL, s, value, NULL,
1592                                           TRUE, FALSE, &bh);
1593   free (name);
1594   if (! res)
1595     return FALSE;
1596
1597   /* Make it a local function.  */
1598   elfh = (struct elf_link_hash_entry *) bh;
1599   elfh->type = ELF_ST_INFO (STB_LOCAL, STT_FUNC);
1600   elfh->size = size;
1601   elfh->forced_local = 1;
1602   if (micromips_p)
1603     elfh->other = ELF_ST_SET_MICROMIPS (elfh->other);
1604   return TRUE;
1605 }
1606
1607 /* We're about to redefine H.  Create a symbol to represent H's
1608    current value and size, to help make the disassembly easier
1609    to read.  */
1610
1611 static bfd_boolean
1612 mips_elf_create_shadow_symbol (struct bfd_link_info *info,
1613                                struct mips_elf_link_hash_entry *h,
1614                                const char *prefix)
1615 {
1616   struct bfd_link_hash_entry *bh;
1617   struct elf_link_hash_entry *elfh;
1618   char *name;
1619   asection *s;
1620   bfd_vma value;
1621   bfd_boolean res;
1622
1623   /* Read the symbol's value.  */
1624   BFD_ASSERT (h->root.root.type == bfd_link_hash_defined
1625               || h->root.root.type == bfd_link_hash_defweak);
1626   s = h->root.root.u.def.section;
1627   value = h->root.root.u.def.value;
1628
1629   /* Create a new symbol.  */
1630   name = concat (prefix, h->root.root.root.string, NULL);
1631   bh = NULL;
1632   res = _bfd_generic_link_add_one_symbol (info, s->owner, name,
1633                                           BSF_LOCAL, s, value, NULL,
1634                                           TRUE, FALSE, &bh);
1635   free (name);
1636   if (! res)
1637     return FALSE;
1638
1639   /* Make it local and copy the other attributes from H.  */
1640   elfh = (struct elf_link_hash_entry *) bh;
1641   elfh->type = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (h->root.type));
1642   elfh->other = h->root.other;
1643   elfh->size = h->root.size;
1644   elfh->forced_local = 1;
1645   return TRUE;
1646 }
1647
1648 /* Return TRUE if relocations in SECTION can refer directly to a MIPS16
1649    function rather than to a hard-float stub.  */
1650
1651 static bfd_boolean
1652 section_allows_mips16_refs_p (asection *section)
1653 {
1654   const char *name;
1655
1656   name = bfd_get_section_name (section->owner, section);
1657   return (FN_STUB_P (name)
1658           || CALL_STUB_P (name)
1659           || CALL_FP_STUB_P (name)
1660           || strcmp (name, ".pdr") == 0);
1661 }
1662
1663 /* [RELOCS, RELEND) are the relocations against SEC, which is a MIPS16
1664    stub section of some kind.  Return the R_SYMNDX of the target
1665    function, or 0 if we can't decide which function that is.  */
1666
1667 static unsigned long
1668 mips16_stub_symndx (const struct elf_backend_data *bed,
1669                     asection *sec ATTRIBUTE_UNUSED,
1670                     const Elf_Internal_Rela *relocs,
1671                     const Elf_Internal_Rela *relend)
1672 {
1673   int int_rels_per_ext_rel = bed->s->int_rels_per_ext_rel;
1674   const Elf_Internal_Rela *rel;
1675
1676   /* Trust the first R_MIPS_NONE relocation, if any, but not a subsequent
1677      one in a compound relocation.  */
1678   for (rel = relocs; rel < relend; rel += int_rels_per_ext_rel)
1679     if (ELF_R_TYPE (sec->owner, rel->r_info) == R_MIPS_NONE)
1680       return ELF_R_SYM (sec->owner, rel->r_info);
1681
1682   /* Otherwise trust the first relocation, whatever its kind.  This is
1683      the traditional behavior.  */
1684   if (relocs < relend)
1685     return ELF_R_SYM (sec->owner, relocs->r_info);
1686
1687   return 0;
1688 }
1689
1690 /* Check the mips16 stubs for a particular symbol, and see if we can
1691    discard them.  */
1692
1693 static void
1694 mips_elf_check_mips16_stubs (struct bfd_link_info *info,
1695                              struct mips_elf_link_hash_entry *h)
1696 {
1697   /* Dynamic symbols must use the standard call interface, in case other
1698      objects try to call them.  */
1699   if (h->fn_stub != NULL
1700       && h->root.dynindx != -1)
1701     {
1702       mips_elf_create_shadow_symbol (info, h, ".mips16.");
1703       h->need_fn_stub = TRUE;
1704     }
1705
1706   if (h->fn_stub != NULL
1707       && ! h->need_fn_stub)
1708     {
1709       /* We don't need the fn_stub; the only references to this symbol
1710          are 16 bit calls.  Clobber the size to 0 to prevent it from
1711          being included in the link.  */
1712       h->fn_stub->size = 0;
1713       h->fn_stub->flags &= ~SEC_RELOC;
1714       h->fn_stub->reloc_count = 0;
1715       h->fn_stub->flags |= SEC_EXCLUDE;
1716       h->fn_stub->output_section = bfd_abs_section_ptr;
1717     }
1718
1719   if (h->call_stub != NULL
1720       && ELF_ST_IS_MIPS16 (h->root.other))
1721     {
1722       /* We don't need the call_stub; this is a 16 bit function, so
1723          calls from other 16 bit functions are OK.  Clobber the size
1724          to 0 to prevent it from being included in the link.  */
1725       h->call_stub->size = 0;
1726       h->call_stub->flags &= ~SEC_RELOC;
1727       h->call_stub->reloc_count = 0;
1728       h->call_stub->flags |= SEC_EXCLUDE;
1729       h->call_stub->output_section = bfd_abs_section_ptr;
1730     }
1731
1732   if (h->call_fp_stub != NULL
1733       && ELF_ST_IS_MIPS16 (h->root.other))
1734     {
1735       /* We don't need the call_stub; this is a 16 bit function, so
1736          calls from other 16 bit functions are OK.  Clobber the size
1737          to 0 to prevent it from being included in the link.  */
1738       h->call_fp_stub->size = 0;
1739       h->call_fp_stub->flags &= ~SEC_RELOC;
1740       h->call_fp_stub->reloc_count = 0;
1741       h->call_fp_stub->flags |= SEC_EXCLUDE;
1742       h->call_fp_stub->output_section = bfd_abs_section_ptr;
1743     }
1744 }
1745
1746 /* Hashtable callbacks for mips_elf_la25_stubs.  */
1747
1748 static hashval_t
1749 mips_elf_la25_stub_hash (const void *entry_)
1750 {
1751   const struct mips_elf_la25_stub *entry;
1752
1753   entry = (struct mips_elf_la25_stub *) entry_;
1754   return entry->h->root.root.u.def.section->id
1755     + entry->h->root.root.u.def.value;
1756 }
1757
1758 static int
1759 mips_elf_la25_stub_eq (const void *entry1_, const void *entry2_)
1760 {
1761   const struct mips_elf_la25_stub *entry1, *entry2;
1762
1763   entry1 = (struct mips_elf_la25_stub *) entry1_;
1764   entry2 = (struct mips_elf_la25_stub *) entry2_;
1765   return ((entry1->h->root.root.u.def.section
1766            == entry2->h->root.root.u.def.section)
1767           && (entry1->h->root.root.u.def.value
1768               == entry2->h->root.root.u.def.value));
1769 }
1770
1771 /* Called by the linker to set up the la25 stub-creation code.  FN is
1772    the linker's implementation of add_stub_function.  Return true on
1773    success.  */
1774
1775 bfd_boolean
1776 _bfd_mips_elf_init_stubs (struct bfd_link_info *info,
1777                           asection *(*fn) (const char *, asection *,
1778                                            asection *))
1779 {
1780   struct mips_elf_link_hash_table *htab;
1781
1782   htab = mips_elf_hash_table (info);
1783   if (htab == NULL)
1784     return FALSE;
1785
1786   htab->add_stub_section = fn;
1787   htab->la25_stubs = htab_try_create (1, mips_elf_la25_stub_hash,
1788                                       mips_elf_la25_stub_eq, NULL);
1789   if (htab->la25_stubs == NULL)
1790     return FALSE;
1791
1792   return TRUE;
1793 }
1794
1795 /* Return true if H is a locally-defined PIC function, in the sense
1796    that it or its fn_stub might need $25 to be valid on entry.
1797    Note that MIPS16 functions set up $gp using PC-relative instructions,
1798    so they themselves never need $25 to be valid.  Only non-MIPS16
1799    entry points are of interest here.  */
1800
1801 static bfd_boolean
1802 mips_elf_local_pic_function_p (struct mips_elf_link_hash_entry *h)
1803 {
1804   return ((h->root.root.type == bfd_link_hash_defined
1805            || h->root.root.type == bfd_link_hash_defweak)
1806           && h->root.def_regular
1807           && !bfd_is_abs_section (h->root.root.u.def.section)
1808           && !bfd_is_und_section (h->root.root.u.def.section)
1809           && (!ELF_ST_IS_MIPS16 (h->root.other)
1810               || (h->fn_stub && h->need_fn_stub))
1811           && (PIC_OBJECT_P (h->root.root.u.def.section->owner)
1812               || ELF_ST_IS_MIPS_PIC (h->root.other)));
1813 }
1814
1815 /* Set *SEC to the input section that contains the target of STUB.
1816    Return the offset of the target from the start of that section.  */
1817
1818 static bfd_vma
1819 mips_elf_get_la25_target (struct mips_elf_la25_stub *stub,
1820                           asection **sec)
1821 {
1822   if (ELF_ST_IS_MIPS16 (stub->h->root.other))
1823     {
1824       BFD_ASSERT (stub->h->need_fn_stub);
1825       *sec = stub->h->fn_stub;
1826       return 0;
1827     }
1828   else
1829     {
1830       *sec = stub->h->root.root.u.def.section;
1831       return stub->h->root.root.u.def.value;
1832     }
1833 }
1834
1835 /* STUB describes an la25 stub that we have decided to implement
1836    by inserting an LUI/ADDIU pair before the target function.
1837    Create the section and redirect the function symbol to it.  */
1838
1839 static bfd_boolean
1840 mips_elf_add_la25_intro (struct mips_elf_la25_stub *stub,
1841                          struct bfd_link_info *info)
1842 {
1843   struct mips_elf_link_hash_table *htab;
1844   char *name;
1845   asection *s, *input_section;
1846   unsigned int align;
1847
1848   htab = mips_elf_hash_table (info);
1849   if (htab == NULL)
1850     return FALSE;
1851
1852   /* Create a unique name for the new section.  */
1853   name = bfd_malloc (11 + sizeof (".text.stub."));
1854   if (name == NULL)
1855     return FALSE;
1856   sprintf (name, ".text.stub.%d", (int) htab_elements (htab->la25_stubs));
1857
1858   /* Create the section.  */
1859   mips_elf_get_la25_target (stub, &input_section);
1860   s = htab->add_stub_section (name, input_section,
1861                               input_section->output_section);
1862   if (s == NULL)
1863     return FALSE;
1864
1865   /* Make sure that any padding goes before the stub.  */
1866   align = input_section->alignment_power;
1867   if (!bfd_set_section_alignment (s->owner, s, align))
1868     return FALSE;
1869   if (align > 3)
1870     s->size = (1 << align) - 8;
1871
1872   /* Create a symbol for the stub.  */
1873   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 8);
1874   stub->stub_section = s;
1875   stub->offset = s->size;
1876
1877   /* Allocate room for it.  */
1878   s->size += 8;
1879   return TRUE;
1880 }
1881
1882 /* STUB describes an la25 stub that we have decided to implement
1883    with a separate trampoline.  Allocate room for it and redirect
1884    the function symbol to it.  */
1885
1886 static bfd_boolean
1887 mips_elf_add_la25_trampoline (struct mips_elf_la25_stub *stub,
1888                               struct bfd_link_info *info)
1889 {
1890   struct mips_elf_link_hash_table *htab;
1891   asection *s;
1892
1893   htab = mips_elf_hash_table (info);
1894   if (htab == NULL)
1895     return FALSE;
1896
1897   /* Create a trampoline section, if we haven't already.  */
1898   s = htab->strampoline;
1899   if (s == NULL)
1900     {
1901       asection *input_section = stub->h->root.root.u.def.section;
1902       s = htab->add_stub_section (".text", NULL,
1903                                   input_section->output_section);
1904       if (s == NULL || !bfd_set_section_alignment (s->owner, s, 4))
1905         return FALSE;
1906       htab->strampoline = s;
1907     }
1908
1909   /* Create a symbol for the stub.  */
1910   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 16);
1911   stub->stub_section = s;
1912   stub->offset = s->size;
1913
1914   /* Allocate room for it.  */
1915   s->size += 16;
1916   return TRUE;
1917 }
1918
1919 /* H describes a symbol that needs an la25 stub.  Make sure that an
1920    appropriate stub exists and point H at it.  */
1921
1922 static bfd_boolean
1923 mips_elf_add_la25_stub (struct bfd_link_info *info,
1924                         struct mips_elf_link_hash_entry *h)
1925 {
1926   struct mips_elf_link_hash_table *htab;
1927   struct mips_elf_la25_stub search, *stub;
1928   bfd_boolean use_trampoline_p;
1929   asection *s;
1930   bfd_vma value;
1931   void **slot;
1932
1933   /* Describe the stub we want.  */
1934   search.stub_section = NULL;
1935   search.offset = 0;
1936   search.h = h;
1937
1938   /* See if we've already created an equivalent stub.  */
1939   htab = mips_elf_hash_table (info);
1940   if (htab == NULL)
1941     return FALSE;
1942
1943   slot = htab_find_slot (htab->la25_stubs, &search, INSERT);
1944   if (slot == NULL)
1945     return FALSE;
1946
1947   stub = (struct mips_elf_la25_stub *) *slot;
1948   if (stub != NULL)
1949     {
1950       /* We can reuse the existing stub.  */
1951       h->la25_stub = stub;
1952       return TRUE;
1953     }
1954
1955   /* Create a permanent copy of ENTRY and add it to the hash table.  */
1956   stub = bfd_malloc (sizeof (search));
1957   if (stub == NULL)
1958     return FALSE;
1959   *stub = search;
1960   *slot = stub;
1961
1962   /* Prefer to use LUI/ADDIU stubs if the function is at the beginning
1963      of the section and if we would need no more than 2 nops.  */
1964   value = mips_elf_get_la25_target (stub, &s);
1965   if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
1966     value &= ~1;
1967   use_trampoline_p = (value != 0 || s->alignment_power > 4);
1968
1969   h->la25_stub = stub;
1970   return (use_trampoline_p
1971           ? mips_elf_add_la25_trampoline (stub, info)
1972           : mips_elf_add_la25_intro (stub, info));
1973 }
1974
1975 /* A mips_elf_link_hash_traverse callback that is called before sizing
1976    sections.  DATA points to a mips_htab_traverse_info structure.  */
1977
1978 static bfd_boolean
1979 mips_elf_check_symbols (struct mips_elf_link_hash_entry *h, void *data)
1980 {
1981   struct mips_htab_traverse_info *hti;
1982
1983   hti = (struct mips_htab_traverse_info *) data;
1984   if (!bfd_link_relocatable (hti->info))
1985     mips_elf_check_mips16_stubs (hti->info, h);
1986
1987   if (mips_elf_local_pic_function_p (h))
1988     {
1989       /* PR 12845: If H is in a section that has been garbage
1990          collected it will have its output section set to *ABS*.  */
1991       if (bfd_is_abs_section (h->root.root.u.def.section->output_section))
1992         return TRUE;
1993
1994       /* H is a function that might need $25 to be valid on entry.
1995          If we're creating a non-PIC relocatable object, mark H as
1996          being PIC.  If we're creating a non-relocatable object with
1997          non-PIC branches and jumps to H, make sure that H has an la25
1998          stub.  */
1999       if (bfd_link_relocatable (hti->info))
2000         {
2001           if (!PIC_OBJECT_P (hti->output_bfd))
2002             h->root.other = ELF_ST_SET_MIPS_PIC (h->root.other);
2003         }
2004       else if (h->has_nonpic_branches && !mips_elf_add_la25_stub (hti->info, h))
2005         {
2006           hti->error = TRUE;
2007           return FALSE;
2008         }
2009     }
2010   return TRUE;
2011 }
2012 \f
2013 /* R_MIPS16_26 is used for the mips16 jal and jalx instructions.
2014    Most mips16 instructions are 16 bits, but these instructions
2015    are 32 bits.
2016
2017    The format of these instructions is:
2018
2019    +--------------+--------------------------------+
2020    |     JALX     | X|   Imm 20:16  |   Imm 25:21  |
2021    +--------------+--------------------------------+
2022    |                Immediate  15:0                |
2023    +-----------------------------------------------+
2024
2025    JALX is the 5-bit value 00011.  X is 0 for jal, 1 for jalx.
2026    Note that the immediate value in the first word is swapped.
2027
2028    When producing a relocatable object file, R_MIPS16_26 is
2029    handled mostly like R_MIPS_26.  In particular, the addend is
2030    stored as a straight 26-bit value in a 32-bit instruction.
2031    (gas makes life simpler for itself by never adjusting a
2032    R_MIPS16_26 reloc to be against a section, so the addend is
2033    always zero).  However, the 32 bit instruction is stored as 2
2034    16-bit values, rather than a single 32-bit value.  In a
2035    big-endian file, the result is the same; in a little-endian
2036    file, the two 16-bit halves of the 32 bit value are swapped.
2037    This is so that a disassembler can recognize the jal
2038    instruction.
2039
2040    When doing a final link, R_MIPS16_26 is treated as a 32 bit
2041    instruction stored as two 16-bit values.  The addend A is the
2042    contents of the targ26 field.  The calculation is the same as
2043    R_MIPS_26.  When storing the calculated value, reorder the
2044    immediate value as shown above, and don't forget to store the
2045    value as two 16-bit values.
2046
2047    To put it in MIPS ABI terms, the relocation field is T-targ26-16,
2048    defined as
2049
2050    big-endian:
2051    +--------+----------------------+
2052    |        |                      |
2053    |        |    targ26-16         |
2054    |31    26|25                   0|
2055    +--------+----------------------+
2056
2057    little-endian:
2058    +----------+------+-------------+
2059    |          |      |             |
2060    |  sub1    |      |     sub2    |
2061    |0        9|10  15|16         31|
2062    +----------+--------------------+
2063    where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is
2064    ((sub1 << 16) | sub2)).
2065
2066    When producing a relocatable object file, the calculation is
2067    (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
2068    When producing a fully linked file, the calculation is
2069    let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
2070    ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff)
2071
2072    The table below lists the other MIPS16 instruction relocations.
2073    Each one is calculated in the same way as the non-MIPS16 relocation
2074    given on the right, but using the extended MIPS16 layout of 16-bit
2075    immediate fields:
2076
2077         R_MIPS16_GPREL          R_MIPS_GPREL16
2078         R_MIPS16_GOT16          R_MIPS_GOT16
2079         R_MIPS16_CALL16         R_MIPS_CALL16
2080         R_MIPS16_HI16           R_MIPS_HI16
2081         R_MIPS16_LO16           R_MIPS_LO16
2082
2083    A typical instruction will have a format like this:
2084
2085    +--------------+--------------------------------+
2086    |    EXTEND    |     Imm 10:5    |   Imm 15:11  |
2087    +--------------+--------------------------------+
2088    |    Major     |   rx   |   ry   |   Imm  4:0   |
2089    +--------------+--------------------------------+
2090
2091    EXTEND is the five bit value 11110.  Major is the instruction
2092    opcode.
2093
2094    All we need to do here is shuffle the bits appropriately.
2095    As above, the two 16-bit halves must be swapped on a
2096    little-endian system.
2097
2098    Finally R_MIPS16_PC16_S1 corresponds to R_MIPS_PC16, however the
2099    relocatable field is shifted by 1 rather than 2 and the same bit
2100    shuffling is done as with the relocations above.  */
2101
2102 static inline bfd_boolean
2103 mips16_reloc_p (int r_type)
2104 {
2105   switch (r_type)
2106     {
2107     case R_MIPS16_26:
2108     case R_MIPS16_GPREL:
2109     case R_MIPS16_GOT16:
2110     case R_MIPS16_CALL16:
2111     case R_MIPS16_HI16:
2112     case R_MIPS16_LO16:
2113     case R_MIPS16_TLS_GD:
2114     case R_MIPS16_TLS_LDM:
2115     case R_MIPS16_TLS_DTPREL_HI16:
2116     case R_MIPS16_TLS_DTPREL_LO16:
2117     case R_MIPS16_TLS_GOTTPREL:
2118     case R_MIPS16_TLS_TPREL_HI16:
2119     case R_MIPS16_TLS_TPREL_LO16:
2120     case R_MIPS16_PC16_S1:
2121       return TRUE;
2122
2123     default:
2124       return FALSE;
2125     }
2126 }
2127
2128 /* Check if a microMIPS reloc.  */
2129
2130 static inline bfd_boolean
2131 micromips_reloc_p (unsigned int r_type)
2132 {
2133   return r_type >= R_MICROMIPS_min && r_type < R_MICROMIPS_max;
2134 }
2135
2136 /* Similar to MIPS16, the two 16-bit halves in microMIPS must be swapped
2137    on a little-endian system.  This does not apply to R_MICROMIPS_PC7_S1
2138    and R_MICROMIPS_PC10_S1 relocs that apply to 16-bit instructions.  */
2139
2140 static inline bfd_boolean
2141 micromips_reloc_shuffle_p (unsigned int r_type)
2142 {
2143   return (micromips_reloc_p (r_type)
2144           && r_type != R_MICROMIPS_PC7_S1
2145           && r_type != R_MICROMIPS_PC10_S1);
2146 }
2147
2148 static inline bfd_boolean
2149 got16_reloc_p (int r_type)
2150 {
2151   return (r_type == R_MIPS_GOT16
2152           || r_type == R_MIPS16_GOT16
2153           || r_type == R_MICROMIPS_GOT16);
2154 }
2155
2156 static inline bfd_boolean
2157 call16_reloc_p (int r_type)
2158 {
2159   return (r_type == R_MIPS_CALL16
2160           || r_type == R_MIPS16_CALL16
2161           || r_type == R_MICROMIPS_CALL16);
2162 }
2163
2164 static inline bfd_boolean
2165 got_disp_reloc_p (unsigned int r_type)
2166 {
2167   return r_type == R_MIPS_GOT_DISP || r_type == R_MICROMIPS_GOT_DISP;
2168 }
2169
2170 static inline bfd_boolean
2171 got_page_reloc_p (unsigned int r_type)
2172 {
2173   return r_type == R_MIPS_GOT_PAGE || r_type == R_MICROMIPS_GOT_PAGE;
2174 }
2175
2176 static inline bfd_boolean
2177 got_lo16_reloc_p (unsigned int r_type)
2178 {
2179   return r_type == R_MIPS_GOT_LO16 || r_type == R_MICROMIPS_GOT_LO16;
2180 }
2181
2182 static inline bfd_boolean
2183 call_hi16_reloc_p (unsigned int r_type)
2184 {
2185   return r_type == R_MIPS_CALL_HI16 || r_type == R_MICROMIPS_CALL_HI16;
2186 }
2187
2188 static inline bfd_boolean
2189 call_lo16_reloc_p (unsigned int r_type)
2190 {
2191   return r_type == R_MIPS_CALL_LO16 || r_type == R_MICROMIPS_CALL_LO16;
2192 }
2193
2194 static inline bfd_boolean
2195 hi16_reloc_p (int r_type)
2196 {
2197   return (r_type == R_MIPS_HI16
2198           || r_type == R_MIPS16_HI16
2199           || r_type == R_MICROMIPS_HI16
2200           || r_type == R_MIPS_PCHI16);
2201 }
2202
2203 static inline bfd_boolean
2204 lo16_reloc_p (int r_type)
2205 {
2206   return (r_type == R_MIPS_LO16
2207           || r_type == R_MIPS16_LO16
2208           || r_type == R_MICROMIPS_LO16
2209           || r_type == R_MIPS_PCLO16);
2210 }
2211
2212 static inline bfd_boolean
2213 mips16_call_reloc_p (int r_type)
2214 {
2215   return r_type == R_MIPS16_26 || r_type == R_MIPS16_CALL16;
2216 }
2217
2218 static inline bfd_boolean
2219 jal_reloc_p (int r_type)
2220 {
2221   return (r_type == R_MIPS_26
2222           || r_type == R_MIPS16_26
2223           || r_type == R_MICROMIPS_26_S1);
2224 }
2225
2226 static inline bfd_boolean
2227 b_reloc_p (int r_type)
2228 {
2229   return (r_type == R_MIPS_PC26_S2
2230           || r_type == R_MIPS_PC21_S2
2231           || r_type == R_MIPS_PC16
2232           || r_type == R_MIPS_GNU_REL16_S2
2233           || r_type == R_MIPS16_PC16_S1
2234           || r_type == R_MICROMIPS_PC16_S1
2235           || r_type == R_MICROMIPS_PC10_S1
2236           || r_type == R_MICROMIPS_PC7_S1);
2237 }
2238
2239 static inline bfd_boolean
2240 aligned_pcrel_reloc_p (int r_type)
2241 {
2242   return (r_type == R_MIPS_PC18_S3
2243           || r_type == R_MIPS_PC19_S2);
2244 }
2245
2246 static inline bfd_boolean
2247 branch_reloc_p (int r_type)
2248 {
2249   return (r_type == R_MIPS_26
2250           || r_type == R_MIPS_PC26_S2
2251           || r_type == R_MIPS_PC21_S2
2252           || r_type == R_MIPS_PC16
2253           || r_type == R_MIPS_GNU_REL16_S2);
2254 }
2255
2256 static inline bfd_boolean
2257 mips16_branch_reloc_p (int r_type)
2258 {
2259   return (r_type == R_MIPS16_26
2260           || r_type == R_MIPS16_PC16_S1);
2261 }
2262
2263 static inline bfd_boolean
2264 micromips_branch_reloc_p (int r_type)
2265 {
2266   return (r_type == R_MICROMIPS_26_S1
2267           || r_type == R_MICROMIPS_PC16_S1
2268           || r_type == R_MICROMIPS_PC10_S1
2269           || r_type == R_MICROMIPS_PC7_S1);
2270 }
2271
2272 static inline bfd_boolean
2273 tls_gd_reloc_p (unsigned int r_type)
2274 {
2275   return (r_type == R_MIPS_TLS_GD
2276           || r_type == R_MIPS16_TLS_GD
2277           || r_type == R_MICROMIPS_TLS_GD);
2278 }
2279
2280 static inline bfd_boolean
2281 tls_ldm_reloc_p (unsigned int r_type)
2282 {
2283   return (r_type == R_MIPS_TLS_LDM
2284           || r_type == R_MIPS16_TLS_LDM
2285           || r_type == R_MICROMIPS_TLS_LDM);
2286 }
2287
2288 static inline bfd_boolean
2289 tls_gottprel_reloc_p (unsigned int r_type)
2290 {
2291   return (r_type == R_MIPS_TLS_GOTTPREL
2292           || r_type == R_MIPS16_TLS_GOTTPREL
2293           || r_type == R_MICROMIPS_TLS_GOTTPREL);
2294 }
2295
2296 void
2297 _bfd_mips_elf_reloc_unshuffle (bfd *abfd, int r_type,
2298                                bfd_boolean jal_shuffle, bfd_byte *data)
2299 {
2300   bfd_vma first, second, val;
2301
2302   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2303     return;
2304
2305   /* Pick up the first and second halfwords of the instruction.  */
2306   first = bfd_get_16 (abfd, data);
2307   second = bfd_get_16 (abfd, data + 2);
2308   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2309     val = first << 16 | second;
2310   else if (r_type != R_MIPS16_26)
2311     val = (((first & 0xf800) << 16) | ((second & 0xffe0) << 11)
2312            | ((first & 0x1f) << 11) | (first & 0x7e0) | (second & 0x1f));
2313   else
2314     val = (((first & 0xfc00) << 16) | ((first & 0x3e0) << 11)
2315            | ((first & 0x1f) << 21) | second);
2316   bfd_put_32 (abfd, val, data);
2317 }
2318
2319 void
2320 _bfd_mips_elf_reloc_shuffle (bfd *abfd, int r_type,
2321                              bfd_boolean jal_shuffle, bfd_byte *data)
2322 {
2323   bfd_vma first, second, val;
2324
2325   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2326     return;
2327
2328   val = bfd_get_32 (abfd, data);
2329   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2330     {
2331       second = val & 0xffff;
2332       first = val >> 16;
2333     }
2334   else if (r_type != R_MIPS16_26)
2335     {
2336       second = ((val >> 11) & 0xffe0) | (val & 0x1f);
2337       first = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0);
2338     }
2339   else
2340     {
2341       second = val & 0xffff;
2342       first = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0)
2343                | ((val >> 21) & 0x1f);
2344     }
2345   bfd_put_16 (abfd, second, data + 2);
2346   bfd_put_16 (abfd, first, data);
2347 }
2348
2349 bfd_reloc_status_type
2350 _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol,
2351                                arelent *reloc_entry, asection *input_section,
2352                                bfd_boolean relocatable, void *data, bfd_vma gp)
2353 {
2354   bfd_vma relocation;
2355   bfd_signed_vma val;
2356   bfd_reloc_status_type status;
2357
2358   if (bfd_is_com_section (symbol->section))
2359     relocation = 0;
2360   else
2361     relocation = symbol->value;
2362
2363   relocation += symbol->section->output_section->vma;
2364   relocation += symbol->section->output_offset;
2365
2366   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2367     return bfd_reloc_outofrange;
2368
2369   /* Set val to the offset into the section or symbol.  */
2370   val = reloc_entry->addend;
2371
2372   _bfd_mips_elf_sign_extend (val, 16);
2373
2374   /* Adjust val for the final section location and GP value.  If we
2375      are producing relocatable output, we don't want to do this for
2376      an external symbol.  */
2377   if (! relocatable
2378       || (symbol->flags & BSF_SECTION_SYM) != 0)
2379     val += relocation - gp;
2380
2381   if (reloc_entry->howto->partial_inplace)
2382     {
2383       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2384                                        (bfd_byte *) data
2385                                        + reloc_entry->address);
2386       if (status != bfd_reloc_ok)
2387         return status;
2388     }
2389   else
2390     reloc_entry->addend = val;
2391
2392   if (relocatable)
2393     reloc_entry->address += input_section->output_offset;
2394
2395   return bfd_reloc_ok;
2396 }
2397
2398 /* Used to store a REL high-part relocation such as R_MIPS_HI16 or
2399    R_MIPS_GOT16.  REL is the relocation, INPUT_SECTION is the section
2400    that contains the relocation field and DATA points to the start of
2401    INPUT_SECTION.  */
2402
2403 struct mips_hi16
2404 {
2405   struct mips_hi16 *next;
2406   bfd_byte *data;
2407   asection *input_section;
2408   arelent rel;
2409 };
2410
2411 /* FIXME: This should not be a static variable.  */
2412
2413 static struct mips_hi16 *mips_hi16_list;
2414
2415 /* A howto special_function for REL *HI16 relocations.  We can only
2416    calculate the correct value once we've seen the partnering
2417    *LO16 relocation, so just save the information for later.
2418
2419    The ABI requires that the *LO16 immediately follow the *HI16.
2420    However, as a GNU extension, we permit an arbitrary number of
2421    *HI16s to be associated with a single *LO16.  This significantly
2422    simplies the relocation handling in gcc.  */
2423
2424 bfd_reloc_status_type
2425 _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2426                           asymbol *symbol ATTRIBUTE_UNUSED, void *data,
2427                           asection *input_section, bfd *output_bfd,
2428                           char **error_message ATTRIBUTE_UNUSED)
2429 {
2430   struct mips_hi16 *n;
2431
2432   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2433     return bfd_reloc_outofrange;
2434
2435   n = bfd_malloc (sizeof *n);
2436   if (n == NULL)
2437     return bfd_reloc_outofrange;
2438
2439   n->next = mips_hi16_list;
2440   n->data = data;
2441   n->input_section = input_section;
2442   n->rel = *reloc_entry;
2443   mips_hi16_list = n;
2444
2445   if (output_bfd != NULL)
2446     reloc_entry->address += input_section->output_offset;
2447
2448   return bfd_reloc_ok;
2449 }
2450
2451 /* A howto special_function for REL R_MIPS*_GOT16 relocations.  This is just
2452    like any other 16-bit relocation when applied to global symbols, but is
2453    treated in the same as R_MIPS_HI16 when applied to local symbols.  */
2454
2455 bfd_reloc_status_type
2456 _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2457                            void *data, asection *input_section,
2458                            bfd *output_bfd, char **error_message)
2459 {
2460   if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2461       || bfd_is_und_section (bfd_get_section (symbol))
2462       || bfd_is_com_section (bfd_get_section (symbol)))
2463     /* The relocation is against a global symbol.  */
2464     return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2465                                         input_section, output_bfd,
2466                                         error_message);
2467
2468   return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
2469                                    input_section, output_bfd, error_message);
2470 }
2471
2472 /* A howto special_function for REL *LO16 relocations.  The *LO16 itself
2473    is a straightforward 16 bit inplace relocation, but we must deal with
2474    any partnering high-part relocations as well.  */
2475
2476 bfd_reloc_status_type
2477 _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2478                           void *data, asection *input_section,
2479                           bfd *output_bfd, char **error_message)
2480 {
2481   bfd_vma vallo;
2482   bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2483
2484   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2485     return bfd_reloc_outofrange;
2486
2487   _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2488                                  location);
2489   vallo = bfd_get_32 (abfd, location);
2490   _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2491                                location);
2492
2493   while (mips_hi16_list != NULL)
2494     {
2495       bfd_reloc_status_type ret;
2496       struct mips_hi16 *hi;
2497
2498       hi = mips_hi16_list;
2499
2500       /* R_MIPS*_GOT16 relocations are something of a special case.  We
2501          want to install the addend in the same way as for a R_MIPS*_HI16
2502          relocation (with a rightshift of 16).  However, since GOT16
2503          relocations can also be used with global symbols, their howto
2504          has a rightshift of 0.  */
2505       if (hi->rel.howto->type == R_MIPS_GOT16)
2506         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE);
2507       else if (hi->rel.howto->type == R_MIPS16_GOT16)
2508         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS16_HI16, FALSE);
2509       else if (hi->rel.howto->type == R_MICROMIPS_GOT16)
2510         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MICROMIPS_HI16, FALSE);
2511
2512       /* VALLO is a signed 16-bit number.  Bias it by 0x8000 so that any
2513          carry or borrow will induce a change of +1 or -1 in the high part.  */
2514       hi->rel.addend += (vallo + 0x8000) & 0xffff;
2515
2516       ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data,
2517                                          hi->input_section, output_bfd,
2518                                          error_message);
2519       if (ret != bfd_reloc_ok)
2520         return ret;
2521
2522       mips_hi16_list = hi->next;
2523       free (hi);
2524     }
2525
2526   return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2527                                       input_section, output_bfd,
2528                                       error_message);
2529 }
2530
2531 /* A generic howto special_function.  This calculates and installs the
2532    relocation itself, thus avoiding the oft-discussed problems in
2533    bfd_perform_relocation and bfd_install_relocation.  */
2534
2535 bfd_reloc_status_type
2536 _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2537                              asymbol *symbol, void *data ATTRIBUTE_UNUSED,
2538                              asection *input_section, bfd *output_bfd,
2539                              char **error_message ATTRIBUTE_UNUSED)
2540 {
2541   bfd_signed_vma val;
2542   bfd_reloc_status_type status;
2543   bfd_boolean relocatable;
2544
2545   relocatable = (output_bfd != NULL);
2546
2547   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2548     return bfd_reloc_outofrange;
2549
2550   /* Build up the field adjustment in VAL.  */
2551   val = 0;
2552   if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)
2553     {
2554       /* Either we're calculating the final field value or we have a
2555          relocation against a section symbol.  Add in the section's
2556          offset or address.  */
2557       val += symbol->section->output_section->vma;
2558       val += symbol->section->output_offset;
2559     }
2560
2561   if (!relocatable)
2562     {
2563       /* We're calculating the final field value.  Add in the symbol's value
2564          and, if pc-relative, subtract the address of the field itself.  */
2565       val += symbol->value;
2566       if (reloc_entry->howto->pc_relative)
2567         {
2568           val -= input_section->output_section->vma;
2569           val -= input_section->output_offset;
2570           val -= reloc_entry->address;
2571         }
2572     }
2573
2574   /* VAL is now the final adjustment.  If we're keeping this relocation
2575      in the output file, and if the relocation uses a separate addend,
2576      we just need to add VAL to that addend.  Otherwise we need to add
2577      VAL to the relocation field itself.  */
2578   if (relocatable && !reloc_entry->howto->partial_inplace)
2579     reloc_entry->addend += val;
2580   else
2581     {
2582       bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2583
2584       /* Add in the separate addend, if any.  */
2585       val += reloc_entry->addend;
2586
2587       /* Add VAL to the relocation field.  */
2588       _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2589                                      location);
2590       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2591                                        location);
2592       _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2593                                    location);
2594
2595       if (status != bfd_reloc_ok)
2596         return status;
2597     }
2598
2599   if (relocatable)
2600     reloc_entry->address += input_section->output_offset;
2601
2602   return bfd_reloc_ok;
2603 }
2604 \f
2605 /* Swap an entry in a .gptab section.  Note that these routines rely
2606    on the equivalence of the two elements of the union.  */
2607
2608 static void
2609 bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex,
2610                               Elf32_gptab *in)
2611 {
2612   in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value);
2613   in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes);
2614 }
2615
2616 static void
2617 bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in,
2618                                Elf32_External_gptab *ex)
2619 {
2620   H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value);
2621   H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes);
2622 }
2623
2624 static void
2625 bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in,
2626                                 Elf32_External_compact_rel *ex)
2627 {
2628   H_PUT_32 (abfd, in->id1, ex->id1);
2629   H_PUT_32 (abfd, in->num, ex->num);
2630   H_PUT_32 (abfd, in->id2, ex->id2);
2631   H_PUT_32 (abfd, in->offset, ex->offset);
2632   H_PUT_32 (abfd, in->reserved0, ex->reserved0);
2633   H_PUT_32 (abfd, in->reserved1, ex->reserved1);
2634 }
2635
2636 static void
2637 bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in,
2638                            Elf32_External_crinfo *ex)
2639 {
2640   unsigned long l;
2641
2642   l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH)
2643        | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH)
2644        | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH)
2645        | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH));
2646   H_PUT_32 (abfd, l, ex->info);
2647   H_PUT_32 (abfd, in->konst, ex->konst);
2648   H_PUT_32 (abfd, in->vaddr, ex->vaddr);
2649 }
2650 \f
2651 /* A .reginfo section holds a single Elf32_RegInfo structure.  These
2652    routines swap this structure in and out.  They are used outside of
2653    BFD, so they are globally visible.  */
2654
2655 void
2656 bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex,
2657                                 Elf32_RegInfo *in)
2658 {
2659   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2660   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2661   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2662   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2663   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2664   in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value);
2665 }
2666
2667 void
2668 bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in,
2669                                  Elf32_External_RegInfo *ex)
2670 {
2671   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2672   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2673   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2674   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2675   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2676   H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value);
2677 }
2678
2679 /* In the 64 bit ABI, the .MIPS.options section holds register
2680    information in an Elf64_Reginfo structure.  These routines swap
2681    them in and out.  They are globally visible because they are used
2682    outside of BFD.  These routines are here so that gas can call them
2683    without worrying about whether the 64 bit ABI has been included.  */
2684
2685 void
2686 bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex,
2687                                 Elf64_Internal_RegInfo *in)
2688 {
2689   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2690   in->ri_pad = H_GET_32 (abfd, ex->ri_pad);
2691   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2692   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2693   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2694   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2695   in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value);
2696 }
2697
2698 void
2699 bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in,
2700                                  Elf64_External_RegInfo *ex)
2701 {
2702   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2703   H_PUT_32 (abfd, in->ri_pad, ex->ri_pad);
2704   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2705   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2706   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2707   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2708   H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value);
2709 }
2710
2711 /* Swap in an options header.  */
2712
2713 void
2714 bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex,
2715                               Elf_Internal_Options *in)
2716 {
2717   in->kind = H_GET_8 (abfd, ex->kind);
2718   in->size = H_GET_8 (abfd, ex->size);
2719   in->section = H_GET_16 (abfd, ex->section);
2720   in->info = H_GET_32 (abfd, ex->info);
2721 }
2722
2723 /* Swap out an options header.  */
2724
2725 void
2726 bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in,
2727                                Elf_External_Options *ex)
2728 {
2729   H_PUT_8 (abfd, in->kind, ex->kind);
2730   H_PUT_8 (abfd, in->size, ex->size);
2731   H_PUT_16 (abfd, in->section, ex->section);
2732   H_PUT_32 (abfd, in->info, ex->info);
2733 }
2734
2735 /* Swap in an abiflags structure.  */
2736
2737 void
2738 bfd_mips_elf_swap_abiflags_v0_in (bfd *abfd,
2739                                   const Elf_External_ABIFlags_v0 *ex,
2740                                   Elf_Internal_ABIFlags_v0 *in)
2741 {
2742   in->version = H_GET_16 (abfd, ex->version);
2743   in->isa_level = H_GET_8 (abfd, ex->isa_level);
2744   in->isa_rev = H_GET_8 (abfd, ex->isa_rev);
2745   in->gpr_size = H_GET_8 (abfd, ex->gpr_size);
2746   in->cpr1_size = H_GET_8 (abfd, ex->cpr1_size);
2747   in->cpr2_size = H_GET_8 (abfd, ex->cpr2_size);
2748   in->fp_abi = H_GET_8 (abfd, ex->fp_abi);
2749   in->isa_ext = H_GET_32 (abfd, ex->isa_ext);
2750   in->ases = H_GET_32 (abfd, ex->ases);
2751   in->flags1 = H_GET_32 (abfd, ex->flags1);
2752   in->flags2 = H_GET_32 (abfd, ex->flags2);
2753 }
2754
2755 /* Swap out an abiflags structure.  */
2756
2757 void
2758 bfd_mips_elf_swap_abiflags_v0_out (bfd *abfd,
2759                                    const Elf_Internal_ABIFlags_v0 *in,
2760                                    Elf_External_ABIFlags_v0 *ex)
2761 {
2762   H_PUT_16 (abfd, in->version, ex->version);
2763   H_PUT_8 (abfd, in->isa_level, ex->isa_level);
2764   H_PUT_8 (abfd, in->isa_rev, ex->isa_rev);
2765   H_PUT_8 (abfd, in->gpr_size, ex->gpr_size);
2766   H_PUT_8 (abfd, in->cpr1_size, ex->cpr1_size);
2767   H_PUT_8 (abfd, in->cpr2_size, ex->cpr2_size);
2768   H_PUT_8 (abfd, in->fp_abi, ex->fp_abi);
2769   H_PUT_32 (abfd, in->isa_ext, ex->isa_ext);
2770   H_PUT_32 (abfd, in->ases, ex->ases);
2771   H_PUT_32 (abfd, in->flags1, ex->flags1);
2772   H_PUT_32 (abfd, in->flags2, ex->flags2);
2773 }
2774 \f
2775 /* This function is called via qsort() to sort the dynamic relocation
2776    entries by increasing r_symndx value.  */
2777
2778 static int
2779 sort_dynamic_relocs (const void *arg1, const void *arg2)
2780 {
2781   Elf_Internal_Rela int_reloc1;
2782   Elf_Internal_Rela int_reloc2;
2783   int diff;
2784
2785   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
2786   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
2787
2788   diff = ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info);
2789   if (diff != 0)
2790     return diff;
2791
2792   if (int_reloc1.r_offset < int_reloc2.r_offset)
2793     return -1;
2794   if (int_reloc1.r_offset > int_reloc2.r_offset)
2795     return 1;
2796   return 0;
2797 }
2798
2799 /* Like sort_dynamic_relocs, but used for elf64 relocations.  */
2800
2801 static int
2802 sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED,
2803                         const void *arg2 ATTRIBUTE_UNUSED)
2804 {
2805 #ifdef BFD64
2806   Elf_Internal_Rela int_reloc1[3];
2807   Elf_Internal_Rela int_reloc2[3];
2808
2809   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2810     (reldyn_sorting_bfd, arg1, int_reloc1);
2811   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2812     (reldyn_sorting_bfd, arg2, int_reloc2);
2813
2814   if (ELF64_R_SYM (int_reloc1[0].r_info) < ELF64_R_SYM (int_reloc2[0].r_info))
2815     return -1;
2816   if (ELF64_R_SYM (int_reloc1[0].r_info) > ELF64_R_SYM (int_reloc2[0].r_info))
2817     return 1;
2818
2819   if (int_reloc1[0].r_offset < int_reloc2[0].r_offset)
2820     return -1;
2821   if (int_reloc1[0].r_offset > int_reloc2[0].r_offset)
2822     return 1;
2823   return 0;
2824 #else
2825   abort ();
2826 #endif
2827 }
2828
2829
2830 /* This routine is used to write out ECOFF debugging external symbol
2831    information.  It is called via mips_elf_link_hash_traverse.  The
2832    ECOFF external symbol information must match the ELF external
2833    symbol information.  Unfortunately, at this point we don't know
2834    whether a symbol is required by reloc information, so the two
2835    tables may wind up being different.  We must sort out the external
2836    symbol information before we can set the final size of the .mdebug
2837    section, and we must set the size of the .mdebug section before we
2838    can relocate any sections, and we can't know which symbols are
2839    required by relocation until we relocate the sections.
2840    Fortunately, it is relatively unlikely that any symbol will be
2841    stripped but required by a reloc.  In particular, it can not happen
2842    when generating a final executable.  */
2843
2844 static bfd_boolean
2845 mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data)
2846 {
2847   struct extsym_info *einfo = data;
2848   bfd_boolean strip;
2849   asection *sec, *output_section;
2850
2851   if (h->root.indx == -2)
2852     strip = FALSE;
2853   else if ((h->root.def_dynamic
2854             || h->root.ref_dynamic
2855             || h->root.type == bfd_link_hash_new)
2856            && !h->root.def_regular
2857            && !h->root.ref_regular)
2858     strip = TRUE;
2859   else if (einfo->info->strip == strip_all
2860            || (einfo->info->strip == strip_some
2861                && bfd_hash_lookup (einfo->info->keep_hash,
2862                                    h->root.root.root.string,
2863                                    FALSE, FALSE) == NULL))
2864     strip = TRUE;
2865   else
2866     strip = FALSE;
2867
2868   if (strip)
2869     return TRUE;
2870
2871   if (h->esym.ifd == -2)
2872     {
2873       h->esym.jmptbl = 0;
2874       h->esym.cobol_main = 0;
2875       h->esym.weakext = 0;
2876       h->esym.reserved = 0;
2877       h->esym.ifd = ifdNil;
2878       h->esym.asym.value = 0;
2879       h->esym.asym.st = stGlobal;
2880
2881       if (h->root.root.type == bfd_link_hash_undefined
2882           || h->root.root.type == bfd_link_hash_undefweak)
2883         {
2884           const char *name;
2885
2886           /* Use undefined class.  Also, set class and type for some
2887              special symbols.  */
2888           name = h->root.root.root.string;
2889           if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
2890               || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
2891             {
2892               h->esym.asym.sc = scData;
2893               h->esym.asym.st = stLabel;
2894               h->esym.asym.value = 0;
2895             }
2896           else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
2897             {
2898               h->esym.asym.sc = scAbs;
2899               h->esym.asym.st = stLabel;
2900               h->esym.asym.value =
2901                 mips_elf_hash_table (einfo->info)->procedure_count;
2902             }
2903           else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd))
2904             {
2905               h->esym.asym.sc = scAbs;
2906               h->esym.asym.st = stLabel;
2907               h->esym.asym.value = elf_gp (einfo->abfd);
2908             }
2909           else
2910             h->esym.asym.sc = scUndefined;
2911         }
2912       else if (h->root.root.type != bfd_link_hash_defined
2913           && h->root.root.type != bfd_link_hash_defweak)
2914         h->esym.asym.sc = scAbs;
2915       else
2916         {
2917           const char *name;
2918
2919           sec = h->root.root.u.def.section;
2920           output_section = sec->output_section;
2921
2922           /* When making a shared library and symbol h is the one from
2923              the another shared library, OUTPUT_SECTION may be null.  */
2924           if (output_section == NULL)
2925             h->esym.asym.sc = scUndefined;
2926           else
2927             {
2928               name = bfd_section_name (output_section->owner, output_section);
2929
2930               if (strcmp (name, ".text") == 0)
2931                 h->esym.asym.sc = scText;
2932               else if (strcmp (name, ".data") == 0)
2933                 h->esym.asym.sc = scData;
2934               else if (strcmp (name, ".sdata") == 0)
2935                 h->esym.asym.sc = scSData;
2936               else if (strcmp (name, ".rodata") == 0
2937                        || strcmp (name, ".rdata") == 0)
2938                 h->esym.asym.sc = scRData;
2939               else if (strcmp (name, ".bss") == 0)
2940                 h->esym.asym.sc = scBss;
2941               else if (strcmp (name, ".sbss") == 0)
2942                 h->esym.asym.sc = scSBss;
2943               else if (strcmp (name, ".init") == 0)
2944                 h->esym.asym.sc = scInit;
2945               else if (strcmp (name, ".fini") == 0)
2946                 h->esym.asym.sc = scFini;
2947               else
2948                 h->esym.asym.sc = scAbs;
2949             }
2950         }
2951
2952       h->esym.asym.reserved = 0;
2953       h->esym.asym.index = indexNil;
2954     }
2955
2956   if (h->root.root.type == bfd_link_hash_common)
2957     h->esym.asym.value = h->root.root.u.c.size;
2958   else if (h->root.root.type == bfd_link_hash_defined
2959            || h->root.root.type == bfd_link_hash_defweak)
2960     {
2961       if (h->esym.asym.sc == scCommon)
2962         h->esym.asym.sc = scBss;
2963       else if (h->esym.asym.sc == scSCommon)
2964         h->esym.asym.sc = scSBss;
2965
2966       sec = h->root.root.u.def.section;
2967       output_section = sec->output_section;
2968       if (output_section != NULL)
2969         h->esym.asym.value = (h->root.root.u.def.value
2970                               + sec->output_offset
2971                               + output_section->vma);
2972       else
2973         h->esym.asym.value = 0;
2974     }
2975   else
2976     {
2977       struct mips_elf_link_hash_entry *hd = h;
2978
2979       while (hd->root.root.type == bfd_link_hash_indirect)
2980         hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link;
2981
2982       if (hd->needs_lazy_stub)
2983         {
2984           BFD_ASSERT (hd->root.plt.plist != NULL);
2985           BFD_ASSERT (hd->root.plt.plist->stub_offset != MINUS_ONE);
2986           /* Set type and value for a symbol with a function stub.  */
2987           h->esym.asym.st = stProc;
2988           sec = hd->root.root.u.def.section;
2989           if (sec == NULL)
2990             h->esym.asym.value = 0;
2991           else
2992             {
2993               output_section = sec->output_section;
2994               if (output_section != NULL)
2995                 h->esym.asym.value = (hd->root.plt.plist->stub_offset
2996                                       + sec->output_offset
2997                                       + output_section->vma);
2998               else
2999                 h->esym.asym.value = 0;
3000             }
3001         }
3002     }
3003
3004   if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap,
3005                                       h->root.root.root.string,
3006                                       &h->esym))
3007     {
3008       einfo->failed = TRUE;
3009       return FALSE;
3010     }
3011
3012   return TRUE;
3013 }
3014
3015 /* A comparison routine used to sort .gptab entries.  */
3016
3017 static int
3018 gptab_compare (const void *p1, const void *p2)
3019 {
3020   const Elf32_gptab *a1 = p1;
3021   const Elf32_gptab *a2 = p2;
3022
3023   return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value;
3024 }
3025 \f
3026 /* Functions to manage the got entry hash table.  */
3027
3028 /* Use all 64 bits of a bfd_vma for the computation of a 32-bit
3029    hash number.  */
3030
3031 static INLINE hashval_t
3032 mips_elf_hash_bfd_vma (bfd_vma addr)
3033 {
3034 #ifdef BFD64
3035   return addr + (addr >> 32);
3036 #else
3037   return addr;
3038 #endif
3039 }
3040
3041 static hashval_t
3042 mips_elf_got_entry_hash (const void *entry_)
3043 {
3044   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
3045
3046   return (entry->symndx
3047           + ((entry->tls_type == GOT_TLS_LDM) << 18)
3048           + (entry->tls_type == GOT_TLS_LDM ? 0
3049              : !entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address)
3050              : entry->symndx >= 0 ? (entry->abfd->id
3051                                      + mips_elf_hash_bfd_vma (entry->d.addend))
3052              : entry->d.h->root.root.root.hash));
3053 }
3054
3055 static int
3056 mips_elf_got_entry_eq (const void *entry1, const void *entry2)
3057 {
3058   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
3059   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
3060
3061   return (e1->symndx == e2->symndx
3062           && e1->tls_type == e2->tls_type
3063           && (e1->tls_type == GOT_TLS_LDM ? TRUE
3064               : !e1->abfd ? !e2->abfd && e1->d.address == e2->d.address
3065               : e1->symndx >= 0 ? (e1->abfd == e2->abfd
3066                                    && e1->d.addend == e2->d.addend)
3067               : e2->abfd && e1->d.h == e2->d.h));
3068 }
3069
3070 static hashval_t
3071 mips_got_page_ref_hash (const void *ref_)
3072 {
3073   const struct mips_got_page_ref *ref;
3074
3075   ref = (const struct mips_got_page_ref *) ref_;
3076   return ((ref->symndx >= 0
3077            ? (hashval_t) (ref->u.abfd->id + ref->symndx)
3078            : ref->u.h->root.root.root.hash)
3079           + mips_elf_hash_bfd_vma (ref->addend));
3080 }
3081
3082 static int
3083 mips_got_page_ref_eq (const void *ref1_, const void *ref2_)
3084 {
3085   const struct mips_got_page_ref *ref1, *ref2;
3086
3087   ref1 = (const struct mips_got_page_ref *) ref1_;
3088   ref2 = (const struct mips_got_page_ref *) ref2_;
3089   return (ref1->symndx == ref2->symndx
3090           && (ref1->symndx < 0
3091               ? ref1->u.h == ref2->u.h
3092               : ref1->u.abfd == ref2->u.abfd)
3093           && ref1->addend == ref2->addend);
3094 }
3095
3096 static hashval_t
3097 mips_got_page_entry_hash (const void *entry_)
3098 {
3099   const struct mips_got_page_entry *entry;
3100
3101   entry = (const struct mips_got_page_entry *) entry_;
3102   return entry->sec->id;
3103 }
3104
3105 static int
3106 mips_got_page_entry_eq (const void *entry1_, const void *entry2_)
3107 {
3108   const struct mips_got_page_entry *entry1, *entry2;
3109
3110   entry1 = (const struct mips_got_page_entry *) entry1_;
3111   entry2 = (const struct mips_got_page_entry *) entry2_;
3112   return entry1->sec == entry2->sec;
3113 }
3114 \f
3115 /* Create and return a new mips_got_info structure.  */
3116
3117 static struct mips_got_info *
3118 mips_elf_create_got_info (bfd *abfd)
3119 {
3120   struct mips_got_info *g;
3121
3122   g = bfd_zalloc (abfd, sizeof (struct mips_got_info));
3123   if (g == NULL)
3124     return NULL;
3125
3126   g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
3127                                     mips_elf_got_entry_eq, NULL);
3128   if (g->got_entries == NULL)
3129     return NULL;
3130
3131   g->got_page_refs = htab_try_create (1, mips_got_page_ref_hash,
3132                                       mips_got_page_ref_eq, NULL);
3133   if (g->got_page_refs == NULL)
3134     return NULL;
3135
3136   return g;
3137 }
3138
3139 /* Return the GOT info for input bfd ABFD, trying to create a new one if
3140    CREATE_P and if ABFD doesn't already have a GOT.  */
3141
3142 static struct mips_got_info *
3143 mips_elf_bfd_got (bfd *abfd, bfd_boolean create_p)
3144 {
3145   struct mips_elf_obj_tdata *tdata;
3146
3147   if (!is_mips_elf (abfd))
3148     return NULL;
3149
3150   tdata = mips_elf_tdata (abfd);
3151   if (!tdata->got && create_p)
3152     tdata->got = mips_elf_create_got_info (abfd);
3153   return tdata->got;
3154 }
3155
3156 /* Record that ABFD should use output GOT G.  */
3157
3158 static void
3159 mips_elf_replace_bfd_got (bfd *abfd, struct mips_got_info *g)
3160 {
3161   struct mips_elf_obj_tdata *tdata;
3162
3163   BFD_ASSERT (is_mips_elf (abfd));
3164   tdata = mips_elf_tdata (abfd);
3165   if (tdata->got)
3166     {
3167       /* The GOT structure itself and the hash table entries are
3168          allocated to a bfd, but the hash tables aren't.  */
3169       htab_delete (tdata->got->got_entries);
3170       htab_delete (tdata->got->got_page_refs);
3171       if (tdata->got->got_page_entries)
3172         htab_delete (tdata->got->got_page_entries);
3173     }
3174   tdata->got = g;
3175 }
3176
3177 /* Return the dynamic relocation section.  If it doesn't exist, try to
3178    create a new it if CREATE_P, otherwise return NULL.  Also return NULL
3179    if creation fails.  */
3180
3181 static asection *
3182 mips_elf_rel_dyn_section (struct bfd_link_info *info, bfd_boolean create_p)
3183 {
3184   const char *dname;
3185   asection *sreloc;
3186   bfd *dynobj;
3187
3188   dname = MIPS_ELF_REL_DYN_NAME (info);
3189   dynobj = elf_hash_table (info)->dynobj;
3190   sreloc = bfd_get_linker_section (dynobj, dname);
3191   if (sreloc == NULL && create_p)
3192     {
3193       sreloc = bfd_make_section_anyway_with_flags (dynobj, dname,
3194                                                    (SEC_ALLOC
3195                                                     | SEC_LOAD
3196                                                     | SEC_HAS_CONTENTS
3197                                                     | SEC_IN_MEMORY
3198                                                     | SEC_LINKER_CREATED
3199                                                     | SEC_READONLY));
3200       if (sreloc == NULL
3201           || ! bfd_set_section_alignment (dynobj, sreloc,
3202                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
3203         return NULL;
3204     }
3205   return sreloc;
3206 }
3207
3208 /* Return the GOT_TLS_* type required by relocation type R_TYPE.  */
3209
3210 static int
3211 mips_elf_reloc_tls_type (unsigned int r_type)
3212 {
3213   if (tls_gd_reloc_p (r_type))
3214     return GOT_TLS_GD;
3215
3216   if (tls_ldm_reloc_p (r_type))
3217     return GOT_TLS_LDM;
3218
3219   if (tls_gottprel_reloc_p (r_type))
3220     return GOT_TLS_IE;
3221
3222   return GOT_TLS_NONE;
3223 }
3224
3225 /* Return the number of GOT slots needed for GOT TLS type TYPE.  */
3226
3227 static int
3228 mips_tls_got_entries (unsigned int type)
3229 {
3230   switch (type)
3231     {
3232     case GOT_TLS_GD:
3233     case GOT_TLS_LDM:
3234       return 2;
3235
3236     case GOT_TLS_IE:
3237       return 1;
3238
3239     case GOT_TLS_NONE:
3240       return 0;
3241     }
3242   abort ();
3243 }
3244
3245 /* Count the number of relocations needed for a TLS GOT entry, with
3246    access types from TLS_TYPE, and symbol H (or a local symbol if H
3247    is NULL).  */
3248
3249 static int
3250 mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type,
3251                      struct elf_link_hash_entry *h)
3252 {
3253   int indx = 0;
3254   bfd_boolean need_relocs = FALSE;
3255   bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3256
3257   if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, bfd_link_pic (info), h)
3258       && (!bfd_link_pic (info) || !SYMBOL_REFERENCES_LOCAL (info, h)))
3259     indx = h->dynindx;
3260
3261   if ((bfd_link_pic (info) || indx != 0)
3262       && (h == NULL
3263           || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
3264           || h->root.type != bfd_link_hash_undefweak))
3265     need_relocs = TRUE;
3266
3267   if (!need_relocs)
3268     return 0;
3269
3270   switch (tls_type)
3271     {
3272     case GOT_TLS_GD:
3273       return indx != 0 ? 2 : 1;
3274
3275     case GOT_TLS_IE:
3276       return 1;
3277
3278     case GOT_TLS_LDM:
3279       return bfd_link_pic (info) ? 1 : 0;
3280
3281     default:
3282       return 0;
3283     }
3284 }
3285
3286 /* Add the number of GOT entries and TLS relocations required by ENTRY
3287    to G.  */
3288
3289 static void
3290 mips_elf_count_got_entry (struct bfd_link_info *info,
3291                           struct mips_got_info *g,
3292                           struct mips_got_entry *entry)
3293 {
3294   if (entry->tls_type)
3295     {
3296       g->tls_gotno += mips_tls_got_entries (entry->tls_type);
3297       g->relocs += mips_tls_got_relocs (info, entry->tls_type,
3298                                         entry->symndx < 0
3299                                         ? &entry->d.h->root : NULL);
3300     }
3301   else if (entry->symndx >= 0 || entry->d.h->global_got_area == GGA_NONE)
3302     g->local_gotno += 1;
3303   else
3304     g->global_gotno += 1;
3305 }
3306
3307 /* Output a simple dynamic relocation into SRELOC.  */
3308
3309 static void
3310 mips_elf_output_dynamic_relocation (bfd *output_bfd,
3311                                     asection *sreloc,
3312                                     unsigned long reloc_index,
3313                                     unsigned long indx,
3314                                     int r_type,
3315                                     bfd_vma offset)
3316 {
3317   Elf_Internal_Rela rel[3];
3318
3319   memset (rel, 0, sizeof (rel));
3320
3321   rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type);
3322   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
3323
3324   if (ABI_64_P (output_bfd))
3325     {
3326       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
3327         (output_bfd, &rel[0],
3328          (sreloc->contents
3329           + reloc_index * sizeof (Elf64_Mips_External_Rel)));
3330     }
3331   else
3332     bfd_elf32_swap_reloc_out
3333       (output_bfd, &rel[0],
3334        (sreloc->contents
3335         + reloc_index * sizeof (Elf32_External_Rel)));
3336 }
3337
3338 /* Initialize a set of TLS GOT entries for one symbol.  */
3339
3340 static void
3341 mips_elf_initialize_tls_slots (bfd *abfd, struct bfd_link_info *info,
3342                                struct mips_got_entry *entry,
3343                                struct mips_elf_link_hash_entry *h,
3344                                bfd_vma value)
3345 {
3346   struct mips_elf_link_hash_table *htab;
3347   int indx;
3348   asection *sreloc, *sgot;
3349   bfd_vma got_offset, got_offset2;
3350   bfd_boolean need_relocs = FALSE;
3351
3352   htab = mips_elf_hash_table (info);
3353   if (htab == NULL)
3354     return;
3355
3356   sgot = htab->root.sgot;
3357
3358   indx = 0;
3359   if (h != NULL)
3360     {
3361       bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3362
3363       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, bfd_link_pic (info),
3364                                            &h->root)
3365           && (!bfd_link_pic (info)
3366               || !SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3367         indx = h->root.dynindx;
3368     }
3369
3370   if (entry->tls_initialized)
3371     return;
3372
3373   if ((bfd_link_pic (info) || indx != 0)
3374       && (h == NULL
3375           || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT
3376           || h->root.type != bfd_link_hash_undefweak))
3377     need_relocs = TRUE;
3378
3379   /* MINUS_ONE means the symbol is not defined in this object.  It may not
3380      be defined at all; assume that the value doesn't matter in that
3381      case.  Otherwise complain if we would use the value.  */
3382   BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs)
3383               || h->root.root.type == bfd_link_hash_undefweak);
3384
3385   /* Emit necessary relocations.  */
3386   sreloc = mips_elf_rel_dyn_section (info, FALSE);
3387   got_offset = entry->gotidx;
3388
3389   switch (entry->tls_type)
3390     {
3391     case GOT_TLS_GD:
3392       /* General Dynamic.  */
3393       got_offset2 = got_offset + MIPS_ELF_GOT_SIZE (abfd);
3394
3395       if (need_relocs)
3396         {
3397           mips_elf_output_dynamic_relocation
3398             (abfd, sreloc, sreloc->reloc_count++, indx,
3399              ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3400              sgot->output_offset + sgot->output_section->vma + got_offset);
3401
3402           if (indx)
3403             mips_elf_output_dynamic_relocation
3404               (abfd, sreloc, sreloc->reloc_count++, indx,
3405                ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32,
3406                sgot->output_offset + sgot->output_section->vma + got_offset2);
3407           else
3408             MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3409                                sgot->contents + got_offset2);
3410         }
3411       else
3412         {
3413           MIPS_ELF_PUT_WORD (abfd, 1,
3414                              sgot->contents + got_offset);
3415           MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3416                              sgot->contents + got_offset2);
3417         }
3418       break;
3419
3420     case GOT_TLS_IE:
3421       /* Initial Exec model.  */
3422       if (need_relocs)
3423         {
3424           if (indx == 0)
3425             MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma,
3426                                sgot->contents + got_offset);
3427           else
3428             MIPS_ELF_PUT_WORD (abfd, 0,
3429                                sgot->contents + got_offset);
3430
3431           mips_elf_output_dynamic_relocation
3432             (abfd, sreloc, sreloc->reloc_count++, indx,
3433              ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32,
3434              sgot->output_offset + sgot->output_section->vma + got_offset);
3435         }
3436       else
3437         MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info),
3438                            sgot->contents + got_offset);
3439       break;
3440
3441     case GOT_TLS_LDM:
3442       /* The initial offset is zero, and the LD offsets will include the
3443          bias by DTP_OFFSET.  */
3444       MIPS_ELF_PUT_WORD (abfd, 0,
3445                          sgot->contents + got_offset
3446                          + MIPS_ELF_GOT_SIZE (abfd));
3447
3448       if (!bfd_link_pic (info))
3449         MIPS_ELF_PUT_WORD (abfd, 1,
3450                            sgot->contents + got_offset);
3451       else
3452         mips_elf_output_dynamic_relocation
3453           (abfd, sreloc, sreloc->reloc_count++, indx,
3454            ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3455            sgot->output_offset + sgot->output_section->vma + got_offset);
3456       break;
3457
3458     default:
3459       abort ();
3460     }
3461
3462   entry->tls_initialized = TRUE;
3463 }
3464
3465 /* Return the offset from _GLOBAL_OFFSET_TABLE_ of the .got.plt entry
3466    for global symbol H.  .got.plt comes before the GOT, so the offset
3467    will be negative.  */
3468
3469 static bfd_vma
3470 mips_elf_gotplt_index (struct bfd_link_info *info,
3471                        struct elf_link_hash_entry *h)
3472 {
3473   bfd_vma got_address, got_value;
3474   struct mips_elf_link_hash_table *htab;
3475
3476   htab = mips_elf_hash_table (info);
3477   BFD_ASSERT (htab != NULL);
3478
3479   BFD_ASSERT (h->plt.plist != NULL);
3480   BFD_ASSERT (h->plt.plist->gotplt_index != MINUS_ONE);
3481
3482   /* Calculate the address of the associated .got.plt entry.  */
3483   got_address = (htab->root.sgotplt->output_section->vma
3484                  + htab->root.sgotplt->output_offset
3485                  + (h->plt.plist->gotplt_index
3486                     * MIPS_ELF_GOT_SIZE (info->output_bfd)));
3487
3488   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
3489   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
3490                + htab->root.hgot->root.u.def.section->output_offset
3491                + htab->root.hgot->root.u.def.value);
3492
3493   return got_address - got_value;
3494 }
3495
3496 /* Return the GOT offset for address VALUE.   If there is not yet a GOT
3497    entry for this value, create one.  If R_SYMNDX refers to a TLS symbol,
3498    create a TLS GOT entry instead.  Return -1 if no satisfactory GOT
3499    offset can be found.  */
3500
3501 static bfd_vma
3502 mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3503                           bfd_vma value, unsigned long r_symndx,
3504                           struct mips_elf_link_hash_entry *h, int r_type)
3505 {
3506   struct mips_elf_link_hash_table *htab;
3507   struct mips_got_entry *entry;
3508
3509   htab = mips_elf_hash_table (info);
3510   BFD_ASSERT (htab != NULL);
3511
3512   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value,
3513                                            r_symndx, h, r_type);
3514   if (!entry)
3515     return MINUS_ONE;
3516
3517   if (entry->tls_type)
3518     mips_elf_initialize_tls_slots (abfd, info, entry, h, value);
3519   return entry->gotidx;
3520 }
3521
3522 /* Return the GOT index of global symbol H in the primary GOT.  */
3523
3524 static bfd_vma
3525 mips_elf_primary_global_got_index (bfd *obfd, struct bfd_link_info *info,
3526                                    struct elf_link_hash_entry *h)
3527 {
3528   struct mips_elf_link_hash_table *htab;
3529   long global_got_dynindx;
3530   struct mips_got_info *g;
3531   bfd_vma got_index;
3532
3533   htab = mips_elf_hash_table (info);
3534   BFD_ASSERT (htab != NULL);
3535
3536   global_got_dynindx = 0;
3537   if (htab->global_gotsym != NULL)
3538     global_got_dynindx = htab->global_gotsym->dynindx;
3539
3540   /* Once we determine the global GOT entry with the lowest dynamic
3541      symbol table index, we must put all dynamic symbols with greater
3542      indices into the primary GOT.  That makes it easy to calculate the
3543      GOT offset.  */
3544   BFD_ASSERT (h->dynindx >= global_got_dynindx);
3545   g = mips_elf_bfd_got (obfd, FALSE);
3546   got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3547                * MIPS_ELF_GOT_SIZE (obfd));
3548   BFD_ASSERT (got_index < htab->root.sgot->size);
3549
3550   return got_index;
3551 }
3552
3553 /* Return the GOT index for the global symbol indicated by H, which is
3554    referenced by a relocation of type R_TYPE in IBFD.  */
3555
3556 static bfd_vma
3557 mips_elf_global_got_index (bfd *obfd, struct bfd_link_info *info, bfd *ibfd,
3558                            struct elf_link_hash_entry *h, int r_type)
3559 {
3560   struct mips_elf_link_hash_table *htab;
3561   struct mips_got_info *g;
3562   struct mips_got_entry lookup, *entry;
3563   bfd_vma gotidx;
3564
3565   htab = mips_elf_hash_table (info);
3566   BFD_ASSERT (htab != NULL);
3567
3568   g = mips_elf_bfd_got (ibfd, FALSE);
3569   BFD_ASSERT (g);
3570
3571   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3572   if (!lookup.tls_type && g == mips_elf_bfd_got (obfd, FALSE))
3573     return mips_elf_primary_global_got_index (obfd, info, h);
3574
3575   lookup.abfd = ibfd;
3576   lookup.symndx = -1;
3577   lookup.d.h = (struct mips_elf_link_hash_entry *) h;
3578   entry = htab_find (g->got_entries, &lookup);
3579   BFD_ASSERT (entry);
3580
3581   gotidx = entry->gotidx;
3582   BFD_ASSERT (gotidx > 0 && gotidx < htab->root.sgot->size);
3583
3584   if (lookup.tls_type)
3585     {
3586       bfd_vma value = MINUS_ONE;
3587
3588       if ((h->root.type == bfd_link_hash_defined
3589            || h->root.type == bfd_link_hash_defweak)
3590           && h->root.u.def.section->output_section)
3591         value = (h->root.u.def.value
3592                  + h->root.u.def.section->output_offset
3593                  + h->root.u.def.section->output_section->vma);
3594
3595       mips_elf_initialize_tls_slots (obfd, info, entry, lookup.d.h, value);
3596     }
3597   return gotidx;
3598 }
3599
3600 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3601    entries are supposed to be placed at small offsets in the GOT, i.e.,
3602    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3603    entry could be created.  If OFFSETP is nonnull, use it to return the
3604    offset of the GOT entry from VALUE.  */
3605
3606 static bfd_vma
3607 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3608                    bfd_vma value, bfd_vma *offsetp)
3609 {
3610   bfd_vma page, got_index;
3611   struct mips_got_entry *entry;
3612
3613   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3614   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3615                                            NULL, R_MIPS_GOT_PAGE);
3616
3617   if (!entry)
3618     return MINUS_ONE;
3619
3620   got_index = entry->gotidx;
3621
3622   if (offsetp)
3623     *offsetp = value - entry->d.address;
3624
3625   return got_index;
3626 }
3627
3628 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3629    EXTERNAL is true if the relocation was originally against a global
3630    symbol that binds locally.  */
3631
3632 static bfd_vma
3633 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3634                       bfd_vma value, bfd_boolean external)
3635 {
3636   struct mips_got_entry *entry;
3637
3638   /* GOT16 relocations against local symbols are followed by a LO16
3639      relocation; those against global symbols are not.  Thus if the
3640      symbol was originally local, the GOT16 relocation should load the
3641      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3642   if (! external)
3643     value = mips_elf_high (value) << 16;
3644
3645   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3646      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3647      same in all cases.  */
3648   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3649                                            NULL, R_MIPS_GOT16);
3650   if (entry)
3651     return entry->gotidx;
3652   else
3653     return MINUS_ONE;
3654 }
3655
3656 /* Returns the offset for the entry at the INDEXth position
3657    in the GOT.  */
3658
3659 static bfd_vma
3660 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3661                                 bfd *input_bfd, bfd_vma got_index)
3662 {
3663   struct mips_elf_link_hash_table *htab;
3664   asection *sgot;
3665   bfd_vma gp;
3666
3667   htab = mips_elf_hash_table (info);
3668   BFD_ASSERT (htab != NULL);
3669
3670   sgot = htab->root.sgot;
3671   gp = _bfd_get_gp_value (output_bfd)
3672     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3673
3674   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3675 }
3676
3677 /* Create and return a local GOT entry for VALUE, which was calculated
3678    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3679    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3680    instead.  */
3681
3682 static struct mips_got_entry *
3683 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3684                                  bfd *ibfd, bfd_vma value,
3685                                  unsigned long r_symndx,
3686                                  struct mips_elf_link_hash_entry *h,
3687                                  int r_type)
3688 {
3689   struct mips_got_entry lookup, *entry;
3690   void **loc;
3691   struct mips_got_info *g;
3692   struct mips_elf_link_hash_table *htab;
3693   bfd_vma gotidx;
3694
3695   htab = mips_elf_hash_table (info);
3696   BFD_ASSERT (htab != NULL);
3697
3698   g = mips_elf_bfd_got (ibfd, FALSE);
3699   if (g == NULL)
3700     {
3701       g = mips_elf_bfd_got (abfd, FALSE);
3702       BFD_ASSERT (g != NULL);
3703     }
3704
3705   /* This function shouldn't be called for symbols that live in the global
3706      area of the GOT.  */
3707   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3708
3709   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3710   if (lookup.tls_type)
3711     {
3712       lookup.abfd = ibfd;
3713       if (tls_ldm_reloc_p (r_type))
3714         {
3715           lookup.symndx = 0;
3716           lookup.d.addend = 0;
3717         }
3718       else if (h == NULL)
3719         {
3720           lookup.symndx = r_symndx;
3721           lookup.d.addend = 0;
3722         }
3723       else
3724         {
3725           lookup.symndx = -1;
3726           lookup.d.h = h;
3727         }
3728
3729       entry = (struct mips_got_entry *) htab_find (g->got_entries, &lookup);
3730       BFD_ASSERT (entry);
3731
3732       gotidx = entry->gotidx;
3733       BFD_ASSERT (gotidx > 0 && gotidx < htab->root.sgot->size);
3734
3735       return entry;
3736     }
3737
3738   lookup.abfd = NULL;
3739   lookup.symndx = -1;
3740   lookup.d.address = value;
3741   loc = htab_find_slot (g->got_entries, &lookup, INSERT);
3742   if (!loc)
3743     return NULL;
3744
3745   entry = (struct mips_got_entry *) *loc;
3746   if (entry)
3747     return entry;
3748
3749   if (g->assigned_low_gotno > g->assigned_high_gotno)
3750     {
3751       /* We didn't allocate enough space in the GOT.  */
3752       _bfd_error_handler
3753         (_("not enough GOT space for local GOT entries"));
3754       bfd_set_error (bfd_error_bad_value);
3755       return NULL;
3756     }
3757
3758   entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3759   if (!entry)
3760     return NULL;
3761
3762   if (got16_reloc_p (r_type)
3763       || call16_reloc_p (r_type)
3764       || got_page_reloc_p (r_type)
3765       || got_disp_reloc_p (r_type))
3766     lookup.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_low_gotno++;
3767   else
3768     lookup.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_high_gotno--;
3769
3770   *entry = lookup;
3771   *loc = entry;
3772
3773   MIPS_ELF_PUT_WORD (abfd, value, htab->root.sgot->contents + entry->gotidx);
3774
3775   /* These GOT entries need a dynamic relocation on VxWorks.  */
3776   if (htab->is_vxworks)
3777     {
3778       Elf_Internal_Rela outrel;
3779       asection *s;
3780       bfd_byte *rloc;
3781       bfd_vma got_address;
3782
3783       s = mips_elf_rel_dyn_section (info, FALSE);
3784       got_address = (htab->root.sgot->output_section->vma
3785                      + htab->root.sgot->output_offset
3786                      + entry->gotidx);
3787
3788       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3789       outrel.r_offset = got_address;
3790       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3791       outrel.r_addend = value;
3792       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3793     }
3794
3795   return entry;
3796 }
3797
3798 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3799    The number might be exact or a worst-case estimate, depending on how
3800    much information is available to elf_backend_omit_section_dynsym at
3801    the current linking stage.  */
3802
3803 static bfd_size_type
3804 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3805 {
3806   bfd_size_type count;
3807
3808   count = 0;
3809   if (bfd_link_pic (info)
3810       || elf_hash_table (info)->is_relocatable_executable)
3811     {
3812       asection *p;
3813       const struct elf_backend_data *bed;
3814
3815       bed = get_elf_backend_data (output_bfd);
3816       for (p = output_bfd->sections; p ; p = p->next)
3817         if ((p->flags & SEC_EXCLUDE) == 0
3818             && (p->flags & SEC_ALLOC) != 0
3819             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3820           ++count;
3821     }
3822   return count;
3823 }
3824
3825 /* Sort the dynamic symbol table so that symbols that need GOT entries
3826    appear towards the end.  */
3827
3828 static bfd_boolean
3829 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3830 {
3831   struct mips_elf_link_hash_table *htab;
3832   struct mips_elf_hash_sort_data hsd;
3833   struct mips_got_info *g;
3834
3835   htab = mips_elf_hash_table (info);
3836   BFD_ASSERT (htab != NULL);
3837
3838   if (elf_hash_table (info)->dynsymcount == 0)
3839     return TRUE;
3840
3841   g = htab->got_info;
3842   if (g == NULL)
3843     return TRUE;
3844
3845   hsd.low = NULL;
3846   hsd.max_unref_got_dynindx
3847     = hsd.min_got_dynindx
3848     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3849   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3850   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3851                                 elf_hash_table (info)),
3852                                mips_elf_sort_hash_table_f,
3853                                &hsd);
3854
3855   /* There should have been enough room in the symbol table to
3856      accommodate both the GOT and non-GOT symbols.  */
3857   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3858   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3859               == elf_hash_table (info)->dynsymcount);
3860   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3861               == g->global_gotno);
3862
3863   /* Now we know which dynamic symbol has the lowest dynamic symbol
3864      table index in the GOT.  */
3865   htab->global_gotsym = hsd.low;
3866
3867   return TRUE;
3868 }
3869
3870 /* If H needs a GOT entry, assign it the highest available dynamic
3871    index.  Otherwise, assign it the lowest available dynamic
3872    index.  */
3873
3874 static bfd_boolean
3875 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3876 {
3877   struct mips_elf_hash_sort_data *hsd = data;
3878
3879   /* Symbols without dynamic symbol table entries aren't interesting
3880      at all.  */
3881   if (h->root.dynindx == -1)
3882     return TRUE;
3883
3884   switch (h->global_got_area)
3885     {
3886     case GGA_NONE:
3887       h->root.dynindx = hsd->max_non_got_dynindx++;
3888       break;
3889
3890     case GGA_NORMAL:
3891       h->root.dynindx = --hsd->min_got_dynindx;
3892       hsd->low = (struct elf_link_hash_entry *) h;
3893       break;
3894
3895     case GGA_RELOC_ONLY:
3896       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3897         hsd->low = (struct elf_link_hash_entry *) h;
3898       h->root.dynindx = hsd->max_unref_got_dynindx++;
3899       break;
3900     }
3901
3902   return TRUE;
3903 }
3904
3905 /* Record that input bfd ABFD requires a GOT entry like *LOOKUP
3906    (which is owned by the caller and shouldn't be added to the
3907    hash table directly).  */
3908
3909 static bfd_boolean
3910 mips_elf_record_got_entry (struct bfd_link_info *info, bfd *abfd,
3911                            struct mips_got_entry *lookup)
3912 {
3913   struct mips_elf_link_hash_table *htab;
3914   struct mips_got_entry *entry;
3915   struct mips_got_info *g;
3916   void **loc, **bfd_loc;
3917
3918   /* Make sure there's a slot for this entry in the master GOT.  */
3919   htab = mips_elf_hash_table (info);
3920   g = htab->got_info;
3921   loc = htab_find_slot (g->got_entries, lookup, INSERT);
3922   if (!loc)
3923     return FALSE;
3924
3925   /* Populate the entry if it isn't already.  */
3926   entry = (struct mips_got_entry *) *loc;
3927   if (!entry)
3928     {
3929       entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3930       if (!entry)
3931         return FALSE;
3932
3933       lookup->tls_initialized = FALSE;
3934       lookup->gotidx = -1;
3935       *entry = *lookup;
3936       *loc = entry;
3937     }
3938
3939   /* Reuse the same GOT entry for the BFD's GOT.  */
3940   g = mips_elf_bfd_got (abfd, TRUE);
3941   if (!g)
3942     return FALSE;
3943
3944   bfd_loc = htab_find_slot (g->got_entries, lookup, INSERT);
3945   if (!bfd_loc)
3946     return FALSE;
3947
3948   if (!*bfd_loc)
3949     *bfd_loc = entry;
3950   return TRUE;
3951 }
3952
3953 /* ABFD has a GOT relocation of type R_TYPE against H.  Reserve a GOT
3954    entry for it.  FOR_CALL is true if the caller is only interested in
3955    using the GOT entry for calls.  */
3956
3957 static bfd_boolean
3958 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3959                                    bfd *abfd, struct bfd_link_info *info,
3960                                    bfd_boolean for_call, int r_type)
3961 {
3962   struct mips_elf_link_hash_table *htab;
3963   struct mips_elf_link_hash_entry *hmips;
3964   struct mips_got_entry entry;
3965   unsigned char tls_type;
3966
3967   htab = mips_elf_hash_table (info);
3968   BFD_ASSERT (htab != NULL);
3969
3970   hmips = (struct mips_elf_link_hash_entry *) h;
3971   if (!for_call)
3972     hmips->got_only_for_calls = FALSE;
3973
3974   /* A global symbol in the GOT must also be in the dynamic symbol
3975      table.  */
3976   if (h->dynindx == -1)
3977     {
3978       switch (ELF_ST_VISIBILITY (h->other))
3979         {
3980         case STV_INTERNAL:
3981         case STV_HIDDEN:
3982           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3983           break;
3984         }
3985       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3986         return FALSE;
3987     }
3988
3989   tls_type = mips_elf_reloc_tls_type (r_type);
3990   if (tls_type == GOT_TLS_NONE && hmips->global_got_area > GGA_NORMAL)
3991     hmips->global_got_area = GGA_NORMAL;
3992
3993   entry.abfd = abfd;
3994   entry.symndx = -1;
3995   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3996   entry.tls_type = tls_type;
3997   return mips_elf_record_got_entry (info, abfd, &entry);
3998 }
3999
4000 /* ABFD has a GOT relocation of type R_TYPE against symbol SYMNDX + ADDEND,
4001    where SYMNDX is a local symbol.  Reserve a GOT entry for it.  */
4002
4003 static bfd_boolean
4004 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
4005                                   struct bfd_link_info *info, int r_type)
4006 {
4007   struct mips_elf_link_hash_table *htab;
4008   struct mips_got_info *g;
4009   struct mips_got_entry entry;
4010
4011   htab = mips_elf_hash_table (info);
4012   BFD_ASSERT (htab != NULL);
4013
4014   g = htab->got_info;
4015   BFD_ASSERT (g != NULL);
4016
4017   entry.abfd = abfd;
4018   entry.symndx = symndx;
4019   entry.d.addend = addend;
4020   entry.tls_type = mips_elf_reloc_tls_type (r_type);
4021   return mips_elf_record_got_entry (info, abfd, &entry);
4022 }
4023
4024 /* Record that ABFD has a page relocation against SYMNDX + ADDEND.
4025    H is the symbol's hash table entry, or null if SYMNDX is local
4026    to ABFD.  */
4027
4028 static bfd_boolean
4029 mips_elf_record_got_page_ref (struct bfd_link_info *info, bfd *abfd,
4030                               long symndx, struct elf_link_hash_entry *h,
4031                               bfd_signed_vma addend)
4032 {
4033   struct mips_elf_link_hash_table *htab;
4034   struct mips_got_info *g1, *g2;
4035   struct mips_got_page_ref lookup, *entry;
4036   void **loc, **bfd_loc;
4037
4038   htab = mips_elf_hash_table (info);
4039   BFD_ASSERT (htab != NULL);
4040
4041   g1 = htab->got_info;
4042   BFD_ASSERT (g1 != NULL);
4043
4044   if (h)
4045     {
4046       lookup.symndx = -1;
4047       lookup.u.h = (struct mips_elf_link_hash_entry *) h;
4048     }
4049   else
4050     {
4051       lookup.symndx = symndx;
4052       lookup.u.abfd = abfd;
4053     }
4054   lookup.addend = addend;
4055   loc = htab_find_slot (g1->got_page_refs, &lookup, INSERT);
4056   if (loc == NULL)
4057     return FALSE;
4058
4059   entry = (struct mips_got_page_ref *) *loc;
4060   if (!entry)
4061     {
4062       entry = bfd_alloc (abfd, sizeof (*entry));
4063       if (!entry)
4064         return FALSE;
4065
4066       *entry = lookup;
4067       *loc = entry;
4068     }
4069
4070   /* Add the same entry to the BFD's GOT.  */
4071   g2 = mips_elf_bfd_got (abfd, TRUE);
4072   if (!g2)
4073     return FALSE;
4074
4075   bfd_loc = htab_find_slot (g2->got_page_refs, &lookup, INSERT);
4076   if (!bfd_loc)
4077     return FALSE;
4078
4079   if (!*bfd_loc)
4080     *bfd_loc = entry;
4081
4082   return TRUE;
4083 }
4084
4085 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
4086
4087 static void
4088 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
4089                                        unsigned int n)
4090 {
4091   asection *s;
4092   struct mips_elf_link_hash_table *htab;
4093
4094   htab = mips_elf_hash_table (info);
4095   BFD_ASSERT (htab != NULL);
4096
4097   s = mips_elf_rel_dyn_section (info, FALSE);
4098   BFD_ASSERT (s != NULL);
4099
4100   if (htab->is_vxworks)
4101     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
4102   else
4103     {
4104       if (s->size == 0)
4105         {
4106           /* Make room for a null element.  */
4107           s->size += MIPS_ELF_REL_SIZE (abfd);
4108           ++s->reloc_count;
4109         }
4110       s->size += n * MIPS_ELF_REL_SIZE (abfd);
4111     }
4112 }
4113 \f
4114 /* A htab_traverse callback for GOT entries, with DATA pointing to a
4115    mips_elf_traverse_got_arg structure.  Count the number of GOT
4116    entries and TLS relocs.  Set DATA->value to true if we need
4117    to resolve indirect or warning symbols and then recreate the GOT.  */
4118
4119 static int
4120 mips_elf_check_recreate_got (void **entryp, void *data)
4121 {
4122   struct mips_got_entry *entry;
4123   struct mips_elf_traverse_got_arg *arg;
4124
4125   entry = (struct mips_got_entry *) *entryp;
4126   arg = (struct mips_elf_traverse_got_arg *) data;
4127   if (entry->abfd != NULL && entry->symndx == -1)
4128     {
4129       struct mips_elf_link_hash_entry *h;
4130
4131       h = entry->d.h;
4132       if (h->root.root.type == bfd_link_hash_indirect
4133           || h->root.root.type == bfd_link_hash_warning)
4134         {
4135           arg->value = TRUE;
4136           return 0;
4137         }
4138     }
4139   mips_elf_count_got_entry (arg->info, arg->g, entry);
4140   return 1;
4141 }
4142
4143 /* A htab_traverse callback for GOT entries, with DATA pointing to a
4144    mips_elf_traverse_got_arg structure.  Add all entries to DATA->g,
4145    converting entries for indirect and warning symbols into entries
4146    for the target symbol.  Set DATA->g to null on error.  */
4147
4148 static int
4149 mips_elf_recreate_got (void **entryp, void *data)
4150 {
4151   struct mips_got_entry new_entry, *entry;
4152   struct mips_elf_traverse_got_arg *arg;
4153   void **slot;
4154
4155   entry = (struct mips_got_entry *) *entryp;
4156   arg = (struct mips_elf_traverse_got_arg *) data;
4157   if (entry->abfd != NULL
4158       && entry->symndx == -1
4159       && (entry->d.h->root.root.type == bfd_link_hash_indirect
4160           || entry->d.h->root.root.type == bfd_link_hash_warning))
4161     {
4162       struct mips_elf_link_hash_entry *h;
4163
4164       new_entry = *entry;
4165       entry = &new_entry;
4166       h = entry->d.h;
4167       do
4168         {
4169           BFD_ASSERT (h->global_got_area == GGA_NONE);
4170           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
4171         }
4172       while (h->root.root.type == bfd_link_hash_indirect
4173              || h->root.root.type == bfd_link_hash_warning);
4174       entry->d.h = h;
4175     }
4176   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
4177   if (slot == NULL)
4178     {
4179       arg->g = NULL;
4180       return 0;
4181     }
4182   if (*slot == NULL)
4183     {
4184       if (entry == &new_entry)
4185         {
4186           entry = bfd_alloc (entry->abfd, sizeof (*entry));
4187           if (!entry)
4188             {
4189               arg->g = NULL;
4190               return 0;
4191             }
4192           *entry = new_entry;
4193         }
4194       *slot = entry;
4195       mips_elf_count_got_entry (arg->info, arg->g, entry);
4196     }
4197   return 1;
4198 }
4199
4200 /* Return the maximum number of GOT page entries required for RANGE.  */
4201
4202 static bfd_vma
4203 mips_elf_pages_for_range (const struct mips_got_page_range *range)
4204 {
4205   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
4206 }
4207
4208 /* Record that G requires a page entry that can reach SEC + ADDEND.  */
4209
4210 static bfd_boolean
4211 mips_elf_record_got_page_entry (struct mips_elf_traverse_got_arg *arg,
4212                                 asection *sec, bfd_signed_vma addend)
4213 {
4214   struct mips_got_info *g = arg->g;
4215   struct mips_got_page_entry lookup, *entry;
4216   struct mips_got_page_range **range_ptr, *range;
4217   bfd_vma old_pages, new_pages;
4218   void **loc;
4219
4220   /* Find the mips_got_page_entry hash table entry for this section.  */
4221   lookup.sec = sec;
4222   loc = htab_find_slot (g->got_page_entries, &lookup, INSERT);
4223   if (loc == NULL)
4224     return FALSE;
4225
4226   /* Create a mips_got_page_entry if this is the first time we've
4227      seen the section.  */
4228   entry = (struct mips_got_page_entry *) *loc;
4229   if (!entry)
4230     {
4231       entry = bfd_zalloc (arg->info->output_bfd, sizeof (*entry));
4232       if (!entry)
4233         return FALSE;
4234
4235       entry->sec = sec;
4236       *loc = entry;
4237     }
4238
4239   /* Skip over ranges whose maximum extent cannot share a page entry
4240      with ADDEND.  */
4241   range_ptr = &entry->ranges;
4242   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
4243     range_ptr = &(*range_ptr)->next;
4244
4245   /* If we scanned to the end of the list, or found a range whose
4246      minimum extent cannot share a page entry with ADDEND, create
4247      a new singleton range.  */
4248   range = *range_ptr;
4249   if (!range || addend < range->min_addend - 0xffff)
4250     {
4251       range = bfd_zalloc (arg->info->output_bfd, sizeof (*range));
4252       if (!range)
4253         return FALSE;
4254
4255       range->next = *range_ptr;
4256       range->min_addend = addend;
4257       range->max_addend = addend;
4258
4259       *range_ptr = range;
4260       entry->num_pages++;
4261       g->page_gotno++;
4262       return TRUE;
4263     }
4264
4265   /* Remember how many pages the old range contributed.  */
4266   old_pages = mips_elf_pages_for_range (range);
4267
4268   /* Update the ranges.  */
4269   if (addend < range->min_addend)
4270     range->min_addend = addend;
4271   else if (addend > range->max_addend)
4272     {
4273       if (range->next && addend >= range->next->min_addend - 0xffff)
4274         {
4275           old_pages += mips_elf_pages_for_range (range->next);
4276           range->max_addend = range->next->max_addend;
4277           range->next = range->next->next;
4278         }
4279       else
4280         range->max_addend = addend;
4281     }
4282
4283   /* Record any change in the total estimate.  */
4284   new_pages = mips_elf_pages_for_range (range);
4285   if (old_pages != new_pages)
4286     {
4287       entry->num_pages += new_pages - old_pages;
4288       g->page_gotno += new_pages - old_pages;
4289     }
4290
4291   return TRUE;
4292 }
4293
4294 /* A htab_traverse callback for which *REFP points to a mips_got_page_ref
4295    and for which DATA points to a mips_elf_traverse_got_arg.  Work out
4296    whether the page reference described by *REFP needs a GOT page entry,
4297    and record that entry in DATA->g if so.  Set DATA->g to null on failure.  */
4298
4299 static bfd_boolean
4300 mips_elf_resolve_got_page_ref (void **refp, void *data)
4301 {
4302   struct mips_got_page_ref *ref;
4303   struct mips_elf_traverse_got_arg *arg;
4304   struct mips_elf_link_hash_table *htab;
4305   asection *sec;
4306   bfd_vma addend;
4307
4308   ref = (struct mips_got_page_ref *) *refp;
4309   arg = (struct mips_elf_traverse_got_arg *) data;
4310   htab = mips_elf_hash_table (arg->info);
4311
4312   if (ref->symndx < 0)
4313     {
4314       struct mips_elf_link_hash_entry *h;
4315
4316       /* Global GOT_PAGEs decay to GOT_DISP and so don't need page entries.  */
4317       h = ref->u.h;
4318       if (!SYMBOL_REFERENCES_LOCAL (arg->info, &h->root))
4319         return 1;
4320
4321       /* Ignore undefined symbols; we'll issue an error later if
4322          appropriate.  */
4323       if (!((h->root.root.type == bfd_link_hash_defined
4324              || h->root.root.type == bfd_link_hash_defweak)
4325             && h->root.root.u.def.section))
4326         return 1;
4327
4328       sec = h->root.root.u.def.section;
4329       addend = h->root.root.u.def.value + ref->addend;
4330     }
4331   else
4332     {
4333       Elf_Internal_Sym *isym;
4334
4335       /* Read in the symbol.  */
4336       isym = bfd_sym_from_r_symndx (&htab->sym_cache, ref->u.abfd,
4337                                     ref->symndx);
4338       if (isym == NULL)
4339         {
4340           arg->g = NULL;
4341           return 0;
4342         }
4343
4344       /* Get the associated input section.  */
4345       sec = bfd_section_from_elf_index (ref->u.abfd, isym->st_shndx);
4346       if (sec == NULL)
4347         {
4348           arg->g = NULL;
4349           return 0;
4350         }
4351
4352       /* If this is a mergable section, work out the section and offset
4353          of the merged data.  For section symbols, the addend specifies
4354          of the offset _of_ the first byte in the data, otherwise it
4355          specifies the offset _from_ the first byte.  */
4356       if (sec->flags & SEC_MERGE)
4357         {
4358           void *secinfo;
4359
4360           secinfo = elf_section_data (sec)->sec_info;
4361           if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
4362             addend = _bfd_merged_section_offset (ref->u.abfd, &sec, secinfo,
4363                                                  isym->st_value + ref->addend);
4364           else
4365             addend = _bfd_merged_section_offset (ref->u.abfd, &sec, secinfo,
4366                                                  isym->st_value) + ref->addend;
4367         }
4368       else
4369         addend = isym->st_value + ref->addend;
4370     }
4371   if (!mips_elf_record_got_page_entry (arg, sec, addend))
4372     {
4373       arg->g = NULL;
4374       return 0;
4375     }
4376   return 1;
4377 }
4378
4379 /* If any entries in G->got_entries are for indirect or warning symbols,
4380    replace them with entries for the target symbol.  Convert g->got_page_refs
4381    into got_page_entry structures and estimate the number of page entries
4382    that they require.  */
4383
4384 static bfd_boolean
4385 mips_elf_resolve_final_got_entries (struct bfd_link_info *info,
4386                                     struct mips_got_info *g)
4387 {
4388   struct mips_elf_traverse_got_arg tga;
4389   struct mips_got_info oldg;
4390
4391   oldg = *g;
4392
4393   tga.info = info;
4394   tga.g = g;
4395   tga.value = FALSE;
4396   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &tga);
4397   if (tga.value)
4398     {
4399       *g = oldg;
4400       g->got_entries = htab_create (htab_size (oldg.got_entries),
4401                                     mips_elf_got_entry_hash,
4402                                     mips_elf_got_entry_eq, NULL);
4403       if (!g->got_entries)
4404         return FALSE;
4405
4406       htab_traverse (oldg.got_entries, mips_elf_recreate_got, &tga);
4407       if (!tga.g)
4408         return FALSE;
4409
4410       htab_delete (oldg.got_entries);
4411     }
4412
4413   g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4414                                          mips_got_page_entry_eq, NULL);
4415   if (g->got_page_entries == NULL)
4416     return FALSE;
4417
4418   tga.info = info;
4419   tga.g = g;
4420   htab_traverse (g->got_page_refs, mips_elf_resolve_got_page_ref, &tga);
4421
4422   return TRUE;
4423 }
4424
4425 /* Return true if a GOT entry for H should live in the local rather than
4426    global GOT area.  */
4427
4428 static bfd_boolean
4429 mips_use_local_got_p (struct bfd_link_info *info,
4430                       struct mips_elf_link_hash_entry *h)
4431 {
4432   /* Symbols that aren't in the dynamic symbol table must live in the
4433      local GOT.  This includes symbols that are completely undefined
4434      and which therefore don't bind locally.  We'll report undefined
4435      symbols later if appropriate.  */
4436   if (h->root.dynindx == -1)
4437     return TRUE;
4438
4439   /* Symbols that bind locally can (and in the case of forced-local
4440      symbols, must) live in the local GOT.  */
4441   if (h->got_only_for_calls
4442       ? SYMBOL_CALLS_LOCAL (info, &h->root)
4443       : SYMBOL_REFERENCES_LOCAL (info, &h->root))
4444     return TRUE;
4445
4446   /* If this is an executable that must provide a definition of the symbol,
4447      either though PLTs or copy relocations, then that address should go in
4448      the local rather than global GOT.  */
4449   if (bfd_link_executable (info) && h->has_static_relocs)
4450     return TRUE;
4451
4452   return FALSE;
4453 }
4454
4455 /* A mips_elf_link_hash_traverse callback for which DATA points to the
4456    link_info structure.  Decide whether the hash entry needs an entry in
4457    the global part of the primary GOT, setting global_got_area accordingly.
4458    Count the number of global symbols that are in the primary GOT only
4459    because they have relocations against them (reloc_only_gotno).  */
4460
4461 static int
4462 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
4463 {
4464   struct bfd_link_info *info;
4465   struct mips_elf_link_hash_table *htab;
4466   struct mips_got_info *g;
4467
4468   info = (struct bfd_link_info *) data;
4469   htab = mips_elf_hash_table (info);
4470   g = htab->got_info;
4471   if (h->global_got_area != GGA_NONE)
4472     {
4473       /* Make a final decision about whether the symbol belongs in the
4474          local or global GOT.  */
4475       if (mips_use_local_got_p (info, h))
4476         /* The symbol belongs in the local GOT.  We no longer need this
4477            entry if it was only used for relocations; those relocations
4478            will be against the null or section symbol instead of H.  */
4479         h->global_got_area = GGA_NONE;
4480       else if (htab->is_vxworks
4481                && h->got_only_for_calls
4482                && h->root.plt.plist->mips_offset != MINUS_ONE)
4483         /* On VxWorks, calls can refer directly to the .got.plt entry;
4484            they don't need entries in the regular GOT.  .got.plt entries
4485            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4486         h->global_got_area = GGA_NONE;
4487       else if (h->global_got_area == GGA_RELOC_ONLY)
4488         {
4489           g->reloc_only_gotno++;
4490           g->global_gotno++;
4491         }
4492     }
4493   return 1;
4494 }
4495 \f
4496 /* A htab_traverse callback for GOT entries.  Add each one to the GOT
4497    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4498
4499 static int
4500 mips_elf_add_got_entry (void **entryp, void *data)
4501 {
4502   struct mips_got_entry *entry;
4503   struct mips_elf_traverse_got_arg *arg;
4504   void **slot;
4505
4506   entry = (struct mips_got_entry *) *entryp;
4507   arg = (struct mips_elf_traverse_got_arg *) data;
4508   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
4509   if (!slot)
4510     {
4511       arg->g = NULL;
4512       return 0;
4513     }
4514   if (!*slot)
4515     {
4516       *slot = entry;
4517       mips_elf_count_got_entry (arg->info, arg->g, entry);
4518     }
4519   return 1;
4520 }
4521
4522 /* A htab_traverse callback for GOT page entries.  Add each one to the GOT
4523    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4524
4525 static int
4526 mips_elf_add_got_page_entry (void **entryp, void *data)
4527 {
4528   struct mips_got_page_entry *entry;
4529   struct mips_elf_traverse_got_arg *arg;
4530   void **slot;
4531
4532   entry = (struct mips_got_page_entry *) *entryp;
4533   arg = (struct mips_elf_traverse_got_arg *) data;
4534   slot = htab_find_slot (arg->g->got_page_entries, entry, INSERT);
4535   if (!slot)
4536     {
4537       arg->g = NULL;
4538       return 0;
4539     }
4540   if (!*slot)
4541     {
4542       *slot = entry;
4543       arg->g->page_gotno += entry->num_pages;
4544     }
4545   return 1;
4546 }
4547
4548 /* Consider merging FROM, which is ABFD's GOT, into TO.  Return -1 if
4549    this would lead to overflow, 1 if they were merged successfully,
4550    and 0 if a merge failed due to lack of memory.  (These values are chosen
4551    so that nonnegative return values can be returned by a htab_traverse
4552    callback.)  */
4553
4554 static int
4555 mips_elf_merge_got_with (bfd *abfd, struct mips_got_info *from,
4556                          struct mips_got_info *to,
4557                          struct mips_elf_got_per_bfd_arg *arg)
4558 {
4559   struct mips_elf_traverse_got_arg tga;
4560   unsigned int estimate;
4561
4562   /* Work out how many page entries we would need for the combined GOT.  */
4563   estimate = arg->max_pages;
4564   if (estimate >= from->page_gotno + to->page_gotno)
4565     estimate = from->page_gotno + to->page_gotno;
4566
4567   /* And conservatively estimate how many local and TLS entries
4568      would be needed.  */
4569   estimate += from->local_gotno + to->local_gotno;
4570   estimate += from->tls_gotno + to->tls_gotno;
4571
4572   /* If we're merging with the primary got, any TLS relocations will
4573      come after the full set of global entries.  Otherwise estimate those
4574      conservatively as well.  */
4575   if (to == arg->primary && from->tls_gotno + to->tls_gotno)
4576     estimate += arg->global_count;
4577   else
4578     estimate += from->global_gotno + to->global_gotno;
4579
4580   /* Bail out if the combined GOT might be too big.  */
4581   if (estimate > arg->max_count)
4582     return -1;
4583
4584   /* Transfer the bfd's got information from FROM to TO.  */
4585   tga.info = arg->info;
4586   tga.g = to;
4587   htab_traverse (from->got_entries, mips_elf_add_got_entry, &tga);
4588   if (!tga.g)
4589     return 0;
4590
4591   htab_traverse (from->got_page_entries, mips_elf_add_got_page_entry, &tga);
4592   if (!tga.g)
4593     return 0;
4594
4595   mips_elf_replace_bfd_got (abfd, to);
4596   return 1;
4597 }
4598
4599 /* Attempt to merge GOT G, which belongs to ABFD.  Try to use as much
4600    as possible of the primary got, since it doesn't require explicit
4601    dynamic relocations, but don't use bfds that would reference global
4602    symbols out of the addressable range.  Failing the primary got,
4603    attempt to merge with the current got, or finish the current got
4604    and then make make the new got current.  */
4605
4606 static bfd_boolean
4607 mips_elf_merge_got (bfd *abfd, struct mips_got_info *g,
4608                     struct mips_elf_got_per_bfd_arg *arg)
4609 {
4610   unsigned int estimate;
4611   int result;
4612
4613   if (!mips_elf_resolve_final_got_entries (arg->info, g))
4614     return FALSE;
4615
4616   /* Work out the number of page, local and TLS entries.  */
4617   estimate = arg->max_pages;
4618   if (estimate > g->page_gotno)
4619     estimate = g->page_gotno;
4620   estimate += g->local_gotno + g->tls_gotno;
4621
4622   /* We place TLS GOT entries after both locals and globals.  The globals
4623      for the primary GOT may overflow the normal GOT size limit, so be
4624      sure not to merge a GOT which requires TLS with the primary GOT in that
4625      case.  This doesn't affect non-primary GOTs.  */
4626   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4627
4628   if (estimate <= arg->max_count)
4629     {
4630       /* If we don't have a primary GOT, use it as
4631          a starting point for the primary GOT.  */
4632       if (!arg->primary)
4633         {
4634           arg->primary = g;
4635           return TRUE;
4636         }
4637
4638       /* Try merging with the primary GOT.  */
4639       result = mips_elf_merge_got_with (abfd, g, arg->primary, arg);
4640       if (result >= 0)
4641         return result;
4642     }
4643
4644   /* If we can merge with the last-created got, do it.  */
4645   if (arg->current)
4646     {
4647       result = mips_elf_merge_got_with (abfd, g, arg->current, arg);
4648       if (result >= 0)
4649         return result;
4650     }
4651
4652   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4653      fits; if it turns out that it doesn't, we'll get relocation
4654      overflows anyway.  */
4655   g->next = arg->current;
4656   arg->current = g;
4657
4658   return TRUE;
4659 }
4660
4661 /* ENTRYP is a hash table entry for a mips_got_entry.  Set its gotidx
4662    to GOTIDX, duplicating the entry if it has already been assigned
4663    an index in a different GOT.  */
4664
4665 static bfd_boolean
4666 mips_elf_set_gotidx (void **entryp, long gotidx)
4667 {
4668   struct mips_got_entry *entry;
4669
4670   entry = (struct mips_got_entry *) *entryp;
4671   if (entry->gotidx > 0)
4672     {
4673       struct mips_got_entry *new_entry;
4674
4675       new_entry = bfd_alloc (entry->abfd, sizeof (*entry));
4676       if (!new_entry)
4677         return FALSE;
4678
4679       *new_entry = *entry;
4680       *entryp = new_entry;
4681       entry = new_entry;
4682     }
4683   entry->gotidx = gotidx;
4684   return TRUE;
4685 }
4686
4687 /* Set the TLS GOT index for the GOT entry in ENTRYP.  DATA points to a
4688    mips_elf_traverse_got_arg in which DATA->value is the size of one
4689    GOT entry.  Set DATA->g to null on failure.  */
4690
4691 static int
4692 mips_elf_initialize_tls_index (void **entryp, void *data)
4693 {
4694   struct mips_got_entry *entry;
4695   struct mips_elf_traverse_got_arg *arg;
4696
4697   /* We're only interested in TLS symbols.  */
4698   entry = (struct mips_got_entry *) *entryp;
4699   if (entry->tls_type == GOT_TLS_NONE)
4700     return 1;
4701
4702   arg = (struct mips_elf_traverse_got_arg *) data;
4703   if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->tls_assigned_gotno))
4704     {
4705       arg->g = NULL;
4706       return 0;
4707     }
4708
4709   /* Account for the entries we've just allocated.  */
4710   arg->g->tls_assigned_gotno += mips_tls_got_entries (entry->tls_type);
4711   return 1;
4712 }
4713
4714 /* A htab_traverse callback for GOT entries, where DATA points to a
4715    mips_elf_traverse_got_arg.  Set the global_got_area of each global
4716    symbol to DATA->value.  */
4717
4718 static int
4719 mips_elf_set_global_got_area (void **entryp, void *data)
4720 {
4721   struct mips_got_entry *entry;
4722   struct mips_elf_traverse_got_arg *arg;
4723
4724   entry = (struct mips_got_entry *) *entryp;
4725   arg = (struct mips_elf_traverse_got_arg *) data;
4726   if (entry->abfd != NULL
4727       && entry->symndx == -1
4728       && entry->d.h->global_got_area != GGA_NONE)
4729     entry->d.h->global_got_area = arg->value;
4730   return 1;
4731 }
4732
4733 /* A htab_traverse callback for secondary GOT entries, where DATA points
4734    to a mips_elf_traverse_got_arg.  Assign GOT indices to global entries
4735    and record the number of relocations they require.  DATA->value is
4736    the size of one GOT entry.  Set DATA->g to null on failure.  */
4737
4738 static int
4739 mips_elf_set_global_gotidx (void **entryp, void *data)
4740 {
4741   struct mips_got_entry *entry;
4742   struct mips_elf_traverse_got_arg *arg;
4743
4744   entry = (struct mips_got_entry *) *entryp;
4745   arg = (struct mips_elf_traverse_got_arg *) data;
4746   if (entry->abfd != NULL
4747       && entry->symndx == -1
4748       && entry->d.h->global_got_area != GGA_NONE)
4749     {
4750       if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->assigned_low_gotno))
4751         {
4752           arg->g = NULL;
4753           return 0;
4754         }
4755       arg->g->assigned_low_gotno += 1;
4756
4757       if (bfd_link_pic (arg->info)
4758           || (elf_hash_table (arg->info)->dynamic_sections_created
4759               && entry->d.h->root.def_dynamic
4760               && !entry->d.h->root.def_regular))
4761         arg->g->relocs += 1;
4762     }
4763
4764   return 1;
4765 }
4766
4767 /* A htab_traverse callback for GOT entries for which DATA is the
4768    bfd_link_info.  Forbid any global symbols from having traditional
4769    lazy-binding stubs.  */
4770
4771 static int
4772 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4773 {
4774   struct bfd_link_info *info;
4775   struct mips_elf_link_hash_table *htab;
4776   struct mips_got_entry *entry;
4777
4778   entry = (struct mips_got_entry *) *entryp;
4779   info = (struct bfd_link_info *) data;
4780   htab = mips_elf_hash_table (info);
4781   BFD_ASSERT (htab != NULL);
4782
4783   if (entry->abfd != NULL
4784       && entry->symndx == -1
4785       && entry->d.h->needs_lazy_stub)
4786     {
4787       entry->d.h->needs_lazy_stub = FALSE;
4788       htab->lazy_stub_count--;
4789     }
4790
4791   return 1;
4792 }
4793
4794 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4795    the primary GOT.  */
4796 static bfd_vma
4797 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4798 {
4799   if (!g->next)
4800     return 0;
4801
4802   g = mips_elf_bfd_got (ibfd, FALSE);
4803   if (! g)
4804     return 0;
4805
4806   BFD_ASSERT (g->next);
4807
4808   g = g->next;
4809
4810   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4811     * MIPS_ELF_GOT_SIZE (abfd);
4812 }
4813
4814 /* Turn a single GOT that is too big for 16-bit addressing into
4815    a sequence of GOTs, each one 16-bit addressable.  */
4816
4817 static bfd_boolean
4818 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4819                     asection *got, bfd_size_type pages)
4820 {
4821   struct mips_elf_link_hash_table *htab;
4822   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4823   struct mips_elf_traverse_got_arg tga;
4824   struct mips_got_info *g, *gg;
4825   unsigned int assign, needed_relocs;
4826   bfd *dynobj, *ibfd;
4827
4828   dynobj = elf_hash_table (info)->dynobj;
4829   htab = mips_elf_hash_table (info);
4830   BFD_ASSERT (htab != NULL);
4831
4832   g = htab->got_info;
4833
4834   got_per_bfd_arg.obfd = abfd;
4835   got_per_bfd_arg.info = info;
4836   got_per_bfd_arg.current = NULL;
4837   got_per_bfd_arg.primary = NULL;
4838   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4839                                 / MIPS_ELF_GOT_SIZE (abfd))
4840                                - htab->reserved_gotno);
4841   got_per_bfd_arg.max_pages = pages;
4842   /* The number of globals that will be included in the primary GOT.
4843      See the calls to mips_elf_set_global_got_area below for more
4844      information.  */
4845   got_per_bfd_arg.global_count = g->global_gotno;
4846
4847   /* Try to merge the GOTs of input bfds together, as long as they
4848      don't seem to exceed the maximum GOT size, choosing one of them
4849      to be the primary GOT.  */
4850   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
4851     {
4852       gg = mips_elf_bfd_got (ibfd, FALSE);
4853       if (gg && !mips_elf_merge_got (ibfd, gg, &got_per_bfd_arg))
4854         return FALSE;
4855     }
4856
4857   /* If we do not find any suitable primary GOT, create an empty one.  */
4858   if (got_per_bfd_arg.primary == NULL)
4859     g->next = mips_elf_create_got_info (abfd);
4860   else
4861     g->next = got_per_bfd_arg.primary;
4862   g->next->next = got_per_bfd_arg.current;
4863
4864   /* GG is now the master GOT, and G is the primary GOT.  */
4865   gg = g;
4866   g = g->next;
4867
4868   /* Map the output bfd to the primary got.  That's what we're going
4869      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4870      didn't mark in check_relocs, and we want a quick way to find it.
4871      We can't just use gg->next because we're going to reverse the
4872      list.  */
4873   mips_elf_replace_bfd_got (abfd, g);
4874
4875   /* Every symbol that is referenced in a dynamic relocation must be
4876      present in the primary GOT, so arrange for them to appear after
4877      those that are actually referenced.  */
4878   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4879   g->global_gotno = gg->global_gotno;
4880
4881   tga.info = info;
4882   tga.value = GGA_RELOC_ONLY;
4883   htab_traverse (gg->got_entries, mips_elf_set_global_got_area, &tga);
4884   tga.value = GGA_NORMAL;
4885   htab_traverse (g->got_entries, mips_elf_set_global_got_area, &tga);
4886
4887   /* Now go through the GOTs assigning them offset ranges.
4888      [assigned_low_gotno, local_gotno[ will be set to the range of local
4889      entries in each GOT.  We can then compute the end of a GOT by
4890      adding local_gotno to global_gotno.  We reverse the list and make
4891      it circular since then we'll be able to quickly compute the
4892      beginning of a GOT, by computing the end of its predecessor.  To
4893      avoid special cases for the primary GOT, while still preserving
4894      assertions that are valid for both single- and multi-got links,
4895      we arrange for the main got struct to have the right number of
4896      global entries, but set its local_gotno such that the initial
4897      offset of the primary GOT is zero.  Remember that the primary GOT
4898      will become the last item in the circular linked list, so it
4899      points back to the master GOT.  */
4900   gg->local_gotno = -g->global_gotno;
4901   gg->global_gotno = g->global_gotno;
4902   gg->tls_gotno = 0;
4903   assign = 0;
4904   gg->next = gg;
4905
4906   do
4907     {
4908       struct mips_got_info *gn;
4909
4910       assign += htab->reserved_gotno;
4911       g->assigned_low_gotno = assign;
4912       g->local_gotno += assign;
4913       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4914       g->assigned_high_gotno = g->local_gotno - 1;
4915       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4916
4917       /* Take g out of the direct list, and push it onto the reversed
4918          list that gg points to.  g->next is guaranteed to be nonnull after
4919          this operation, as required by mips_elf_initialize_tls_index. */
4920       gn = g->next;
4921       g->next = gg->next;
4922       gg->next = g;
4923
4924       /* Set up any TLS entries.  We always place the TLS entries after
4925          all non-TLS entries.  */
4926       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4927       tga.g = g;
4928       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4929       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
4930       if (!tga.g)
4931         return FALSE;
4932       BFD_ASSERT (g->tls_assigned_gotno == assign);
4933
4934       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4935       g = gn;
4936
4937       /* Forbid global symbols in every non-primary GOT from having
4938          lazy-binding stubs.  */
4939       if (g)
4940         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4941     }
4942   while (g);
4943
4944   got->size = assign * MIPS_ELF_GOT_SIZE (abfd);
4945
4946   needed_relocs = 0;
4947   for (g = gg->next; g && g->next != gg; g = g->next)
4948     {
4949       unsigned int save_assign;
4950
4951       /* Assign offsets to global GOT entries and count how many
4952          relocations they need.  */
4953       save_assign = g->assigned_low_gotno;
4954       g->assigned_low_gotno = g->local_gotno;
4955       tga.info = info;
4956       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4957       tga.g = g;
4958       htab_traverse (g->got_entries, mips_elf_set_global_gotidx, &tga);
4959       if (!tga.g)
4960         return FALSE;
4961       BFD_ASSERT (g->assigned_low_gotno == g->local_gotno + g->global_gotno);
4962       g->assigned_low_gotno = save_assign;
4963
4964       if (bfd_link_pic (info))
4965         {
4966           g->relocs += g->local_gotno - g->assigned_low_gotno;
4967           BFD_ASSERT (g->assigned_low_gotno == g->next->local_gotno
4968                       + g->next->global_gotno
4969                       + g->next->tls_gotno
4970                       + htab->reserved_gotno);
4971         }
4972       needed_relocs += g->relocs;
4973     }
4974   needed_relocs += g->relocs;
4975
4976   if (needed_relocs)
4977     mips_elf_allocate_dynamic_relocations (dynobj, info,
4978                                            needed_relocs);
4979
4980   return TRUE;
4981 }
4982
4983 \f
4984 /* Returns the first relocation of type r_type found, beginning with
4985    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4986
4987 static const Elf_Internal_Rela *
4988 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4989                           const Elf_Internal_Rela *relocation,
4990                           const Elf_Internal_Rela *relend)
4991 {
4992   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4993
4994   while (relocation < relend)
4995     {
4996       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4997           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4998         return relocation;
4999
5000       ++relocation;
5001     }
5002
5003   /* We didn't find it.  */
5004   return NULL;
5005 }
5006
5007 /* Return whether an input relocation is against a local symbol.  */
5008
5009 static bfd_boolean
5010 mips_elf_local_relocation_p (bfd *input_bfd,
5011                              const Elf_Internal_Rela *relocation,
5012                              asection **local_sections)
5013 {
5014   unsigned long r_symndx;
5015   Elf_Internal_Shdr *symtab_hdr;
5016   size_t extsymoff;
5017
5018   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
5019   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
5020   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
5021
5022   if (r_symndx < extsymoff)
5023     return TRUE;
5024   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
5025     return TRUE;
5026
5027   return FALSE;
5028 }
5029 \f
5030 /* Sign-extend VALUE, which has the indicated number of BITS.  */
5031
5032 bfd_vma
5033 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
5034 {
5035   if (value & ((bfd_vma) 1 << (bits - 1)))
5036     /* VALUE is negative.  */
5037     value |= ((bfd_vma) - 1) << bits;
5038
5039   return value;
5040 }
5041
5042 /* Return non-zero if the indicated VALUE has overflowed the maximum
5043    range expressible by a signed number with the indicated number of
5044    BITS.  */
5045
5046 static bfd_boolean
5047 mips_elf_overflow_p (bfd_vma value, int bits)
5048 {
5049   bfd_signed_vma svalue = (bfd_signed_vma) value;
5050
5051   if (svalue > (1 << (bits - 1)) - 1)
5052     /* The value is too big.  */
5053     return TRUE;
5054   else if (svalue < -(1 << (bits - 1)))
5055     /* The value is too small.  */
5056     return TRUE;
5057
5058   /* All is well.  */
5059   return FALSE;
5060 }
5061
5062 /* Calculate the %high function.  */
5063
5064 static bfd_vma
5065 mips_elf_high (bfd_vma value)
5066 {
5067   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
5068 }
5069
5070 /* Calculate the %higher function.  */
5071
5072 static bfd_vma
5073 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
5074 {
5075 #ifdef BFD64
5076   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
5077 #else
5078   abort ();
5079   return MINUS_ONE;
5080 #endif
5081 }
5082
5083 /* Calculate the %highest function.  */
5084
5085 static bfd_vma
5086 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
5087 {
5088 #ifdef BFD64
5089   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
5090 #else
5091   abort ();
5092   return MINUS_ONE;
5093 #endif
5094 }
5095 \f
5096 /* Create the .compact_rel section.  */
5097
5098 static bfd_boolean
5099 mips_elf_create_compact_rel_section
5100   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
5101 {
5102   flagword flags;
5103   register asection *s;
5104
5105   if (bfd_get_linker_section (abfd, ".compact_rel") == NULL)
5106     {
5107       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
5108                | SEC_READONLY);
5109
5110       s = bfd_make_section_anyway_with_flags (abfd, ".compact_rel", flags);
5111       if (s == NULL
5112           || ! bfd_set_section_alignment (abfd, s,
5113                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
5114         return FALSE;
5115
5116       s->size = sizeof (Elf32_External_compact_rel);
5117     }
5118
5119   return TRUE;
5120 }
5121
5122 /* Create the .got section to hold the global offset table.  */
5123
5124 static bfd_boolean
5125 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
5126 {
5127   flagword flags;
5128   register asection *s;
5129   struct elf_link_hash_entry *h;
5130   struct bfd_link_hash_entry *bh;
5131   struct mips_elf_link_hash_table *htab;
5132
5133   htab = mips_elf_hash_table (info);
5134   BFD_ASSERT (htab != NULL);
5135
5136   /* This function may be called more than once.  */
5137   if (htab->root.sgot)
5138     return TRUE;
5139
5140   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
5141            | SEC_LINKER_CREATED);
5142
5143   /* We have to use an alignment of 2**4 here because this is hardcoded
5144      in the function stub generation and in the linker script.  */
5145   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
5146   if (s == NULL
5147       || ! bfd_set_section_alignment (abfd, s, 4))
5148     return FALSE;
5149   htab->root.sgot = s;
5150
5151   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
5152      linker script because we don't want to define the symbol if we
5153      are not creating a global offset table.  */
5154   bh = NULL;
5155   if (! (_bfd_generic_link_add_one_symbol
5156          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
5157           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
5158     return FALSE;
5159
5160   h = (struct elf_link_hash_entry *) bh;
5161   h->non_elf = 0;
5162   h->def_regular = 1;
5163   h->type = STT_OBJECT;
5164   h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
5165   elf_hash_table (info)->hgot = h;
5166
5167   if (bfd_link_pic (info)
5168       && ! bfd_elf_link_record_dynamic_symbol (info, h))
5169     return FALSE;
5170
5171   htab->got_info = mips_elf_create_got_info (abfd);
5172   mips_elf_section_data (s)->elf.this_hdr.sh_flags
5173     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
5174
5175   /* We also need a .got.plt section when generating PLTs.  */
5176   s = bfd_make_section_anyway_with_flags (abfd, ".got.plt",
5177                                           SEC_ALLOC | SEC_LOAD
5178                                           | SEC_HAS_CONTENTS
5179                                           | SEC_IN_MEMORY
5180                                           | SEC_LINKER_CREATED);
5181   if (s == NULL)
5182     return FALSE;
5183   htab->root.sgotplt = s;
5184
5185   return TRUE;
5186 }
5187 \f
5188 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
5189    __GOTT_INDEX__ symbols.  These symbols are only special for
5190    shared objects; they are not used in executables.  */
5191
5192 static bfd_boolean
5193 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
5194 {
5195   return (mips_elf_hash_table (info)->is_vxworks
5196           && bfd_link_pic (info)
5197           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
5198               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
5199 }
5200
5201 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
5202    require an la25 stub.  See also mips_elf_local_pic_function_p,
5203    which determines whether the destination function ever requires a
5204    stub.  */
5205
5206 static bfd_boolean
5207 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type,
5208                                      bfd_boolean target_is_16_bit_code_p)
5209 {
5210   /* We specifically ignore branches and jumps from EF_PIC objects,
5211      where the onus is on the compiler or programmer to perform any
5212      necessary initialization of $25.  Sometimes such initialization
5213      is unnecessary; for example, -mno-shared functions do not use
5214      the incoming value of $25, and may therefore be called directly.  */
5215   if (PIC_OBJECT_P (input_bfd))
5216     return FALSE;
5217
5218   switch (r_type)
5219     {
5220     case R_MIPS_26:
5221     case R_MIPS_PC16:
5222     case R_MIPS_PC21_S2:
5223     case R_MIPS_PC26_S2:
5224     case R_MICROMIPS_26_S1:
5225     case R_MICROMIPS_PC7_S1:
5226     case R_MICROMIPS_PC10_S1:
5227     case R_MICROMIPS_PC16_S1:
5228     case R_MICROMIPS_PC23_S2:
5229       return TRUE;
5230
5231     case R_MIPS16_26:
5232       return !target_is_16_bit_code_p;
5233
5234     default:
5235       return FALSE;
5236     }
5237 }
5238 \f
5239 /* Calculate the value produced by the RELOCATION (which comes from
5240    the INPUT_BFD).  The ADDEND is the addend to use for this
5241    RELOCATION; RELOCATION->R_ADDEND is ignored.
5242
5243    The result of the relocation calculation is stored in VALUEP.
5244    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
5245    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5246
5247    This function returns bfd_reloc_continue if the caller need take no
5248    further action regarding this relocation, bfd_reloc_notsupported if
5249    something goes dramatically wrong, bfd_reloc_overflow if an
5250    overflow occurs, and bfd_reloc_ok to indicate success.  */
5251
5252 static bfd_reloc_status_type
5253 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
5254                                asection *input_section,
5255                                struct bfd_link_info *info,
5256                                const Elf_Internal_Rela *relocation,
5257                                bfd_vma addend, reloc_howto_type *howto,
5258                                Elf_Internal_Sym *local_syms,
5259                                asection **local_sections, bfd_vma *valuep,
5260                                const char **namep,
5261                                bfd_boolean *cross_mode_jump_p,
5262                                bfd_boolean save_addend)
5263 {
5264   /* The eventual value we will return.  */
5265   bfd_vma value;
5266   /* The address of the symbol against which the relocation is
5267      occurring.  */
5268   bfd_vma symbol = 0;
5269   /* The final GP value to be used for the relocatable, executable, or
5270      shared object file being produced.  */
5271   bfd_vma gp;
5272   /* The place (section offset or address) of the storage unit being
5273      relocated.  */
5274   bfd_vma p;
5275   /* The value of GP used to create the relocatable object.  */
5276   bfd_vma gp0;
5277   /* The offset into the global offset table at which the address of
5278      the relocation entry symbol, adjusted by the addend, resides
5279      during execution.  */
5280   bfd_vma g = MINUS_ONE;
5281   /* The section in which the symbol referenced by the relocation is
5282      located.  */
5283   asection *sec = NULL;
5284   struct mips_elf_link_hash_entry *h = NULL;
5285   /* TRUE if the symbol referred to by this relocation is a local
5286      symbol.  */
5287   bfd_boolean local_p, was_local_p;
5288   /* TRUE if the symbol referred to by this relocation is a section
5289      symbol.  */
5290   bfd_boolean section_p = FALSE;
5291   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
5292   bfd_boolean gp_disp_p = FALSE;
5293   /* TRUE if the symbol referred to by this relocation is
5294      "__gnu_local_gp".  */
5295   bfd_boolean gnu_local_gp_p = FALSE;
5296   Elf_Internal_Shdr *symtab_hdr;
5297   size_t extsymoff;
5298   unsigned long r_symndx;
5299   int r_type;
5300   /* TRUE if overflow occurred during the calculation of the
5301      relocation value.  */
5302   bfd_boolean overflowed_p;
5303   /* TRUE if this relocation refers to a MIPS16 function.  */
5304   bfd_boolean target_is_16_bit_code_p = FALSE;
5305   bfd_boolean target_is_micromips_code_p = FALSE;
5306   struct mips_elf_link_hash_table *htab;
5307   bfd *dynobj;
5308
5309   dynobj = elf_hash_table (info)->dynobj;
5310   htab = mips_elf_hash_table (info);
5311   BFD_ASSERT (htab != NULL);
5312
5313   /* Parse the relocation.  */
5314   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
5315   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5316   p = (input_section->output_section->vma
5317        + input_section->output_offset
5318        + relocation->r_offset);
5319
5320   /* Assume that there will be no overflow.  */
5321   overflowed_p = FALSE;
5322
5323   /* Figure out whether or not the symbol is local, and get the offset
5324      used in the array of hash table entries.  */
5325   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
5326   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
5327                                          local_sections);
5328   was_local_p = local_p;
5329   if (! elf_bad_symtab (input_bfd))
5330     extsymoff = symtab_hdr->sh_info;
5331   else
5332     {
5333       /* The symbol table does not follow the rule that local symbols
5334          must come before globals.  */
5335       extsymoff = 0;
5336     }
5337
5338   /* Figure out the value of the symbol.  */
5339   if (local_p)
5340     {
5341       bfd_boolean micromips_p = MICROMIPS_P (abfd);
5342       Elf_Internal_Sym *sym;
5343
5344       sym = local_syms + r_symndx;
5345       sec = local_sections[r_symndx];
5346
5347       section_p = ELF_ST_TYPE (sym->st_info) == STT_SECTION;
5348
5349       symbol = sec->output_section->vma + sec->output_offset;
5350       if (!section_p || (sec->flags & SEC_MERGE))
5351         symbol += sym->st_value;
5352       if ((sec->flags & SEC_MERGE) && section_p)
5353         {
5354           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
5355           addend -= symbol;
5356           addend += sec->output_section->vma + sec->output_offset;
5357         }
5358
5359       /* MIPS16/microMIPS text labels should be treated as odd.  */
5360       if (ELF_ST_IS_COMPRESSED (sym->st_other))
5361         ++symbol;
5362
5363       /* Record the name of this symbol, for our caller.  */
5364       *namep = bfd_elf_string_from_elf_section (input_bfd,
5365                                                 symtab_hdr->sh_link,
5366                                                 sym->st_name);
5367       if (*namep == NULL || **namep == '\0')
5368         *namep = bfd_section_name (input_bfd, sec);
5369
5370       /* For relocations against a section symbol and ones against no
5371          symbol (absolute relocations) infer the ISA mode from the addend.  */
5372       if (section_p || r_symndx == STN_UNDEF)
5373         {
5374           target_is_16_bit_code_p = (addend & 1) && !micromips_p;
5375           target_is_micromips_code_p = (addend & 1) && micromips_p;
5376         }
5377       /* For relocations against an absolute symbol infer the ISA mode
5378          from the value of the symbol plus addend.  */
5379       else if (bfd_is_abs_section (sec))
5380         {
5381           target_is_16_bit_code_p = ((symbol + addend) & 1) && !micromips_p;
5382           target_is_micromips_code_p = ((symbol + addend) & 1) && micromips_p;
5383         }
5384       /* Otherwise just use the regular symbol annotation available.  */
5385       else
5386         {
5387           target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
5388           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
5389         }
5390     }
5391   else
5392     {
5393       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
5394
5395       /* For global symbols we look up the symbol in the hash-table.  */
5396       h = ((struct mips_elf_link_hash_entry *)
5397            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
5398       /* Find the real hash-table entry for this symbol.  */
5399       while (h->root.root.type == bfd_link_hash_indirect
5400              || h->root.root.type == bfd_link_hash_warning)
5401         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
5402
5403       /* Record the name of this symbol, for our caller.  */
5404       *namep = h->root.root.root.string;
5405
5406       /* See if this is the special _gp_disp symbol.  Note that such a
5407          symbol must always be a global symbol.  */
5408       if (strcmp (*namep, "_gp_disp") == 0
5409           && ! NEWABI_P (input_bfd))
5410         {
5411           /* Relocations against _gp_disp are permitted only with
5412              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
5413           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
5414             return bfd_reloc_notsupported;
5415
5416           gp_disp_p = TRUE;
5417         }
5418       /* See if this is the special _gp symbol.  Note that such a
5419          symbol must always be a global symbol.  */
5420       else if (strcmp (*namep, "__gnu_local_gp") == 0)
5421         gnu_local_gp_p = TRUE;
5422
5423
5424       /* If this symbol is defined, calculate its address.  Note that
5425          _gp_disp is a magic symbol, always implicitly defined by the
5426          linker, so it's inappropriate to check to see whether or not
5427          its defined.  */
5428       else if ((h->root.root.type == bfd_link_hash_defined
5429                 || h->root.root.type == bfd_link_hash_defweak)
5430                && h->root.root.u.def.section)
5431         {
5432           sec = h->root.root.u.def.section;
5433           if (sec->output_section)
5434             symbol = (h->root.root.u.def.value
5435                       + sec->output_section->vma
5436                       + sec->output_offset);
5437           else
5438             symbol = h->root.root.u.def.value;
5439         }
5440       else if (h->root.root.type == bfd_link_hash_undefweak)
5441         /* We allow relocations against undefined weak symbols, giving
5442            it the value zero, so that you can undefined weak functions
5443            and check to see if they exist by looking at their
5444            addresses.  */
5445         symbol = 0;
5446       else if (info->unresolved_syms_in_objects == RM_IGNORE
5447                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5448         symbol = 0;
5449       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
5450                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
5451         {
5452           /* If this is a dynamic link, we should have created a
5453              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
5454              in in _bfd_mips_elf_create_dynamic_sections.
5455              Otherwise, we should define the symbol with a value of 0.
5456              FIXME: It should probably get into the symbol table
5457              somehow as well.  */
5458           BFD_ASSERT (! bfd_link_pic (info));
5459           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
5460           symbol = 0;
5461         }
5462       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
5463         {
5464           /* This is an optional symbol - an Irix specific extension to the
5465              ELF spec.  Ignore it for now.
5466              XXX - FIXME - there is more to the spec for OPTIONAL symbols
5467              than simply ignoring them, but we do not handle this for now.
5468              For information see the "64-bit ELF Object File Specification"
5469              which is available from here:
5470              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
5471           symbol = 0;
5472         }
5473       else
5474         {
5475           (*info->callbacks->undefined_symbol)
5476             (info, h->root.root.root.string, input_bfd,
5477              input_section, relocation->r_offset,
5478              (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
5479              || ELF_ST_VISIBILITY (h->root.other));
5480           return bfd_reloc_undefined;
5481         }
5482
5483       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
5484       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (h->root.other);
5485     }
5486
5487   /* If this is a reference to a 16-bit function with a stub, we need
5488      to redirect the relocation to the stub unless:
5489
5490      (a) the relocation is for a MIPS16 JAL;
5491
5492      (b) the relocation is for a MIPS16 PIC call, and there are no
5493          non-MIPS16 uses of the GOT slot; or
5494
5495      (c) the section allows direct references to MIPS16 functions.  */
5496   if (r_type != R_MIPS16_26
5497       && !bfd_link_relocatable (info)
5498       && ((h != NULL
5499            && h->fn_stub != NULL
5500            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5501           || (local_p
5502               && mips_elf_tdata (input_bfd)->local_stubs != NULL
5503               && mips_elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5504       && !section_allows_mips16_refs_p (input_section))
5505     {
5506       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5507          have already noticed that we were going to need the
5508          stub.  */
5509       if (local_p)
5510         {
5511           sec = mips_elf_tdata (input_bfd)->local_stubs[r_symndx];
5512           value = 0;
5513         }
5514       else
5515         {
5516           BFD_ASSERT (h->need_fn_stub);
5517           if (h->la25_stub)
5518             {
5519               /* If a LA25 header for the stub itself exists, point to the
5520                  prepended LUI/ADDIU sequence.  */
5521               sec = h->la25_stub->stub_section;
5522               value = h->la25_stub->offset;
5523             }
5524           else
5525             {
5526               sec = h->fn_stub;
5527               value = 0;
5528             }
5529         }
5530
5531       symbol = sec->output_section->vma + sec->output_offset + value;
5532       /* The target is 16-bit, but the stub isn't.  */
5533       target_is_16_bit_code_p = FALSE;
5534     }
5535   /* If this is a MIPS16 call with a stub, that is made through the PLT or
5536      to a standard MIPS function, we need to redirect the call to the stub.
5537      Note that we specifically exclude R_MIPS16_CALL16 from this behavior;
5538      indirect calls should use an indirect stub instead.  */
5539   else if (r_type == R_MIPS16_26 && !bfd_link_relocatable (info)
5540            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5541                || (local_p
5542                    && mips_elf_tdata (input_bfd)->local_call_stubs != NULL
5543                    && mips_elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5544            && ((h != NULL && h->use_plt_entry) || !target_is_16_bit_code_p))
5545     {
5546       if (local_p)
5547         sec = mips_elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5548       else
5549         {
5550           /* If both call_stub and call_fp_stub are defined, we can figure
5551              out which one to use by checking which one appears in the input
5552              file.  */
5553           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5554             {
5555               asection *o;
5556
5557               sec = NULL;
5558               for (o = input_bfd->sections; o != NULL; o = o->next)
5559                 {
5560                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5561                     {
5562                       sec = h->call_fp_stub;
5563                       break;
5564                     }
5565                 }
5566               if (sec == NULL)
5567                 sec = h->call_stub;
5568             }
5569           else if (h->call_stub != NULL)
5570             sec = h->call_stub;
5571           else
5572             sec = h->call_fp_stub;
5573         }
5574
5575       BFD_ASSERT (sec->size > 0);
5576       symbol = sec->output_section->vma + sec->output_offset;
5577     }
5578   /* If this is a direct call to a PIC function, redirect to the
5579      non-PIC stub.  */
5580   else if (h != NULL && h->la25_stub
5581            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type,
5582                                                    target_is_16_bit_code_p))
5583     {
5584         symbol = (h->la25_stub->stub_section->output_section->vma
5585                   + h->la25_stub->stub_section->output_offset
5586                   + h->la25_stub->offset);
5587         if (ELF_ST_IS_MICROMIPS (h->root.other))
5588           symbol |= 1;
5589     }
5590   /* For direct MIPS16 and microMIPS calls make sure the compressed PLT
5591      entry is used if a standard PLT entry has also been made.  In this
5592      case the symbol will have been set by mips_elf_set_plt_sym_value
5593      to point to the standard PLT entry, so redirect to the compressed
5594      one.  */
5595   else if ((mips16_branch_reloc_p (r_type)
5596             || micromips_branch_reloc_p (r_type))
5597            && !bfd_link_relocatable (info)
5598            && h != NULL
5599            && h->use_plt_entry
5600            && h->root.plt.plist->comp_offset != MINUS_ONE
5601            && h->root.plt.plist->mips_offset != MINUS_ONE)
5602     {
5603       bfd_boolean micromips_p = MICROMIPS_P (abfd);
5604
5605       sec = htab->root.splt;
5606       symbol = (sec->output_section->vma
5607                 + sec->output_offset
5608                 + htab->plt_header_size
5609                 + htab->plt_mips_offset
5610                 + h->root.plt.plist->comp_offset
5611                 + 1);
5612
5613       target_is_16_bit_code_p = !micromips_p;
5614       target_is_micromips_code_p = micromips_p;
5615     }
5616
5617   /* Make sure MIPS16 and microMIPS are not used together.  */
5618   if ((mips16_branch_reloc_p (r_type) && target_is_micromips_code_p)
5619       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5620    {
5621       _bfd_error_handler
5622         (_("MIPS16 and microMIPS functions cannot call each other"));
5623       return bfd_reloc_notsupported;
5624    }
5625
5626   /* Calls from 16-bit code to 32-bit code and vice versa require the
5627      mode change.  However, we can ignore calls to undefined weak symbols,
5628      which should never be executed at runtime.  This exception is important
5629      because the assembly writer may have "known" that any definition of the
5630      symbol would be 16-bit code, and that direct jumps were therefore
5631      acceptable.  */
5632   *cross_mode_jump_p = (!bfd_link_relocatable (info)
5633                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5634                         && ((mips16_branch_reloc_p (r_type)
5635                              && !target_is_16_bit_code_p)
5636                             || (micromips_branch_reloc_p (r_type)
5637                                 && !target_is_micromips_code_p)
5638                             || ((branch_reloc_p (r_type)
5639                                  || r_type == R_MIPS_JALR)
5640                                 && (target_is_16_bit_code_p
5641                                     || target_is_micromips_code_p))));
5642
5643   local_p = (h == NULL || mips_use_local_got_p (info, h));
5644
5645   gp0 = _bfd_get_gp_value (input_bfd);
5646   gp = _bfd_get_gp_value (abfd);
5647   if (htab->got_info)
5648     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5649
5650   if (gnu_local_gp_p)
5651     symbol = gp;
5652
5653   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5654      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5655      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5656   if (got_page_reloc_p (r_type) && !local_p)
5657     {
5658       r_type = (micromips_reloc_p (r_type)
5659                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5660       addend = 0;
5661     }
5662
5663   /* If we haven't already determined the GOT offset, and we're going
5664      to need it, get it now.  */
5665   switch (r_type)
5666     {
5667     case R_MIPS16_CALL16:
5668     case R_MIPS16_GOT16:
5669     case R_MIPS_CALL16:
5670     case R_MIPS_GOT16:
5671     case R_MIPS_GOT_DISP:
5672     case R_MIPS_GOT_HI16:
5673     case R_MIPS_CALL_HI16:
5674     case R_MIPS_GOT_LO16:
5675     case R_MIPS_CALL_LO16:
5676     case R_MICROMIPS_CALL16:
5677     case R_MICROMIPS_GOT16:
5678     case R_MICROMIPS_GOT_DISP:
5679     case R_MICROMIPS_GOT_HI16:
5680     case R_MICROMIPS_CALL_HI16:
5681     case R_MICROMIPS_GOT_LO16:
5682     case R_MICROMIPS_CALL_LO16:
5683     case R_MIPS_TLS_GD:
5684     case R_MIPS_TLS_GOTTPREL:
5685     case R_MIPS_TLS_LDM:
5686     case R_MIPS16_TLS_GD:
5687     case R_MIPS16_TLS_GOTTPREL:
5688     case R_MIPS16_TLS_LDM:
5689     case R_MICROMIPS_TLS_GD:
5690     case R_MICROMIPS_TLS_GOTTPREL:
5691     case R_MICROMIPS_TLS_LDM:
5692       /* Find the index into the GOT where this value is located.  */
5693       if (tls_ldm_reloc_p (r_type))
5694         {
5695           g = mips_elf_local_got_index (abfd, input_bfd, info,
5696                                         0, 0, NULL, r_type);
5697           if (g == MINUS_ONE)
5698             return bfd_reloc_outofrange;
5699         }
5700       else if (!local_p)
5701         {
5702           /* On VxWorks, CALL relocations should refer to the .got.plt
5703              entry, which is initialized to point at the PLT stub.  */
5704           if (htab->is_vxworks
5705               && (call_hi16_reloc_p (r_type)
5706                   || call_lo16_reloc_p (r_type)
5707                   || call16_reloc_p (r_type)))
5708             {
5709               BFD_ASSERT (addend == 0);
5710               BFD_ASSERT (h->root.needs_plt);
5711               g = mips_elf_gotplt_index (info, &h->root);
5712             }
5713           else
5714             {
5715               BFD_ASSERT (addend == 0);
5716               g = mips_elf_global_got_index (abfd, info, input_bfd,
5717                                              &h->root, r_type);
5718               if (!TLS_RELOC_P (r_type)
5719                   && !elf_hash_table (info)->dynamic_sections_created)
5720                 /* This is a static link.  We must initialize the GOT entry.  */
5721                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->root.sgot->contents + g);
5722             }
5723         }
5724       else if (!htab->is_vxworks
5725                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5726         /* The calculation below does not involve "g".  */
5727         break;
5728       else
5729         {
5730           g = mips_elf_local_got_index (abfd, input_bfd, info,
5731                                         symbol + addend, r_symndx, h, r_type);
5732           if (g == MINUS_ONE)
5733             return bfd_reloc_outofrange;
5734         }
5735
5736       /* Convert GOT indices to actual offsets.  */
5737       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5738       break;
5739     }
5740
5741   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5742      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5743   if (h != NULL && is_gott_symbol (info, &h->root))
5744     {
5745       Elf_Internal_Rela outrel;
5746       bfd_byte *loc;
5747       asection *s;
5748
5749       s = mips_elf_rel_dyn_section (info, FALSE);
5750       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5751
5752       outrel.r_offset = (input_section->output_section->vma
5753                          + input_section->output_offset
5754                          + relocation->r_offset);
5755       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5756       outrel.r_addend = addend;
5757       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5758
5759       /* If we've written this relocation for a readonly section,
5760          we need to set DF_TEXTREL again, so that we do not delete the
5761          DT_TEXTREL tag.  */
5762       if (MIPS_ELF_READONLY_SECTION (input_section))
5763         info->flags |= DF_TEXTREL;
5764
5765       *valuep = 0;
5766       return bfd_reloc_ok;
5767     }
5768
5769   /* Figure out what kind of relocation is being performed.  */
5770   switch (r_type)
5771     {
5772     case R_MIPS_NONE:
5773       return bfd_reloc_continue;
5774
5775     case R_MIPS_16:
5776       if (howto->partial_inplace)
5777         addend = _bfd_mips_elf_sign_extend (addend, 16);
5778       value = symbol + addend;
5779       overflowed_p = mips_elf_overflow_p (value, 16);
5780       break;
5781
5782     case R_MIPS_32:
5783     case R_MIPS_REL32:
5784     case R_MIPS_64:
5785       if ((bfd_link_pic (info)
5786            || (htab->root.dynamic_sections_created
5787                && h != NULL
5788                && h->root.def_dynamic
5789                && !h->root.def_regular
5790                && !h->has_static_relocs))
5791           && r_symndx != STN_UNDEF
5792           && (h == NULL
5793               || h->root.root.type != bfd_link_hash_undefweak
5794               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5795           && (input_section->flags & SEC_ALLOC) != 0)
5796         {
5797           /* If we're creating a shared library, then we can't know
5798              where the symbol will end up.  So, we create a relocation
5799              record in the output, and leave the job up to the dynamic
5800              linker.  We must do the same for executable references to
5801              shared library symbols, unless we've decided to use copy
5802              relocs or PLTs instead.  */
5803           value = addend;
5804           if (!mips_elf_create_dynamic_relocation (abfd,
5805                                                    info,
5806                                                    relocation,
5807                                                    h,
5808                                                    sec,
5809                                                    symbol,
5810                                                    &value,
5811                                                    input_section))
5812             return bfd_reloc_undefined;
5813         }
5814       else
5815         {
5816           if (r_type != R_MIPS_REL32)
5817             value = symbol + addend;
5818           else
5819             value = addend;
5820         }
5821       value &= howto->dst_mask;
5822       break;
5823
5824     case R_MIPS_PC32:
5825       value = symbol + addend - p;
5826       value &= howto->dst_mask;
5827       break;
5828
5829     case R_MIPS16_26:
5830       /* The calculation for R_MIPS16_26 is just the same as for an
5831          R_MIPS_26.  It's only the storage of the relocated field into
5832          the output file that's different.  That's handled in
5833          mips_elf_perform_relocation.  So, we just fall through to the
5834          R_MIPS_26 case here.  */
5835     case R_MIPS_26:
5836     case R_MICROMIPS_26_S1:
5837       {
5838         unsigned int shift;
5839
5840         /* Shift is 2, unusually, for microMIPS JALX.  */
5841         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5842
5843         if (howto->partial_inplace && !section_p)
5844           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5845         else
5846           value = addend;
5847         value += symbol;
5848
5849         /* Make sure the target of a jump is suitably aligned.  Bit 0 must
5850            be the correct ISA mode selector except for weak undefined
5851            symbols.  */
5852         if ((was_local_p || h->root.root.type != bfd_link_hash_undefweak)
5853             && (*cross_mode_jump_p
5854                 ? (value & 3) != (r_type == R_MIPS_26)
5855                 : (value & ((1 << shift) - 1)) != (r_type != R_MIPS_26)))
5856           return bfd_reloc_outofrange;
5857
5858         value >>= shift;
5859         if (was_local_p || h->root.root.type != bfd_link_hash_undefweak)
5860           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5861         value &= howto->dst_mask;
5862       }
5863       break;
5864
5865     case R_MIPS_TLS_DTPREL_HI16:
5866     case R_MIPS16_TLS_DTPREL_HI16:
5867     case R_MICROMIPS_TLS_DTPREL_HI16:
5868       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5869                & howto->dst_mask);
5870       break;
5871
5872     case R_MIPS_TLS_DTPREL_LO16:
5873     case R_MIPS_TLS_DTPREL32:
5874     case R_MIPS_TLS_DTPREL64:
5875     case R_MIPS16_TLS_DTPREL_LO16:
5876     case R_MICROMIPS_TLS_DTPREL_LO16:
5877       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5878       break;
5879
5880     case R_MIPS_TLS_TPREL_HI16:
5881     case R_MIPS16_TLS_TPREL_HI16:
5882     case R_MICROMIPS_TLS_TPREL_HI16:
5883       value = (mips_elf_high (addend + symbol - tprel_base (info))
5884                & howto->dst_mask);
5885       break;
5886
5887     case R_MIPS_TLS_TPREL_LO16:
5888     case R_MIPS_TLS_TPREL32:
5889     case R_MIPS_TLS_TPREL64:
5890     case R_MIPS16_TLS_TPREL_LO16:
5891     case R_MICROMIPS_TLS_TPREL_LO16:
5892       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5893       break;
5894
5895     case R_MIPS_HI16:
5896     case R_MIPS16_HI16:
5897     case R_MICROMIPS_HI16:
5898       if (!gp_disp_p)
5899         {
5900           value = mips_elf_high (addend + symbol);
5901           value &= howto->dst_mask;
5902         }
5903       else
5904         {
5905           /* For MIPS16 ABI code we generate this sequence
5906                 0: li      $v0,%hi(_gp_disp)
5907                 4: addiupc $v1,%lo(_gp_disp)
5908                 8: sll     $v0,16
5909                12: addu    $v0,$v1
5910                14: move    $gp,$v0
5911              So the offsets of hi and lo relocs are the same, but the
5912              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5913              ADDIUPC clears the low two bits of the instruction address,
5914              so the base is ($t9 + 4) & ~3.  */
5915           if (r_type == R_MIPS16_HI16)
5916             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5917           /* The microMIPS .cpload sequence uses the same assembly
5918              instructions as the traditional psABI version, but the
5919              incoming $t9 has the low bit set.  */
5920           else if (r_type == R_MICROMIPS_HI16)
5921             value = mips_elf_high (addend + gp - p - 1);
5922           else
5923             value = mips_elf_high (addend + gp - p);
5924         }
5925       break;
5926
5927     case R_MIPS_LO16:
5928     case R_MIPS16_LO16:
5929     case R_MICROMIPS_LO16:
5930     case R_MICROMIPS_HI0_LO16:
5931       if (!gp_disp_p)
5932         value = (symbol + addend) & howto->dst_mask;
5933       else
5934         {
5935           /* See the comment for R_MIPS16_HI16 above for the reason
5936              for this conditional.  */
5937           if (r_type == R_MIPS16_LO16)
5938             value = addend + gp - (p & ~(bfd_vma) 0x3);
5939           else if (r_type == R_MICROMIPS_LO16
5940                    || r_type == R_MICROMIPS_HI0_LO16)
5941             value = addend + gp - p + 3;
5942           else
5943             value = addend + gp - p + 4;
5944           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5945              for overflow.  But, on, say, IRIX5, relocations against
5946              _gp_disp are normally generated from the .cpload
5947              pseudo-op.  It generates code that normally looks like
5948              this:
5949
5950                lui    $gp,%hi(_gp_disp)
5951                addiu  $gp,$gp,%lo(_gp_disp)
5952                addu   $gp,$gp,$t9
5953
5954              Here $t9 holds the address of the function being called,
5955              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5956              relocation can easily overflow in this situation, but the
5957              R_MIPS_HI16 relocation will handle the overflow.
5958              Therefore, we consider this a bug in the MIPS ABI, and do
5959              not check for overflow here.  */
5960         }
5961       break;
5962
5963     case R_MIPS_LITERAL:
5964     case R_MICROMIPS_LITERAL:
5965       /* Because we don't merge literal sections, we can handle this
5966          just like R_MIPS_GPREL16.  In the long run, we should merge
5967          shared literals, and then we will need to additional work
5968          here.  */
5969
5970       /* Fall through.  */
5971
5972     case R_MIPS16_GPREL:
5973       /* The R_MIPS16_GPREL performs the same calculation as
5974          R_MIPS_GPREL16, but stores the relocated bits in a different
5975          order.  We don't need to do anything special here; the
5976          differences are handled in mips_elf_perform_relocation.  */
5977     case R_MIPS_GPREL16:
5978     case R_MICROMIPS_GPREL7_S2:
5979     case R_MICROMIPS_GPREL16:
5980       /* Only sign-extend the addend if it was extracted from the
5981          instruction.  If the addend was separate, leave it alone,
5982          otherwise we may lose significant bits.  */
5983       if (howto->partial_inplace)
5984         addend = _bfd_mips_elf_sign_extend (addend, 16);
5985       value = symbol + addend - gp;
5986       /* If the symbol was local, any earlier relocatable links will
5987          have adjusted its addend with the gp offset, so compensate
5988          for that now.  Don't do it for symbols forced local in this
5989          link, though, since they won't have had the gp offset applied
5990          to them before.  */
5991       if (was_local_p)
5992         value += gp0;
5993       if (was_local_p || h->root.root.type != bfd_link_hash_undefweak)
5994         overflowed_p = mips_elf_overflow_p (value, 16);
5995       break;
5996
5997     case R_MIPS16_GOT16:
5998     case R_MIPS16_CALL16:
5999     case R_MIPS_GOT16:
6000     case R_MIPS_CALL16:
6001     case R_MICROMIPS_GOT16:
6002     case R_MICROMIPS_CALL16:
6003       /* VxWorks does not have separate local and global semantics for
6004          R_MIPS*_GOT16; every relocation evaluates to "G".  */
6005       if (!htab->is_vxworks && local_p)
6006         {
6007           value = mips_elf_got16_entry (abfd, input_bfd, info,
6008                                         symbol + addend, !was_local_p);
6009           if (value == MINUS_ONE)
6010             return bfd_reloc_outofrange;
6011           value
6012             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
6013           overflowed_p = mips_elf_overflow_p (value, 16);
6014           break;
6015         }
6016
6017       /* Fall through.  */
6018
6019     case R_MIPS_TLS_GD:
6020     case R_MIPS_TLS_GOTTPREL:
6021     case R_MIPS_TLS_LDM:
6022     case R_MIPS_GOT_DISP:
6023     case R_MIPS16_TLS_GD:
6024     case R_MIPS16_TLS_GOTTPREL:
6025     case R_MIPS16_TLS_LDM:
6026     case R_MICROMIPS_TLS_GD:
6027     case R_MICROMIPS_TLS_GOTTPREL:
6028     case R_MICROMIPS_TLS_LDM:
6029     case R_MICROMIPS_GOT_DISP:
6030       value = g;
6031       overflowed_p = mips_elf_overflow_p (value, 16);
6032       break;
6033
6034     case R_MIPS_GPREL32:
6035       value = (addend + symbol + gp0 - gp);
6036       if (!save_addend)
6037         value &= howto->dst_mask;
6038       break;
6039
6040     case R_MIPS_PC16:
6041     case R_MIPS_GNU_REL16_S2:
6042       if (howto->partial_inplace)
6043         addend = _bfd_mips_elf_sign_extend (addend, 18);
6044
6045       /* No need to exclude weak undefined symbols here as they resolve
6046          to 0 and never set `*cross_mode_jump_p', so this alignment check
6047          will never trigger for them.  */
6048       if (*cross_mode_jump_p
6049           ? ((symbol + addend) & 3) != 1
6050           : ((symbol + addend) & 3) != 0)
6051         return bfd_reloc_outofrange;
6052
6053       value = symbol + addend - p;
6054       if (was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6055         overflowed_p = mips_elf_overflow_p (value, 18);
6056       value >>= howto->rightshift;
6057       value &= howto->dst_mask;
6058       break;
6059
6060     case R_MIPS16_PC16_S1:
6061       if (howto->partial_inplace)
6062         addend = _bfd_mips_elf_sign_extend (addend, 17);
6063
6064       if ((was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6065           && (*cross_mode_jump_p
6066               ? ((symbol + addend) & 3) != 0
6067               : ((symbol + addend) & 1) == 0))
6068         return bfd_reloc_outofrange;
6069
6070       value = symbol + addend - p;
6071       if (was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6072         overflowed_p = mips_elf_overflow_p (value, 17);
6073       value >>= howto->rightshift;
6074       value &= howto->dst_mask;
6075       break;
6076
6077     case R_MIPS_PC21_S2:
6078       if (howto->partial_inplace)
6079         addend = _bfd_mips_elf_sign_extend (addend, 23);
6080
6081       if ((symbol + addend) & 3)
6082         return bfd_reloc_outofrange;
6083
6084       value = symbol + addend - p;
6085       if (was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6086         overflowed_p = mips_elf_overflow_p (value, 23);
6087       value >>= howto->rightshift;
6088       value &= howto->dst_mask;
6089       break;
6090
6091     case R_MIPS_PC26_S2:
6092       if (howto->partial_inplace)
6093         addend = _bfd_mips_elf_sign_extend (addend, 28);
6094
6095       if ((symbol + addend) & 3)
6096         return bfd_reloc_outofrange;
6097
6098       value = symbol + addend - p;
6099       if (was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6100         overflowed_p = mips_elf_overflow_p (value, 28);
6101       value >>= howto->rightshift;
6102       value &= howto->dst_mask;
6103       break;
6104
6105     case R_MIPS_PC18_S3:
6106       if (howto->partial_inplace)
6107         addend = _bfd_mips_elf_sign_extend (addend, 21);
6108
6109       if ((symbol + addend) & 7)
6110         return bfd_reloc_outofrange;
6111
6112       value = symbol + addend - ((p | 7) ^ 7);
6113       if (was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6114         overflowed_p = mips_elf_overflow_p (value, 21);
6115       value >>= howto->rightshift;
6116       value &= howto->dst_mask;
6117       break;
6118
6119     case R_MIPS_PC19_S2:
6120       if (howto->partial_inplace)
6121         addend = _bfd_mips_elf_sign_extend (addend, 21);
6122
6123       if ((symbol + addend) & 3)
6124         return bfd_reloc_outofrange;
6125
6126       value = symbol + addend - p;
6127       if (was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6128         overflowed_p = mips_elf_overflow_p (value, 21);
6129       value >>= howto->rightshift;
6130       value &= howto->dst_mask;
6131       break;
6132
6133     case R_MIPS_PCHI16:
6134       value = mips_elf_high (symbol + addend - p);
6135       if (was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6136         overflowed_p = mips_elf_overflow_p (value, 16);
6137       value &= howto->dst_mask;
6138       break;
6139
6140     case R_MIPS_PCLO16:
6141       if (howto->partial_inplace)
6142         addend = _bfd_mips_elf_sign_extend (addend, 16);
6143       value = symbol + addend - p;
6144       value &= howto->dst_mask;
6145       break;
6146
6147     case R_MICROMIPS_PC7_S1:
6148       if (howto->partial_inplace)
6149         addend = _bfd_mips_elf_sign_extend (addend, 8);
6150
6151       if ((was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6152           && (*cross_mode_jump_p
6153               ? ((symbol + addend + 2) & 3) != 0
6154               : ((symbol + addend + 2) & 1) == 0))
6155         return bfd_reloc_outofrange;
6156
6157       value = symbol + addend - p;
6158       if (was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6159         overflowed_p = mips_elf_overflow_p (value, 8);
6160       value >>= howto->rightshift;
6161       value &= howto->dst_mask;
6162       break;
6163
6164     case R_MICROMIPS_PC10_S1:
6165       if (howto->partial_inplace)
6166         addend = _bfd_mips_elf_sign_extend (addend, 11);
6167
6168       if ((was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6169           && (*cross_mode_jump_p
6170               ? ((symbol + addend + 2) & 3) != 0
6171               : ((symbol + addend + 2) & 1) == 0))
6172         return bfd_reloc_outofrange;
6173
6174       value = symbol + addend - p;
6175       if (was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6176         overflowed_p = mips_elf_overflow_p (value, 11);
6177       value >>= howto->rightshift;
6178       value &= howto->dst_mask;
6179       break;
6180
6181     case R_MICROMIPS_PC16_S1:
6182       if (howto->partial_inplace)
6183         addend = _bfd_mips_elf_sign_extend (addend, 17);
6184
6185       if ((was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6186           && (*cross_mode_jump_p
6187               ? ((symbol + addend) & 3) != 0
6188               : ((symbol + addend) & 1) == 0))
6189         return bfd_reloc_outofrange;
6190
6191       value = symbol + addend - p;
6192       if (was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6193         overflowed_p = mips_elf_overflow_p (value, 17);
6194       value >>= howto->rightshift;
6195       value &= howto->dst_mask;
6196       break;
6197
6198     case R_MICROMIPS_PC23_S2:
6199       if (howto->partial_inplace)
6200         addend = _bfd_mips_elf_sign_extend (addend, 25);
6201       value = symbol + addend - ((p | 3) ^ 3);
6202       if (was_local_p || h->root.root.type != bfd_link_hash_undefweak)
6203         overflowed_p = mips_elf_overflow_p (value, 25);
6204       value >>= howto->rightshift;
6205       value &= howto->dst_mask;
6206       break;
6207
6208     case R_MIPS_GOT_HI16:
6209     case R_MIPS_CALL_HI16:
6210     case R_MICROMIPS_GOT_HI16:
6211     case R_MICROMIPS_CALL_HI16:
6212       /* We're allowed to handle these two relocations identically.
6213          The dynamic linker is allowed to handle the CALL relocations
6214          differently by creating a lazy evaluation stub.  */
6215       value = g;
6216       value = mips_elf_high (value);
6217       value &= howto->dst_mask;
6218       break;
6219
6220     case R_MIPS_GOT_LO16:
6221     case R_MIPS_CALL_LO16:
6222     case R_MICROMIPS_GOT_LO16:
6223     case R_MICROMIPS_CALL_LO16:
6224       value = g & howto->dst_mask;
6225       break;
6226
6227     case R_MIPS_GOT_PAGE:
6228     case R_MICROMIPS_GOT_PAGE:
6229       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
6230       if (value == MINUS_ONE)
6231         return bfd_reloc_outofrange;
6232       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
6233       overflowed_p = mips_elf_overflow_p (value, 16);
6234       break;
6235
6236     case R_MIPS_GOT_OFST:
6237     case R_MICROMIPS_GOT_OFST:
6238       if (local_p)
6239         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
6240       else
6241         value = addend;
6242       overflowed_p = mips_elf_overflow_p (value, 16);
6243       break;
6244
6245     case R_MIPS_SUB:
6246     case R_MICROMIPS_SUB:
6247       value = symbol - addend;
6248       value &= howto->dst_mask;
6249       break;
6250
6251     case R_MIPS_HIGHER:
6252     case R_MICROMIPS_HIGHER:
6253       value = mips_elf_higher (addend + symbol);
6254       value &= howto->dst_mask;
6255       break;
6256
6257     case R_MIPS_HIGHEST:
6258     case R_MICROMIPS_HIGHEST:
6259       value = mips_elf_highest (addend + symbol);
6260       value &= howto->dst_mask;
6261       break;
6262
6263     case R_MIPS_SCN_DISP:
6264     case R_MICROMIPS_SCN_DISP:
6265       value = symbol + addend - sec->output_offset;
6266       value &= howto->dst_mask;
6267       break;
6268
6269     case R_MIPS_JALR:
6270     case R_MICROMIPS_JALR:
6271       /* This relocation is only a hint.  In some cases, we optimize
6272          it into a bal instruction.  But we don't try to optimize
6273          when the symbol does not resolve locally.  */
6274       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
6275         return bfd_reloc_continue;
6276       value = symbol + addend;
6277       break;
6278
6279     case R_MIPS_PJUMP:
6280     case R_MIPS_GNU_VTINHERIT:
6281     case R_MIPS_GNU_VTENTRY:
6282       /* We don't do anything with these at present.  */
6283       return bfd_reloc_continue;
6284
6285     default:
6286       /* An unrecognized relocation type.  */
6287       return bfd_reloc_notsupported;
6288     }
6289
6290   /* Store the VALUE for our caller.  */
6291   *valuep = value;
6292   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
6293 }
6294
6295 /* Obtain the field relocated by RELOCATION.  */
6296
6297 static bfd_vma
6298 mips_elf_obtain_contents (reloc_howto_type *howto,
6299                           const Elf_Internal_Rela *relocation,
6300                           bfd *input_bfd, bfd_byte *contents)
6301 {
6302   bfd_vma x = 0;
6303   bfd_byte *location = contents + relocation->r_offset;
6304   unsigned int size = bfd_get_reloc_size (howto);
6305
6306   /* Obtain the bytes.  */
6307   if (size != 0)
6308     x = bfd_get (8 * size, input_bfd, location);
6309
6310   return x;
6311 }
6312
6313 /* It has been determined that the result of the RELOCATION is the
6314    VALUE.  Use HOWTO to place VALUE into the output file at the
6315    appropriate position.  The SECTION is the section to which the
6316    relocation applies.
6317    CROSS_MODE_JUMP_P is true if the relocation field
6318    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
6319
6320    Returns FALSE if anything goes wrong.  */
6321
6322 static bfd_boolean
6323 mips_elf_perform_relocation (struct bfd_link_info *info,
6324                              reloc_howto_type *howto,
6325                              const Elf_Internal_Rela *relocation,
6326                              bfd_vma value, bfd *input_bfd,
6327                              asection *input_section, bfd_byte *contents,
6328                              bfd_boolean cross_mode_jump_p)
6329 {
6330   bfd_vma x;
6331   bfd_byte *location;
6332   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
6333   unsigned int size;
6334
6335   /* Figure out where the relocation is occurring.  */
6336   location = contents + relocation->r_offset;
6337
6338   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
6339
6340   /* Obtain the current value.  */
6341   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
6342
6343   /* Clear the field we are setting.  */
6344   x &= ~howto->dst_mask;
6345
6346   /* Set the field.  */
6347   x |= (value & howto->dst_mask);
6348
6349   /* Detect incorrect JALX usage.  If required, turn JAL or BAL into JALX.  */
6350   if (!cross_mode_jump_p && jal_reloc_p (r_type))
6351     {
6352       bfd_vma opcode = x >> 26;
6353
6354       if (r_type == R_MIPS16_26 ? opcode == 0x7
6355           : r_type == R_MICROMIPS_26_S1 ? opcode == 0x3c
6356           : opcode == 0x1d)
6357         {
6358           info->callbacks->einfo
6359             (_("%X%H: Unsupported JALX to the same ISA mode\n"),
6360              input_bfd, input_section, relocation->r_offset);
6361           return TRUE;
6362         }
6363     }
6364   if (cross_mode_jump_p && jal_reloc_p (r_type))
6365     {
6366       bfd_boolean ok;
6367       bfd_vma opcode = x >> 26;
6368       bfd_vma jalx_opcode;
6369
6370       /* Check to see if the opcode is already JAL or JALX.  */
6371       if (r_type == R_MIPS16_26)
6372         {
6373           ok = ((opcode == 0x6) || (opcode == 0x7));
6374           jalx_opcode = 0x7;
6375         }
6376       else if (r_type == R_MICROMIPS_26_S1)
6377         {
6378           ok = ((opcode == 0x3d) || (opcode == 0x3c));
6379           jalx_opcode = 0x3c;
6380         }
6381       else
6382         {
6383           ok = ((opcode == 0x3) || (opcode == 0x1d));
6384           jalx_opcode = 0x1d;
6385         }
6386
6387       /* If the opcode is not JAL or JALX, there's a problem.  We cannot
6388          convert J or JALS to JALX.  */
6389       if (!ok)
6390         {
6391           info->callbacks->einfo
6392             (_("%X%H: Unsupported jump between ISA modes; "
6393                "consider recompiling with interlinking enabled\n"),
6394              input_bfd, input_section, relocation->r_offset);
6395           return TRUE;
6396         }
6397
6398       /* Make this the JALX opcode.  */
6399       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
6400     }
6401   else if (cross_mode_jump_p && b_reloc_p (r_type))
6402     {
6403       bfd_boolean ok = FALSE;
6404       bfd_vma opcode = x >> 16;
6405       bfd_vma jalx_opcode = 0;
6406       bfd_vma addr;
6407       bfd_vma dest;
6408
6409       if (r_type == R_MICROMIPS_PC16_S1)
6410         {
6411           ok = opcode == 0x4060;
6412           jalx_opcode = 0x3c;
6413           value <<= 1;
6414         }
6415       else if (r_type == R_MIPS_PC16 || r_type == R_MIPS_GNU_REL16_S2)
6416         {
6417           ok = opcode == 0x411;
6418           jalx_opcode = 0x1d;
6419           value <<= 2;
6420         }
6421
6422       if (ok && !bfd_link_pic (info))
6423         {
6424           addr = (input_section->output_section->vma
6425                   + input_section->output_offset
6426                   + relocation->r_offset
6427                   + 4);
6428           dest = addr + (((value & 0x3ffff) ^ 0x20000) - 0x20000);
6429
6430           if ((addr >> 28) << 28 != (dest >> 28) << 28)
6431             {
6432               info->callbacks->einfo
6433                 (_("%X%H: Cannot convert branch between ISA modes "
6434                    "to JALX: relocation out of range\n"),
6435                  input_bfd, input_section, relocation->r_offset);
6436               return TRUE;
6437             }
6438
6439           /* Make this the JALX opcode.  */
6440           x = ((dest >> 2) & 0x3ffffff) | jalx_opcode << 26;
6441         }
6442       else if (!mips_elf_hash_table (info)->ignore_branch_isa)
6443         {
6444           info->callbacks->einfo
6445             (_("%X%H: Unsupported branch between ISA modes\n"),
6446              input_bfd, input_section, relocation->r_offset);
6447           return TRUE;
6448         }
6449     }
6450
6451   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
6452      range.  */
6453   if (!bfd_link_relocatable (info)
6454       && !cross_mode_jump_p
6455       && ((JAL_TO_BAL_P (input_bfd)
6456            && r_type == R_MIPS_26
6457            && (x >> 26) == 0x3)         /* jal addr */
6458           || (JALR_TO_BAL_P (input_bfd)
6459               && r_type == R_MIPS_JALR
6460               && x == 0x0320f809)       /* jalr t9 */
6461           || (JR_TO_B_P (input_bfd)
6462               && r_type == R_MIPS_JALR
6463               && x == 0x03200008)))     /* jr t9 */
6464     {
6465       bfd_vma addr;
6466       bfd_vma dest;
6467       bfd_signed_vma off;
6468
6469       addr = (input_section->output_section->vma
6470               + input_section->output_offset
6471               + relocation->r_offset
6472               + 4);
6473       if (r_type == R_MIPS_26)
6474         dest = (value << 2) | ((addr >> 28) << 28);
6475       else
6476         dest = value;
6477       off = dest - addr;
6478       if (off <= 0x1ffff && off >= -0x20000)
6479         {
6480           if (x == 0x03200008)  /* jr t9 */
6481             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
6482           else
6483             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
6484         }
6485     }
6486
6487   /* Put the value into the output.  */
6488   size = bfd_get_reloc_size (howto);
6489   if (size != 0)
6490     bfd_put (8 * size, input_bfd, x, location);
6491
6492   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !bfd_link_relocatable (info),
6493                                location);
6494
6495   return TRUE;
6496 }
6497 \f
6498 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
6499    is the original relocation, which is now being transformed into a
6500    dynamic relocation.  The ADDENDP is adjusted if necessary; the
6501    caller should store the result in place of the original addend.  */
6502
6503 static bfd_boolean
6504 mips_elf_create_dynamic_relocation (bfd *output_bfd,
6505                                     struct bfd_link_info *info,
6506                                     const Elf_Internal_Rela *rel,
6507                                     struct mips_elf_link_hash_entry *h,
6508                                     asection *sec, bfd_vma symbol,
6509                                     bfd_vma *addendp, asection *input_section)
6510 {
6511   Elf_Internal_Rela outrel[3];
6512   asection *sreloc;
6513   bfd *dynobj;
6514   int r_type;
6515   long indx;
6516   bfd_boolean defined_p;
6517   struct mips_elf_link_hash_table *htab;
6518
6519   htab = mips_elf_hash_table (info);
6520   BFD_ASSERT (htab != NULL);
6521
6522   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
6523   dynobj = elf_hash_table (info)->dynobj;
6524   sreloc = mips_elf_rel_dyn_section (info, FALSE);
6525   BFD_ASSERT (sreloc != NULL);
6526   BFD_ASSERT (sreloc->contents != NULL);
6527   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
6528               < sreloc->size);
6529
6530   outrel[0].r_offset =
6531     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
6532   if (ABI_64_P (output_bfd))
6533     {
6534       outrel[1].r_offset =
6535         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
6536       outrel[2].r_offset =
6537         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
6538     }
6539
6540   if (outrel[0].r_offset == MINUS_ONE)
6541     /* The relocation field has been deleted.  */
6542     return TRUE;
6543
6544   if (outrel[0].r_offset == MINUS_TWO)
6545     {
6546       /* The relocation field has been converted into a relative value of
6547          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
6548          the field to be fully relocated, so add in the symbol's value.  */
6549       *addendp += symbol;
6550       return TRUE;
6551     }
6552
6553   /* We must now calculate the dynamic symbol table index to use
6554      in the relocation.  */
6555   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
6556     {
6557       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
6558       indx = h->root.dynindx;
6559       if (SGI_COMPAT (output_bfd))
6560         defined_p = h->root.def_regular;
6561       else
6562         /* ??? glibc's ld.so just adds the final GOT entry to the
6563            relocation field.  It therefore treats relocs against
6564            defined symbols in the same way as relocs against
6565            undefined symbols.  */
6566         defined_p = FALSE;
6567     }
6568   else
6569     {
6570       if (sec != NULL && bfd_is_abs_section (sec))
6571         indx = 0;
6572       else if (sec == NULL || sec->owner == NULL)
6573         {
6574           bfd_set_error (bfd_error_bad_value);
6575           return FALSE;
6576         }
6577       else
6578         {
6579           indx = elf_section_data (sec->output_section)->dynindx;
6580           if (indx == 0)
6581             {
6582               asection *osec = htab->root.text_index_section;
6583               indx = elf_section_data (osec)->dynindx;
6584             }
6585           if (indx == 0)
6586             abort ();
6587         }
6588
6589       /* Instead of generating a relocation using the section
6590          symbol, we may as well make it a fully relative
6591          relocation.  We want to avoid generating relocations to
6592          local symbols because we used to generate them
6593          incorrectly, without adding the original symbol value,
6594          which is mandated by the ABI for section symbols.  In
6595          order to give dynamic loaders and applications time to
6596          phase out the incorrect use, we refrain from emitting
6597          section-relative relocations.  It's not like they're
6598          useful, after all.  This should be a bit more efficient
6599          as well.  */
6600       /* ??? Although this behavior is compatible with glibc's ld.so,
6601          the ABI says that relocations against STN_UNDEF should have
6602          a symbol value of 0.  Irix rld honors this, so relocations
6603          against STN_UNDEF have no effect.  */
6604       if (!SGI_COMPAT (output_bfd))
6605         indx = 0;
6606       defined_p = TRUE;
6607     }
6608
6609   /* If the relocation was previously an absolute relocation and
6610      this symbol will not be referred to by the relocation, we must
6611      adjust it by the value we give it in the dynamic symbol table.
6612      Otherwise leave the job up to the dynamic linker.  */
6613   if (defined_p && r_type != R_MIPS_REL32)
6614     *addendp += symbol;
6615
6616   if (htab->is_vxworks)
6617     /* VxWorks uses non-relative relocations for this.  */
6618     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
6619   else
6620     /* The relocation is always an REL32 relocation because we don't
6621        know where the shared library will wind up at load-time.  */
6622     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
6623                                    R_MIPS_REL32);
6624
6625   /* For strict adherence to the ABI specification, we should
6626      generate a R_MIPS_64 relocation record by itself before the
6627      _REL32/_64 record as well, such that the addend is read in as
6628      a 64-bit value (REL32 is a 32-bit relocation, after all).
6629      However, since none of the existing ELF64 MIPS dynamic
6630      loaders seems to care, we don't waste space with these
6631      artificial relocations.  If this turns out to not be true,
6632      mips_elf_allocate_dynamic_relocation() should be tweaked so
6633      as to make room for a pair of dynamic relocations per
6634      invocation if ABI_64_P, and here we should generate an
6635      additional relocation record with R_MIPS_64 by itself for a
6636      NULL symbol before this relocation record.  */
6637   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
6638                                  ABI_64_P (output_bfd)
6639                                  ? R_MIPS_64
6640                                  : R_MIPS_NONE);
6641   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
6642
6643   /* Adjust the output offset of the relocation to reference the
6644      correct location in the output file.  */
6645   outrel[0].r_offset += (input_section->output_section->vma
6646                          + input_section->output_offset);
6647   outrel[1].r_offset += (input_section->output_section->vma
6648                          + input_section->output_offset);
6649   outrel[2].r_offset += (input_section->output_section->vma
6650                          + input_section->output_offset);
6651
6652   /* Put the relocation back out.  We have to use the special
6653      relocation outputter in the 64-bit case since the 64-bit
6654      relocation format is non-standard.  */
6655   if (ABI_64_P (output_bfd))
6656     {
6657       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
6658         (output_bfd, &outrel[0],
6659          (sreloc->contents
6660           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
6661     }
6662   else if (htab->is_vxworks)
6663     {
6664       /* VxWorks uses RELA rather than REL dynamic relocations.  */
6665       outrel[0].r_addend = *addendp;
6666       bfd_elf32_swap_reloca_out
6667         (output_bfd, &outrel[0],
6668          (sreloc->contents
6669           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
6670     }
6671   else
6672     bfd_elf32_swap_reloc_out
6673       (output_bfd, &outrel[0],
6674        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
6675
6676   /* We've now added another relocation.  */
6677   ++sreloc->reloc_count;
6678
6679   /* Make sure the output section is writable.  The dynamic linker
6680      will be writing to it.  */
6681   elf_section_data (input_section->output_section)->this_hdr.sh_flags
6682     |= SHF_WRITE;
6683
6684   /* On IRIX5, make an entry of compact relocation info.  */
6685   if (IRIX_COMPAT (output_bfd) == ict_irix5)
6686     {
6687       asection *scpt = bfd_get_linker_section (dynobj, ".compact_rel");
6688       bfd_byte *cr;
6689
6690       if (scpt)
6691         {
6692           Elf32_crinfo cptrel;
6693
6694           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
6695           cptrel.vaddr = (rel->r_offset
6696                           + input_section->output_section->vma
6697                           + input_section->output_offset);
6698           if (r_type == R_MIPS_REL32)
6699             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
6700           else
6701             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
6702           mips_elf_set_cr_dist2to (cptrel, 0);
6703           cptrel.konst = *addendp;
6704
6705           cr = (scpt->contents
6706                 + sizeof (Elf32_External_compact_rel));
6707           mips_elf_set_cr_relvaddr (cptrel, 0);
6708           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
6709                                      ((Elf32_External_crinfo *) cr
6710                                       + scpt->reloc_count));
6711           ++scpt->reloc_count;
6712         }
6713     }
6714
6715   /* If we've written this relocation for a readonly section,
6716      we need to set DF_TEXTREL again, so that we do not delete the
6717      DT_TEXTREL tag.  */
6718   if (MIPS_ELF_READONLY_SECTION (input_section))
6719     info->flags |= DF_TEXTREL;
6720
6721   return TRUE;
6722 }
6723 \f
6724 /* Return the MACH for a MIPS e_flags value.  */
6725
6726 unsigned long
6727 _bfd_elf_mips_mach (flagword flags)
6728 {
6729   switch (flags & EF_MIPS_MACH)
6730     {
6731     case E_MIPS_MACH_3900:
6732       return bfd_mach_mips3900;
6733
6734     case E_MIPS_MACH_4010:
6735       return bfd_mach_mips4010;
6736
6737     case E_MIPS_MACH_4100:
6738       return bfd_mach_mips4100;
6739
6740     case E_MIPS_MACH_4111:
6741       return bfd_mach_mips4111;
6742
6743     case E_MIPS_MACH_4120:
6744       return bfd_mach_mips4120;
6745
6746     case E_MIPS_MACH_4650:
6747       return bfd_mach_mips4650;
6748
6749     case E_MIPS_MACH_5400:
6750       return bfd_mach_mips5400;
6751
6752     case E_MIPS_MACH_5500:
6753       return bfd_mach_mips5500;
6754
6755     case E_MIPS_MACH_5900:
6756       return bfd_mach_mips5900;
6757
6758     case E_MIPS_MACH_9000:
6759       return bfd_mach_mips9000;
6760
6761     case E_MIPS_MACH_SB1:
6762       return bfd_mach_mips_sb1;
6763
6764     case E_MIPS_MACH_LS2E:
6765       return bfd_mach_mips_loongson_2e;
6766
6767     case E_MIPS_MACH_LS2F:
6768       return bfd_mach_mips_loongson_2f;
6769
6770     case E_MIPS_MACH_LS3A:
6771       return bfd_mach_mips_loongson_3a;
6772
6773     case E_MIPS_MACH_OCTEON3:
6774       return bfd_mach_mips_octeon3;
6775
6776     case E_MIPS_MACH_OCTEON2:
6777       return bfd_mach_mips_octeon2;
6778
6779     case E_MIPS_MACH_OCTEON:
6780       return bfd_mach_mips_octeon;
6781
6782     case E_MIPS_MACH_XLR:
6783       return bfd_mach_mips_xlr;
6784
6785     default:
6786       switch (flags & EF_MIPS_ARCH)
6787         {
6788         default:
6789         case E_MIPS_ARCH_1:
6790           return bfd_mach_mips3000;
6791
6792         case E_MIPS_ARCH_2:
6793           return bfd_mach_mips6000;
6794
6795         case E_MIPS_ARCH_3:
6796           return bfd_mach_mips4000;
6797
6798         case E_MIPS_ARCH_4:
6799           return bfd_mach_mips8000;
6800
6801         case E_MIPS_ARCH_5:
6802           return bfd_mach_mips5;
6803
6804         case E_MIPS_ARCH_32:
6805           return bfd_mach_mipsisa32;
6806
6807         case E_MIPS_ARCH_64:
6808           return bfd_mach_mipsisa64;
6809
6810         case E_MIPS_ARCH_32R2:
6811           return bfd_mach_mipsisa32r2;
6812
6813         case E_MIPS_ARCH_64R2:
6814           return bfd_mach_mipsisa64r2;
6815
6816         case E_MIPS_ARCH_32R6:
6817           return bfd_mach_mipsisa32r6;
6818
6819         case E_MIPS_ARCH_64R6:
6820           return bfd_mach_mipsisa64r6;
6821         }
6822     }
6823
6824   return 0;
6825 }
6826
6827 /* Return printable name for ABI.  */
6828
6829 static INLINE char *
6830 elf_mips_abi_name (bfd *abfd)
6831 {
6832   flagword flags;
6833
6834   flags = elf_elfheader (abfd)->e_flags;
6835   switch (flags & EF_MIPS_ABI)
6836     {
6837     case 0:
6838       if (ABI_N32_P (abfd))
6839         return "N32";
6840       else if (ABI_64_P (abfd))
6841         return "64";
6842       else
6843         return "none";
6844     case E_MIPS_ABI_O32:
6845       return "O32";
6846     case E_MIPS_ABI_O64:
6847       return "O64";
6848     case E_MIPS_ABI_EABI32:
6849       return "EABI32";
6850     case E_MIPS_ABI_EABI64:
6851       return "EABI64";
6852     default:
6853       return "unknown abi";
6854     }
6855 }
6856 \f
6857 /* MIPS ELF uses two common sections.  One is the usual one, and the
6858    other is for small objects.  All the small objects are kept
6859    together, and then referenced via the gp pointer, which yields
6860    faster assembler code.  This is what we use for the small common
6861    section.  This approach is copied from ecoff.c.  */
6862 static asection mips_elf_scom_section;
6863 static asymbol mips_elf_scom_symbol;
6864 static asymbol *mips_elf_scom_symbol_ptr;
6865
6866 /* MIPS ELF also uses an acommon section, which represents an
6867    allocated common symbol which may be overridden by a
6868    definition in a shared library.  */
6869 static asection mips_elf_acom_section;
6870 static asymbol mips_elf_acom_symbol;
6871 static asymbol *mips_elf_acom_symbol_ptr;
6872
6873 /* This is used for both the 32-bit and the 64-bit ABI.  */
6874
6875 void
6876 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6877 {
6878   elf_symbol_type *elfsym;
6879
6880   /* Handle the special MIPS section numbers that a symbol may use.  */
6881   elfsym = (elf_symbol_type *) asym;
6882   switch (elfsym->internal_elf_sym.st_shndx)
6883     {
6884     case SHN_MIPS_ACOMMON:
6885       /* This section is used in a dynamically linked executable file.
6886          It is an allocated common section.  The dynamic linker can
6887          either resolve these symbols to something in a shared
6888          library, or it can just leave them here.  For our purposes,
6889          we can consider these symbols to be in a new section.  */
6890       if (mips_elf_acom_section.name == NULL)
6891         {
6892           /* Initialize the acommon section.  */
6893           mips_elf_acom_section.name = ".acommon";
6894           mips_elf_acom_section.flags = SEC_ALLOC;
6895           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6896           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6897           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6898           mips_elf_acom_symbol.name = ".acommon";
6899           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6900           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6901           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6902         }
6903       asym->section = &mips_elf_acom_section;
6904       break;
6905
6906     case SHN_COMMON:
6907       /* Common symbols less than the GP size are automatically
6908          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6909       if (asym->value > elf_gp_size (abfd)
6910           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6911           || IRIX_COMPAT (abfd) == ict_irix6)
6912         break;
6913       /* Fall through.  */
6914     case SHN_MIPS_SCOMMON:
6915       if (mips_elf_scom_section.name == NULL)
6916         {
6917           /* Initialize the small common section.  */
6918           mips_elf_scom_section.name = ".scommon";
6919           mips_elf_scom_section.flags = SEC_IS_COMMON;
6920           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6921           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6922           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6923           mips_elf_scom_symbol.name = ".scommon";
6924           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6925           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6926           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6927         }
6928       asym->section = &mips_elf_scom_section;
6929       asym->value = elfsym->internal_elf_sym.st_size;
6930       break;
6931
6932     case SHN_MIPS_SUNDEFINED:
6933       asym->section = bfd_und_section_ptr;
6934       break;
6935
6936     case SHN_MIPS_TEXT:
6937       {
6938         asection *section = bfd_get_section_by_name (abfd, ".text");
6939
6940         if (section != NULL)
6941           {
6942             asym->section = section;
6943             /* MIPS_TEXT is a bit special, the address is not an offset
6944                to the base of the .text section.  So substract the section
6945                base address to make it an offset.  */
6946             asym->value -= section->vma;
6947           }
6948       }
6949       break;
6950
6951     case SHN_MIPS_DATA:
6952       {
6953         asection *section = bfd_get_section_by_name (abfd, ".data");
6954
6955         if (section != NULL)
6956           {
6957             asym->section = section;
6958             /* MIPS_DATA is a bit special, the address is not an offset
6959                to the base of the .data section.  So substract the section
6960                base address to make it an offset.  */
6961             asym->value -= section->vma;
6962           }
6963       }
6964       break;
6965     }
6966
6967   /* If this is an odd-valued function symbol, assume it's a MIPS16
6968      or microMIPS one.  */
6969   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6970       && (asym->value & 1) != 0)
6971     {
6972       asym->value--;
6973       if (MICROMIPS_P (abfd))
6974         elfsym->internal_elf_sym.st_other
6975           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6976       else
6977         elfsym->internal_elf_sym.st_other
6978           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6979     }
6980 }
6981 \f
6982 /* Implement elf_backend_eh_frame_address_size.  This differs from
6983    the default in the way it handles EABI64.
6984
6985    EABI64 was originally specified as an LP64 ABI, and that is what
6986    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6987    historically accepted the combination of -mabi=eabi and -mlong32,
6988    and this ILP32 variation has become semi-official over time.
6989    Both forms use elf32 and have pointer-sized FDE addresses.
6990
6991    If an EABI object was generated by GCC 4.0 or above, it will have
6992    an empty .gcc_compiled_longXX section, where XX is the size of longs
6993    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6994    have no special marking to distinguish them from LP64 objects.
6995
6996    We don't want users of the official LP64 ABI to be punished for the
6997    existence of the ILP32 variant, but at the same time, we don't want
6998    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6999    We therefore take the following approach:
7000
7001       - If ABFD contains a .gcc_compiled_longXX section, use it to
7002         determine the pointer size.
7003
7004       - Otherwise check the type of the first relocation.  Assume that
7005         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
7006
7007       - Otherwise punt.
7008
7009    The second check is enough to detect LP64 objects generated by pre-4.0
7010    compilers because, in the kind of output generated by those compilers,
7011    the first relocation will be associated with either a CIE personality
7012    routine or an FDE start address.  Furthermore, the compilers never
7013    used a special (non-pointer) encoding for this ABI.
7014
7015    Checking the relocation type should also be safe because there is no
7016    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
7017    did so.  */
7018
7019 unsigned int
7020 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
7021 {
7022   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
7023     return 8;
7024   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
7025     {
7026       bfd_boolean long32_p, long64_p;
7027
7028       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
7029       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
7030       if (long32_p && long64_p)
7031         return 0;
7032       if (long32_p)
7033         return 4;
7034       if (long64_p)
7035         return 8;
7036
7037       if (sec->reloc_count > 0
7038           && elf_section_data (sec)->relocs != NULL
7039           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
7040               == R_MIPS_64))
7041         return 8;
7042
7043       return 0;
7044     }
7045   return 4;
7046 }
7047 \f
7048 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
7049    relocations against two unnamed section symbols to resolve to the
7050    same address.  For example, if we have code like:
7051
7052         lw      $4,%got_disp(.data)($gp)
7053         lw      $25,%got_disp(.text)($gp)
7054         jalr    $25
7055
7056    then the linker will resolve both relocations to .data and the program
7057    will jump there rather than to .text.
7058
7059    We can work around this problem by giving names to local section symbols.
7060    This is also what the MIPSpro tools do.  */
7061
7062 bfd_boolean
7063 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
7064 {
7065   return SGI_COMPAT (abfd);
7066 }
7067 \f
7068 /* Work over a section just before writing it out.  This routine is
7069    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
7070    sections that need the SHF_MIPS_GPREL flag by name; there has to be
7071    a better way.  */
7072
7073 bfd_boolean
7074 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
7075 {
7076   if (hdr->sh_type == SHT_MIPS_REGINFO
7077       && hdr->sh_size > 0)
7078     {
7079       bfd_byte buf[4];
7080
7081       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
7082       BFD_ASSERT (hdr->contents == NULL);
7083
7084       if (bfd_seek (abfd,
7085                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
7086                     SEEK_SET) != 0)
7087         return FALSE;
7088       H_PUT_32 (abfd, elf_gp (abfd), buf);
7089       if (bfd_bwrite (buf, 4, abfd) != 4)
7090         return FALSE;
7091     }
7092
7093   if (hdr->sh_type == SHT_MIPS_OPTIONS
7094       && hdr->bfd_section != NULL
7095       && mips_elf_section_data (hdr->bfd_section) != NULL
7096       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
7097     {
7098       bfd_byte *contents, *l, *lend;
7099
7100       /* We stored the section contents in the tdata field in the
7101          set_section_contents routine.  We save the section contents
7102          so that we don't have to read them again.
7103          At this point we know that elf_gp is set, so we can look
7104          through the section contents to see if there is an
7105          ODK_REGINFO structure.  */
7106
7107       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
7108       l = contents;
7109       lend = contents + hdr->sh_size;
7110       while (l + sizeof (Elf_External_Options) <= lend)
7111         {
7112           Elf_Internal_Options intopt;
7113
7114           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
7115                                         &intopt);
7116           if (intopt.size < sizeof (Elf_External_Options))
7117             {
7118               _bfd_error_handler
7119                 /* xgettext:c-format */
7120                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
7121                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
7122               break;
7123             }
7124           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
7125             {
7126               bfd_byte buf[8];
7127
7128               if (bfd_seek (abfd,
7129                             (hdr->sh_offset
7130                              + (l - contents)
7131                              + sizeof (Elf_External_Options)
7132                              + (sizeof (Elf64_External_RegInfo) - 8)),
7133                              SEEK_SET) != 0)
7134                 return FALSE;
7135               H_PUT_64 (abfd, elf_gp (abfd), buf);
7136               if (bfd_bwrite (buf, 8, abfd) != 8)
7137                 return FALSE;
7138             }
7139           else if (intopt.kind == ODK_REGINFO)
7140             {
7141               bfd_byte buf[4];
7142
7143               if (bfd_seek (abfd,
7144                             (hdr->sh_offset
7145                              + (l - contents)
7146                              + sizeof (Elf_External_Options)
7147                              + (sizeof (Elf32_External_RegInfo) - 4)),
7148                             SEEK_SET) != 0)
7149                 return FALSE;
7150               H_PUT_32 (abfd, elf_gp (abfd), buf);
7151               if (bfd_bwrite (buf, 4, abfd) != 4)
7152                 return FALSE;
7153             }
7154           l += intopt.size;
7155         }
7156     }
7157
7158   if (hdr->bfd_section != NULL)
7159     {
7160       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
7161
7162       /* .sbss is not handled specially here because the GNU/Linux
7163          prelinker can convert .sbss from NOBITS to PROGBITS and
7164          changing it back to NOBITS breaks the binary.  The entry in
7165          _bfd_mips_elf_special_sections will ensure the correct flags
7166          are set on .sbss if BFD creates it without reading it from an
7167          input file, and without special handling here the flags set
7168          on it in an input file will be followed.  */
7169       if (strcmp (name, ".sdata") == 0
7170           || strcmp (name, ".lit8") == 0
7171           || strcmp (name, ".lit4") == 0)
7172         hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
7173       else if (strcmp (name, ".srdata") == 0)
7174         hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
7175       else if (strcmp (name, ".compact_rel") == 0)
7176         hdr->sh_flags = 0;
7177       else if (strcmp (name, ".rtproc") == 0)
7178         {
7179           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
7180             {
7181               unsigned int adjust;
7182
7183               adjust = hdr->sh_size % hdr->sh_addralign;
7184               if (adjust != 0)
7185                 hdr->sh_size += hdr->sh_addralign - adjust;
7186             }
7187         }
7188     }
7189
7190   return TRUE;
7191 }
7192
7193 /* Handle a MIPS specific section when reading an object file.  This
7194    is called when elfcode.h finds a section with an unknown type.
7195    This routine supports both the 32-bit and 64-bit ELF ABI.
7196
7197    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
7198    how to.  */
7199
7200 bfd_boolean
7201 _bfd_mips_elf_section_from_shdr (bfd *abfd,
7202                                  Elf_Internal_Shdr *hdr,
7203                                  const char *name,
7204                                  int shindex)
7205 {
7206   flagword flags = 0;
7207
7208   /* There ought to be a place to keep ELF backend specific flags, but
7209      at the moment there isn't one.  We just keep track of the
7210      sections by their name, instead.  Fortunately, the ABI gives
7211      suggested names for all the MIPS specific sections, so we will
7212      probably get away with this.  */
7213   switch (hdr->sh_type)
7214     {
7215     case SHT_MIPS_LIBLIST:
7216       if (strcmp (name, ".liblist") != 0)
7217         return FALSE;
7218       break;
7219     case SHT_MIPS_MSYM:
7220       if (strcmp (name, ".msym") != 0)
7221         return FALSE;
7222       break;
7223     case SHT_MIPS_CONFLICT:
7224       if (strcmp (name, ".conflict") != 0)
7225         return FALSE;
7226       break;
7227     case SHT_MIPS_GPTAB:
7228       if (! CONST_STRNEQ (name, ".gptab."))
7229         return FALSE;
7230       break;
7231     case SHT_MIPS_UCODE:
7232       if (strcmp (name, ".ucode") != 0)
7233         return FALSE;
7234       break;
7235     case SHT_MIPS_DEBUG:
7236       if (strcmp (name, ".mdebug") != 0)
7237         return FALSE;
7238       flags = SEC_DEBUGGING;
7239       break;
7240     case SHT_MIPS_REGINFO:
7241       if (strcmp (name, ".reginfo") != 0
7242           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
7243         return FALSE;
7244       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
7245       break;
7246     case SHT_MIPS_IFACE:
7247       if (strcmp (name, ".MIPS.interfaces") != 0)
7248         return FALSE;
7249       break;
7250     case SHT_MIPS_CONTENT:
7251       if (! CONST_STRNEQ (name, ".MIPS.content"))
7252         return FALSE;
7253       break;
7254     case SHT_MIPS_OPTIONS:
7255       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
7256         return FALSE;
7257       break;
7258     case SHT_MIPS_ABIFLAGS:
7259       if (!MIPS_ELF_ABIFLAGS_SECTION_NAME_P (name))
7260         return FALSE;
7261       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
7262       break;
7263     case SHT_MIPS_DWARF:
7264       if (! CONST_STRNEQ (name, ".debug_")
7265           && ! CONST_STRNEQ (name, ".zdebug_"))
7266         return FALSE;
7267       break;
7268     case SHT_MIPS_SYMBOL_LIB:
7269       if (strcmp (name, ".MIPS.symlib") != 0)
7270         return FALSE;
7271       break;
7272     case SHT_MIPS_EVENTS:
7273       if (! CONST_STRNEQ (name, ".MIPS.events")
7274           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
7275         return FALSE;
7276       break;
7277     default:
7278       break;
7279     }
7280
7281   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
7282     return FALSE;
7283
7284   if (flags)
7285     {
7286       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
7287                                    (bfd_get_section_flags (abfd,
7288                                                            hdr->bfd_section)
7289                                     | flags)))
7290         return FALSE;
7291     }
7292
7293   if (hdr->sh_type == SHT_MIPS_ABIFLAGS)
7294     {
7295       Elf_External_ABIFlags_v0 ext;
7296
7297       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
7298                                       &ext, 0, sizeof ext))
7299         return FALSE;
7300       bfd_mips_elf_swap_abiflags_v0_in (abfd, &ext,
7301                                         &mips_elf_tdata (abfd)->abiflags);
7302       if (mips_elf_tdata (abfd)->abiflags.version != 0)
7303         return FALSE;
7304       mips_elf_tdata (abfd)->abiflags_valid = TRUE;
7305     }
7306
7307   /* FIXME: We should record sh_info for a .gptab section.  */
7308
7309   /* For a .reginfo section, set the gp value in the tdata information
7310      from the contents of this section.  We need the gp value while
7311      processing relocs, so we just get it now.  The .reginfo section
7312      is not used in the 64-bit MIPS ELF ABI.  */
7313   if (hdr->sh_type == SHT_MIPS_REGINFO)
7314     {
7315       Elf32_External_RegInfo ext;
7316       Elf32_RegInfo s;
7317
7318       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
7319                                       &ext, 0, sizeof ext))
7320         return FALSE;
7321       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
7322       elf_gp (abfd) = s.ri_gp_value;
7323     }
7324
7325   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
7326      set the gp value based on what we find.  We may see both
7327      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
7328      they should agree.  */
7329   if (hdr->sh_type == SHT_MIPS_OPTIONS)
7330     {
7331       bfd_byte *contents, *l, *lend;
7332
7333       contents = bfd_malloc (hdr->sh_size);
7334       if (contents == NULL)
7335         return FALSE;
7336       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
7337                                       0, hdr->sh_size))
7338         {
7339           free (contents);
7340           return FALSE;
7341         }
7342       l = contents;
7343       lend = contents + hdr->sh_size;
7344       while (l + sizeof (Elf_External_Options) <= lend)
7345         {
7346           Elf_Internal_Options intopt;
7347
7348           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
7349                                         &intopt);
7350           if (intopt.size < sizeof (Elf_External_Options))
7351             {
7352               _bfd_error_handler
7353                 /* xgettext:c-format */
7354                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
7355                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
7356               break;
7357             }
7358           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
7359             {
7360               Elf64_Internal_RegInfo intreg;
7361
7362               bfd_mips_elf64_swap_reginfo_in
7363                 (abfd,
7364                  ((Elf64_External_RegInfo *)
7365                   (l + sizeof (Elf_External_Options))),
7366                  &intreg);
7367               elf_gp (abfd) = intreg.ri_gp_value;
7368             }
7369           else if (intopt.kind == ODK_REGINFO)
7370             {
7371               Elf32_RegInfo intreg;
7372
7373               bfd_mips_elf32_swap_reginfo_in
7374                 (abfd,
7375                  ((Elf32_External_RegInfo *)
7376                   (l + sizeof (Elf_External_Options))),
7377                  &intreg);
7378               elf_gp (abfd) = intreg.ri_gp_value;
7379             }
7380           l += intopt.size;
7381         }
7382       free (contents);
7383     }
7384
7385   return TRUE;
7386 }
7387
7388 /* Set the correct type for a MIPS ELF section.  We do this by the
7389    section name, which is a hack, but ought to work.  This routine is
7390    used by both the 32-bit and the 64-bit ABI.  */
7391
7392 bfd_boolean
7393 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
7394 {
7395   const char *name = bfd_get_section_name (abfd, sec);
7396
7397   if (strcmp (name, ".liblist") == 0)
7398     {
7399       hdr->sh_type = SHT_MIPS_LIBLIST;
7400       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
7401       /* The sh_link field is set in final_write_processing.  */
7402     }
7403   else if (strcmp (name, ".conflict") == 0)
7404     hdr->sh_type = SHT_MIPS_CONFLICT;
7405   else if (CONST_STRNEQ (name, ".gptab."))
7406     {
7407       hdr->sh_type = SHT_MIPS_GPTAB;
7408       hdr->sh_entsize = sizeof (Elf32_External_gptab);
7409       /* The sh_info field is set in final_write_processing.  */
7410     }
7411   else if (strcmp (name, ".ucode") == 0)
7412     hdr->sh_type = SHT_MIPS_UCODE;
7413   else if (strcmp (name, ".mdebug") == 0)
7414     {
7415       hdr->sh_type = SHT_MIPS_DEBUG;
7416       /* In a shared object on IRIX 5.3, the .mdebug section has an
7417          entsize of 0.  FIXME: Does this matter?  */
7418       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
7419         hdr->sh_entsize = 0;
7420       else
7421         hdr->sh_entsize = 1;
7422     }
7423   else if (strcmp (name, ".reginfo") == 0)
7424     {
7425       hdr->sh_type = SHT_MIPS_REGINFO;
7426       /* In a shared object on IRIX 5.3, the .reginfo section has an
7427          entsize of 0x18.  FIXME: Does this matter?  */
7428       if (SGI_COMPAT (abfd))
7429         {
7430           if ((abfd->flags & DYNAMIC) != 0)
7431             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
7432           else
7433             hdr->sh_entsize = 1;
7434         }
7435       else
7436         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
7437     }
7438   else if (SGI_COMPAT (abfd)
7439            && (strcmp (name, ".hash") == 0
7440                || strcmp (name, ".dynamic") == 0
7441                || strcmp (name, ".dynstr") == 0))
7442     {
7443       if (SGI_COMPAT (abfd))
7444         hdr->sh_entsize = 0;
7445 #if 0
7446       /* This isn't how the IRIX6 linker behaves.  */
7447       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
7448 #endif
7449     }
7450   else if (strcmp (name, ".got") == 0
7451            || strcmp (name, ".srdata") == 0
7452            || strcmp (name, ".sdata") == 0
7453            || strcmp (name, ".sbss") == 0
7454            || strcmp (name, ".lit4") == 0
7455            || strcmp (name, ".lit8") == 0)
7456     hdr->sh_flags |= SHF_MIPS_GPREL;
7457   else if (strcmp (name, ".MIPS.interfaces") == 0)
7458     {
7459       hdr->sh_type = SHT_MIPS_IFACE;
7460       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7461     }
7462   else if (CONST_STRNEQ (name, ".MIPS.content"))
7463     {
7464       hdr->sh_type = SHT_MIPS_CONTENT;
7465       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7466       /* The sh_info field is set in final_write_processing.  */
7467     }
7468   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
7469     {
7470       hdr->sh_type = SHT_MIPS_OPTIONS;
7471       hdr->sh_entsize = 1;
7472       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7473     }
7474   else if (CONST_STRNEQ (name, ".MIPS.abiflags"))
7475     {
7476       hdr->sh_type = SHT_MIPS_ABIFLAGS;
7477       hdr->sh_entsize = sizeof (Elf_External_ABIFlags_v0);
7478     }
7479   else if (CONST_STRNEQ (name, ".debug_")
7480            || CONST_STRNEQ (name, ".zdebug_"))
7481     {
7482       hdr->sh_type = SHT_MIPS_DWARF;
7483
7484       /* Irix facilities such as libexc expect a single .debug_frame
7485          per executable, the system ones have NOSTRIP set and the linker
7486          doesn't merge sections with different flags so ...  */
7487       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
7488         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7489     }
7490   else if (strcmp (name, ".MIPS.symlib") == 0)
7491     {
7492       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
7493       /* The sh_link and sh_info fields are set in
7494          final_write_processing.  */
7495     }
7496   else if (CONST_STRNEQ (name, ".MIPS.events")
7497            || CONST_STRNEQ (name, ".MIPS.post_rel"))
7498     {
7499       hdr->sh_type = SHT_MIPS_EVENTS;
7500       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7501       /* The sh_link field is set in final_write_processing.  */
7502     }
7503   else if (strcmp (name, ".msym") == 0)
7504     {
7505       hdr->sh_type = SHT_MIPS_MSYM;
7506       hdr->sh_flags |= SHF_ALLOC;
7507       hdr->sh_entsize = 8;
7508     }
7509
7510   /* The generic elf_fake_sections will set up REL_HDR using the default
7511    kind of relocations.  We used to set up a second header for the
7512    non-default kind of relocations here, but only NewABI would use
7513    these, and the IRIX ld doesn't like resulting empty RELA sections.
7514    Thus we create those header only on demand now.  */
7515
7516   return TRUE;
7517 }
7518
7519 /* Given a BFD section, try to locate the corresponding ELF section
7520    index.  This is used by both the 32-bit and the 64-bit ABI.
7521    Actually, it's not clear to me that the 64-bit ABI supports these,
7522    but for non-PIC objects we will certainly want support for at least
7523    the .scommon section.  */
7524
7525 bfd_boolean
7526 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
7527                                         asection *sec, int *retval)
7528 {
7529   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
7530     {
7531       *retval = SHN_MIPS_SCOMMON;
7532       return TRUE;
7533     }
7534   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
7535     {
7536       *retval = SHN_MIPS_ACOMMON;
7537       return TRUE;
7538     }
7539   return FALSE;
7540 }
7541 \f
7542 /* Hook called by the linker routine which adds symbols from an object
7543    file.  We must handle the special MIPS section numbers here.  */
7544
7545 bfd_boolean
7546 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
7547                                Elf_Internal_Sym *sym, const char **namep,
7548                                flagword *flagsp ATTRIBUTE_UNUSED,
7549                                asection **secp, bfd_vma *valp)
7550 {
7551   if (SGI_COMPAT (abfd)
7552       && (abfd->flags & DYNAMIC) != 0
7553       && strcmp (*namep, "_rld_new_interface") == 0)
7554     {
7555       /* Skip IRIX5 rld entry name.  */
7556       *namep = NULL;
7557       return TRUE;
7558     }
7559
7560   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
7561      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
7562      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
7563      a magic symbol resolved by the linker, we ignore this bogus definition
7564      of _gp_disp.  New ABI objects do not suffer from this problem so this
7565      is not done for them. */
7566   if (!NEWABI_P(abfd)
7567       && (sym->st_shndx == SHN_ABS)
7568       && (strcmp (*namep, "_gp_disp") == 0))
7569     {
7570       *namep = NULL;
7571       return TRUE;
7572     }
7573
7574   switch (sym->st_shndx)
7575     {
7576     case SHN_COMMON:
7577       /* Common symbols less than the GP size are automatically
7578          treated as SHN_MIPS_SCOMMON symbols.  */
7579       if (sym->st_size > elf_gp_size (abfd)
7580           || ELF_ST_TYPE (sym->st_info) == STT_TLS
7581           || IRIX_COMPAT (abfd) == ict_irix6)
7582         break;
7583       /* Fall through.  */
7584     case SHN_MIPS_SCOMMON:
7585       *secp = bfd_make_section_old_way (abfd, ".scommon");
7586       (*secp)->flags |= SEC_IS_COMMON;
7587       *valp = sym->st_size;
7588       break;
7589
7590     case SHN_MIPS_TEXT:
7591       /* This section is used in a shared object.  */
7592       if (mips_elf_tdata (abfd)->elf_text_section == NULL)
7593         {
7594           asymbol *elf_text_symbol;
7595           asection *elf_text_section;
7596           bfd_size_type amt = sizeof (asection);
7597
7598           elf_text_section = bfd_zalloc (abfd, amt);
7599           if (elf_text_section == NULL)
7600             return FALSE;
7601
7602           amt = sizeof (asymbol);
7603           elf_text_symbol = bfd_zalloc (abfd, amt);
7604           if (elf_text_symbol == NULL)
7605             return FALSE;
7606
7607           /* Initialize the section.  */
7608
7609           mips_elf_tdata (abfd)->elf_text_section = elf_text_section;
7610           mips_elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
7611
7612           elf_text_section->symbol = elf_text_symbol;
7613           elf_text_section->symbol_ptr_ptr = &mips_elf_tdata (abfd)->elf_text_symbol;
7614
7615           elf_text_section->name = ".text";
7616           elf_text_section->flags = SEC_NO_FLAGS;
7617           elf_text_section->output_section = NULL;
7618           elf_text_section->owner = abfd;
7619           elf_text_symbol->name = ".text";
7620           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7621           elf_text_symbol->section = elf_text_section;
7622         }
7623       /* This code used to do *secp = bfd_und_section_ptr if
7624          bfd_link_pic (info).  I don't know why, and that doesn't make sense,
7625          so I took it out.  */
7626       *secp = mips_elf_tdata (abfd)->elf_text_section;
7627       break;
7628
7629     case SHN_MIPS_ACOMMON:
7630       /* Fall through. XXX Can we treat this as allocated data?  */
7631     case SHN_MIPS_DATA:
7632       /* This section is used in a shared object.  */
7633       if (mips_elf_tdata (abfd)->elf_data_section == NULL)
7634         {
7635           asymbol *elf_data_symbol;
7636           asection *elf_data_section;
7637           bfd_size_type amt = sizeof (asection);
7638
7639           elf_data_section = bfd_zalloc (abfd, amt);
7640           if (elf_data_section == NULL)
7641             return FALSE;
7642
7643           amt = sizeof (asymbol);
7644           elf_data_symbol = bfd_zalloc (abfd, amt);
7645           if (elf_data_symbol == NULL)
7646             return FALSE;
7647
7648           /* Initialize the section.  */
7649
7650           mips_elf_tdata (abfd)->elf_data_section = elf_data_section;
7651           mips_elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
7652
7653           elf_data_section->symbol = elf_data_symbol;
7654           elf_data_section->symbol_ptr_ptr = &mips_elf_tdata (abfd)->elf_data_symbol;
7655
7656           elf_data_section->name = ".data";
7657           elf_data_section->flags = SEC_NO_FLAGS;
7658           elf_data_section->output_section = NULL;
7659           elf_data_section->owner = abfd;
7660           elf_data_symbol->name = ".data";
7661           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7662           elf_data_symbol->section = elf_data_section;
7663         }
7664       /* This code used to do *secp = bfd_und_section_ptr if
7665          bfd_link_pic (info).  I don't know why, and that doesn't make sense,
7666          so I took it out.  */
7667       *secp = mips_elf_tdata (abfd)->elf_data_section;
7668       break;
7669
7670     case SHN_MIPS_SUNDEFINED:
7671       *secp = bfd_und_section_ptr;
7672       break;
7673     }
7674
7675   if (SGI_COMPAT (abfd)
7676       && ! bfd_link_pic (info)
7677       && info->output_bfd->xvec == abfd->xvec
7678       && strcmp (*namep, "__rld_obj_head") == 0)
7679     {
7680       struct elf_link_hash_entry *h;
7681       struct bfd_link_hash_entry *bh;
7682
7683       /* Mark __rld_obj_head as dynamic.  */
7684       bh = NULL;
7685       if (! (_bfd_generic_link_add_one_symbol
7686              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
7687               get_elf_backend_data (abfd)->collect, &bh)))
7688         return FALSE;
7689
7690       h = (struct elf_link_hash_entry *) bh;
7691       h->non_elf = 0;
7692       h->def_regular = 1;
7693       h->type = STT_OBJECT;
7694
7695       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7696         return FALSE;
7697
7698       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
7699       mips_elf_hash_table (info)->rld_symbol = h;
7700     }
7701
7702   /* If this is a mips16 text symbol, add 1 to the value to make it
7703      odd.  This will cause something like .word SYM to come up with
7704      the right value when it is loaded into the PC.  */
7705   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7706     ++*valp;
7707
7708   return TRUE;
7709 }
7710
7711 /* This hook function is called before the linker writes out a global
7712    symbol.  We mark symbols as small common if appropriate.  This is
7713    also where we undo the increment of the value for a mips16 symbol.  */
7714
7715 int
7716 _bfd_mips_elf_link_output_symbol_hook
7717   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
7718    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
7719    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
7720 {
7721   /* If we see a common symbol, which implies a relocatable link, then
7722      if a symbol was small common in an input file, mark it as small
7723      common in the output file.  */
7724   if (sym->st_shndx == SHN_COMMON
7725       && strcmp (input_sec->name, ".scommon") == 0)
7726     sym->st_shndx = SHN_MIPS_SCOMMON;
7727
7728   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7729     sym->st_value &= ~1;
7730
7731   return 1;
7732 }
7733 \f
7734 /* Functions for the dynamic linker.  */
7735
7736 /* Create dynamic sections when linking against a dynamic object.  */
7737
7738 bfd_boolean
7739 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
7740 {
7741   struct elf_link_hash_entry *h;
7742   struct bfd_link_hash_entry *bh;
7743   flagword flags;
7744   register asection *s;
7745   const char * const *namep;
7746   struct mips_elf_link_hash_table *htab;
7747
7748   htab = mips_elf_hash_table (info);
7749   BFD_ASSERT (htab != NULL);
7750
7751   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
7752            | SEC_LINKER_CREATED | SEC_READONLY);
7753
7754   /* The psABI requires a read-only .dynamic section, but the VxWorks
7755      EABI doesn't.  */
7756   if (!htab->is_vxworks)
7757     {
7758       s = bfd_get_linker_section (abfd, ".dynamic");
7759       if (s != NULL)
7760         {
7761           if (! bfd_set_section_flags (abfd, s, flags))
7762             return FALSE;
7763         }
7764     }
7765
7766   /* We need to create .got section.  */
7767   if (!mips_elf_create_got_section (abfd, info))
7768     return FALSE;
7769
7770   if (! mips_elf_rel_dyn_section (info, TRUE))
7771     return FALSE;
7772
7773   /* Create .stub section.  */
7774   s = bfd_make_section_anyway_with_flags (abfd,
7775                                           MIPS_ELF_STUB_SECTION_NAME (abfd),
7776                                           flags | SEC_CODE);
7777   if (s == NULL
7778       || ! bfd_set_section_alignment (abfd, s,
7779                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7780     return FALSE;
7781   htab->sstubs = s;
7782
7783   if (!mips_elf_hash_table (info)->use_rld_obj_head
7784       && bfd_link_executable (info)
7785       && bfd_get_linker_section (abfd, ".rld_map") == NULL)
7786     {
7787       s = bfd_make_section_anyway_with_flags (abfd, ".rld_map",
7788                                               flags &~ (flagword) SEC_READONLY);
7789       if (s == NULL
7790           || ! bfd_set_section_alignment (abfd, s,
7791                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7792         return FALSE;
7793     }
7794
7795   /* On IRIX5, we adjust add some additional symbols and change the
7796      alignments of several sections.  There is no ABI documentation
7797      indicating that this is necessary on IRIX6, nor any evidence that
7798      the linker takes such action.  */
7799   if (IRIX_COMPAT (abfd) == ict_irix5)
7800     {
7801       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7802         {
7803           bh = NULL;
7804           if (! (_bfd_generic_link_add_one_symbol
7805                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7806                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7807             return FALSE;
7808
7809           h = (struct elf_link_hash_entry *) bh;
7810           h->non_elf = 0;
7811           h->def_regular = 1;
7812           h->type = STT_SECTION;
7813
7814           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7815             return FALSE;
7816         }
7817
7818       /* We need to create a .compact_rel section.  */
7819       if (SGI_COMPAT (abfd))
7820         {
7821           if (!mips_elf_create_compact_rel_section (abfd, info))
7822             return FALSE;
7823         }
7824
7825       /* Change alignments of some sections.  */
7826       s = bfd_get_linker_section (abfd, ".hash");
7827       if (s != NULL)
7828         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7829
7830       s = bfd_get_linker_section (abfd, ".dynsym");
7831       if (s != NULL)
7832         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7833
7834       s = bfd_get_linker_section (abfd, ".dynstr");
7835       if (s != NULL)
7836         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7837
7838       /* ??? */
7839       s = bfd_get_section_by_name (abfd, ".reginfo");
7840       if (s != NULL)
7841         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7842
7843       s = bfd_get_linker_section (abfd, ".dynamic");
7844       if (s != NULL)
7845         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7846     }
7847
7848   if (bfd_link_executable (info))
7849     {
7850       const char *name;
7851
7852       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7853       bh = NULL;
7854       if (!(_bfd_generic_link_add_one_symbol
7855             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7856              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7857         return FALSE;
7858
7859       h = (struct elf_link_hash_entry *) bh;
7860       h->non_elf = 0;
7861       h->def_regular = 1;
7862       h->type = STT_SECTION;
7863
7864       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7865         return FALSE;
7866
7867       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7868         {
7869           /* __rld_map is a four byte word located in the .data section
7870              and is filled in by the rtld to contain a pointer to
7871              the _r_debug structure. Its symbol value will be set in
7872              _bfd_mips_elf_finish_dynamic_symbol.  */
7873           s = bfd_get_linker_section (abfd, ".rld_map");
7874           BFD_ASSERT (s != NULL);
7875
7876           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7877           bh = NULL;
7878           if (!(_bfd_generic_link_add_one_symbol
7879                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7880                  get_elf_backend_data (abfd)->collect, &bh)))
7881             return FALSE;
7882
7883           h = (struct elf_link_hash_entry *) bh;
7884           h->non_elf = 0;
7885           h->def_regular = 1;
7886           h->type = STT_OBJECT;
7887
7888           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7889             return FALSE;
7890           mips_elf_hash_table (info)->rld_symbol = h;
7891         }
7892     }
7893
7894   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7895      Also, on VxWorks, create the _PROCEDURE_LINKAGE_TABLE_ symbol.  */
7896   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7897     return FALSE;
7898
7899   /* Do the usual VxWorks handling.  */
7900   if (htab->is_vxworks
7901       && !elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7902     return FALSE;
7903
7904   return TRUE;
7905 }
7906 \f
7907 /* Return true if relocation REL against section SEC is a REL rather than
7908    RELA relocation.  RELOCS is the first relocation in the section and
7909    ABFD is the bfd that contains SEC.  */
7910
7911 static bfd_boolean
7912 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7913                            const Elf_Internal_Rela *relocs,
7914                            const Elf_Internal_Rela *rel)
7915 {
7916   Elf_Internal_Shdr *rel_hdr;
7917   const struct elf_backend_data *bed;
7918
7919   /* To determine which flavor of relocation this is, we depend on the
7920      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7921   rel_hdr = elf_section_data (sec)->rel.hdr;
7922   if (rel_hdr == NULL)
7923     return FALSE;
7924   bed = get_elf_backend_data (abfd);
7925   return ((size_t) (rel - relocs)
7926           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7927 }
7928
7929 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7930    HOWTO is the relocation's howto and CONTENTS points to the contents
7931    of the section that REL is against.  */
7932
7933 static bfd_vma
7934 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7935                           reloc_howto_type *howto, bfd_byte *contents)
7936 {
7937   bfd_byte *location;
7938   unsigned int r_type;
7939   bfd_vma addend;
7940   bfd_vma bytes;
7941
7942   r_type = ELF_R_TYPE (abfd, rel->r_info);
7943   location = contents + rel->r_offset;
7944
7945   /* Get the addend, which is stored in the input file.  */
7946   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7947   bytes = mips_elf_obtain_contents (howto, rel, abfd, contents);
7948   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7949
7950   addend = bytes & howto->src_mask;
7951
7952   /* Shift is 2, unusually, for microMIPS JALX.  Adjust the addend
7953      accordingly.  */
7954   if (r_type == R_MICROMIPS_26_S1 && (bytes >> 26) == 0x3c)
7955     addend <<= 1;
7956
7957   return addend;
7958 }
7959
7960 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7961    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7962    and update *ADDEND with the final addend.  Return true on success
7963    or false if the LO16 could not be found.  RELEND is the exclusive
7964    upper bound on the relocations for REL's section.  */
7965
7966 static bfd_boolean
7967 mips_elf_add_lo16_rel_addend (bfd *abfd,
7968                               const Elf_Internal_Rela *rel,
7969                               const Elf_Internal_Rela *relend,
7970                               bfd_byte *contents, bfd_vma *addend)
7971 {
7972   unsigned int r_type, lo16_type;
7973   const Elf_Internal_Rela *lo16_relocation;
7974   reloc_howto_type *lo16_howto;
7975   bfd_vma l;
7976
7977   r_type = ELF_R_TYPE (abfd, rel->r_info);
7978   if (mips16_reloc_p (r_type))
7979     lo16_type = R_MIPS16_LO16;
7980   else if (micromips_reloc_p (r_type))
7981     lo16_type = R_MICROMIPS_LO16;
7982   else if (r_type == R_MIPS_PCHI16)
7983     lo16_type = R_MIPS_PCLO16;
7984   else
7985     lo16_type = R_MIPS_LO16;
7986
7987   /* The combined value is the sum of the HI16 addend, left-shifted by
7988      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7989      code does a `lui' of the HI16 value, and then an `addiu' of the
7990      LO16 value.)
7991
7992      Scan ahead to find a matching LO16 relocation.
7993
7994      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7995      be immediately following.  However, for the IRIX6 ABI, the next
7996      relocation may be a composed relocation consisting of several
7997      relocations for the same address.  In that case, the R_MIPS_LO16
7998      relocation may occur as one of these.  We permit a similar
7999      extension in general, as that is useful for GCC.
8000
8001      In some cases GCC dead code elimination removes the LO16 but keeps
8002      the corresponding HI16.  This is strictly speaking a violation of
8003      the ABI but not immediately harmful.  */
8004   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
8005   if (lo16_relocation == NULL)
8006     return FALSE;
8007
8008   /* Obtain the addend kept there.  */
8009   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
8010   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
8011
8012   l <<= lo16_howto->rightshift;
8013   l = _bfd_mips_elf_sign_extend (l, 16);
8014
8015   *addend <<= 16;
8016   *addend += l;
8017   return TRUE;
8018 }
8019
8020 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
8021    store the contents in *CONTENTS on success.  Assume that *CONTENTS
8022    already holds the contents if it is nonull on entry.  */
8023
8024 static bfd_boolean
8025 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
8026 {
8027   if (*contents)
8028     return TRUE;
8029
8030   /* Get cached copy if it exists.  */
8031   if (elf_section_data (sec)->this_hdr.contents != NULL)
8032     {
8033       *contents = elf_section_data (sec)->this_hdr.contents;
8034       return TRUE;
8035     }
8036
8037   return bfd_malloc_and_get_section (abfd, sec, contents);
8038 }
8039
8040 /* Make a new PLT record to keep internal data.  */
8041
8042 static struct plt_entry *
8043 mips_elf_make_plt_record (bfd *abfd)
8044 {
8045   struct plt_entry *entry;
8046
8047   entry = bfd_zalloc (abfd, sizeof (*entry));
8048   if (entry == NULL)
8049     return NULL;
8050
8051   entry->stub_offset = MINUS_ONE;
8052   entry->mips_offset = MINUS_ONE;
8053   entry->comp_offset = MINUS_ONE;
8054   entry->gotplt_index = MINUS_ONE;
8055   return entry;
8056 }
8057
8058 /* Look through the relocs for a section during the first phase, and
8059    allocate space in the global offset table and record the need for
8060    standard MIPS and compressed procedure linkage table entries.  */
8061
8062 bfd_boolean
8063 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
8064                             asection *sec, const Elf_Internal_Rela *relocs)
8065 {
8066   const char *name;
8067   bfd *dynobj;
8068   Elf_Internal_Shdr *symtab_hdr;
8069   struct elf_link_hash_entry **sym_hashes;
8070   size_t extsymoff;
8071   const Elf_Internal_Rela *rel;
8072   const Elf_Internal_Rela *rel_end;
8073   asection *sreloc;
8074   const struct elf_backend_data *bed;
8075   struct mips_elf_link_hash_table *htab;
8076   bfd_byte *contents;
8077   bfd_vma addend;
8078   reloc_howto_type *howto;
8079
8080   if (bfd_link_relocatable (info))
8081     return TRUE;
8082
8083   htab = mips_elf_hash_table (info);
8084   BFD_ASSERT (htab != NULL);
8085
8086   dynobj = elf_hash_table (info)->dynobj;
8087   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8088   sym_hashes = elf_sym_hashes (abfd);
8089   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8090
8091   bed = get_elf_backend_data (abfd);
8092   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
8093
8094   /* Check for the mips16 stub sections.  */
8095
8096   name = bfd_get_section_name (abfd, sec);
8097   if (FN_STUB_P (name))
8098     {
8099       unsigned long r_symndx;
8100
8101       /* Look at the relocation information to figure out which symbol
8102          this is for.  */
8103
8104       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
8105       if (r_symndx == 0)
8106         {
8107           _bfd_error_handler
8108             /* xgettext:c-format */
8109             (_("%B: Warning: cannot determine the target function for"
8110                " stub section `%s'"),
8111              abfd, name);
8112           bfd_set_error (bfd_error_bad_value);
8113           return FALSE;
8114         }
8115
8116       if (r_symndx < extsymoff
8117           || sym_hashes[r_symndx - extsymoff] == NULL)
8118         {
8119           asection *o;
8120
8121           /* This stub is for a local symbol.  This stub will only be
8122              needed if there is some relocation in this BFD, other
8123              than a 16 bit function call, which refers to this symbol.  */
8124           for (o = abfd->sections; o != NULL; o = o->next)
8125             {
8126               Elf_Internal_Rela *sec_relocs;
8127               const Elf_Internal_Rela *r, *rend;
8128
8129               /* We can ignore stub sections when looking for relocs.  */
8130               if ((o->flags & SEC_RELOC) == 0
8131                   || o->reloc_count == 0
8132                   || section_allows_mips16_refs_p (o))
8133                 continue;
8134
8135               sec_relocs
8136                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
8137                                              info->keep_memory);
8138               if (sec_relocs == NULL)
8139                 return FALSE;
8140
8141               rend = sec_relocs + o->reloc_count;
8142               for (r = sec_relocs; r < rend; r++)
8143                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
8144                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
8145                   break;
8146
8147               if (elf_section_data (o)->relocs != sec_relocs)
8148                 free (sec_relocs);
8149
8150               if (r < rend)
8151                 break;
8152             }
8153
8154           if (o == NULL)
8155             {
8156               /* There is no non-call reloc for this stub, so we do
8157                  not need it.  Since this function is called before
8158                  the linker maps input sections to output sections, we
8159                  can easily discard it by setting the SEC_EXCLUDE
8160                  flag.  */
8161               sec->flags |= SEC_EXCLUDE;
8162               return TRUE;
8163             }
8164
8165           /* Record this stub in an array of local symbol stubs for
8166              this BFD.  */
8167           if (mips_elf_tdata (abfd)->local_stubs == NULL)
8168             {
8169               unsigned long symcount;
8170               asection **n;
8171               bfd_size_type amt;
8172
8173               if (elf_bad_symtab (abfd))
8174                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
8175               else
8176                 symcount = symtab_hdr->sh_info;
8177               amt = symcount * sizeof (asection *);
8178               n = bfd_zalloc (abfd, amt);
8179               if (n == NULL)
8180                 return FALSE;
8181               mips_elf_tdata (abfd)->local_stubs = n;
8182             }
8183
8184           sec->flags |= SEC_KEEP;
8185           mips_elf_tdata (abfd)->local_stubs[r_symndx] = sec;
8186
8187           /* We don't need to set mips16_stubs_seen in this case.
8188              That flag is used to see whether we need to look through
8189              the global symbol table for stubs.  We don't need to set
8190              it here, because we just have a local stub.  */
8191         }
8192       else
8193         {
8194           struct mips_elf_link_hash_entry *h;
8195
8196           h = ((struct mips_elf_link_hash_entry *)
8197                sym_hashes[r_symndx - extsymoff]);
8198
8199           while (h->root.root.type == bfd_link_hash_indirect
8200                  || h->root.root.type == bfd_link_hash_warning)
8201             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8202
8203           /* H is the symbol this stub is for.  */
8204
8205           /* If we already have an appropriate stub for this function, we
8206              don't need another one, so we can discard this one.  Since
8207              this function is called before the linker maps input sections
8208              to output sections, we can easily discard it by setting the
8209              SEC_EXCLUDE flag.  */
8210           if (h->fn_stub != NULL)
8211             {
8212               sec->flags |= SEC_EXCLUDE;
8213               return TRUE;
8214             }
8215
8216           sec->flags |= SEC_KEEP;
8217           h->fn_stub = sec;
8218           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
8219         }
8220     }
8221   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
8222     {
8223       unsigned long r_symndx;
8224       struct mips_elf_link_hash_entry *h;
8225       asection **loc;
8226
8227       /* Look at the relocation information to figure out which symbol
8228          this is for.  */
8229
8230       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
8231       if (r_symndx == 0)
8232         {
8233           _bfd_error_handler
8234             /* xgettext:c-format */
8235             (_("%B: Warning: cannot determine the target function for"
8236                " stub section `%s'"),
8237              abfd, name);
8238           bfd_set_error (bfd_error_bad_value);
8239           return FALSE;
8240         }
8241
8242       if (r_symndx < extsymoff
8243           || sym_hashes[r_symndx - extsymoff] == NULL)
8244         {
8245           asection *o;
8246
8247           /* This stub is for a local symbol.  This stub will only be
8248              needed if there is some relocation (R_MIPS16_26) in this BFD
8249              that refers to this symbol.  */
8250           for (o = abfd->sections; o != NULL; o = o->next)
8251             {
8252               Elf_Internal_Rela *sec_relocs;
8253               const Elf_Internal_Rela *r, *rend;
8254
8255               /* We can ignore stub sections when looking for relocs.  */
8256               if ((o->flags & SEC_RELOC) == 0
8257                   || o->reloc_count == 0
8258                   || section_allows_mips16_refs_p (o))
8259                 continue;
8260
8261               sec_relocs
8262                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
8263                                              info->keep_memory);
8264               if (sec_relocs == NULL)
8265                 return FALSE;
8266
8267               rend = sec_relocs + o->reloc_count;
8268               for (r = sec_relocs; r < rend; r++)
8269                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
8270                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
8271                     break;
8272
8273               if (elf_section_data (o)->relocs != sec_relocs)
8274                 free (sec_relocs);
8275
8276               if (r < rend)
8277                 break;
8278             }
8279
8280           if (o == NULL)
8281             {
8282               /* There is no non-call reloc for this stub, so we do
8283                  not need it.  Since this function is called before
8284                  the linker maps input sections to output sections, we
8285                  can easily discard it by setting the SEC_EXCLUDE
8286                  flag.  */
8287               sec->flags |= SEC_EXCLUDE;
8288               return TRUE;
8289             }
8290
8291           /* Record this stub in an array of local symbol call_stubs for
8292              this BFD.  */
8293           if (mips_elf_tdata (abfd)->local_call_stubs == NULL)
8294             {
8295               unsigned long symcount;
8296               asection **n;
8297               bfd_size_type amt;
8298
8299               if (elf_bad_symtab (abfd))
8300                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
8301               else
8302                 symcount = symtab_hdr->sh_info;
8303               amt = symcount * sizeof (asection *);
8304               n = bfd_zalloc (abfd, amt);
8305               if (n == NULL)
8306                 return FALSE;
8307               mips_elf_tdata (abfd)->local_call_stubs = n;
8308             }
8309
8310           sec->flags |= SEC_KEEP;
8311           mips_elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
8312
8313           /* We don't need to set mips16_stubs_seen in this case.
8314              That flag is used to see whether we need to look through
8315              the global symbol table for stubs.  We don't need to set
8316              it here, because we just have a local stub.  */
8317         }
8318       else
8319         {
8320           h = ((struct mips_elf_link_hash_entry *)
8321                sym_hashes[r_symndx - extsymoff]);
8322
8323           /* H is the symbol this stub is for.  */
8324
8325           if (CALL_FP_STUB_P (name))
8326             loc = &h->call_fp_stub;
8327           else
8328             loc = &h->call_stub;
8329
8330           /* If we already have an appropriate stub for this function, we
8331              don't need another one, so we can discard this one.  Since
8332              this function is called before the linker maps input sections
8333              to output sections, we can easily discard it by setting the
8334              SEC_EXCLUDE flag.  */
8335           if (*loc != NULL)
8336             {
8337               sec->flags |= SEC_EXCLUDE;
8338               return TRUE;
8339             }
8340
8341           sec->flags |= SEC_KEEP;
8342           *loc = sec;
8343           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
8344         }
8345     }
8346
8347   sreloc = NULL;
8348   contents = NULL;
8349   for (rel = relocs; rel < rel_end; ++rel)
8350     {
8351       unsigned long r_symndx;
8352       unsigned int r_type;
8353       struct elf_link_hash_entry *h;
8354       bfd_boolean can_make_dynamic_p;
8355       bfd_boolean call_reloc_p;
8356       bfd_boolean constrain_symbol_p;
8357
8358       r_symndx = ELF_R_SYM (abfd, rel->r_info);
8359       r_type = ELF_R_TYPE (abfd, rel->r_info);
8360
8361       if (r_symndx < extsymoff)
8362         h = NULL;
8363       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
8364         {
8365           _bfd_error_handler
8366             /* xgettext:c-format */
8367             (_("%B: Malformed reloc detected for section %s"),
8368              abfd, name);
8369           bfd_set_error (bfd_error_bad_value);
8370           return FALSE;
8371         }
8372       else
8373         {
8374           h = sym_hashes[r_symndx - extsymoff];
8375           if (h != NULL)
8376             {
8377               while (h->root.type == bfd_link_hash_indirect
8378                      || h->root.type == bfd_link_hash_warning)
8379                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
8380
8381               /* PR15323, ref flags aren't set for references in the
8382                  same object.  */
8383               h->root.non_ir_ref = 1;
8384             }
8385         }
8386
8387       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
8388          relocation into a dynamic one.  */
8389       can_make_dynamic_p = FALSE;
8390
8391       /* Set CALL_RELOC_P to true if the relocation is for a call,
8392          and if pointer equality therefore doesn't matter.  */
8393       call_reloc_p = FALSE;
8394
8395       /* Set CONSTRAIN_SYMBOL_P if we need to take the relocation
8396          into account when deciding how to define the symbol.
8397          Relocations in nonallocatable sections such as .pdr and
8398          .debug* should have no effect.  */
8399       constrain_symbol_p = ((sec->flags & SEC_ALLOC) != 0);
8400
8401       switch (r_type)
8402         {
8403         case R_MIPS_CALL16:
8404         case R_MIPS_CALL_HI16:
8405         case R_MIPS_CALL_LO16:
8406         case R_MIPS16_CALL16:
8407         case R_MICROMIPS_CALL16:
8408         case R_MICROMIPS_CALL_HI16:
8409         case R_MICROMIPS_CALL_LO16:
8410           call_reloc_p = TRUE;
8411           /* Fall through.  */
8412
8413         case R_MIPS_GOT16:
8414         case R_MIPS_GOT_HI16:
8415         case R_MIPS_GOT_LO16:
8416         case R_MIPS_GOT_PAGE:
8417         case R_MIPS_GOT_OFST:
8418         case R_MIPS_GOT_DISP:
8419         case R_MIPS_TLS_GOTTPREL:
8420         case R_MIPS_TLS_GD:
8421         case R_MIPS_TLS_LDM:
8422         case R_MIPS16_GOT16:
8423         case R_MIPS16_TLS_GOTTPREL:
8424         case R_MIPS16_TLS_GD:
8425         case R_MIPS16_TLS_LDM:
8426         case R_MICROMIPS_GOT16:
8427         case R_MICROMIPS_GOT_HI16:
8428         case R_MICROMIPS_GOT_LO16:
8429         case R_MICROMIPS_GOT_PAGE:
8430         case R_MICROMIPS_GOT_OFST:
8431         case R_MICROMIPS_GOT_DISP:
8432         case R_MICROMIPS_TLS_GOTTPREL:
8433         case R_MICROMIPS_TLS_GD:
8434         case R_MICROMIPS_TLS_LDM:
8435           if (dynobj == NULL)
8436             elf_hash_table (info)->dynobj = dynobj = abfd;
8437           if (!mips_elf_create_got_section (dynobj, info))
8438             return FALSE;
8439           if (htab->is_vxworks && !bfd_link_pic (info))
8440             {
8441               _bfd_error_handler
8442                 /* xgettext:c-format */
8443                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
8444                  abfd, (unsigned long) rel->r_offset);
8445               bfd_set_error (bfd_error_bad_value);
8446               return FALSE;
8447             }
8448           can_make_dynamic_p = TRUE;
8449           break;
8450
8451         case R_MIPS_NONE:
8452         case R_MIPS_JALR:
8453         case R_MICROMIPS_JALR:
8454           /* These relocations have empty fields and are purely there to
8455              provide link information.  The symbol value doesn't matter.  */
8456           constrain_symbol_p = FALSE;
8457           break;
8458
8459         case R_MIPS_GPREL16:
8460         case R_MIPS_GPREL32:
8461         case R_MIPS16_GPREL:
8462         case R_MICROMIPS_GPREL16:
8463           /* GP-relative relocations always resolve to a definition in a
8464              regular input file, ignoring the one-definition rule.  This is
8465              important for the GP setup sequence in NewABI code, which
8466              always resolves to a local function even if other relocations
8467              against the symbol wouldn't.  */
8468           constrain_symbol_p = FALSE;
8469           break;
8470
8471         case R_MIPS_32:
8472         case R_MIPS_REL32:
8473         case R_MIPS_64:
8474           /* In VxWorks executables, references to external symbols
8475              must be handled using copy relocs or PLT entries; it is not
8476              possible to convert this relocation into a dynamic one.
8477
8478              For executables that use PLTs and copy-relocs, we have a
8479              choice between converting the relocation into a dynamic
8480              one or using copy relocations or PLT entries.  It is
8481              usually better to do the former, unless the relocation is
8482              against a read-only section.  */
8483           if ((bfd_link_pic (info)
8484                || (h != NULL
8485                    && !htab->is_vxworks
8486                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
8487                    && !(!info->nocopyreloc
8488                         && !PIC_OBJECT_P (abfd)
8489                         && MIPS_ELF_READONLY_SECTION (sec))))
8490               && (sec->flags & SEC_ALLOC) != 0)
8491             {
8492               can_make_dynamic_p = TRUE;
8493               if (dynobj == NULL)
8494                 elf_hash_table (info)->dynobj = dynobj = abfd;
8495             }
8496           break;
8497
8498         case R_MIPS_26:
8499         case R_MIPS_PC16:
8500         case R_MIPS_PC21_S2:
8501         case R_MIPS_PC26_S2:
8502         case R_MIPS16_26:
8503         case R_MIPS16_PC16_S1:
8504         case R_MICROMIPS_26_S1:
8505         case R_MICROMIPS_PC7_S1:
8506         case R_MICROMIPS_PC10_S1:
8507         case R_MICROMIPS_PC16_S1:
8508         case R_MICROMIPS_PC23_S2:
8509           call_reloc_p = TRUE;
8510           break;
8511         }
8512
8513       if (h)
8514         {
8515           if (constrain_symbol_p)
8516             {
8517               if (!can_make_dynamic_p)
8518                 ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = 1;
8519
8520               if (!call_reloc_p)
8521                 h->pointer_equality_needed = 1;
8522
8523               /* We must not create a stub for a symbol that has
8524                  relocations related to taking the function's address.
8525                  This doesn't apply to VxWorks, where CALL relocs refer
8526                  to a .got.plt entry instead of a normal .got entry.  */
8527               if (!htab->is_vxworks && (!can_make_dynamic_p || !call_reloc_p))
8528                 ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8529             }
8530
8531           /* Relocations against the special VxWorks __GOTT_BASE__ and
8532              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
8533              room for them in .rela.dyn.  */
8534           if (is_gott_symbol (info, h))
8535             {
8536               if (sreloc == NULL)
8537                 {
8538                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8539                   if (sreloc == NULL)
8540                     return FALSE;
8541                 }
8542               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8543               if (MIPS_ELF_READONLY_SECTION (sec))
8544                 /* We tell the dynamic linker that there are
8545                    relocations against the text segment.  */
8546                 info->flags |= DF_TEXTREL;
8547             }
8548         }
8549       else if (call_lo16_reloc_p (r_type)
8550                || got_lo16_reloc_p (r_type)
8551                || got_disp_reloc_p (r_type)
8552                || (got16_reloc_p (r_type) && htab->is_vxworks))
8553         {
8554           /* We may need a local GOT entry for this relocation.  We
8555              don't count R_MIPS_GOT_PAGE because we can estimate the
8556              maximum number of pages needed by looking at the size of
8557              the segment.  Similar comments apply to R_MIPS*_GOT16 and
8558              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
8559              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
8560              R_MIPS_CALL_HI16 because these are always followed by an
8561              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
8562           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8563                                                  rel->r_addend, info, r_type))
8564             return FALSE;
8565         }
8566
8567       if (h != NULL
8568           && mips_elf_relocation_needs_la25_stub (abfd, r_type,
8569                                                   ELF_ST_IS_MIPS16 (h->other)))
8570         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
8571
8572       switch (r_type)
8573         {
8574         case R_MIPS_CALL16:
8575         case R_MIPS16_CALL16:
8576         case R_MICROMIPS_CALL16:
8577           if (h == NULL)
8578             {
8579               _bfd_error_handler
8580                 /* xgettext:c-format */
8581                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
8582                  abfd, (unsigned long) rel->r_offset);
8583               bfd_set_error (bfd_error_bad_value);
8584               return FALSE;
8585             }
8586           /* Fall through.  */
8587
8588         case R_MIPS_CALL_HI16:
8589         case R_MIPS_CALL_LO16:
8590         case R_MICROMIPS_CALL_HI16:
8591         case R_MICROMIPS_CALL_LO16:
8592           if (h != NULL)
8593             {
8594               /* Make sure there is room in the regular GOT to hold the
8595                  function's address.  We may eliminate it in favour of
8596                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
8597               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE,
8598                                                       r_type))
8599                 return FALSE;
8600
8601               /* We need a stub, not a plt entry for the undefined
8602                  function.  But we record it as if it needs plt.  See
8603                  _bfd_elf_adjust_dynamic_symbol.  */
8604               h->needs_plt = 1;
8605               h->type = STT_FUNC;
8606             }
8607           break;
8608
8609         case R_MIPS_GOT_PAGE:
8610         case R_MICROMIPS_GOT_PAGE:
8611         case R_MIPS16_GOT16:
8612         case R_MIPS_GOT16:
8613         case R_MIPS_GOT_HI16:
8614         case R_MIPS_GOT_LO16:
8615         case R_MICROMIPS_GOT16:
8616         case R_MICROMIPS_GOT_HI16:
8617         case R_MICROMIPS_GOT_LO16:
8618           if (!h || got_page_reloc_p (r_type))
8619             {
8620               /* This relocation needs (or may need, if h != NULL) a
8621                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
8622                  know for sure until we know whether the symbol is
8623                  preemptible.  */
8624               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
8625                 {
8626                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
8627                     return FALSE;
8628                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8629                   addend = mips_elf_read_rel_addend (abfd, rel,
8630                                                      howto, contents);
8631                   if (got16_reloc_p (r_type))
8632                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
8633                                                   contents, &addend);
8634                   else
8635                     addend <<= howto->rightshift;
8636                 }
8637               else
8638                 addend = rel->r_addend;
8639               if (!mips_elf_record_got_page_ref (info, abfd, r_symndx,
8640                                                  h, addend))
8641                 return FALSE;
8642
8643               if (h)
8644                 {
8645                   struct mips_elf_link_hash_entry *hmips =
8646                     (struct mips_elf_link_hash_entry *) h;
8647
8648                   /* This symbol is definitely not overridable.  */
8649                   if (hmips->root.def_regular
8650                       && ! (bfd_link_pic (info) && ! info->symbolic
8651                             && ! hmips->root.forced_local))
8652                     h = NULL;
8653                 }
8654             }
8655           /* If this is a global, overridable symbol, GOT_PAGE will
8656              decay to GOT_DISP, so we'll need a GOT entry for it.  */
8657           /* Fall through.  */
8658
8659         case R_MIPS_GOT_DISP:
8660         case R_MICROMIPS_GOT_DISP:
8661           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8662                                                        FALSE, r_type))
8663             return FALSE;
8664           break;
8665
8666         case R_MIPS_TLS_GOTTPREL:
8667         case R_MIPS16_TLS_GOTTPREL:
8668         case R_MICROMIPS_TLS_GOTTPREL:
8669           if (bfd_link_pic (info))
8670             info->flags |= DF_STATIC_TLS;
8671           /* Fall through */
8672
8673         case R_MIPS_TLS_LDM:
8674         case R_MIPS16_TLS_LDM:
8675         case R_MICROMIPS_TLS_LDM:
8676           if (tls_ldm_reloc_p (r_type))
8677             {
8678               r_symndx = STN_UNDEF;
8679               h = NULL;
8680             }
8681           /* Fall through */
8682
8683         case R_MIPS_TLS_GD:
8684         case R_MIPS16_TLS_GD:
8685         case R_MICROMIPS_TLS_GD:
8686           /* This symbol requires a global offset table entry, or two
8687              for TLS GD relocations.  */
8688           if (h != NULL)
8689             {
8690               if (!mips_elf_record_global_got_symbol (h, abfd, info,
8691                                                       FALSE, r_type))
8692                 return FALSE;
8693             }
8694           else
8695             {
8696               if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8697                                                      rel->r_addend,
8698                                                      info, r_type))
8699                 return FALSE;
8700             }
8701           break;
8702
8703         case R_MIPS_32:
8704         case R_MIPS_REL32:
8705         case R_MIPS_64:
8706           /* In VxWorks executables, references to external symbols
8707              are handled using copy relocs or PLT stubs, so there's
8708              no need to add a .rela.dyn entry for this relocation.  */
8709           if (can_make_dynamic_p)
8710             {
8711               if (sreloc == NULL)
8712                 {
8713                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8714                   if (sreloc == NULL)
8715                     return FALSE;
8716                 }
8717               if (bfd_link_pic (info) && h == NULL)
8718                 {
8719                   /* When creating a shared object, we must copy these
8720                      reloc types into the output file as R_MIPS_REL32
8721                      relocs.  Make room for this reloc in .rel(a).dyn.  */
8722                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8723                   if (MIPS_ELF_READONLY_SECTION (sec))
8724                     /* We tell the dynamic linker that there are
8725                        relocations against the text segment.  */
8726                     info->flags |= DF_TEXTREL;
8727                 }
8728               else
8729                 {
8730                   struct mips_elf_link_hash_entry *hmips;
8731
8732                   /* For a shared object, we must copy this relocation
8733                      unless the symbol turns out to be undefined and
8734                      weak with non-default visibility, in which case
8735                      it will be left as zero.
8736
8737                      We could elide R_MIPS_REL32 for locally binding symbols
8738                      in shared libraries, but do not yet do so.
8739
8740                      For an executable, we only need to copy this
8741                      reloc if the symbol is defined in a dynamic
8742                      object.  */
8743                   hmips = (struct mips_elf_link_hash_entry *) h;
8744                   ++hmips->possibly_dynamic_relocs;
8745                   if (MIPS_ELF_READONLY_SECTION (sec))
8746                     /* We need it to tell the dynamic linker if there
8747                        are relocations against the text segment.  */
8748                     hmips->readonly_reloc = TRUE;
8749                 }
8750             }
8751
8752           if (SGI_COMPAT (abfd))
8753             mips_elf_hash_table (info)->compact_rel_size +=
8754               sizeof (Elf32_External_crinfo);
8755           break;
8756
8757         case R_MIPS_26:
8758         case R_MIPS_GPREL16:
8759         case R_MIPS_LITERAL:
8760         case R_MIPS_GPREL32:
8761         case R_MICROMIPS_26_S1:
8762         case R_MICROMIPS_GPREL16:
8763         case R_MICROMIPS_LITERAL:
8764         case R_MICROMIPS_GPREL7_S2:
8765           if (SGI_COMPAT (abfd))
8766             mips_elf_hash_table (info)->compact_rel_size +=
8767               sizeof (Elf32_External_crinfo);
8768           break;
8769
8770           /* This relocation describes the C++ object vtable hierarchy.
8771              Reconstruct it for later use during GC.  */
8772         case R_MIPS_GNU_VTINHERIT:
8773           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
8774             return FALSE;
8775           break;
8776
8777           /* This relocation describes which C++ vtable entries are actually
8778              used.  Record for later use during GC.  */
8779         case R_MIPS_GNU_VTENTRY:
8780           BFD_ASSERT (h != NULL);
8781           if (h != NULL
8782               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
8783             return FALSE;
8784           break;
8785
8786         default:
8787           break;
8788         }
8789
8790       /* Record the need for a PLT entry.  At this point we don't know
8791          yet if we are going to create a PLT in the first place, but
8792          we only record whether the relocation requires a standard MIPS
8793          or a compressed code entry anyway.  If we don't make a PLT after
8794          all, then we'll just ignore these arrangements.  Likewise if
8795          a PLT entry is not created because the symbol is satisfied
8796          locally.  */
8797       if (h != NULL
8798           && (branch_reloc_p (r_type)
8799               || mips16_branch_reloc_p (r_type)
8800               || micromips_branch_reloc_p (r_type))
8801           && !SYMBOL_CALLS_LOCAL (info, h))
8802         {
8803           if (h->plt.plist == NULL)
8804             h->plt.plist = mips_elf_make_plt_record (abfd);
8805           if (h->plt.plist == NULL)
8806             return FALSE;
8807
8808           if (branch_reloc_p (r_type))
8809             h->plt.plist->need_mips = TRUE;
8810           else
8811             h->plt.plist->need_comp = TRUE;
8812         }
8813
8814       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8815          if there is one.  We only need to handle global symbols here;
8816          we decide whether to keep or delete stubs for local symbols
8817          when processing the stub's relocations.  */
8818       if (h != NULL
8819           && !mips16_call_reloc_p (r_type)
8820           && !section_allows_mips16_refs_p (sec))
8821         {
8822           struct mips_elf_link_hash_entry *mh;
8823
8824           mh = (struct mips_elf_link_hash_entry *) h;
8825           mh->need_fn_stub = TRUE;
8826         }
8827
8828       /* Refuse some position-dependent relocations when creating a
8829          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8830          not PIC, but we can create dynamic relocations and the result
8831          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8832          combined with R_MIPS_GOT16.  */
8833       if (bfd_link_pic (info))
8834         {
8835           switch (r_type)
8836             {
8837             case R_MIPS16_HI16:
8838             case R_MIPS_HI16:
8839             case R_MIPS_HIGHER:
8840             case R_MIPS_HIGHEST:
8841             case R_MICROMIPS_HI16:
8842             case R_MICROMIPS_HIGHER:
8843             case R_MICROMIPS_HIGHEST:
8844               /* Don't refuse a high part relocation if it's against
8845                  no symbol (e.g. part of a compound relocation).  */
8846               if (r_symndx == STN_UNDEF)
8847                 break;
8848
8849               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8850                  and has a special meaning.  */
8851               if (!NEWABI_P (abfd) && h != NULL
8852                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8853                 break;
8854
8855               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8856               if (is_gott_symbol (info, h))
8857                 break;
8858
8859               /* FALLTHROUGH */
8860
8861             case R_MIPS16_26:
8862             case R_MIPS_26:
8863             case R_MICROMIPS_26_S1:
8864               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8865               _bfd_error_handler
8866                 /* xgettext:c-format */
8867                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8868                  abfd, howto->name,
8869                  (h) ? h->root.root.string : "a local symbol");
8870               bfd_set_error (bfd_error_bad_value);
8871               return FALSE;
8872             default:
8873               break;
8874             }
8875         }
8876     }
8877
8878   return TRUE;
8879 }
8880 \f
8881 bfd_boolean
8882 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8883                          struct bfd_link_info *link_info,
8884                          bfd_boolean *again)
8885 {
8886   Elf_Internal_Rela *internal_relocs;
8887   Elf_Internal_Rela *irel, *irelend;
8888   Elf_Internal_Shdr *symtab_hdr;
8889   bfd_byte *contents = NULL;
8890   size_t extsymoff;
8891   bfd_boolean changed_contents = FALSE;
8892   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8893   Elf_Internal_Sym *isymbuf = NULL;
8894
8895   /* We are not currently changing any sizes, so only one pass.  */
8896   *again = FALSE;
8897
8898   if (bfd_link_relocatable (link_info))
8899     return TRUE;
8900
8901   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8902                                                link_info->keep_memory);
8903   if (internal_relocs == NULL)
8904     return TRUE;
8905
8906   irelend = internal_relocs + sec->reloc_count
8907     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8908   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8909   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8910
8911   for (irel = internal_relocs; irel < irelend; irel++)
8912     {
8913       bfd_vma symval;
8914       bfd_signed_vma sym_offset;
8915       unsigned int r_type;
8916       unsigned long r_symndx;
8917       asection *sym_sec;
8918       unsigned long instruction;
8919
8920       /* Turn jalr into bgezal, and jr into beq, if they're marked
8921          with a JALR relocation, that indicate where they jump to.
8922          This saves some pipeline bubbles.  */
8923       r_type = ELF_R_TYPE (abfd, irel->r_info);
8924       if (r_type != R_MIPS_JALR)
8925         continue;
8926
8927       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8928       /* Compute the address of the jump target.  */
8929       if (r_symndx >= extsymoff)
8930         {
8931           struct mips_elf_link_hash_entry *h
8932             = ((struct mips_elf_link_hash_entry *)
8933                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8934
8935           while (h->root.root.type == bfd_link_hash_indirect
8936                  || h->root.root.type == bfd_link_hash_warning)
8937             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8938
8939           /* If a symbol is undefined, or if it may be overridden,
8940              skip it.  */
8941           if (! ((h->root.root.type == bfd_link_hash_defined
8942                   || h->root.root.type == bfd_link_hash_defweak)
8943                  && h->root.root.u.def.section)
8944               || (bfd_link_pic (link_info) && ! link_info->symbolic
8945                   && !h->root.forced_local))
8946             continue;
8947
8948           sym_sec = h->root.root.u.def.section;
8949           if (sym_sec->output_section)
8950             symval = (h->root.root.u.def.value
8951                       + sym_sec->output_section->vma
8952                       + sym_sec->output_offset);
8953           else
8954             symval = h->root.root.u.def.value;
8955         }
8956       else
8957         {
8958           Elf_Internal_Sym *isym;
8959
8960           /* Read this BFD's symbols if we haven't done so already.  */
8961           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8962             {
8963               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8964               if (isymbuf == NULL)
8965                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8966                                                 symtab_hdr->sh_info, 0,
8967                                                 NULL, NULL, NULL);
8968               if (isymbuf == NULL)
8969                 goto relax_return;
8970             }
8971
8972           isym = isymbuf + r_symndx;
8973           if (isym->st_shndx == SHN_UNDEF)
8974             continue;
8975           else if (isym->st_shndx == SHN_ABS)
8976             sym_sec = bfd_abs_section_ptr;
8977           else if (isym->st_shndx == SHN_COMMON)
8978             sym_sec = bfd_com_section_ptr;
8979           else
8980             sym_sec
8981               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8982           symval = isym->st_value
8983             + sym_sec->output_section->vma
8984             + sym_sec->output_offset;
8985         }
8986
8987       /* Compute branch offset, from delay slot of the jump to the
8988          branch target.  */
8989       sym_offset = (symval + irel->r_addend)
8990         - (sec_start + irel->r_offset + 4);
8991
8992       /* Branch offset must be properly aligned.  */
8993       if ((sym_offset & 3) != 0)
8994         continue;
8995
8996       sym_offset >>= 2;
8997
8998       /* Check that it's in range.  */
8999       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
9000         continue;
9001
9002       /* Get the section contents if we haven't done so already.  */
9003       if (!mips_elf_get_section_contents (abfd, sec, &contents))
9004         goto relax_return;
9005
9006       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
9007
9008       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
9009       if ((instruction & 0xfc1fffff) == 0x0000f809)
9010         instruction = 0x04110000;
9011       /* If it was jr <reg>, turn it into b <target>.  */
9012       else if ((instruction & 0xfc1fffff) == 0x00000008)
9013         instruction = 0x10000000;
9014       else
9015         continue;
9016
9017       instruction |= (sym_offset & 0xffff);
9018       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
9019       changed_contents = TRUE;
9020     }
9021
9022   if (contents != NULL
9023       && elf_section_data (sec)->this_hdr.contents != contents)
9024     {
9025       if (!changed_contents && !link_info->keep_memory)
9026         free (contents);
9027       else
9028         {
9029           /* Cache the section contents for elf_link_input_bfd.  */
9030           elf_section_data (sec)->this_hdr.contents = contents;
9031         }
9032     }
9033   return TRUE;
9034
9035  relax_return:
9036   if (contents != NULL
9037       && elf_section_data (sec)->this_hdr.contents != contents)
9038     free (contents);
9039   return FALSE;
9040 }
9041 \f
9042 /* Allocate space for global sym dynamic relocs.  */
9043
9044 static bfd_boolean
9045 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
9046 {
9047   struct bfd_link_info *info = inf;
9048   bfd *dynobj;
9049   struct mips_elf_link_hash_entry *hmips;
9050   struct mips_elf_link_hash_table *htab;
9051
9052   htab = mips_elf_hash_table (info);
9053   BFD_ASSERT (htab != NULL);
9054
9055   dynobj = elf_hash_table (info)->dynobj;
9056   hmips = (struct mips_elf_link_hash_entry *) h;
9057
9058   /* VxWorks executables are handled elsewhere; we only need to
9059      allocate relocations in shared objects.  */
9060   if (htab->is_vxworks && !bfd_link_pic (info))
9061     return TRUE;
9062
9063   /* Ignore indirect symbols.  All relocations against such symbols
9064      will be redirected to the target symbol.  */
9065   if (h->root.type == bfd_link_hash_indirect)
9066     return TRUE;
9067
9068   /* If this symbol is defined in a dynamic object, or we are creating
9069      a shared library, we will need to copy any R_MIPS_32 or
9070      R_MIPS_REL32 relocs against it into the output file.  */
9071   if (! bfd_link_relocatable (info)
9072       && hmips->possibly_dynamic_relocs != 0
9073       && (h->root.type == bfd_link_hash_defweak
9074           || (!h->def_regular && !ELF_COMMON_DEF_P (h))
9075           || bfd_link_pic (info)))
9076     {
9077       bfd_boolean do_copy = TRUE;
9078
9079       if (h->root.type == bfd_link_hash_undefweak)
9080         {
9081           /* Do not copy relocations for undefined weak symbols with
9082              non-default visibility.  */
9083           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
9084             do_copy = FALSE;
9085
9086           /* Make sure undefined weak symbols are output as a dynamic
9087              symbol in PIEs.  */
9088           else if (h->dynindx == -1 && !h->forced_local)
9089             {
9090               if (! bfd_elf_link_record_dynamic_symbol (info, h))
9091                 return FALSE;
9092             }
9093         }
9094
9095       if (do_copy)
9096         {
9097           /* Even though we don't directly need a GOT entry for this symbol,
9098              the SVR4 psABI requires it to have a dynamic symbol table
9099              index greater that DT_MIPS_GOTSYM if there are dynamic
9100              relocations against it.
9101
9102              VxWorks does not enforce the same mapping between the GOT
9103              and the symbol table, so the same requirement does not
9104              apply there.  */
9105           if (!htab->is_vxworks)
9106             {
9107               if (hmips->global_got_area > GGA_RELOC_ONLY)
9108                 hmips->global_got_area = GGA_RELOC_ONLY;
9109               hmips->got_only_for_calls = FALSE;
9110             }
9111
9112           mips_elf_allocate_dynamic_relocations
9113             (dynobj, info, hmips->possibly_dynamic_relocs);
9114           if (hmips->readonly_reloc)
9115             /* We tell the dynamic linker that there are relocations
9116                against the text segment.  */
9117             info->flags |= DF_TEXTREL;
9118         }
9119     }
9120
9121   return TRUE;
9122 }
9123
9124 /* Adjust a symbol defined by a dynamic object and referenced by a
9125    regular object.  The current definition is in some section of the
9126    dynamic object, but we're not including those sections.  We have to
9127    change the definition to something the rest of the link can
9128    understand.  */
9129
9130 bfd_boolean
9131 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
9132                                      struct elf_link_hash_entry *h)
9133 {
9134   bfd *dynobj;
9135   struct mips_elf_link_hash_entry *hmips;
9136   struct mips_elf_link_hash_table *htab;
9137   asection *s, *srel;
9138
9139   htab = mips_elf_hash_table (info);
9140   BFD_ASSERT (htab != NULL);
9141
9142   dynobj = elf_hash_table (info)->dynobj;
9143   hmips = (struct mips_elf_link_hash_entry *) h;
9144
9145   /* Make sure we know what is going on here.  */
9146   BFD_ASSERT (dynobj != NULL
9147               && (h->needs_plt
9148                   || h->u.weakdef != NULL
9149                   || (h->def_dynamic
9150                       && h->ref_regular
9151                       && !h->def_regular)));
9152
9153   hmips = (struct mips_elf_link_hash_entry *) h;
9154
9155   /* If there are call relocations against an externally-defined symbol,
9156      see whether we can create a MIPS lazy-binding stub for it.  We can
9157      only do this if all references to the function are through call
9158      relocations, and in that case, the traditional lazy-binding stubs
9159      are much more efficient than PLT entries.
9160
9161      Traditional stubs are only available on SVR4 psABI-based systems;
9162      VxWorks always uses PLTs instead.  */
9163   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
9164     {
9165       if (! elf_hash_table (info)->dynamic_sections_created)
9166         return TRUE;
9167
9168       /* If this symbol is not defined in a regular file, then set
9169          the symbol to the stub location.  This is required to make
9170          function pointers compare as equal between the normal
9171          executable and the shared library.  */
9172       if (!h->def_regular)
9173         {
9174           hmips->needs_lazy_stub = TRUE;
9175           htab->lazy_stub_count++;
9176           return TRUE;
9177         }
9178     }
9179   /* As above, VxWorks requires PLT entries for externally-defined
9180      functions that are only accessed through call relocations.
9181
9182      Both VxWorks and non-VxWorks targets also need PLT entries if there
9183      are static-only relocations against an externally-defined function.
9184      This can technically occur for shared libraries if there are
9185      branches to the symbol, although it is unlikely that this will be
9186      used in practice due to the short ranges involved.  It can occur
9187      for any relative or absolute relocation in executables; in that
9188      case, the PLT entry becomes the function's canonical address.  */
9189   else if (((h->needs_plt && !hmips->no_fn_stub)
9190             || (h->type == STT_FUNC && hmips->has_static_relocs))
9191            && htab->use_plts_and_copy_relocs
9192            && !SYMBOL_CALLS_LOCAL (info, h)
9193            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
9194                 && h->root.type == bfd_link_hash_undefweak))
9195     {
9196       bfd_boolean micromips_p = MICROMIPS_P (info->output_bfd);
9197       bfd_boolean newabi_p = NEWABI_P (info->output_bfd);
9198
9199       /* If this is the first symbol to need a PLT entry, then make some
9200          basic setup.  Also work out PLT entry sizes.  We'll need them
9201          for PLT offset calculations.  */
9202       if (htab->plt_mips_offset + htab->plt_comp_offset == 0)
9203         {
9204           BFD_ASSERT (htab->root.sgotplt->size == 0);
9205           BFD_ASSERT (htab->plt_got_index == 0);
9206
9207           /* If we're using the PLT additions to the psABI, each PLT
9208              entry is 16 bytes and the PLT0 entry is 32 bytes.
9209              Encourage better cache usage by aligning.  We do this
9210              lazily to avoid pessimizing traditional objects.  */
9211           if (!htab->is_vxworks
9212               && !bfd_set_section_alignment (dynobj, htab->root.splt, 5))
9213             return FALSE;
9214
9215           /* Make sure that .got.plt is word-aligned.  We do this lazily
9216              for the same reason as above.  */
9217           if (!bfd_set_section_alignment (dynobj, htab->root.sgotplt,
9218                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
9219             return FALSE;
9220
9221           /* On non-VxWorks targets, the first two entries in .got.plt
9222              are reserved.  */
9223           if (!htab->is_vxworks)
9224             htab->plt_got_index
9225               += (get_elf_backend_data (dynobj)->got_header_size
9226                   / MIPS_ELF_GOT_SIZE (dynobj));
9227
9228           /* On VxWorks, also allocate room for the header's
9229              .rela.plt.unloaded entries.  */
9230           if (htab->is_vxworks && !bfd_link_pic (info))
9231             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
9232
9233           /* Now work out the sizes of individual PLT entries.  */
9234           if (htab->is_vxworks && bfd_link_pic (info))
9235             htab->plt_mips_entry_size
9236               = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
9237           else if (htab->is_vxworks)
9238             htab->plt_mips_entry_size
9239               = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
9240           else if (newabi_p)
9241             htab->plt_mips_entry_size
9242               = 4 * ARRAY_SIZE (mips_exec_plt_entry);
9243           else if (!micromips_p)
9244             {
9245               htab->plt_mips_entry_size
9246                 = 4 * ARRAY_SIZE (mips_exec_plt_entry);
9247               htab->plt_comp_entry_size
9248                 = 2 * ARRAY_SIZE (mips16_o32_exec_plt_entry);
9249             }
9250           else if (htab->insn32)
9251             {
9252               htab->plt_mips_entry_size
9253                 = 4 * ARRAY_SIZE (mips_exec_plt_entry);
9254               htab->plt_comp_entry_size
9255                 = 2 * ARRAY_SIZE (micromips_insn32_o32_exec_plt_entry);
9256             }
9257           else
9258             {
9259               htab->plt_mips_entry_size
9260                 = 4 * ARRAY_SIZE (mips_exec_plt_entry);
9261               htab->plt_comp_entry_size
9262                 = 2 * ARRAY_SIZE (micromips_o32_exec_plt_entry);
9263             }
9264         }
9265
9266       if (h->plt.plist == NULL)
9267         h->plt.plist = mips_elf_make_plt_record (dynobj);
9268       if (h->plt.plist == NULL)
9269         return FALSE;
9270
9271       /* There are no defined MIPS16 or microMIPS PLT entries for VxWorks,
9272          n32 or n64, so always use a standard entry there.
9273
9274          If the symbol has a MIPS16 call stub and gets a PLT entry, then
9275          all MIPS16 calls will go via that stub, and there is no benefit
9276          to having a MIPS16 entry.  And in the case of call_stub a
9277          standard entry actually has to be used as the stub ends with a J
9278          instruction.  */
9279       if (newabi_p
9280           || htab->is_vxworks
9281           || hmips->call_stub
9282           || hmips->call_fp_stub)
9283         {
9284           h->plt.plist->need_mips = TRUE;
9285           h->plt.plist->need_comp = FALSE;
9286         }
9287
9288       /* Otherwise, if there are no direct calls to the function, we
9289          have a free choice of whether to use standard or compressed
9290          entries.  Prefer microMIPS entries if the object is known to
9291          contain microMIPS code, so that it becomes possible to create
9292          pure microMIPS binaries.  Prefer standard entries otherwise,
9293          because MIPS16 ones are no smaller and are usually slower.  */
9294       if (!h->plt.plist->need_mips && !h->plt.plist->need_comp)
9295         {
9296           if (micromips_p)
9297             h->plt.plist->need_comp = TRUE;
9298           else
9299             h->plt.plist->need_mips = TRUE;
9300         }
9301
9302       if (h->plt.plist->need_mips)
9303         {
9304           h->plt.plist->mips_offset = htab->plt_mips_offset;
9305           htab->plt_mips_offset += htab->plt_mips_entry_size;
9306         }
9307       if (h->plt.plist->need_comp)
9308         {
9309           h->plt.plist->comp_offset = htab->plt_comp_offset;
9310           htab->plt_comp_offset += htab->plt_comp_entry_size;
9311         }
9312
9313       /* Reserve the corresponding .got.plt entry now too.  */
9314       h->plt.plist->gotplt_index = htab->plt_got_index++;
9315
9316       /* If the output file has no definition of the symbol, set the
9317          symbol's value to the address of the stub.  */
9318       if (!bfd_link_pic (info) && !h->def_regular)
9319         hmips->use_plt_entry = TRUE;
9320
9321       /* Make room for the R_MIPS_JUMP_SLOT relocation.  */
9322       htab->root.srelplt->size += (htab->is_vxworks
9323                                    ? MIPS_ELF_RELA_SIZE (dynobj)
9324                                    : MIPS_ELF_REL_SIZE (dynobj));
9325
9326       /* Make room for the .rela.plt.unloaded relocations.  */
9327       if (htab->is_vxworks && !bfd_link_pic (info))
9328         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
9329
9330       /* All relocations against this symbol that could have been made
9331          dynamic will now refer to the PLT entry instead.  */
9332       hmips->possibly_dynamic_relocs = 0;
9333
9334       return TRUE;
9335     }
9336
9337   /* If this is a weak symbol, and there is a real definition, the
9338      processor independent code will have arranged for us to see the
9339      real definition first, and we can just use the same value.  */
9340   if (h->u.weakdef != NULL)
9341     {
9342       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
9343                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
9344       h->root.u.def.section = h->u.weakdef->root.u.def.section;
9345       h->root.u.def.value = h->u.weakdef->root.u.def.value;
9346       return TRUE;
9347     }
9348
9349   /* Otherwise, there is nothing further to do for symbols defined
9350      in regular objects.  */
9351   if (h->def_regular)
9352     return TRUE;
9353
9354   /* There's also nothing more to do if we'll convert all relocations
9355      against this symbol into dynamic relocations.  */
9356   if (!hmips->has_static_relocs)
9357     return TRUE;
9358
9359   /* We're now relying on copy relocations.  Complain if we have
9360      some that we can't convert.  */
9361   if (!htab->use_plts_and_copy_relocs || bfd_link_pic (info))
9362     {
9363       _bfd_error_handler (_("non-dynamic relocations refer to "
9364                             "dynamic symbol %s"),
9365                           h->root.root.string);
9366       bfd_set_error (bfd_error_bad_value);
9367       return FALSE;
9368     }
9369
9370   /* We must allocate the symbol in our .dynbss section, which will
9371      become part of the .bss section of the executable.  There will be
9372      an entry for this symbol in the .dynsym section.  The dynamic
9373      object will contain position independent code, so all references
9374      from the dynamic object to this symbol will go through the global
9375      offset table.  The dynamic linker will use the .dynsym entry to
9376      determine the address it must put in the global offset table, so
9377      both the dynamic object and the regular object will refer to the
9378      same memory location for the variable.  */
9379
9380   if ((h->root.u.def.section->flags & SEC_READONLY) != 0)
9381     {
9382       s = htab->root.sdynrelro;
9383       srel = htab->root.sreldynrelro;
9384     }
9385   else
9386     {
9387       s = htab->root.sdynbss;
9388       srel = htab->root.srelbss;
9389     }
9390   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
9391     {
9392       if (htab->is_vxworks)
9393         srel->size += sizeof (Elf32_External_Rela);
9394       else
9395         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
9396       h->needs_copy = 1;
9397     }
9398
9399   /* All relocations against this symbol that could have been made
9400      dynamic will now refer to the local copy instead.  */
9401   hmips->possibly_dynamic_relocs = 0;
9402
9403   return _bfd_elf_adjust_dynamic_copy (info, h, s);
9404 }
9405 \f
9406 /* This function is called after all the input files have been read,
9407    and the input sections have been assigned to output sections.  We
9408    check for any mips16 stub sections that we can discard.  */
9409
9410 bfd_boolean
9411 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
9412                                     struct bfd_link_info *info)
9413 {
9414   asection *sect;
9415   struct mips_elf_link_hash_table *htab;
9416   struct mips_htab_traverse_info hti;
9417
9418   htab = mips_elf_hash_table (info);
9419   BFD_ASSERT (htab != NULL);
9420
9421   /* The .reginfo section has a fixed size.  */
9422   sect = bfd_get_section_by_name (output_bfd, ".reginfo");
9423   if (sect != NULL)
9424     bfd_set_section_size (output_bfd, sect, sizeof (Elf32_External_RegInfo));
9425
9426   /* The .MIPS.abiflags section has a fixed size.  */
9427   sect = bfd_get_section_by_name (output_bfd, ".MIPS.abiflags");
9428   if (sect != NULL)
9429     bfd_set_section_size (output_bfd, sect, sizeof (Elf_External_ABIFlags_v0));
9430
9431   hti.info = info;
9432   hti.output_bfd = output_bfd;
9433   hti.error = FALSE;
9434   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
9435                                mips_elf_check_symbols, &hti);
9436   if (hti.error)
9437     return FALSE;
9438
9439   return TRUE;
9440 }
9441
9442 /* If the link uses a GOT, lay it out and work out its size.  */
9443
9444 static bfd_boolean
9445 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
9446 {
9447   bfd *dynobj;
9448   asection *s;
9449   struct mips_got_info *g;
9450   bfd_size_type loadable_size = 0;
9451   bfd_size_type page_gotno;
9452   bfd *ibfd;
9453   struct mips_elf_traverse_got_arg tga;
9454   struct mips_elf_link_hash_table *htab;
9455
9456   htab = mips_elf_hash_table (info);
9457   BFD_ASSERT (htab != NULL);
9458
9459   s = htab->root.sgot;
9460   if (s == NULL)
9461     return TRUE;
9462
9463   dynobj = elf_hash_table (info)->dynobj;
9464   g = htab->got_info;
9465
9466   /* Allocate room for the reserved entries.  VxWorks always reserves
9467      3 entries; other objects only reserve 2 entries.  */
9468   BFD_ASSERT (g->assigned_low_gotno == 0);
9469   if (htab->is_vxworks)
9470     htab->reserved_gotno = 3;
9471   else
9472     htab->reserved_gotno = 2;
9473   g->local_gotno += htab->reserved_gotno;
9474   g->assigned_low_gotno = htab->reserved_gotno;
9475
9476   /* Decide which symbols need to go in the global part of the GOT and
9477      count the number of reloc-only GOT symbols.  */
9478   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
9479
9480   if (!mips_elf_resolve_final_got_entries (info, g))
9481     return FALSE;
9482
9483   /* Calculate the total loadable size of the output.  That
9484      will give us the maximum number of GOT_PAGE entries
9485      required.  */
9486   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
9487     {
9488       asection *subsection;
9489
9490       for (subsection = ibfd->sections;
9491            subsection;
9492            subsection = subsection->next)
9493         {
9494           if ((subsection->flags & SEC_ALLOC) == 0)
9495             continue;
9496           loadable_size += ((subsection->size + 0xf)
9497                             &~ (bfd_size_type) 0xf);
9498         }
9499     }
9500
9501   if (htab->is_vxworks)
9502     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
9503        relocations against local symbols evaluate to "G", and the EABI does
9504        not include R_MIPS_GOT_PAGE.  */
9505     page_gotno = 0;
9506   else
9507     /* Assume there are two loadable segments consisting of contiguous
9508        sections.  Is 5 enough?  */
9509     page_gotno = (loadable_size >> 16) + 5;
9510
9511   /* Choose the smaller of the two page estimates; both are intended to be
9512      conservative.  */
9513   if (page_gotno > g->page_gotno)
9514     page_gotno = g->page_gotno;
9515
9516   g->local_gotno += page_gotno;
9517   g->assigned_high_gotno = g->local_gotno - 1;
9518
9519   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
9520   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
9521   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
9522
9523   /* VxWorks does not support multiple GOTs.  It initializes $gp to
9524      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
9525      dynamic loader.  */
9526   if (!htab->is_vxworks && s->size > MIPS_ELF_GOT_MAX_SIZE (info))
9527     {
9528       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
9529         return FALSE;
9530     }
9531   else
9532     {
9533       /* Record that all bfds use G.  This also has the effect of freeing
9534          the per-bfd GOTs, which we no longer need.  */
9535       for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
9536         if (mips_elf_bfd_got (ibfd, FALSE))
9537           mips_elf_replace_bfd_got (ibfd, g);
9538       mips_elf_replace_bfd_got (output_bfd, g);
9539
9540       /* Set up TLS entries.  */
9541       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
9542       tga.info = info;
9543       tga.g = g;
9544       tga.value = MIPS_ELF_GOT_SIZE (output_bfd);
9545       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
9546       if (!tga.g)
9547         return FALSE;
9548       BFD_ASSERT (g->tls_assigned_gotno
9549                   == g->global_gotno + g->local_gotno + g->tls_gotno);
9550
9551       /* Each VxWorks GOT entry needs an explicit relocation.  */
9552       if (htab->is_vxworks && bfd_link_pic (info))
9553         g->relocs += g->global_gotno + g->local_gotno - htab->reserved_gotno;
9554
9555       /* Allocate room for the TLS relocations.  */
9556       if (g->relocs)
9557         mips_elf_allocate_dynamic_relocations (dynobj, info, g->relocs);
9558     }
9559
9560   return TRUE;
9561 }
9562
9563 /* Estimate the size of the .MIPS.stubs section.  */
9564
9565 static void
9566 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
9567 {
9568   struct mips_elf_link_hash_table *htab;
9569   bfd_size_type dynsymcount;
9570
9571   htab = mips_elf_hash_table (info);
9572   BFD_ASSERT (htab != NULL);
9573
9574   if (htab->lazy_stub_count == 0)
9575     return;
9576
9577   /* IRIX rld assumes that a function stub isn't at the end of the .text
9578      section, so add a dummy entry to the end.  */
9579   htab->lazy_stub_count++;
9580
9581   /* Get a worst-case estimate of the number of dynamic symbols needed.
9582      At this point, dynsymcount does not account for section symbols
9583      and count_section_dynsyms may overestimate the number that will
9584      be needed.  */
9585   dynsymcount = (elf_hash_table (info)->dynsymcount
9586                  + count_section_dynsyms (output_bfd, info));
9587
9588   /* Determine the size of one stub entry.  There's no disadvantage
9589      from using microMIPS code here, so for the sake of pure-microMIPS
9590      binaries we prefer it whenever there's any microMIPS code in
9591      output produced at all.  This has a benefit of stubs being
9592      shorter by 4 bytes each too, unless in the insn32 mode.  */
9593   if (!MICROMIPS_P (output_bfd))
9594     htab->function_stub_size = (dynsymcount > 0x10000
9595                                 ? MIPS_FUNCTION_STUB_BIG_SIZE
9596                                 : MIPS_FUNCTION_STUB_NORMAL_SIZE);
9597   else if (htab->insn32)
9598     htab->function_stub_size = (dynsymcount > 0x10000
9599                                 ? MICROMIPS_INSN32_FUNCTION_STUB_BIG_SIZE
9600                                 : MICROMIPS_INSN32_FUNCTION_STUB_NORMAL_SIZE);
9601   else
9602     htab->function_stub_size = (dynsymcount > 0x10000
9603                                 ? MICROMIPS_FUNCTION_STUB_BIG_SIZE
9604                                 : MICROMIPS_FUNCTION_STUB_NORMAL_SIZE);
9605
9606   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
9607 }
9608
9609 /* A mips_elf_link_hash_traverse callback for which DATA points to a
9610    mips_htab_traverse_info.  If H needs a traditional MIPS lazy-binding
9611    stub, allocate an entry in the stubs section.  */
9612
9613 static bfd_boolean
9614 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void *data)
9615 {
9616   struct mips_htab_traverse_info *hti = data;
9617   struct mips_elf_link_hash_table *htab;
9618   struct bfd_link_info *info;
9619   bfd *output_bfd;
9620
9621   info = hti->info;
9622   output_bfd = hti->output_bfd;
9623   htab = mips_elf_hash_table (info);
9624   BFD_ASSERT (htab != NULL);
9625
9626   if (h->needs_lazy_stub)
9627     {
9628       bfd_boolean micromips_p = MICROMIPS_P (output_bfd);
9629       unsigned int other = micromips_p ? STO_MICROMIPS : 0;
9630       bfd_vma isa_bit = micromips_p;
9631
9632       BFD_ASSERT (htab->root.dynobj != NULL);
9633       if (h->root.plt.plist == NULL)
9634         h->root.plt.plist = mips_elf_make_plt_record (htab->sstubs->owner);
9635       if (h->root.plt.plist == NULL)
9636         {
9637           hti->error = TRUE;
9638           return FALSE;
9639         }
9640       h->root.root.u.def.section = htab->sstubs;
9641       h->root.root.u.def.value = htab->sstubs->size + isa_bit;
9642       h->root.plt.plist->stub_offset = htab->sstubs->size;
9643       h->root.other = other;
9644       htab->sstubs->size += htab->function_stub_size;
9645     }
9646   return TRUE;
9647 }
9648
9649 /* Allocate offsets in the stubs section to each symbol that needs one.
9650    Set the final size of the .MIPS.stub section.  */
9651
9652 static bfd_boolean
9653 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
9654 {
9655   bfd *output_bfd = info->output_bfd;
9656   bfd_boolean micromips_p = MICROMIPS_P (output_bfd);
9657   unsigned int other = micromips_p ? STO_MICROMIPS : 0;
9658   bfd_vma isa_bit = micromips_p;
9659   struct mips_elf_link_hash_table *htab;
9660   struct mips_htab_traverse_info hti;
9661   struct elf_link_hash_entry *h;
9662   bfd *dynobj;
9663
9664   htab = mips_elf_hash_table (info);
9665   BFD_ASSERT (htab != NULL);
9666
9667   if (htab->lazy_stub_count == 0)
9668     return TRUE;
9669
9670   htab->sstubs->size = 0;
9671   hti.info = info;
9672   hti.output_bfd = output_bfd;
9673   hti.error = FALSE;
9674   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, &hti);
9675   if (hti.error)
9676     return FALSE;
9677   htab->sstubs->size += htab->function_stub_size;
9678   BFD_ASSERT (htab->sstubs->size
9679               == htab->lazy_stub_count * htab->function_stub_size);
9680
9681   dynobj = elf_hash_table (info)->dynobj;
9682   BFD_ASSERT (dynobj != NULL);
9683   h = _bfd_elf_define_linkage_sym (dynobj, info, htab->sstubs, "_MIPS_STUBS_");
9684   if (h == NULL)
9685     return FALSE;
9686   h->root.u.def.value = isa_bit;
9687   h->other = other;
9688   h->type = STT_FUNC;
9689
9690   return TRUE;
9691 }
9692
9693 /* A mips_elf_link_hash_traverse callback for which DATA points to a
9694    bfd_link_info.  If H uses the address of a PLT entry as the value
9695    of the symbol, then set the entry in the symbol table now.  Prefer
9696    a standard MIPS PLT entry.  */
9697
9698 static bfd_boolean
9699 mips_elf_set_plt_sym_value (struct mips_elf_link_hash_entry *h, void *data)
9700 {
9701   struct bfd_link_info *info = data;
9702   bfd_boolean micromips_p = MICROMIPS_P (info->output_bfd);
9703   struct mips_elf_link_hash_table *htab;
9704   unsigned int other;
9705   bfd_vma isa_bit;
9706   bfd_vma val;
9707
9708   htab = mips_elf_hash_table (info);
9709   BFD_ASSERT (htab != NULL);
9710
9711   if (h->use_plt_entry)
9712     {
9713       BFD_ASSERT (h->root.plt.plist != NULL);
9714       BFD_ASSERT (h->root.plt.plist->mips_offset != MINUS_ONE
9715                   || h->root.plt.plist->comp_offset != MINUS_ONE);
9716
9717       val = htab->plt_header_size;
9718       if (h->root.plt.plist->mips_offset != MINUS_ONE)
9719         {
9720           isa_bit = 0;
9721           val += h->root.plt.plist->mips_offset;
9722           other = 0;
9723         }
9724       else
9725         {
9726           isa_bit = 1;
9727           val += htab->plt_mips_offset + h->root.plt.plist->comp_offset;
9728           other = micromips_p ? STO_MICROMIPS : STO_MIPS16;
9729         }
9730       val += isa_bit;
9731       /* For VxWorks, point at the PLT load stub rather than the lazy
9732          resolution stub; this stub will become the canonical function
9733          address.  */
9734       if (htab->is_vxworks)
9735         val += 8;
9736
9737       h->root.root.u.def.section = htab->root.splt;
9738       h->root.root.u.def.value = val;
9739       h->root.other = other;
9740     }
9741
9742   return TRUE;
9743 }
9744
9745 /* Set the sizes of the dynamic sections.  */
9746
9747 bfd_boolean
9748 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
9749                                      struct bfd_link_info *info)
9750 {
9751   bfd *dynobj;
9752   asection *s, *sreldyn;
9753   bfd_boolean reltext;
9754   struct mips_elf_link_hash_table *htab;
9755
9756   htab = mips_elf_hash_table (info);
9757   BFD_ASSERT (htab != NULL);
9758   dynobj = elf_hash_table (info)->dynobj;
9759   BFD_ASSERT (dynobj != NULL);
9760
9761   if (elf_hash_table (info)->dynamic_sections_created)
9762     {
9763       /* Set the contents of the .interp section to the interpreter.  */
9764       if (bfd_link_executable (info) && !info->nointerp)
9765         {
9766           s = bfd_get_linker_section (dynobj, ".interp");
9767           BFD_ASSERT (s != NULL);
9768           s->size
9769             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
9770           s->contents
9771             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
9772         }
9773
9774       /* Figure out the size of the PLT header if we know that we
9775          are using it.  For the sake of cache alignment always use
9776          a standard header whenever any standard entries are present
9777          even if microMIPS entries are present as well.  This also
9778          lets the microMIPS header rely on the value of $v0 only set
9779          by microMIPS entries, for a small size reduction.
9780
9781          Set symbol table entry values for symbols that use the
9782          address of their PLT entry now that we can calculate it.
9783
9784          Also create the _PROCEDURE_LINKAGE_TABLE_ symbol if we
9785          haven't already in _bfd_elf_create_dynamic_sections.  */
9786       if (htab->root.splt && htab->plt_mips_offset + htab->plt_comp_offset != 0)
9787         {
9788           bfd_boolean micromips_p = (MICROMIPS_P (output_bfd)
9789                                      && !htab->plt_mips_offset);
9790           unsigned int other = micromips_p ? STO_MICROMIPS : 0;
9791           bfd_vma isa_bit = micromips_p;
9792           struct elf_link_hash_entry *h;
9793           bfd_vma size;
9794
9795           BFD_ASSERT (htab->use_plts_and_copy_relocs);
9796           BFD_ASSERT (htab->root.sgotplt->size == 0);
9797           BFD_ASSERT (htab->root.splt->size == 0);
9798
9799           if (htab->is_vxworks && bfd_link_pic (info))
9800             size = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
9801           else if (htab->is_vxworks)
9802             size = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
9803           else if (ABI_64_P (output_bfd))
9804             size = 4 * ARRAY_SIZE (mips_n64_exec_plt0_entry);
9805           else if (ABI_N32_P (output_bfd))
9806             size = 4 * ARRAY_SIZE (mips_n32_exec_plt0_entry);
9807           else if (!micromips_p)
9808             size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
9809           else if (htab->insn32)
9810             size = 2 * ARRAY_SIZE (micromips_insn32_o32_exec_plt0_entry);
9811           else
9812             size = 2 * ARRAY_SIZE (micromips_o32_exec_plt0_entry);
9813
9814           htab->plt_header_is_comp = micromips_p;
9815           htab->plt_header_size = size;
9816           htab->root.splt->size = (size
9817                                    + htab->plt_mips_offset
9818                                    + htab->plt_comp_offset);
9819           htab->root.sgotplt->size = (htab->plt_got_index
9820                                       * MIPS_ELF_GOT_SIZE (dynobj));
9821
9822           mips_elf_link_hash_traverse (htab, mips_elf_set_plt_sym_value, info);
9823
9824           if (htab->root.hplt == NULL)
9825             {
9826               h = _bfd_elf_define_linkage_sym (dynobj, info, htab->root.splt,
9827                                                "_PROCEDURE_LINKAGE_TABLE_");
9828               htab->root.hplt = h;
9829               if (h == NULL)
9830                 return FALSE;
9831             }
9832
9833           h = htab->root.hplt;
9834           h->root.u.def.value = isa_bit;
9835           h->other = other;
9836           h->type = STT_FUNC;
9837         }
9838     }
9839
9840   /* Allocate space for global sym dynamic relocs.  */
9841   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, info);
9842
9843   mips_elf_estimate_stub_size (output_bfd, info);
9844
9845   if (!mips_elf_lay_out_got (output_bfd, info))
9846     return FALSE;
9847
9848   mips_elf_lay_out_lazy_stubs (info);
9849
9850   /* The check_relocs and adjust_dynamic_symbol entry points have
9851      determined the sizes of the various dynamic sections.  Allocate
9852      memory for them.  */
9853   reltext = FALSE;
9854   for (s = dynobj->sections; s != NULL; s = s->next)
9855     {
9856       const char *name;
9857
9858       /* It's OK to base decisions on the section name, because none
9859          of the dynobj section names depend upon the input files.  */
9860       name = bfd_get_section_name (dynobj, s);
9861
9862       if ((s->flags & SEC_LINKER_CREATED) == 0)
9863         continue;
9864
9865       if (CONST_STRNEQ (name, ".rel"))
9866         {
9867           if (s->size != 0)
9868             {
9869               const char *outname;
9870               asection *target;
9871
9872               /* If this relocation section applies to a read only
9873                  section, then we probably need a DT_TEXTREL entry.
9874                  If the relocation section is .rel(a).dyn, we always
9875                  assert a DT_TEXTREL entry rather than testing whether
9876                  there exists a relocation to a read only section or
9877                  not.  */
9878               outname = bfd_get_section_name (output_bfd,
9879                                               s->output_section);
9880               target = bfd_get_section_by_name (output_bfd, outname + 4);
9881               if ((target != NULL
9882                    && (target->flags & SEC_READONLY) != 0
9883                    && (target->flags & SEC_ALLOC) != 0)
9884                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
9885                 reltext = TRUE;
9886
9887               /* We use the reloc_count field as a counter if we need
9888                  to copy relocs into the output file.  */
9889               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
9890                 s->reloc_count = 0;
9891
9892               /* If combreloc is enabled, elf_link_sort_relocs() will
9893                  sort relocations, but in a different way than we do,
9894                  and before we're done creating relocations.  Also, it
9895                  will move them around between input sections'
9896                  relocation's contents, so our sorting would be
9897                  broken, so don't let it run.  */
9898               info->combreloc = 0;
9899             }
9900         }
9901       else if (bfd_link_executable (info)
9902                && ! mips_elf_hash_table (info)->use_rld_obj_head
9903                && CONST_STRNEQ (name, ".rld_map"))
9904         {
9905           /* We add a room for __rld_map.  It will be filled in by the
9906              rtld to contain a pointer to the _r_debug structure.  */
9907           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
9908         }
9909       else if (SGI_COMPAT (output_bfd)
9910                && CONST_STRNEQ (name, ".compact_rel"))
9911         s->size += mips_elf_hash_table (info)->compact_rel_size;
9912       else if (s == htab->root.splt)
9913         {
9914           /* If the last PLT entry has a branch delay slot, allocate
9915              room for an extra nop to fill the delay slot.  This is
9916              for CPUs without load interlocking.  */
9917           if (! LOAD_INTERLOCKS_P (output_bfd)
9918               && ! htab->is_vxworks && s->size > 0)
9919             s->size += 4;
9920         }
9921       else if (! CONST_STRNEQ (name, ".init")
9922                && s != htab->root.sgot
9923                && s != htab->root.sgotplt
9924                && s != htab->sstubs
9925                && s != htab->root.sdynbss
9926                && s != htab->root.sdynrelro)
9927         {
9928           /* It's not one of our sections, so don't allocate space.  */
9929           continue;
9930         }
9931
9932       if (s->size == 0)
9933         {
9934           s->flags |= SEC_EXCLUDE;
9935           continue;
9936         }
9937
9938       if ((s->flags & SEC_HAS_CONTENTS) == 0)
9939         continue;
9940
9941       /* Allocate memory for the section contents.  */
9942       s->contents = bfd_zalloc (dynobj, s->size);
9943       if (s->contents == NULL)
9944         {
9945           bfd_set_error (bfd_error_no_memory);
9946           return FALSE;
9947         }
9948     }
9949
9950   if (elf_hash_table (info)->dynamic_sections_created)
9951     {
9952       /* Add some entries to the .dynamic section.  We fill in the
9953          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
9954          must add the entries now so that we get the correct size for
9955          the .dynamic section.  */
9956
9957       /* SGI object has the equivalence of DT_DEBUG in the
9958          DT_MIPS_RLD_MAP entry.  This must come first because glibc
9959          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and some tools
9960          may only look at the first one they see.  */
9961       if (!bfd_link_pic (info)
9962           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
9963         return FALSE;
9964
9965       if (bfd_link_executable (info)
9966           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP_REL, 0))
9967         return FALSE;
9968
9969       /* The DT_DEBUG entry may be filled in by the dynamic linker and
9970          used by the debugger.  */
9971       if (bfd_link_executable (info)
9972           && !SGI_COMPAT (output_bfd)
9973           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
9974         return FALSE;
9975
9976       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
9977         info->flags |= DF_TEXTREL;
9978
9979       if ((info->flags & DF_TEXTREL) != 0)
9980         {
9981           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
9982             return FALSE;
9983
9984           /* Clear the DF_TEXTREL flag.  It will be set again if we
9985              write out an actual text relocation; we may not, because
9986              at this point we do not know whether e.g. any .eh_frame
9987              absolute relocations have been converted to PC-relative.  */
9988           info->flags &= ~DF_TEXTREL;
9989         }
9990
9991       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
9992         return FALSE;
9993
9994       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
9995       if (htab->is_vxworks)
9996         {
9997           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
9998              use any of the DT_MIPS_* tags.  */
9999           if (sreldyn && sreldyn->size > 0)
10000             {
10001               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
10002                 return FALSE;
10003
10004               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
10005                 return FALSE;
10006
10007               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
10008                 return FALSE;
10009             }
10010         }
10011       else
10012         {
10013           if (sreldyn && sreldyn->size > 0)
10014             {
10015               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
10016                 return FALSE;
10017
10018               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
10019                 return FALSE;
10020
10021               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
10022                 return FALSE;
10023             }
10024
10025           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
10026             return FALSE;
10027
10028           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
10029             return FALSE;
10030
10031           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
10032             return FALSE;
10033
10034           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
10035             return FALSE;
10036
10037           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
10038             return FALSE;
10039
10040           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
10041             return FALSE;
10042
10043           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
10044             return FALSE;
10045
10046           if (IRIX_COMPAT (dynobj) == ict_irix5
10047               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
10048             return FALSE;
10049
10050           if (IRIX_COMPAT (dynobj) == ict_irix6
10051               && (bfd_get_section_by_name
10052                   (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
10053               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
10054             return FALSE;
10055         }
10056       if (htab->root.splt->size > 0)
10057         {
10058           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
10059             return FALSE;
10060
10061           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
10062             return FALSE;
10063
10064           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
10065             return FALSE;
10066
10067           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
10068             return FALSE;
10069         }
10070       if (htab->is_vxworks
10071           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
10072         return FALSE;
10073     }
10074
10075   return TRUE;
10076 }
10077 \f
10078 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
10079    Adjust its R_ADDEND field so that it is correct for the output file.
10080    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
10081    and sections respectively; both use symbol indexes.  */
10082
10083 static void
10084 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
10085                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
10086                         asection **local_sections, Elf_Internal_Rela *rel)
10087 {
10088   unsigned int r_type, r_symndx;
10089   Elf_Internal_Sym *sym;
10090   asection *sec;
10091
10092   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
10093     {
10094       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
10095       if (gprel16_reloc_p (r_type)
10096           || r_type == R_MIPS_GPREL32
10097           || literal_reloc_p (r_type))
10098         {
10099           rel->r_addend += _bfd_get_gp_value (input_bfd);
10100           rel->r_addend -= _bfd_get_gp_value (output_bfd);
10101         }
10102
10103       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
10104       sym = local_syms + r_symndx;
10105
10106       /* Adjust REL's addend to account for section merging.  */
10107       if (!bfd_link_relocatable (info))
10108         {
10109           sec = local_sections[r_symndx];
10110           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
10111         }
10112
10113       /* This would normally be done by the rela_normal code in elflink.c.  */
10114       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
10115         rel->r_addend += local_sections[r_symndx]->output_offset;
10116     }
10117 }
10118
10119 /* Handle relocations against symbols from removed linkonce sections,
10120    or sections discarded by a linker script.  We use this wrapper around
10121    RELOC_AGAINST_DISCARDED_SECTION to handle triplets of compound relocs
10122    on 64-bit ELF targets.  In this case for any relocation handled, which
10123    always be the first in a triplet, the remaining two have to be processed
10124    together with the first, even if they are R_MIPS_NONE.  It is the symbol
10125    index referred by the first reloc that applies to all the three and the
10126    remaining two never refer to an object symbol.  And it is the final
10127    relocation (the last non-null one) that determines the output field of
10128    the whole relocation so retrieve the corresponding howto structure for
10129    the relocatable field to be cleared by RELOC_AGAINST_DISCARDED_SECTION.
10130
10131    Note that RELOC_AGAINST_DISCARDED_SECTION is a macro that uses "continue"
10132    and therefore requires to be pasted in a loop.  It also defines a block
10133    and does not protect any of its arguments, hence the extra brackets.  */
10134
10135 static void
10136 mips_reloc_against_discarded_section (bfd *output_bfd,
10137                                       struct bfd_link_info *info,
10138                                       bfd *input_bfd, asection *input_section,
10139                                       Elf_Internal_Rela **rel,
10140                                       const Elf_Internal_Rela **relend,
10141                                       bfd_boolean rel_reloc,
10142                                       reloc_howto_type *howto,
10143                                       bfd_byte *contents)
10144 {
10145   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10146   int count = bed->s->int_rels_per_ext_rel;
10147   unsigned int r_type;
10148   int i;
10149
10150   for (i = count - 1; i > 0; i--)
10151     {
10152       r_type = ELF_R_TYPE (output_bfd, (*rel)[i].r_info);
10153       if (r_type != R_MIPS_NONE)
10154         {
10155           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
10156           break;
10157         }
10158     }
10159   do
10160     {
10161        RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
10162                                         (*rel), count, (*relend),
10163                                         howto, i, contents);
10164     }
10165   while (0);
10166 }
10167
10168 /* Relocate a MIPS ELF section.  */
10169
10170 bfd_boolean
10171 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
10172                                 bfd *input_bfd, asection *input_section,
10173                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
10174                                 Elf_Internal_Sym *local_syms,
10175                                 asection **local_sections)
10176 {
10177   Elf_Internal_Rela *rel;
10178   const Elf_Internal_Rela *relend;
10179   bfd_vma addend = 0;
10180   bfd_boolean use_saved_addend_p = FALSE;
10181   const struct elf_backend_data *bed;
10182
10183   bed = get_elf_backend_data (output_bfd);
10184   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
10185   for (rel = relocs; rel < relend; ++rel)
10186     {
10187       const char *name;
10188       bfd_vma value = 0;
10189       reloc_howto_type *howto;
10190       bfd_boolean cross_mode_jump_p = FALSE;
10191       /* TRUE if the relocation is a RELA relocation, rather than a
10192          REL relocation.  */
10193       bfd_boolean rela_relocation_p = TRUE;
10194       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
10195       const char *msg;
10196       unsigned long r_symndx;
10197       asection *sec;
10198       Elf_Internal_Shdr *symtab_hdr;
10199       struct elf_link_hash_entry *h;
10200       bfd_boolean rel_reloc;
10201
10202       rel_reloc = (NEWABI_P (input_bfd)
10203                    && mips_elf_rel_relocation_p (input_bfd, input_section,
10204                                                  relocs, rel));
10205       /* Find the relocation howto for this relocation.  */
10206       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
10207
10208       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
10209       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
10210       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
10211         {
10212           sec = local_sections[r_symndx];
10213           h = NULL;
10214         }
10215       else
10216         {
10217           unsigned long extsymoff;
10218
10219           extsymoff = 0;
10220           if (!elf_bad_symtab (input_bfd))
10221             extsymoff = symtab_hdr->sh_info;
10222           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
10223           while (h->root.type == bfd_link_hash_indirect
10224                  || h->root.type == bfd_link_hash_warning)
10225             h = (struct elf_link_hash_entry *) h->root.u.i.link;
10226
10227           sec = NULL;
10228           if (h->root.type == bfd_link_hash_defined
10229               || h->root.type == bfd_link_hash_defweak)
10230             sec = h->root.u.def.section;
10231         }
10232
10233       if (sec != NULL && discarded_section (sec))
10234         {
10235           mips_reloc_against_discarded_section (output_bfd, info, input_bfd,
10236                                                 input_section, &rel, &relend,
10237                                                 rel_reloc, howto, contents);
10238           continue;
10239         }
10240
10241       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
10242         {
10243           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
10244              64-bit code, but make sure all their addresses are in the
10245              lowermost or uppermost 32-bit section of the 64-bit address
10246              space.  Thus, when they use an R_MIPS_64 they mean what is
10247              usually meant by R_MIPS_32, with the exception that the
10248              stored value is sign-extended to 64 bits.  */
10249           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
10250
10251           /* On big-endian systems, we need to lie about the position
10252              of the reloc.  */
10253           if (bfd_big_endian (input_bfd))
10254             rel->r_offset += 4;
10255         }
10256
10257       if (!use_saved_addend_p)
10258         {
10259           /* If these relocations were originally of the REL variety,
10260              we must pull the addend out of the field that will be
10261              relocated.  Otherwise, we simply use the contents of the
10262              RELA relocation.  */
10263           if (mips_elf_rel_relocation_p (input_bfd, input_section,
10264                                          relocs, rel))
10265             {
10266               rela_relocation_p = FALSE;
10267               addend = mips_elf_read_rel_addend (input_bfd, rel,
10268                                                  howto, contents);
10269               if (hi16_reloc_p (r_type)
10270                   || (got16_reloc_p (r_type)
10271                       && mips_elf_local_relocation_p (input_bfd, rel,
10272                                                       local_sections)))
10273                 {
10274                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
10275                                                      contents, &addend))
10276                     {
10277                       if (h)
10278                         name = h->root.root.string;
10279                       else
10280                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10281                                                  local_syms + r_symndx,
10282                                                  sec);
10283                       _bfd_error_handler
10284                         /* xgettext:c-format */
10285                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
10286                          input_bfd, input_section, name, howto->name,
10287                          rel->r_offset);
10288                     }
10289                 }
10290               else
10291                 addend <<= howto->rightshift;
10292             }
10293           else
10294             addend = rel->r_addend;
10295           mips_elf_adjust_addend (output_bfd, info, input_bfd,
10296                                   local_syms, local_sections, rel);
10297         }
10298
10299       if (bfd_link_relocatable (info))
10300         {
10301           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
10302               && bfd_big_endian (input_bfd))
10303             rel->r_offset -= 4;
10304
10305           if (!rela_relocation_p && rel->r_addend)
10306             {
10307               addend += rel->r_addend;
10308               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
10309                 addend = mips_elf_high (addend);
10310               else if (r_type == R_MIPS_HIGHER)
10311                 addend = mips_elf_higher (addend);
10312               else if (r_type == R_MIPS_HIGHEST)
10313                 addend = mips_elf_highest (addend);
10314               else
10315                 addend >>= howto->rightshift;
10316
10317               /* We use the source mask, rather than the destination
10318                  mask because the place to which we are writing will be
10319                  source of the addend in the final link.  */
10320               addend &= howto->src_mask;
10321
10322               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
10323                 /* See the comment above about using R_MIPS_64 in the 32-bit
10324                    ABI.  Here, we need to update the addend.  It would be
10325                    possible to get away with just using the R_MIPS_32 reloc
10326                    but for endianness.  */
10327                 {
10328                   bfd_vma sign_bits;
10329                   bfd_vma low_bits;
10330                   bfd_vma high_bits;
10331
10332                   if (addend & ((bfd_vma) 1 << 31))
10333 #ifdef BFD64
10334                     sign_bits = ((bfd_vma) 1 << 32) - 1;
10335 #else
10336                     sign_bits = -1;
10337 #endif
10338                   else
10339                     sign_bits = 0;
10340
10341                   /* If we don't know that we have a 64-bit type,
10342                      do two separate stores.  */
10343                   if (bfd_big_endian (input_bfd))
10344                     {
10345                       /* Store the sign-bits (which are most significant)
10346                          first.  */
10347                       low_bits = sign_bits;
10348                       high_bits = addend;
10349                     }
10350                   else
10351                     {
10352                       low_bits = addend;
10353                       high_bits = sign_bits;
10354                     }
10355                   bfd_put_32 (input_bfd, low_bits,
10356                               contents + rel->r_offset);
10357                   bfd_put_32 (input_bfd, high_bits,
10358                               contents + rel->r_offset + 4);
10359                   continue;
10360                 }
10361
10362               if (! mips_elf_perform_relocation (info, howto, rel, addend,
10363                                                  input_bfd, input_section,
10364                                                  contents, FALSE))
10365                 return FALSE;
10366             }
10367
10368           /* Go on to the next relocation.  */
10369           continue;
10370         }
10371
10372       /* In the N32 and 64-bit ABIs there may be multiple consecutive
10373          relocations for the same offset.  In that case we are
10374          supposed to treat the output of each relocation as the addend
10375          for the next.  */
10376       if (rel + 1 < relend
10377           && rel->r_offset == rel[1].r_offset
10378           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
10379         use_saved_addend_p = TRUE;
10380       else
10381         use_saved_addend_p = FALSE;
10382
10383       /* Figure out what value we are supposed to relocate.  */
10384       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
10385                                              input_section, info, rel,
10386                                              addend, howto, local_syms,
10387                                              local_sections, &value,
10388                                              &name, &cross_mode_jump_p,
10389                                              use_saved_addend_p))
10390         {
10391         case bfd_reloc_continue:
10392           /* There's nothing to do.  */
10393           continue;
10394
10395         case bfd_reloc_undefined:
10396           /* mips_elf_calculate_relocation already called the
10397              undefined_symbol callback.  There's no real point in
10398              trying to perform the relocation at this point, so we
10399              just skip ahead to the next relocation.  */
10400           continue;
10401
10402         case bfd_reloc_notsupported:
10403           msg = _("internal error: unsupported relocation error");
10404           info->callbacks->warning
10405             (info, msg, name, input_bfd, input_section, rel->r_offset);
10406           return FALSE;
10407
10408         case bfd_reloc_overflow:
10409           if (use_saved_addend_p)
10410             /* Ignore overflow until we reach the last relocation for
10411                a given location.  */
10412             ;
10413           else
10414             {
10415               struct mips_elf_link_hash_table *htab;
10416
10417               htab = mips_elf_hash_table (info);
10418               BFD_ASSERT (htab != NULL);
10419               BFD_ASSERT (name != NULL);
10420               if (!htab->small_data_overflow_reported
10421                   && (gprel16_reloc_p (howto->type)
10422                       || literal_reloc_p (howto->type)))
10423                 {
10424                   msg = _("small-data section exceeds 64KB;"
10425                           " lower small-data size limit (see option -G)");
10426
10427                   htab->small_data_overflow_reported = TRUE;
10428                   (*info->callbacks->einfo) ("%P: %s\n", msg);
10429                 }
10430               (*info->callbacks->reloc_overflow)
10431                 (info, NULL, name, howto->name, (bfd_vma) 0,
10432                  input_bfd, input_section, rel->r_offset);
10433             }
10434           break;
10435
10436         case bfd_reloc_ok:
10437           break;
10438
10439         case bfd_reloc_outofrange:
10440           msg = NULL;
10441           if (jal_reloc_p (howto->type))
10442             msg = (cross_mode_jump_p
10443                    ? _("Cannot convert a jump to JALX "
10444                        "for a non-word-aligned address")
10445                    : (howto->type == R_MIPS16_26
10446                       ? _("Jump to a non-word-aligned address")
10447                       : _("Jump to a non-instruction-aligned address")));
10448           else if (b_reloc_p (howto->type))
10449             msg = (cross_mode_jump_p
10450                    ? _("Cannot convert a branch to JALX "
10451                        "for a non-word-aligned address")
10452                    : _("Branch to a non-instruction-aligned address"));
10453           else if (aligned_pcrel_reloc_p (howto->type))
10454             msg = _("PC-relative load from unaligned address");
10455           if (msg)
10456             {
10457               info->callbacks->einfo
10458                 ("%X%H: %s\n", input_bfd, input_section, rel->r_offset, msg);
10459               break;
10460             }
10461           /* Fall through.  */
10462
10463         default:
10464           abort ();
10465           break;
10466         }
10467
10468       /* If we've got another relocation for the address, keep going
10469          until we reach the last one.  */
10470       if (use_saved_addend_p)
10471         {
10472           addend = value;
10473           continue;
10474         }
10475
10476       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
10477         /* See the comment above about using R_MIPS_64 in the 32-bit
10478            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
10479            that calculated the right value.  Now, however, we
10480            sign-extend the 32-bit result to 64-bits, and store it as a
10481            64-bit value.  We are especially generous here in that we
10482            go to extreme lengths to support this usage on systems with
10483            only a 32-bit VMA.  */
10484         {
10485           bfd_vma sign_bits;
10486           bfd_vma low_bits;
10487           bfd_vma high_bits;
10488
10489           if (value & ((bfd_vma) 1 << 31))
10490 #ifdef BFD64
10491             sign_bits = ((bfd_vma) 1 << 32) - 1;
10492 #else
10493             sign_bits = -1;
10494 #endif
10495           else
10496             sign_bits = 0;
10497
10498           /* If we don't know that we have a 64-bit type,
10499              do two separate stores.  */
10500           if (bfd_big_endian (input_bfd))
10501             {
10502               /* Undo what we did above.  */
10503               rel->r_offset -= 4;
10504               /* Store the sign-bits (which are most significant)
10505                  first.  */
10506               low_bits = sign_bits;
10507               high_bits = value;
10508             }
10509           else
10510             {
10511               low_bits = value;
10512               high_bits = sign_bits;
10513             }
10514           bfd_put_32 (input_bfd, low_bits,
10515                       contents + rel->r_offset);
10516           bfd_put_32 (input_bfd, high_bits,
10517                       contents + rel->r_offset + 4);
10518           continue;
10519         }
10520
10521       /* Actually perform the relocation.  */
10522       if (! mips_elf_perform_relocation (info, howto, rel, value,
10523                                          input_bfd, input_section,
10524                                          contents, cross_mode_jump_p))
10525         return FALSE;
10526     }
10527
10528   return TRUE;
10529 }
10530 \f
10531 /* A function that iterates over each entry in la25_stubs and fills
10532    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
10533
10534 static int
10535 mips_elf_create_la25_stub (void **slot, void *data)
10536 {
10537   struct mips_htab_traverse_info *hti;
10538   struct mips_elf_link_hash_table *htab;
10539   struct mips_elf_la25_stub *stub;
10540   asection *s;
10541   bfd_byte *loc;
10542   bfd_vma offset, target, target_high, target_low;
10543
10544   stub = (struct mips_elf_la25_stub *) *slot;
10545   hti = (struct mips_htab_traverse_info *) data;
10546   htab = mips_elf_hash_table (hti->info);
10547   BFD_ASSERT (htab != NULL);
10548
10549   /* Create the section contents, if we haven't already.  */
10550   s = stub->stub_section;
10551   loc = s->contents;
10552   if (loc == NULL)
10553     {
10554       loc = bfd_malloc (s->size);
10555       if (loc == NULL)
10556         {
10557           hti->error = TRUE;
10558           return FALSE;
10559         }
10560       s->contents = loc;
10561     }
10562
10563   /* Work out where in the section this stub should go.  */
10564   offset = stub->offset;
10565
10566   /* Work out the target address.  */
10567   target = mips_elf_get_la25_target (stub, &s);
10568   target += s->output_section->vma + s->output_offset;
10569
10570   target_high = ((target + 0x8000) >> 16) & 0xffff;
10571   target_low = (target & 0xffff);
10572
10573   if (stub->stub_section != htab->strampoline)
10574     {
10575       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
10576          of the section and write the two instructions at the end.  */
10577       memset (loc, 0, offset);
10578       loc += offset;
10579       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
10580         {
10581           bfd_put_micromips_32 (hti->output_bfd,
10582                                 LA25_LUI_MICROMIPS (target_high),
10583                                 loc);
10584           bfd_put_micromips_32 (hti->output_bfd,
10585                                 LA25_ADDIU_MICROMIPS (target_low),
10586                                 loc + 4);
10587         }
10588       else
10589         {
10590           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
10591           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
10592         }
10593     }
10594   else
10595     {
10596       /* This is trampoline.  */
10597       loc += offset;
10598       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
10599         {
10600           bfd_put_micromips_32 (hti->output_bfd,
10601                                 LA25_LUI_MICROMIPS (target_high), loc);
10602           bfd_put_micromips_32 (hti->output_bfd,
10603                                 LA25_J_MICROMIPS (target), loc + 4);
10604           bfd_put_micromips_32 (hti->output_bfd,
10605                                 LA25_ADDIU_MICROMIPS (target_low), loc + 8);
10606           bfd_put_32 (hti->output_bfd, 0, loc + 12);
10607         }
10608       else
10609         {
10610           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
10611           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
10612           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
10613           bfd_put_32 (hti->output_bfd, 0, loc + 12);
10614         }
10615     }
10616   return TRUE;
10617 }
10618
10619 /* If NAME is one of the special IRIX6 symbols defined by the linker,
10620    adjust it appropriately now.  */
10621
10622 static void
10623 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
10624                                       const char *name, Elf_Internal_Sym *sym)
10625 {
10626   /* The linker script takes care of providing names and values for
10627      these, but we must place them into the right sections.  */
10628   static const char* const text_section_symbols[] = {
10629     "_ftext",
10630     "_etext",
10631     "__dso_displacement",
10632     "__elf_header",
10633     "__program_header_table",
10634     NULL
10635   };
10636
10637   static const char* const data_section_symbols[] = {
10638     "_fdata",
10639     "_edata",
10640     "_end",
10641     "_fbss",
10642     NULL
10643   };
10644
10645   const char* const *p;
10646   int i;
10647
10648   for (i = 0; i < 2; ++i)
10649     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
10650          *p;
10651          ++p)
10652       if (strcmp (*p, name) == 0)
10653         {
10654           /* All of these symbols are given type STT_SECTION by the
10655              IRIX6 linker.  */
10656           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10657           sym->st_other = STO_PROTECTED;
10658
10659           /* The IRIX linker puts these symbols in special sections.  */
10660           if (i == 0)
10661             sym->st_shndx = SHN_MIPS_TEXT;
10662           else
10663             sym->st_shndx = SHN_MIPS_DATA;
10664
10665           break;
10666         }
10667 }
10668
10669 /* Finish up dynamic symbol handling.  We set the contents of various
10670    dynamic sections here.  */
10671
10672 bfd_boolean
10673 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
10674                                      struct bfd_link_info *info,
10675                                      struct elf_link_hash_entry *h,
10676                                      Elf_Internal_Sym *sym)
10677 {
10678   bfd *dynobj;
10679   asection *sgot;
10680   struct mips_got_info *g, *gg;
10681   const char *name;
10682   int idx;
10683   struct mips_elf_link_hash_table *htab;
10684   struct mips_elf_link_hash_entry *hmips;
10685
10686   htab = mips_elf_hash_table (info);
10687   BFD_ASSERT (htab != NULL);
10688   dynobj = elf_hash_table (info)->dynobj;
10689   hmips = (struct mips_elf_link_hash_entry *) h;
10690
10691   BFD_ASSERT (!htab->is_vxworks);
10692
10693   if (h->plt.plist != NULL
10694       && (h->plt.plist->mips_offset != MINUS_ONE
10695           || h->plt.plist->comp_offset != MINUS_ONE))
10696     {
10697       /* We've decided to create a PLT entry for this symbol.  */
10698       bfd_byte *loc;
10699       bfd_vma header_address, got_address;
10700       bfd_vma got_address_high, got_address_low, load;
10701       bfd_vma got_index;
10702       bfd_vma isa_bit;
10703
10704       got_index = h->plt.plist->gotplt_index;
10705
10706       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10707       BFD_ASSERT (h->dynindx != -1);
10708       BFD_ASSERT (htab->root.splt != NULL);
10709       BFD_ASSERT (got_index != MINUS_ONE);
10710       BFD_ASSERT (!h->def_regular);
10711
10712       /* Calculate the address of the PLT header.  */
10713       isa_bit = htab->plt_header_is_comp;
10714       header_address = (htab->root.splt->output_section->vma
10715                         + htab->root.splt->output_offset + isa_bit);
10716
10717       /* Calculate the address of the .got.plt entry.  */
10718       got_address = (htab->root.sgotplt->output_section->vma
10719                      + htab->root.sgotplt->output_offset
10720                      + got_index * MIPS_ELF_GOT_SIZE (dynobj));
10721
10722       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10723       got_address_low = got_address & 0xffff;
10724
10725       /* Initially point the .got.plt entry at the PLT header.  */
10726       loc = (htab->root.sgotplt->contents + got_index * MIPS_ELF_GOT_SIZE (dynobj));
10727       if (ABI_64_P (output_bfd))
10728         bfd_put_64 (output_bfd, header_address, loc);
10729       else
10730         bfd_put_32 (output_bfd, header_address, loc);
10731
10732       /* Now handle the PLT itself.  First the standard entry (the order
10733          does not matter, we just have to pick one).  */
10734       if (h->plt.plist->mips_offset != MINUS_ONE)
10735         {
10736           const bfd_vma *plt_entry;
10737           bfd_vma plt_offset;
10738
10739           plt_offset = htab->plt_header_size + h->plt.plist->mips_offset;
10740
10741           BFD_ASSERT (plt_offset <= htab->root.splt->size);
10742
10743           /* Find out where the .plt entry should go.  */
10744           loc = htab->root.splt->contents + plt_offset;
10745
10746           /* Pick the load opcode.  */
10747           load = MIPS_ELF_LOAD_WORD (output_bfd);
10748
10749           /* Fill in the PLT entry itself.  */
10750
10751           if (MIPSR6_P (output_bfd))
10752             plt_entry = mipsr6_exec_plt_entry;
10753           else
10754             plt_entry = mips_exec_plt_entry;
10755           bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
10756           bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load,
10757                       loc + 4);
10758
10759           if (! LOAD_INTERLOCKS_P (output_bfd))
10760             {
10761               bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
10762               bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10763             }
10764           else
10765             {
10766               bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
10767               bfd_put_32 (output_bfd, plt_entry[2] | got_address_low,
10768                           loc + 12);
10769             }
10770         }
10771
10772       /* Now the compressed entry.  They come after any standard ones.  */
10773       if (h->plt.plist->comp_offset != MINUS_ONE)
10774         {
10775           bfd_vma plt_offset;
10776
10777           plt_offset = (htab->plt_header_size + htab->plt_mips_offset
10778                         + h->plt.plist->comp_offset);
10779
10780           BFD_ASSERT (plt_offset <= htab->root.splt->size);
10781
10782           /* Find out where the .plt entry should go.  */
10783           loc = htab->root.splt->contents + plt_offset;
10784
10785           /* Fill in the PLT entry itself.  */
10786           if (!MICROMIPS_P (output_bfd))
10787             {
10788               const bfd_vma *plt_entry = mips16_o32_exec_plt_entry;
10789
10790               bfd_put_16 (output_bfd, plt_entry[0], loc);
10791               bfd_put_16 (output_bfd, plt_entry[1], loc + 2);
10792               bfd_put_16 (output_bfd, plt_entry[2], loc + 4);
10793               bfd_put_16 (output_bfd, plt_entry[3], loc + 6);
10794               bfd_put_16 (output_bfd, plt_entry[4], loc + 8);
10795               bfd_put_16 (output_bfd, plt_entry[5], loc + 10);
10796               bfd_put_32 (output_bfd, got_address, loc + 12);
10797             }
10798           else if (htab->insn32)
10799             {
10800               const bfd_vma *plt_entry = micromips_insn32_o32_exec_plt_entry;
10801
10802               bfd_put_16 (output_bfd, plt_entry[0], loc);
10803               bfd_put_16 (output_bfd, got_address_high, loc + 2);
10804               bfd_put_16 (output_bfd, plt_entry[2], loc + 4);
10805               bfd_put_16 (output_bfd, got_address_low, loc + 6);
10806               bfd_put_16 (output_bfd, plt_entry[4], loc + 8);
10807               bfd_put_16 (output_bfd, plt_entry[5], loc + 10);
10808               bfd_put_16 (output_bfd, plt_entry[6], loc + 12);
10809               bfd_put_16 (output_bfd, got_address_low, loc + 14);
10810             }
10811           else
10812             {
10813               const bfd_vma *plt_entry = micromips_o32_exec_plt_entry;
10814               bfd_signed_vma gotpc_offset;
10815               bfd_vma loc_address;
10816
10817               BFD_ASSERT (got_address % 4 == 0);
10818
10819               loc_address = (htab->root.splt->output_section->vma
10820                              + htab->root.splt->output_offset + plt_offset);
10821               gotpc_offset = got_address - ((loc_address | 3) ^ 3);
10822
10823               /* ADDIUPC has a span of +/-16MB, check we're in range.  */
10824               if (gotpc_offset + 0x1000000 >= 0x2000000)
10825                 {
10826                   _bfd_error_handler
10827                     /* xgettext:c-format */
10828                     (_("%B: `%A' offset of %ld from `%A' "
10829                        "beyond the range of ADDIUPC"),
10830                      output_bfd,
10831                      htab->root.sgotplt->output_section,
10832                      htab->root.splt->output_section,
10833                      (long) gotpc_offset);
10834                   bfd_set_error (bfd_error_no_error);
10835                   return FALSE;
10836                 }
10837               bfd_put_16 (output_bfd,
10838                           plt_entry[0] | ((gotpc_offset >> 18) & 0x7f), loc);
10839               bfd_put_16 (output_bfd, (gotpc_offset >> 2) & 0xffff, loc + 2);
10840               bfd_put_16 (output_bfd, plt_entry[2], loc + 4);
10841               bfd_put_16 (output_bfd, plt_entry[3], loc + 6);
10842               bfd_put_16 (output_bfd, plt_entry[4], loc + 8);
10843               bfd_put_16 (output_bfd, plt_entry[5], loc + 10);
10844             }
10845         }
10846
10847       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10848       mips_elf_output_dynamic_relocation (output_bfd, htab->root.srelplt,
10849                                           got_index - 2, h->dynindx,
10850                                           R_MIPS_JUMP_SLOT, got_address);
10851
10852       /* We distinguish between PLT entries and lazy-binding stubs by
10853          giving the former an st_other value of STO_MIPS_PLT.  Set the
10854          flag and leave the value if there are any relocations in the
10855          binary where pointer equality matters.  */
10856       sym->st_shndx = SHN_UNDEF;
10857       if (h->pointer_equality_needed)
10858         sym->st_other = ELF_ST_SET_MIPS_PLT (sym->st_other);
10859       else
10860         {
10861           sym->st_value = 0;
10862           sym->st_other = 0;
10863         }
10864     }
10865
10866   if (h->plt.plist != NULL && h->plt.plist->stub_offset != MINUS_ONE)
10867     {
10868       /* We've decided to create a lazy-binding stub.  */
10869       bfd_boolean micromips_p = MICROMIPS_P (output_bfd);
10870       unsigned int other = micromips_p ? STO_MICROMIPS : 0;
10871       bfd_vma stub_size = htab->function_stub_size;
10872       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
10873       bfd_vma isa_bit = micromips_p;
10874       bfd_vma stub_big_size;
10875
10876       if (!micromips_p)
10877         stub_big_size = MIPS_FUNCTION_STUB_BIG_SIZE;
10878       else if (htab->insn32)
10879         stub_big_size = MICROMIPS_INSN32_FUNCTION_STUB_BIG_SIZE;
10880       else
10881         stub_big_size = MICROMIPS_FUNCTION_STUB_BIG_SIZE;
10882
10883       /* This symbol has a stub.  Set it up.  */
10884
10885       BFD_ASSERT (h->dynindx != -1);
10886
10887       BFD_ASSERT (stub_size == stub_big_size || h->dynindx <= 0xffff);
10888
10889       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
10890          sign extension at runtime in the stub, resulting in a negative
10891          index value.  */
10892       if (h->dynindx & ~0x7fffffff)
10893         return FALSE;
10894
10895       /* Fill the stub.  */
10896       if (micromips_p)
10897         {
10898           idx = 0;
10899           bfd_put_micromips_32 (output_bfd, STUB_LW_MICROMIPS (output_bfd),
10900                                 stub + idx);
10901           idx += 4;
10902           if (htab->insn32)
10903             {
10904               bfd_put_micromips_32 (output_bfd,
10905                                     STUB_MOVE32_MICROMIPS, stub + idx);
10906               idx += 4;
10907             }
10908           else
10909             {
10910               bfd_put_16 (output_bfd, STUB_MOVE_MICROMIPS, stub + idx);
10911               idx += 2;
10912             }
10913           if (stub_size == stub_big_size)
10914             {
10915               long dynindx_hi = (h->dynindx >> 16) & 0x7fff;
10916
10917               bfd_put_micromips_32 (output_bfd,
10918                                     STUB_LUI_MICROMIPS (dynindx_hi),
10919                                     stub + idx);
10920               idx += 4;
10921             }
10922           if (htab->insn32)
10923             {
10924               bfd_put_micromips_32 (output_bfd, STUB_JALR32_MICROMIPS,
10925                                     stub + idx);
10926               idx += 4;
10927             }
10928           else
10929             {
10930               bfd_put_16 (output_bfd, STUB_JALR_MICROMIPS, stub + idx);
10931               idx += 2;
10932             }
10933
10934           /* If a large stub is not required and sign extension is not a
10935              problem, then use legacy code in the stub.  */
10936           if (stub_size == stub_big_size)
10937             bfd_put_micromips_32 (output_bfd,
10938                                   STUB_ORI_MICROMIPS (h->dynindx & 0xffff),
10939                                   stub + idx);
10940           else if (h->dynindx & ~0x7fff)
10941             bfd_put_micromips_32 (output_bfd,
10942                                   STUB_LI16U_MICROMIPS (h->dynindx & 0xffff),
10943                                   stub + idx);
10944           else
10945             bfd_put_micromips_32 (output_bfd,
10946                                   STUB_LI16S_MICROMIPS (output_bfd,
10947                                                         h->dynindx),
10948                                   stub + idx);
10949         }
10950       else
10951         {
10952           idx = 0;
10953           bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
10954           idx += 4;
10955           bfd_put_32 (output_bfd, STUB_MOVE, stub + idx);
10956           idx += 4;
10957           if (stub_size == stub_big_size)
10958             {
10959               bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
10960                           stub + idx);
10961               idx += 4;
10962             }
10963           bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
10964           idx += 4;
10965
10966           /* If a large stub is not required and sign extension is not a
10967              problem, then use legacy code in the stub.  */
10968           if (stub_size == stub_big_size)
10969             bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff),
10970                         stub + idx);
10971           else if (h->dynindx & ~0x7fff)
10972             bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff),
10973                         stub + idx);
10974           else
10975             bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
10976                         stub + idx);
10977         }
10978
10979       BFD_ASSERT (h->plt.plist->stub_offset <= htab->sstubs->size);
10980       memcpy (htab->sstubs->contents + h->plt.plist->stub_offset,
10981               stub, stub_size);
10982
10983       /* Mark the symbol as undefined.  stub_offset != -1 occurs
10984          only for the referenced symbol.  */
10985       sym->st_shndx = SHN_UNDEF;
10986
10987       /* The run-time linker uses the st_value field of the symbol
10988          to reset the global offset table entry for this external
10989          to its stub address when unlinking a shared object.  */
10990       sym->st_value = (htab->sstubs->output_section->vma
10991                        + htab->sstubs->output_offset
10992                        + h->plt.plist->stub_offset
10993                        + isa_bit);
10994       sym->st_other = other;
10995     }
10996
10997   /* If we have a MIPS16 function with a stub, the dynamic symbol must
10998      refer to the stub, since only the stub uses the standard calling
10999      conventions.  */
11000   if (h->dynindx != -1 && hmips->fn_stub != NULL)
11001     {
11002       BFD_ASSERT (hmips->need_fn_stub);
11003       sym->st_value = (hmips->fn_stub->output_section->vma
11004                        + hmips->fn_stub->output_offset);
11005       sym->st_size = hmips->fn_stub->size;
11006       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
11007     }
11008
11009   BFD_ASSERT (h->dynindx != -1
11010               || h->forced_local);
11011
11012   sgot = htab->root.sgot;
11013   g = htab->got_info;
11014   BFD_ASSERT (g != NULL);
11015
11016   /* Run through the global symbol table, creating GOT entries for all
11017      the symbols that need them.  */
11018   if (hmips->global_got_area != GGA_NONE)
11019     {
11020       bfd_vma offset;
11021       bfd_vma value;
11022
11023       value = sym->st_value;
11024       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
11025       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
11026     }
11027
11028   if (hmips->global_got_area != GGA_NONE && g->next)
11029     {
11030       struct mips_got_entry e, *p;
11031       bfd_vma entry;
11032       bfd_vma offset;
11033
11034       gg = g;
11035
11036       e.abfd = output_bfd;
11037       e.symndx = -1;
11038       e.d.h = hmips;
11039       e.tls_type = GOT_TLS_NONE;
11040
11041       for (g = g->next; g->next != gg; g = g->next)
11042         {
11043           if (g->got_entries
11044               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
11045                                                            &e)))
11046             {
11047               offset = p->gotidx;
11048               BFD_ASSERT (offset > 0 && offset < htab->root.sgot->size);
11049               if (bfd_link_pic (info)
11050                   || (elf_hash_table (info)->dynamic_sections_created
11051                       && p->d.h != NULL
11052                       && p->d.h->root.def_dynamic
11053                       && !p->d.h->root.def_regular))
11054                 {
11055                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
11056                      the various compatibility problems, it's easier to mock
11057                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
11058                      mips_elf_create_dynamic_relocation to calculate the
11059                      appropriate addend.  */
11060                   Elf_Internal_Rela rel[3];
11061
11062                   memset (rel, 0, sizeof (rel));
11063                   if (ABI_64_P (output_bfd))
11064                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
11065                   else
11066                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
11067                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
11068
11069                   entry = 0;
11070                   if (! (mips_elf_create_dynamic_relocation
11071                          (output_bfd, info, rel,
11072                           e.d.h, NULL, sym->st_value, &entry, sgot)))
11073                     return FALSE;
11074                 }
11075               else
11076                 entry = sym->st_value;
11077               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
11078             }
11079         }
11080     }
11081
11082   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
11083   name = h->root.root.string;
11084   if (h == elf_hash_table (info)->hdynamic
11085       || h == elf_hash_table (info)->hgot)
11086     sym->st_shndx = SHN_ABS;
11087   else if (strcmp (name, "_DYNAMIC_LINK") == 0
11088            || strcmp (name, "_DYNAMIC_LINKING") == 0)
11089     {
11090       sym->st_shndx = SHN_ABS;
11091       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
11092       sym->st_value = 1;
11093     }
11094   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
11095     {
11096       sym->st_shndx = SHN_ABS;
11097       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
11098       sym->st_value = elf_gp (output_bfd);
11099     }
11100   else if (SGI_COMPAT (output_bfd))
11101     {
11102       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
11103           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
11104         {
11105           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
11106           sym->st_other = STO_PROTECTED;
11107           sym->st_value = 0;
11108           sym->st_shndx = SHN_MIPS_DATA;
11109         }
11110       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
11111         {
11112           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
11113           sym->st_other = STO_PROTECTED;
11114           sym->st_value = mips_elf_hash_table (info)->procedure_count;
11115           sym->st_shndx = SHN_ABS;
11116         }
11117       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
11118         {
11119           if (h->type == STT_FUNC)
11120             sym->st_shndx = SHN_MIPS_TEXT;
11121           else if (h->type == STT_OBJECT)
11122             sym->st_shndx = SHN_MIPS_DATA;
11123         }
11124     }
11125
11126   /* Emit a copy reloc, if needed.  */
11127   if (h->needs_copy)
11128     {
11129       asection *s;
11130       bfd_vma symval;
11131
11132       BFD_ASSERT (h->dynindx != -1);
11133       BFD_ASSERT (htab->use_plts_and_copy_relocs);
11134
11135       s = mips_elf_rel_dyn_section (info, FALSE);
11136       symval = (h->root.u.def.section->output_section->vma
11137                 + h->root.u.def.section->output_offset
11138                 + h->root.u.def.value);
11139       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
11140                                           h->dynindx, R_MIPS_COPY, symval);
11141     }
11142
11143   /* Handle the IRIX6-specific symbols.  */
11144   if (IRIX_COMPAT (output_bfd) == ict_irix6)
11145     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
11146
11147   /* Keep dynamic compressed symbols odd.  This allows the dynamic linker
11148      to treat compressed symbols like any other.  */
11149   if (ELF_ST_IS_MIPS16 (sym->st_other))
11150     {
11151       BFD_ASSERT (sym->st_value & 1);
11152       sym->st_other -= STO_MIPS16;
11153     }
11154   else if (ELF_ST_IS_MICROMIPS (sym->st_other))
11155     {
11156       BFD_ASSERT (sym->st_value & 1);
11157       sym->st_other -= STO_MICROMIPS;
11158     }
11159
11160   return TRUE;
11161 }
11162
11163 /* Likewise, for VxWorks.  */
11164
11165 bfd_boolean
11166 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
11167                                          struct bfd_link_info *info,
11168                                          struct elf_link_hash_entry *h,
11169                                          Elf_Internal_Sym *sym)
11170 {
11171   bfd *dynobj;
11172   asection *sgot;
11173   struct mips_got_info *g;
11174   struct mips_elf_link_hash_table *htab;
11175   struct mips_elf_link_hash_entry *hmips;
11176
11177   htab = mips_elf_hash_table (info);
11178   BFD_ASSERT (htab != NULL);
11179   dynobj = elf_hash_table (info)->dynobj;
11180   hmips = (struct mips_elf_link_hash_entry *) h;
11181
11182   if (h->plt.plist != NULL && h->plt.plist->mips_offset != MINUS_ONE)
11183     {
11184       bfd_byte *loc;
11185       bfd_vma plt_address, got_address, got_offset, branch_offset;
11186       Elf_Internal_Rela rel;
11187       static const bfd_vma *plt_entry;
11188       bfd_vma gotplt_index;
11189       bfd_vma plt_offset;
11190
11191       plt_offset = htab->plt_header_size + h->plt.plist->mips_offset;
11192       gotplt_index = h->plt.plist->gotplt_index;
11193
11194       BFD_ASSERT (h->dynindx != -1);
11195       BFD_ASSERT (htab->root.splt != NULL);
11196       BFD_ASSERT (gotplt_index != MINUS_ONE);
11197       BFD_ASSERT (plt_offset <= htab->root.splt->size);
11198
11199       /* Calculate the address of the .plt entry.  */
11200       plt_address = (htab->root.splt->output_section->vma
11201                      + htab->root.splt->output_offset
11202                      + plt_offset);
11203
11204       /* Calculate the address of the .got.plt entry.  */
11205       got_address = (htab->root.sgotplt->output_section->vma
11206                      + htab->root.sgotplt->output_offset
11207                      + gotplt_index * MIPS_ELF_GOT_SIZE (output_bfd));
11208
11209       /* Calculate the offset of the .got.plt entry from
11210          _GLOBAL_OFFSET_TABLE_.  */
11211       got_offset = mips_elf_gotplt_index (info, h);
11212
11213       /* Calculate the offset for the branch at the start of the PLT
11214          entry.  The branch jumps to the beginning of .plt.  */
11215       branch_offset = -(plt_offset / 4 + 1) & 0xffff;
11216
11217       /* Fill in the initial value of the .got.plt entry.  */
11218       bfd_put_32 (output_bfd, plt_address,
11219                   (htab->root.sgotplt->contents
11220                    + gotplt_index * MIPS_ELF_GOT_SIZE (output_bfd)));
11221
11222       /* Find out where the .plt entry should go.  */
11223       loc = htab->root.splt->contents + plt_offset;
11224
11225       if (bfd_link_pic (info))
11226         {
11227           plt_entry = mips_vxworks_shared_plt_entry;
11228           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
11229           bfd_put_32 (output_bfd, plt_entry[1] | gotplt_index, loc + 4);
11230         }
11231       else
11232         {
11233           bfd_vma got_address_high, got_address_low;
11234
11235           plt_entry = mips_vxworks_exec_plt_entry;
11236           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
11237           got_address_low = got_address & 0xffff;
11238
11239           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
11240           bfd_put_32 (output_bfd, plt_entry[1] | gotplt_index, loc + 4);
11241           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
11242           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
11243           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
11244           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
11245           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
11246           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
11247
11248           loc = (htab->srelplt2->contents
11249                  + (gotplt_index * 3 + 2) * sizeof (Elf32_External_Rela));
11250
11251           /* Emit a relocation for the .got.plt entry.  */
11252           rel.r_offset = got_address;
11253           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
11254           rel.r_addend = plt_offset;
11255           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
11256
11257           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
11258           loc += sizeof (Elf32_External_Rela);
11259           rel.r_offset = plt_address + 8;
11260           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
11261           rel.r_addend = got_offset;
11262           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
11263
11264           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
11265           loc += sizeof (Elf32_External_Rela);
11266           rel.r_offset += 4;
11267           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
11268           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
11269         }
11270
11271       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
11272       loc = (htab->root.srelplt->contents
11273              + gotplt_index * sizeof (Elf32_External_Rela));
11274       rel.r_offset = got_address;
11275       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
11276       rel.r_addend = 0;
11277       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
11278
11279       if (!h->def_regular)
11280         sym->st_shndx = SHN_UNDEF;
11281     }
11282
11283   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
11284
11285   sgot = htab->root.sgot;
11286   g = htab->got_info;
11287   BFD_ASSERT (g != NULL);
11288
11289   /* See if this symbol has an entry in the GOT.  */
11290   if (hmips->global_got_area != GGA_NONE)
11291     {
11292       bfd_vma offset;
11293       Elf_Internal_Rela outrel;
11294       bfd_byte *loc;
11295       asection *s;
11296
11297       /* Install the symbol value in the GOT.   */
11298       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
11299       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
11300
11301       /* Add a dynamic relocation for it.  */
11302       s = mips_elf_rel_dyn_section (info, FALSE);
11303       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
11304       outrel.r_offset = (sgot->output_section->vma
11305                          + sgot->output_offset
11306                          + offset);
11307       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
11308       outrel.r_addend = 0;
11309       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
11310     }
11311
11312   /* Emit a copy reloc, if needed.  */
11313   if (h->needs_copy)
11314     {
11315       Elf_Internal_Rela rel;
11316       asection *srel;
11317       bfd_byte *loc;
11318
11319       BFD_ASSERT (h->dynindx != -1);
11320
11321       rel.r_offset = (h->root.u.def.section->output_section->vma
11322                       + h->root.u.def.section->output_offset
11323                       + h->root.u.def.value);
11324       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
11325       rel.r_addend = 0;
11326       if ((h->root.u.def.section->flags & SEC_READONLY) != 0)
11327         srel = htab->root.sreldynrelro;
11328       else
11329         srel = htab->root.srelbss;
11330       loc = srel->contents + srel->reloc_count * sizeof (Elf32_External_Rela);
11331       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
11332       ++srel->reloc_count;
11333     }
11334
11335   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
11336   if (ELF_ST_IS_COMPRESSED (sym->st_other))
11337     sym->st_value &= ~1;
11338
11339   return TRUE;
11340 }
11341
11342 /* Write out a plt0 entry to the beginning of .plt.  */
11343
11344 static bfd_boolean
11345 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
11346 {
11347   bfd_byte *loc;
11348   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
11349   static const bfd_vma *plt_entry;
11350   struct mips_elf_link_hash_table *htab;
11351
11352   htab = mips_elf_hash_table (info);
11353   BFD_ASSERT (htab != NULL);
11354
11355   if (ABI_64_P (output_bfd))
11356     plt_entry = mips_n64_exec_plt0_entry;
11357   else if (ABI_N32_P (output_bfd))
11358     plt_entry = mips_n32_exec_plt0_entry;
11359   else if (!htab->plt_header_is_comp)
11360     plt_entry = mips_o32_exec_plt0_entry;
11361   else if (htab->insn32)
11362     plt_entry = micromips_insn32_o32_exec_plt0_entry;
11363   else
11364     plt_entry = micromips_o32_exec_plt0_entry;
11365
11366   /* Calculate the value of .got.plt.  */
11367   gotplt_value = (htab->root.sgotplt->output_section->vma
11368                   + htab->root.sgotplt->output_offset);
11369   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
11370   gotplt_value_low = gotplt_value & 0xffff;
11371
11372   /* The PLT sequence is not safe for N64 if .got.plt's address can
11373      not be loaded in two instructions.  */
11374   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
11375               || ~(gotplt_value | 0x7fffffff) == 0);
11376
11377   /* Install the PLT header.  */
11378   loc = htab->root.splt->contents;
11379   if (plt_entry == micromips_o32_exec_plt0_entry)
11380     {
11381       bfd_vma gotpc_offset;
11382       bfd_vma loc_address;
11383       size_t i;
11384
11385       BFD_ASSERT (gotplt_value % 4 == 0);
11386
11387       loc_address = (htab->root.splt->output_section->vma
11388                      + htab->root.splt->output_offset);
11389       gotpc_offset = gotplt_value - ((loc_address | 3) ^ 3);
11390
11391       /* ADDIUPC has a span of +/-16MB, check we're in range.  */
11392       if (gotpc_offset + 0x1000000 >= 0x2000000)
11393         {
11394           _bfd_error_handler
11395             /* xgettext:c-format */
11396             (_("%B: `%A' offset of %ld from `%A' beyond the range of ADDIUPC"),
11397              output_bfd,
11398              htab->root.sgotplt->output_section,
11399              htab->root.splt->output_section,
11400              (long) gotpc_offset);
11401           bfd_set_error (bfd_error_no_error);
11402           return FALSE;
11403         }
11404       bfd_put_16 (output_bfd,
11405                   plt_entry[0] | ((gotpc_offset >> 18) & 0x7f), loc);
11406       bfd_put_16 (output_bfd, (gotpc_offset >> 2) & 0xffff, loc + 2);
11407       for (i = 2; i < ARRAY_SIZE (micromips_o32_exec_plt0_entry); i++)
11408         bfd_put_16 (output_bfd, plt_entry[i], loc + (i * 2));
11409     }
11410   else if (plt_entry == micromips_insn32_o32_exec_plt0_entry)
11411     {
11412       size_t i;
11413
11414       bfd_put_16 (output_bfd, plt_entry[0], loc);
11415       bfd_put_16 (output_bfd, gotplt_value_high, loc + 2);
11416       bfd_put_16 (output_bfd, plt_entry[2], loc + 4);
11417       bfd_put_16 (output_bfd, gotplt_value_low, loc + 6);
11418       bfd_put_16 (output_bfd, plt_entry[4], loc + 8);
11419       bfd_put_16 (output_bfd, gotplt_value_low, loc + 10);
11420       for (i = 6; i < ARRAY_SIZE (micromips_insn32_o32_exec_plt0_entry); i++)
11421         bfd_put_16 (output_bfd, plt_entry[i], loc + (i * 2));
11422     }
11423   else
11424     {
11425       bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
11426       bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
11427       bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
11428       bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
11429       bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
11430       bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
11431       bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
11432       bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
11433     }
11434
11435   return TRUE;
11436 }
11437
11438 /* Install the PLT header for a VxWorks executable and finalize the
11439    contents of .rela.plt.unloaded.  */
11440
11441 static void
11442 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
11443 {
11444   Elf_Internal_Rela rela;
11445   bfd_byte *loc;
11446   bfd_vma got_value, got_value_high, got_value_low, plt_address;
11447   static const bfd_vma *plt_entry;
11448   struct mips_elf_link_hash_table *htab;
11449
11450   htab = mips_elf_hash_table (info);
11451   BFD_ASSERT (htab != NULL);
11452
11453   plt_entry = mips_vxworks_exec_plt0_entry;
11454
11455   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
11456   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
11457                + htab->root.hgot->root.u.def.section->output_offset
11458                + htab->root.hgot->root.u.def.value);
11459
11460   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
11461   got_value_low = got_value & 0xffff;
11462
11463   /* Calculate the address of the PLT header.  */
11464   plt_address = (htab->root.splt->output_section->vma
11465                  + htab->root.splt->output_offset);
11466
11467   /* Install the PLT header.  */
11468   loc = htab->root.splt->contents;
11469   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
11470   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
11471   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
11472   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
11473   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
11474   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
11475
11476   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
11477   loc = htab->srelplt2->contents;
11478   rela.r_offset = plt_address;
11479   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
11480   rela.r_addend = 0;
11481   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
11482   loc += sizeof (Elf32_External_Rela);
11483
11484   /* Output the relocation for the following addiu of
11485      %lo(_GLOBAL_OFFSET_TABLE_).  */
11486   rela.r_offset += 4;
11487   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
11488   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
11489   loc += sizeof (Elf32_External_Rela);
11490
11491   /* Fix up the remaining relocations.  They may have the wrong
11492      symbol index for _G_O_T_ or _P_L_T_ depending on the order
11493      in which symbols were output.  */
11494   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
11495     {
11496       Elf_Internal_Rela rel;
11497
11498       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
11499       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
11500       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
11501       loc += sizeof (Elf32_External_Rela);
11502
11503       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
11504       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
11505       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
11506       loc += sizeof (Elf32_External_Rela);
11507
11508       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
11509       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
11510       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
11511       loc += sizeof (Elf32_External_Rela);
11512     }
11513 }
11514
11515 /* Install the PLT header for a VxWorks shared library.  */
11516
11517 static void
11518 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
11519 {
11520   unsigned int i;
11521   struct mips_elf_link_hash_table *htab;
11522
11523   htab = mips_elf_hash_table (info);
11524   BFD_ASSERT (htab != NULL);
11525
11526   /* We just need to copy the entry byte-by-byte.  */
11527   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
11528     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
11529                 htab->root.splt->contents + i * 4);
11530 }
11531
11532 /* Finish up the dynamic sections.  */
11533
11534 bfd_boolean
11535 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
11536                                        struct bfd_link_info *info)
11537 {
11538   bfd *dynobj;
11539   asection *sdyn;
11540   asection *sgot;
11541   struct mips_got_info *gg, *g;
11542   struct mips_elf_link_hash_table *htab;
11543
11544   htab = mips_elf_hash_table (info);
11545   BFD_ASSERT (htab != NULL);
11546
11547   dynobj = elf_hash_table (info)->dynobj;
11548
11549   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
11550
11551   sgot = htab->root.sgot;
11552   gg = htab->got_info;
11553
11554   if (elf_hash_table (info)->dynamic_sections_created)
11555     {
11556       bfd_byte *b;
11557       int dyn_to_skip = 0, dyn_skipped = 0;
11558
11559       BFD_ASSERT (sdyn != NULL);
11560       BFD_ASSERT (gg != NULL);
11561
11562       g = mips_elf_bfd_got (output_bfd, FALSE);
11563       BFD_ASSERT (g != NULL);
11564
11565       for (b = sdyn->contents;
11566            b < sdyn->contents + sdyn->size;
11567            b += MIPS_ELF_DYN_SIZE (dynobj))
11568         {
11569           Elf_Internal_Dyn dyn;
11570           const char *name;
11571           size_t elemsize;
11572           asection *s;
11573           bfd_boolean swap_out_p;
11574
11575           /* Read in the current dynamic entry.  */
11576           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
11577
11578           /* Assume that we're going to modify it and write it out.  */
11579           swap_out_p = TRUE;
11580
11581           switch (dyn.d_tag)
11582             {
11583             case DT_RELENT:
11584               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
11585               break;
11586
11587             case DT_RELAENT:
11588               BFD_ASSERT (htab->is_vxworks);
11589               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
11590               break;
11591
11592             case DT_STRSZ:
11593               /* Rewrite DT_STRSZ.  */
11594               dyn.d_un.d_val =
11595                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
11596               break;
11597
11598             case DT_PLTGOT:
11599               s = htab->root.sgot;
11600               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
11601               break;
11602
11603             case DT_MIPS_PLTGOT:
11604               s = htab->root.sgotplt;
11605               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
11606               break;
11607
11608             case DT_MIPS_RLD_VERSION:
11609               dyn.d_un.d_val = 1; /* XXX */
11610               break;
11611
11612             case DT_MIPS_FLAGS:
11613               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
11614               break;
11615
11616             case DT_MIPS_TIME_STAMP:
11617               {
11618                 time_t t;
11619                 time (&t);
11620                 dyn.d_un.d_val = t;
11621               }
11622               break;
11623
11624             case DT_MIPS_ICHECKSUM:
11625               /* XXX FIXME: */
11626               swap_out_p = FALSE;
11627               break;
11628
11629             case DT_MIPS_IVERSION:
11630               /* XXX FIXME: */
11631               swap_out_p = FALSE;
11632               break;
11633
11634             case DT_MIPS_BASE_ADDRESS:
11635               s = output_bfd->sections;
11636               BFD_ASSERT (s != NULL);
11637               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
11638               break;
11639
11640             case DT_MIPS_LOCAL_GOTNO:
11641               dyn.d_un.d_val = g->local_gotno;
11642               break;
11643
11644             case DT_MIPS_UNREFEXTNO:
11645               /* The index into the dynamic symbol table which is the
11646                  entry of the first external symbol that is not
11647                  referenced within the same object.  */
11648               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
11649               break;
11650
11651             case DT_MIPS_GOTSYM:
11652               if (htab->global_gotsym)
11653                 {
11654                   dyn.d_un.d_val = htab->global_gotsym->dynindx;
11655                   break;
11656                 }
11657               /* In case if we don't have global got symbols we default
11658                  to setting DT_MIPS_GOTSYM to the same value as
11659                  DT_MIPS_SYMTABNO.  */
11660               /* Fall through.  */
11661
11662             case DT_MIPS_SYMTABNO:
11663               name = ".dynsym";
11664               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
11665               s = bfd_get_linker_section (dynobj, name);
11666
11667               if (s != NULL)
11668                 dyn.d_un.d_val = s->size / elemsize;
11669               else
11670                 dyn.d_un.d_val = 0;
11671               break;
11672
11673             case DT_MIPS_HIPAGENO:
11674               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
11675               break;
11676
11677             case DT_MIPS_RLD_MAP:
11678               {
11679                 struct elf_link_hash_entry *h;
11680                 h = mips_elf_hash_table (info)->rld_symbol;
11681                 if (!h)
11682                   {
11683                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
11684                     swap_out_p = FALSE;
11685                     break;
11686                   }
11687                 s = h->root.u.def.section;
11688
11689                 /* The MIPS_RLD_MAP tag stores the absolute address of the
11690                    debug pointer.  */
11691                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
11692                                   + h->root.u.def.value);
11693               }
11694               break;
11695
11696             case DT_MIPS_RLD_MAP_REL:
11697               {
11698                 struct elf_link_hash_entry *h;
11699                 bfd_vma dt_addr, rld_addr;
11700                 h = mips_elf_hash_table (info)->rld_symbol;
11701                 if (!h)
11702                   {
11703                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
11704                     swap_out_p = FALSE;
11705                     break;
11706                   }
11707                 s = h->root.u.def.section;
11708
11709                 /* The MIPS_RLD_MAP_REL tag stores the offset to the debug
11710                    pointer, relative to the address of the tag.  */
11711                 dt_addr = (sdyn->output_section->vma + sdyn->output_offset
11712                            + (b - sdyn->contents));
11713                 rld_addr = (s->output_section->vma + s->output_offset
11714                             + h->root.u.def.value);
11715                 dyn.d_un.d_ptr = rld_addr - dt_addr;
11716               }
11717               break;
11718
11719             case DT_MIPS_OPTIONS:
11720               s = (bfd_get_section_by_name
11721                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
11722               dyn.d_un.d_ptr = s->vma;
11723               break;
11724
11725             case DT_PLTREL:
11726               BFD_ASSERT (htab->use_plts_and_copy_relocs);
11727               if (htab->is_vxworks)
11728                 dyn.d_un.d_val = DT_RELA;
11729               else
11730                 dyn.d_un.d_val = DT_REL;
11731               break;
11732
11733             case DT_PLTRELSZ:
11734               BFD_ASSERT (htab->use_plts_and_copy_relocs);
11735               dyn.d_un.d_val = htab->root.srelplt->size;
11736               break;
11737
11738             case DT_JMPREL:
11739               BFD_ASSERT (htab->use_plts_and_copy_relocs);
11740               dyn.d_un.d_ptr = (htab->root.srelplt->output_section->vma
11741                                 + htab->root.srelplt->output_offset);
11742               break;
11743
11744             case DT_TEXTREL:
11745               /* If we didn't need any text relocations after all, delete
11746                  the dynamic tag.  */
11747               if (!(info->flags & DF_TEXTREL))
11748                 {
11749                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
11750                   swap_out_p = FALSE;
11751                 }
11752               break;
11753
11754             case DT_FLAGS:
11755               /* If we didn't need any text relocations after all, clear
11756                  DF_TEXTREL from DT_FLAGS.  */
11757               if (!(info->flags & DF_TEXTREL))
11758                 dyn.d_un.d_val &= ~DF_TEXTREL;
11759               else
11760                 swap_out_p = FALSE;
11761               break;
11762
11763             default:
11764               swap_out_p = FALSE;
11765               if (htab->is_vxworks
11766                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
11767                 swap_out_p = TRUE;
11768               break;
11769             }
11770
11771           if (swap_out_p || dyn_skipped)
11772             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
11773               (dynobj, &dyn, b - dyn_skipped);
11774
11775           if (dyn_to_skip)
11776             {
11777               dyn_skipped += dyn_to_skip;
11778               dyn_to_skip = 0;
11779             }
11780         }
11781
11782       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
11783       if (dyn_skipped > 0)
11784         memset (b - dyn_skipped, 0, dyn_skipped);
11785     }
11786
11787   if (sgot != NULL && sgot->size > 0
11788       && !bfd_is_abs_section (sgot->output_section))
11789     {
11790       if (htab->is_vxworks)
11791         {
11792           /* The first entry of the global offset table points to the
11793              ".dynamic" section.  The second is initialized by the
11794              loader and contains the shared library identifier.
11795              The third is also initialized by the loader and points
11796              to the lazy resolution stub.  */
11797           MIPS_ELF_PUT_WORD (output_bfd,
11798                              sdyn->output_offset + sdyn->output_section->vma,
11799                              sgot->contents);
11800           MIPS_ELF_PUT_WORD (output_bfd, 0,
11801                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
11802           MIPS_ELF_PUT_WORD (output_bfd, 0,
11803                              sgot->contents
11804                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
11805         }
11806       else
11807         {
11808           /* The first entry of the global offset table will be filled at
11809              runtime. The second entry will be used by some runtime loaders.
11810              This isn't the case of IRIX rld.  */
11811           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
11812           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
11813                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
11814         }
11815
11816       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
11817          = MIPS_ELF_GOT_SIZE (output_bfd);
11818     }
11819
11820   /* Generate dynamic relocations for the non-primary gots.  */
11821   if (gg != NULL && gg->next)
11822     {
11823       Elf_Internal_Rela rel[3];
11824       bfd_vma addend = 0;
11825
11826       memset (rel, 0, sizeof (rel));
11827       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
11828
11829       for (g = gg->next; g->next != gg; g = g->next)
11830         {
11831           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
11832             + g->next->tls_gotno;
11833
11834           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
11835                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
11836           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
11837                              sgot->contents
11838                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
11839
11840           if (! bfd_link_pic (info))
11841             continue;
11842
11843           for (; got_index < g->local_gotno; got_index++)
11844             {
11845               if (got_index >= g->assigned_low_gotno
11846                   && got_index <= g->assigned_high_gotno)
11847                 continue;
11848
11849               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
11850                 = got_index * MIPS_ELF_GOT_SIZE (output_bfd);
11851               if (!(mips_elf_create_dynamic_relocation
11852                     (output_bfd, info, rel, NULL,
11853                      bfd_abs_section_ptr,
11854                      0, &addend, sgot)))
11855                 return FALSE;
11856               BFD_ASSERT (addend == 0);
11857             }
11858         }
11859     }
11860
11861   /* The generation of dynamic relocations for the non-primary gots
11862      adds more dynamic relocations.  We cannot count them until
11863      here.  */
11864
11865   if (elf_hash_table (info)->dynamic_sections_created)
11866     {
11867       bfd_byte *b;
11868       bfd_boolean swap_out_p;
11869
11870       BFD_ASSERT (sdyn != NULL);
11871
11872       for (b = sdyn->contents;
11873            b < sdyn->contents + sdyn->size;
11874            b += MIPS_ELF_DYN_SIZE (dynobj))
11875         {
11876           Elf_Internal_Dyn dyn;
11877           asection *s;
11878
11879           /* Read in the current dynamic entry.  */
11880           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
11881
11882           /* Assume that we're going to modify it and write it out.  */
11883           swap_out_p = TRUE;
11884
11885           switch (dyn.d_tag)
11886             {
11887             case DT_RELSZ:
11888               /* Reduce DT_RELSZ to account for any relocations we
11889                  decided not to make.  This is for the n64 irix rld,
11890                  which doesn't seem to apply any relocations if there
11891                  are trailing null entries.  */
11892               s = mips_elf_rel_dyn_section (info, FALSE);
11893               dyn.d_un.d_val = (s->reloc_count
11894                                 * (ABI_64_P (output_bfd)
11895                                    ? sizeof (Elf64_Mips_External_Rel)
11896                                    : sizeof (Elf32_External_Rel)));
11897               /* Adjust the section size too.  Tools like the prelinker
11898                  can reasonably expect the values to the same.  */
11899               elf_section_data (s->output_section)->this_hdr.sh_size
11900                 = dyn.d_un.d_val;
11901               break;
11902
11903             default:
11904               swap_out_p = FALSE;
11905               break;
11906             }
11907
11908           if (swap_out_p)
11909             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
11910               (dynobj, &dyn, b);
11911         }
11912     }
11913
11914   {
11915     asection *s;
11916     Elf32_compact_rel cpt;
11917
11918     if (SGI_COMPAT (output_bfd))
11919       {
11920         /* Write .compact_rel section out.  */
11921         s = bfd_get_linker_section (dynobj, ".compact_rel");
11922         if (s != NULL)
11923           {
11924             cpt.id1 = 1;
11925             cpt.num = s->reloc_count;
11926             cpt.id2 = 2;
11927             cpt.offset = (s->output_section->filepos
11928                           + sizeof (Elf32_External_compact_rel));
11929             cpt.reserved0 = 0;
11930             cpt.reserved1 = 0;
11931             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
11932                                             ((Elf32_External_compact_rel *)
11933                                              s->contents));
11934
11935             /* Clean up a dummy stub function entry in .text.  */
11936             if (htab->sstubs != NULL)
11937               {
11938                 file_ptr dummy_offset;
11939
11940                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
11941                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
11942                 memset (htab->sstubs->contents + dummy_offset, 0,
11943                         htab->function_stub_size);
11944               }
11945           }
11946       }
11947
11948     /* The psABI says that the dynamic relocations must be sorted in
11949        increasing order of r_symndx.  The VxWorks EABI doesn't require
11950        this, and because the code below handles REL rather than RELA
11951        relocations, using it for VxWorks would be outright harmful.  */
11952     if (!htab->is_vxworks)
11953       {
11954         s = mips_elf_rel_dyn_section (info, FALSE);
11955         if (s != NULL
11956             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
11957           {
11958             reldyn_sorting_bfd = output_bfd;
11959
11960             if (ABI_64_P (output_bfd))
11961               qsort ((Elf64_External_Rel *) s->contents + 1,
11962                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
11963                      sort_dynamic_relocs_64);
11964             else
11965               qsort ((Elf32_External_Rel *) s->contents + 1,
11966                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
11967                      sort_dynamic_relocs);
11968           }
11969       }
11970   }
11971
11972   if (htab->root.splt && htab->root.splt->size > 0)
11973     {
11974       if (htab->is_vxworks)
11975         {
11976           if (bfd_link_pic (info))
11977             mips_vxworks_finish_shared_plt (output_bfd, info);
11978           else
11979             mips_vxworks_finish_exec_plt (output_bfd, info);
11980         }
11981       else
11982         {
11983           BFD_ASSERT (!bfd_link_pic (info));
11984           if (!mips_finish_exec_plt (output_bfd, info))
11985             return FALSE;
11986         }
11987     }
11988   return TRUE;
11989 }
11990
11991
11992 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
11993
11994 static void
11995 mips_set_isa_flags (bfd *abfd)
11996 {
11997   flagword val;
11998
11999   switch (bfd_get_mach (abfd))
12000     {
12001     default:
12002     case bfd_mach_mips3000:
12003       val = E_MIPS_ARCH_1;
12004       break;
12005
12006     case bfd_mach_mips3900:
12007       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
12008       break;
12009
12010     case bfd_mach_mips6000:
12011       val = E_MIPS_ARCH_2;
12012       break;
12013
12014     case bfd_mach_mips4000:
12015     case bfd_mach_mips4300:
12016     case bfd_mach_mips4400:
12017     case bfd_mach_mips4600:
12018       val = E_MIPS_ARCH_3;
12019       break;
12020
12021     case bfd_mach_mips4010:
12022       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
12023       break;
12024
12025     case bfd_mach_mips4100:
12026       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
12027       break;
12028
12029     case bfd_mach_mips4111:
12030       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
12031       break;
12032
12033     case bfd_mach_mips4120:
12034       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
12035       break;
12036
12037     case bfd_mach_mips4650:
12038       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
12039       break;
12040
12041     case bfd_mach_mips5400:
12042       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
12043       break;
12044
12045     case bfd_mach_mips5500:
12046       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
12047       break;
12048
12049     case bfd_mach_mips5900:
12050       val = E_MIPS_ARCH_3 | E_MIPS_MACH_5900;
12051       break;
12052
12053     case bfd_mach_mips9000:
12054       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
12055       break;
12056
12057     case bfd_mach_mips5000:
12058     case bfd_mach_mips7000:
12059     case bfd_mach_mips8000:
12060     case bfd_mach_mips10000:
12061     case bfd_mach_mips12000:
12062     case bfd_mach_mips14000:
12063     case bfd_mach_mips16000:
12064       val = E_MIPS_ARCH_4;
12065       break;
12066
12067     case bfd_mach_mips5:
12068       val = E_MIPS_ARCH_5;
12069       break;
12070
12071     case bfd_mach_mips_loongson_2e:
12072       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
12073       break;
12074
12075     case bfd_mach_mips_loongson_2f:
12076       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
12077       break;
12078
12079     case bfd_mach_mips_sb1:
12080       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
12081       break;
12082
12083     case bfd_mach_mips_loongson_3a:
12084       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_LS3A;
12085       break;
12086
12087     case bfd_mach_mips_octeon:
12088     case bfd_mach_mips_octeonp:
12089       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
12090       break;
12091
12092     case bfd_mach_mips_octeon3:
12093       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON3;
12094       break;
12095
12096     case bfd_mach_mips_xlr:
12097       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
12098       break;
12099
12100     case bfd_mach_mips_octeon2:
12101       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
12102       break;
12103
12104     case bfd_mach_mipsisa32:
12105       val = E_MIPS_ARCH_32;
12106       break;
12107
12108     case bfd_mach_mipsisa64:
12109       val = E_MIPS_ARCH_64;
12110       break;
12111
12112     case bfd_mach_mipsisa32r2:
12113     case bfd_mach_mipsisa32r3:
12114     case bfd_mach_mipsisa32r5:
12115       val = E_MIPS_ARCH_32R2;
12116       break;
12117
12118     case bfd_mach_mipsisa64r2:
12119     case bfd_mach_mipsisa64r3:
12120     case bfd_mach_mipsisa64r5:
12121       val = E_MIPS_ARCH_64R2;
12122       break;
12123
12124     case bfd_mach_mipsisa32r6:
12125       val = E_MIPS_ARCH_32R6;
12126       break;
12127
12128     case bfd_mach_mipsisa64r6:
12129       val = E_MIPS_ARCH_64R6;
12130       break;
12131     }
12132   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
12133   elf_elfheader (abfd)->e_flags |= val;
12134
12135 }
12136
12137
12138 /* Whether to sort relocs output by ld -r or ld --emit-relocs, by r_offset.
12139    Don't do so for code sections.  We want to keep ordering of HI16/LO16
12140    as is.  On the other hand, elf-eh-frame.c processing requires .eh_frame
12141    relocs to be sorted.  */
12142
12143 bfd_boolean
12144 _bfd_mips_elf_sort_relocs_p (asection *sec)
12145 {
12146   return (sec->flags & SEC_CODE) == 0;
12147 }
12148
12149
12150 /* The final processing done just before writing out a MIPS ELF object
12151    file.  This gets the MIPS architecture right based on the machine
12152    number.  This is used by both the 32-bit and the 64-bit ABI.  */
12153
12154 void
12155 _bfd_mips_elf_final_write_processing (bfd *abfd,
12156                                       bfd_boolean linker ATTRIBUTE_UNUSED)
12157 {
12158   unsigned int i;
12159   Elf_Internal_Shdr **hdrpp;
12160   const char *name;
12161   asection *sec;
12162
12163   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
12164      is nonzero.  This is for compatibility with old objects, which used
12165      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
12166   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
12167     mips_set_isa_flags (abfd);
12168
12169   /* Set the sh_info field for .gptab sections and other appropriate
12170      info for each special section.  */
12171   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
12172        i < elf_numsections (abfd);
12173        i++, hdrpp++)
12174     {
12175       switch ((*hdrpp)->sh_type)
12176         {
12177         case SHT_MIPS_MSYM:
12178         case SHT_MIPS_LIBLIST:
12179           sec = bfd_get_section_by_name (abfd, ".dynstr");
12180           if (sec != NULL)
12181             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
12182           break;
12183
12184         case SHT_MIPS_GPTAB:
12185           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
12186           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
12187           BFD_ASSERT (name != NULL
12188                       && CONST_STRNEQ (name, ".gptab."));
12189           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
12190           BFD_ASSERT (sec != NULL);
12191           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
12192           break;
12193
12194         case SHT_MIPS_CONTENT:
12195           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
12196           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
12197           BFD_ASSERT (name != NULL
12198                       && CONST_STRNEQ (name, ".MIPS.content"));
12199           sec = bfd_get_section_by_name (abfd,
12200                                          name + sizeof ".MIPS.content" - 1);
12201           BFD_ASSERT (sec != NULL);
12202           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
12203           break;
12204
12205         case SHT_MIPS_SYMBOL_LIB:
12206           sec = bfd_get_section_by_name (abfd, ".dynsym");
12207           if (sec != NULL)
12208             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
12209           sec = bfd_get_section_by_name (abfd, ".liblist");
12210           if (sec != NULL)
12211             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
12212           break;
12213
12214         case SHT_MIPS_EVENTS:
12215           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
12216           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
12217           BFD_ASSERT (name != NULL);
12218           if (CONST_STRNEQ (name, ".MIPS.events"))
12219             sec = bfd_get_section_by_name (abfd,
12220                                            name + sizeof ".MIPS.events" - 1);
12221           else
12222             {
12223               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
12224               sec = bfd_get_section_by_name (abfd,
12225                                              (name
12226                                               + sizeof ".MIPS.post_rel" - 1));
12227             }
12228           BFD_ASSERT (sec != NULL);
12229           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
12230           break;
12231
12232         }
12233     }
12234 }
12235 \f
12236 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
12237    segments.  */
12238
12239 int
12240 _bfd_mips_elf_additional_program_headers (bfd *abfd,
12241                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
12242 {
12243   asection *s;
12244   int ret = 0;
12245
12246   /* See if we need a PT_MIPS_REGINFO segment.  */
12247   s = bfd_get_section_by_name (abfd, ".reginfo");
12248   if (s && (s->flags & SEC_LOAD))
12249     ++ret;
12250
12251   /* See if we need a PT_MIPS_ABIFLAGS segment.  */
12252   if (bfd_get_section_by_name (abfd, ".MIPS.abiflags"))
12253     ++ret;
12254
12255   /* See if we need a PT_MIPS_OPTIONS segment.  */
12256   if (IRIX_COMPAT (abfd) == ict_irix6
12257       && bfd_get_section_by_name (abfd,
12258                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
12259     ++ret;
12260
12261   /* See if we need a PT_MIPS_RTPROC segment.  */
12262   if (IRIX_COMPAT (abfd) == ict_irix5
12263       && bfd_get_section_by_name (abfd, ".dynamic")
12264       && bfd_get_section_by_name (abfd, ".mdebug"))
12265     ++ret;
12266
12267   /* Allocate a PT_NULL header in dynamic objects.  See
12268      _bfd_mips_elf_modify_segment_map for details.  */
12269   if (!SGI_COMPAT (abfd)
12270       && bfd_get_section_by_name (abfd, ".dynamic"))
12271     ++ret;
12272
12273   return ret;
12274 }
12275
12276 /* Modify the segment map for an IRIX5 executable.  */
12277
12278 bfd_boolean
12279 _bfd_mips_elf_modify_segment_map (bfd *abfd,
12280                                   struct bfd_link_info *info)
12281 {
12282   asection *s;
12283   struct elf_segment_map *m, **pm;
12284   bfd_size_type amt;
12285
12286   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
12287      segment.  */
12288   s = bfd_get_section_by_name (abfd, ".reginfo");
12289   if (s != NULL && (s->flags & SEC_LOAD) != 0)
12290     {
12291       for (m = elf_seg_map (abfd); m != NULL; m = m->next)
12292         if (m->p_type == PT_MIPS_REGINFO)
12293           break;
12294       if (m == NULL)
12295         {
12296           amt = sizeof *m;
12297           m = bfd_zalloc (abfd, amt);
12298           if (m == NULL)
12299             return FALSE;
12300
12301           m->p_type = PT_MIPS_REGINFO;
12302           m->count = 1;
12303           m->sections[0] = s;
12304
12305           /* We want to put it after the PHDR and INTERP segments.  */
12306           pm = &elf_seg_map (abfd);
12307           while (*pm != NULL
12308                  && ((*pm)->p_type == PT_PHDR
12309                      || (*pm)->p_type == PT_INTERP))
12310             pm = &(*pm)->next;
12311
12312           m->next = *pm;
12313           *pm = m;
12314         }
12315     }
12316
12317   /* If there is a .MIPS.abiflags section, we need a PT_MIPS_ABIFLAGS
12318      segment.  */
12319   s = bfd_get_section_by_name (abfd, ".MIPS.abiflags");
12320   if (s != NULL && (s->flags & SEC_LOAD) != 0)
12321     {
12322       for (m = elf_seg_map (abfd); m != NULL; m = m->next)
12323         if (m->p_type == PT_MIPS_ABIFLAGS)
12324           break;
12325       if (m == NULL)
12326         {
12327           amt = sizeof *m;
12328           m = bfd_zalloc (abfd, amt);
12329           if (m == NULL)
12330             return FALSE;
12331
12332           m->p_type = PT_MIPS_ABIFLAGS;
12333           m->count = 1;
12334           m->sections[0] = s;
12335
12336           /* We want to put it after the PHDR and INTERP segments.  */
12337           pm = &elf_seg_map (abfd);
12338           while (*pm != NULL
12339                  && ((*pm)->p_type == PT_PHDR
12340                      || (*pm)->p_type == PT_INTERP))
12341             pm = &(*pm)->next;
12342
12343           m->next = *pm;
12344           *pm = m;
12345         }
12346     }
12347
12348   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
12349      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
12350      PT_MIPS_OPTIONS segment immediately following the program header
12351      table.  */
12352   if (NEWABI_P (abfd)
12353       /* On non-IRIX6 new abi, we'll have already created a segment
12354          for this section, so don't create another.  I'm not sure this
12355          is not also the case for IRIX 6, but I can't test it right
12356          now.  */
12357       && IRIX_COMPAT (abfd) == ict_irix6)
12358     {
12359       for (s = abfd->sections; s; s = s->next)
12360         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
12361           break;
12362
12363       if (s)
12364         {
12365           struct elf_segment_map *options_segment;
12366
12367           pm = &elf_seg_map (abfd);
12368           while (*pm != NULL
12369                  && ((*pm)->p_type == PT_PHDR
12370                      || (*pm)->p_type == PT_INTERP))
12371             pm = &(*pm)->next;
12372
12373           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
12374             {
12375               amt = sizeof (struct elf_segment_map);
12376               options_segment = bfd_zalloc (abfd, amt);
12377               options_segment->next = *pm;
12378               options_segment->p_type = PT_MIPS_OPTIONS;
12379               options_segment->p_flags = PF_R;
12380               options_segment->p_flags_valid = TRUE;
12381               options_segment->count = 1;
12382               options_segment->sections[0] = s;
12383               *pm = options_segment;
12384             }
12385         }
12386     }
12387   else
12388     {
12389       if (IRIX_COMPAT (abfd) == ict_irix5)
12390         {
12391           /* If there are .dynamic and .mdebug sections, we make a room
12392              for the RTPROC header.  FIXME: Rewrite without section names.  */
12393           if (bfd_get_section_by_name (abfd, ".interp") == NULL
12394               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
12395               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
12396             {
12397               for (m = elf_seg_map (abfd); m != NULL; m = m->next)
12398                 if (m->p_type == PT_MIPS_RTPROC)
12399                   break;
12400               if (m == NULL)
12401                 {
12402                   amt = sizeof *m;
12403                   m = bfd_zalloc (abfd, amt);
12404                   if (m == NULL)
12405                     return FALSE;
12406
12407                   m->p_type = PT_MIPS_RTPROC;
12408
12409                   s = bfd_get_section_by_name (abfd, ".rtproc");
12410                   if (s == NULL)
12411                     {
12412                       m->count = 0;
12413                       m->p_flags = 0;
12414                       m->p_flags_valid = 1;
12415                     }
12416                   else
12417                     {
12418                       m->count = 1;
12419                       m->sections[0] = s;
12420                     }
12421
12422                   /* We want to put it after the DYNAMIC segment.  */
12423                   pm = &elf_seg_map (abfd);
12424                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
12425                     pm = &(*pm)->next;
12426                   if (*pm != NULL)
12427                     pm = &(*pm)->next;
12428
12429                   m->next = *pm;
12430                   *pm = m;
12431                 }
12432             }
12433         }
12434       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
12435          .dynstr, .dynsym, and .hash sections, and everything in
12436          between.  */
12437       for (pm = &elf_seg_map (abfd); *pm != NULL;
12438            pm = &(*pm)->next)
12439         if ((*pm)->p_type == PT_DYNAMIC)
12440           break;
12441       m = *pm;
12442       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
12443          glibc's dynamic linker has traditionally derived the number of
12444          tags from the p_filesz field, and sometimes allocates stack
12445          arrays of that size.  An overly-big PT_DYNAMIC segment can
12446          be actively harmful in such cases.  Making PT_DYNAMIC contain
12447          other sections can also make life hard for the prelinker,
12448          which might move one of the other sections to a different
12449          PT_LOAD segment.  */
12450       if (SGI_COMPAT (abfd)
12451           && m != NULL
12452           && m->count == 1
12453           && strcmp (m->sections[0]->name, ".dynamic") == 0)
12454         {
12455           static const char *sec_names[] =
12456           {
12457             ".dynamic", ".dynstr", ".dynsym", ".hash"
12458           };
12459           bfd_vma low, high;
12460           unsigned int i, c;
12461           struct elf_segment_map *n;
12462
12463           low = ~(bfd_vma) 0;
12464           high = 0;
12465           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
12466             {
12467               s = bfd_get_section_by_name (abfd, sec_names[i]);
12468               if (s != NULL && (s->flags & SEC_LOAD) != 0)
12469                 {
12470                   bfd_size_type sz;
12471
12472                   if (low > s->vma)
12473                     low = s->vma;
12474                   sz = s->size;
12475                   if (high < s->vma + sz)
12476                     high = s->vma + sz;
12477                 }
12478             }
12479
12480           c = 0;
12481           for (s = abfd->sections; s != NULL; s = s->next)
12482             if ((s->flags & SEC_LOAD) != 0
12483                 && s->vma >= low
12484                 && s->vma + s->size <= high)
12485               ++c;
12486
12487           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
12488           n = bfd_zalloc (abfd, amt);
12489           if (n == NULL)
12490             return FALSE;
12491           *n = *m;
12492           n->count = c;
12493
12494           i = 0;
12495           for (s = abfd->sections; s != NULL; s = s->next)
12496             {
12497               if ((s->flags & SEC_LOAD) != 0
12498                   && s->vma >= low
12499                   && s->vma + s->size <= high)
12500                 {
12501                   n->sections[i] = s;
12502                   ++i;
12503                 }
12504             }
12505
12506           *pm = n;
12507         }
12508     }
12509
12510   /* Allocate a spare program header in dynamic objects so that tools
12511      like the prelinker can add an extra PT_LOAD entry.
12512
12513      If the prelinker needs to make room for a new PT_LOAD entry, its
12514      standard procedure is to move the first (read-only) sections into
12515      the new (writable) segment.  However, the MIPS ABI requires
12516      .dynamic to be in a read-only segment, and the section will often
12517      start within sizeof (ElfNN_Phdr) bytes of the last program header.
12518
12519      Although the prelinker could in principle move .dynamic to a
12520      writable segment, it seems better to allocate a spare program
12521      header instead, and avoid the need to move any sections.
12522      There is a long tradition of allocating spare dynamic tags,
12523      so allocating a spare program header seems like a natural
12524      extension.
12525
12526      If INFO is NULL, we may be copying an already prelinked binary
12527      with objcopy or strip, so do not add this header.  */
12528   if (info != NULL
12529       && !SGI_COMPAT (abfd)
12530       && bfd_get_section_by_name (abfd, ".dynamic"))
12531     {
12532       for (pm = &elf_seg_map (abfd); *pm != NULL; pm = &(*pm)->next)
12533         if ((*pm)->p_type == PT_NULL)
12534           break;
12535       if (*pm == NULL)
12536         {
12537           m = bfd_zalloc (abfd, sizeof (*m));
12538           if (m == NULL)
12539             return FALSE;
12540
12541           m->p_type = PT_NULL;
12542           *pm = m;
12543         }
12544     }
12545
12546   return TRUE;
12547 }
12548 \f
12549 /* Return the section that should be marked against GC for a given
12550    relocation.  */
12551
12552 asection *
12553 _bfd_mips_elf_gc_mark_hook (asection *sec,
12554                             struct bfd_link_info *info,
12555                             Elf_Internal_Rela *rel,
12556                             struct elf_link_hash_entry *h,
12557                             Elf_Internal_Sym *sym)
12558 {
12559   /* ??? Do mips16 stub sections need to be handled special?  */
12560
12561   if (h != NULL)
12562     switch (ELF_R_TYPE (sec->owner, rel->r_info))
12563       {
12564       case R_MIPS_GNU_VTINHERIT:
12565       case R_MIPS_GNU_VTENTRY:
12566         return NULL;
12567       }
12568
12569   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
12570 }
12571
12572 /* Update the got entry reference counts for the section being removed.  */
12573
12574 bfd_boolean
12575 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
12576                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
12577                              asection *sec ATTRIBUTE_UNUSED,
12578                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
12579 {
12580 #if 0
12581   Elf_Internal_Shdr *symtab_hdr;
12582   struct elf_link_hash_entry **sym_hashes;
12583   bfd_signed_vma *local_got_refcounts;
12584   const Elf_Internal_Rela *rel, *relend;
12585   unsigned long r_symndx;
12586   struct elf_link_hash_entry *h;
12587
12588   if (bfd_link_relocatable (info))
12589     return TRUE;
12590
12591   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12592   sym_hashes = elf_sym_hashes (abfd);
12593   local_got_refcounts = elf_local_got_refcounts (abfd);
12594
12595   relend = relocs + sec->reloc_count;
12596   for (rel = relocs; rel < relend; rel++)
12597     switch (ELF_R_TYPE (abfd, rel->r_info))
12598       {
12599       case R_MIPS16_GOT16:
12600       case R_MIPS16_CALL16:
12601       case R_MIPS_GOT16:
12602       case R_MIPS_CALL16:
12603       case R_MIPS_CALL_HI16:
12604       case R_MIPS_CALL_LO16:
12605       case R_MIPS_GOT_HI16:
12606       case R_MIPS_GOT_LO16:
12607       case R_MIPS_GOT_DISP:
12608       case R_MIPS_GOT_PAGE:
12609       case R_MIPS_GOT_OFST:
12610       case R_MICROMIPS_GOT16:
12611       case R_MICROMIPS_CALL16:
12612       case R_MICROMIPS_CALL_HI16:
12613       case R_MICROMIPS_CALL_LO16:
12614       case R_MICROMIPS_GOT_HI16:
12615       case R_MICROMIPS_GOT_LO16:
12616       case R_MICROMIPS_GOT_DISP:
12617       case R_MICROMIPS_GOT_PAGE:
12618       case R_MICROMIPS_GOT_OFST:
12619         /* ??? It would seem that the existing MIPS code does no sort
12620            of reference counting or whatnot on its GOT and PLT entries,
12621            so it is not possible to garbage collect them at this time.  */
12622         break;
12623
12624       default:
12625         break;
12626       }
12627 #endif
12628
12629   return TRUE;
12630 }
12631
12632 /* Prevent .MIPS.abiflags from being discarded with --gc-sections.  */
12633
12634 bfd_boolean
12635 _bfd_mips_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12636                                       elf_gc_mark_hook_fn gc_mark_hook)
12637 {
12638   bfd *sub;
12639
12640   _bfd_elf_gc_mark_extra_sections (info, gc_mark_hook);
12641
12642   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12643     {
12644       asection *o;
12645
12646       if (! is_mips_elf (sub))
12647         continue;
12648
12649       for (o = sub->sections; o != NULL; o = o->next)
12650         if (!o->gc_mark
12651             && MIPS_ELF_ABIFLAGS_SECTION_NAME_P
12652                  (bfd_get_section_name (sub, o)))
12653           {
12654             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
12655               return FALSE;
12656           }
12657     }
12658
12659   return TRUE;
12660 }
12661 \f
12662 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
12663    hiding the old indirect symbol.  Process additional relocation
12664    information.  Also called for weakdefs, in which case we just let
12665    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
12666
12667 void
12668 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
12669                                     struct elf_link_hash_entry *dir,
12670                                     struct elf_link_hash_entry *ind)
12671 {
12672   struct mips_elf_link_hash_entry *dirmips, *indmips;
12673
12674   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
12675
12676   dirmips = (struct mips_elf_link_hash_entry *) dir;
12677   indmips = (struct mips_elf_link_hash_entry *) ind;
12678   /* Any absolute non-dynamic relocations against an indirect or weak
12679      definition will be against the target symbol.  */
12680   if (indmips->has_static_relocs)
12681     dirmips->has_static_relocs = TRUE;
12682
12683   if (ind->root.type != bfd_link_hash_indirect)
12684     return;
12685
12686   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
12687   if (indmips->readonly_reloc)
12688     dirmips->readonly_reloc = TRUE;
12689   if (indmips->no_fn_stub)
12690     dirmips->no_fn_stub = TRUE;
12691   if (indmips->fn_stub)
12692     {
12693       dirmips->fn_stub = indmips->fn_stub;
12694       indmips->fn_stub = NULL;
12695     }
12696   if (indmips->need_fn_stub)
12697     {
12698       dirmips->need_fn_stub = TRUE;
12699       indmips->need_fn_stub = FALSE;
12700     }
12701   if (indmips->call_stub)
12702     {
12703       dirmips->call_stub = indmips->call_stub;
12704       indmips->call_stub = NULL;
12705     }
12706   if (indmips->call_fp_stub)
12707     {
12708       dirmips->call_fp_stub = indmips->call_fp_stub;
12709       indmips->call_fp_stub = NULL;
12710     }
12711   if (indmips->global_got_area < dirmips->global_got_area)
12712     dirmips->global_got_area = indmips->global_got_area;
12713   if (indmips->global_got_area < GGA_NONE)
12714     indmips->global_got_area = GGA_NONE;
12715   if (indmips->has_nonpic_branches)
12716     dirmips->has_nonpic_branches = TRUE;
12717 }
12718 \f
12719 #define PDR_SIZE 32
12720
12721 bfd_boolean
12722 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
12723                             struct bfd_link_info *info)
12724 {
12725   asection *o;
12726   bfd_boolean ret = FALSE;
12727   unsigned char *tdata;
12728   size_t i, skip;
12729
12730   o = bfd_get_section_by_name (abfd, ".pdr");
12731   if (! o)
12732     return FALSE;
12733   if (o->size == 0)
12734     return FALSE;
12735   if (o->size % PDR_SIZE != 0)
12736     return FALSE;
12737   if (o->output_section != NULL
12738       && bfd_is_abs_section (o->output_section))
12739     return FALSE;
12740
12741   tdata = bfd_zmalloc (o->size / PDR_SIZE);
12742   if (! tdata)
12743     return FALSE;
12744
12745   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
12746                                             info->keep_memory);
12747   if (!cookie->rels)
12748     {
12749       free (tdata);
12750       return FALSE;
12751     }
12752
12753   cookie->rel = cookie->rels;
12754   cookie->relend = cookie->rels + o->reloc_count;
12755
12756   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
12757     {
12758       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
12759         {
12760           tdata[i] = 1;
12761           skip ++;
12762         }
12763     }
12764
12765   if (skip != 0)
12766     {
12767       mips_elf_section_data (o)->u.tdata = tdata;
12768       if (o->rawsize == 0)
12769         o->rawsize = o->size;
12770       o->size -= skip * PDR_SIZE;
12771       ret = TRUE;
12772     }
12773   else
12774     free (tdata);
12775
12776   if (! info->keep_memory)
12777     free (cookie->rels);
12778
12779   return ret;
12780 }
12781
12782 bfd_boolean
12783 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
12784 {
12785   if (strcmp (sec->name, ".pdr") == 0)
12786     return TRUE;
12787   return FALSE;
12788 }
12789
12790 bfd_boolean
12791 _bfd_mips_elf_write_section (bfd *output_bfd,
12792                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
12793                              asection *sec, bfd_byte *contents)
12794 {
12795   bfd_byte *to, *from, *end;
12796   int i;
12797
12798   if (strcmp (sec->name, ".pdr") != 0)
12799     return FALSE;
12800
12801   if (mips_elf_section_data (sec)->u.tdata == NULL)
12802     return FALSE;
12803
12804   to = contents;
12805   end = contents + sec->size;
12806   for (from = contents, i = 0;
12807        from < end;
12808        from += PDR_SIZE, i++)
12809     {
12810       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
12811         continue;
12812       if (to != from)
12813         memcpy (to, from, PDR_SIZE);
12814       to += PDR_SIZE;
12815     }
12816   bfd_set_section_contents (output_bfd, sec->output_section, contents,
12817                             sec->output_offset, sec->size);
12818   return TRUE;
12819 }
12820 \f
12821 /* microMIPS code retains local labels for linker relaxation.  Omit them
12822    from output by default for clarity.  */
12823
12824 bfd_boolean
12825 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
12826 {
12827   return _bfd_elf_is_local_label_name (abfd, sym->name);
12828 }
12829
12830 /* MIPS ELF uses a special find_nearest_line routine in order the
12831    handle the ECOFF debugging information.  */
12832
12833 struct mips_elf_find_line
12834 {
12835   struct ecoff_debug_info d;
12836   struct ecoff_find_line i;
12837 };
12838
12839 bfd_boolean
12840 _bfd_mips_elf_find_nearest_line (bfd *abfd, asymbol **symbols,
12841                                  asection *section, bfd_vma offset,
12842                                  const char **filename_ptr,
12843                                  const char **functionname_ptr,
12844                                  unsigned int *line_ptr,
12845                                  unsigned int *discriminator_ptr)
12846 {
12847   asection *msec;
12848
12849   if (_bfd_dwarf2_find_nearest_line (abfd, symbols, NULL, section, offset,
12850                                      filename_ptr, functionname_ptr,
12851                                      line_ptr, discriminator_ptr,
12852                                      dwarf_debug_sections,
12853                                      ABI_64_P (abfd) ? 8 : 0,
12854                                      &elf_tdata (abfd)->dwarf2_find_line_info))
12855     return TRUE;
12856
12857   if (_bfd_dwarf1_find_nearest_line (abfd, symbols, section, offset,
12858                                      filename_ptr, functionname_ptr,
12859                                      line_ptr))
12860     return TRUE;
12861
12862   msec = bfd_get_section_by_name (abfd, ".mdebug");
12863   if (msec != NULL)
12864     {
12865       flagword origflags;
12866       struct mips_elf_find_line *fi;
12867       const struct ecoff_debug_swap * const swap =
12868         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
12869
12870       /* If we are called during a link, mips_elf_final_link may have
12871          cleared the SEC_HAS_CONTENTS field.  We force it back on here
12872          if appropriate (which it normally will be).  */
12873       origflags = msec->flags;
12874       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
12875         msec->flags |= SEC_HAS_CONTENTS;
12876
12877       fi = mips_elf_tdata (abfd)->find_line_info;
12878       if (fi == NULL)
12879         {
12880           bfd_size_type external_fdr_size;
12881           char *fraw_src;
12882           char *fraw_end;
12883           struct fdr *fdr_ptr;
12884           bfd_size_type amt = sizeof (struct mips_elf_find_line);
12885
12886           fi = bfd_zalloc (abfd, amt);
12887           if (fi == NULL)
12888             {
12889               msec->flags = origflags;
12890               return FALSE;
12891             }
12892
12893           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
12894             {
12895               msec->flags = origflags;
12896               return FALSE;
12897             }
12898
12899           /* Swap in the FDR information.  */
12900           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
12901           fi->d.fdr = bfd_alloc (abfd, amt);
12902           if (fi->d.fdr == NULL)
12903             {
12904               msec->flags = origflags;
12905               return FALSE;
12906             }
12907           external_fdr_size = swap->external_fdr_size;
12908           fdr_ptr = fi->d.fdr;
12909           fraw_src = (char *) fi->d.external_fdr;
12910           fraw_end = (fraw_src
12911                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
12912           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
12913             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
12914
12915           mips_elf_tdata (abfd)->find_line_info = fi;
12916
12917           /* Note that we don't bother to ever free this information.
12918              find_nearest_line is either called all the time, as in
12919              objdump -l, so the information should be saved, or it is
12920              rarely called, as in ld error messages, so the memory
12921              wasted is unimportant.  Still, it would probably be a
12922              good idea for free_cached_info to throw it away.  */
12923         }
12924
12925       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
12926                                   &fi->i, filename_ptr, functionname_ptr,
12927                                   line_ptr))
12928         {
12929           msec->flags = origflags;
12930           return TRUE;
12931         }
12932
12933       msec->flags = origflags;
12934     }
12935
12936   /* Fall back on the generic ELF find_nearest_line routine.  */
12937
12938   return _bfd_elf_find_nearest_line (abfd, symbols, section, offset,
12939                                      filename_ptr, functionname_ptr,
12940                                      line_ptr, discriminator_ptr);
12941 }
12942
12943 bfd_boolean
12944 _bfd_mips_elf_find_inliner_info (bfd *abfd,
12945                                  const char **filename_ptr,
12946                                  const char **functionname_ptr,
12947                                  unsigned int *line_ptr)
12948 {
12949   bfd_boolean found;
12950   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
12951                                          functionname_ptr, line_ptr,
12952                                          & elf_tdata (abfd)->dwarf2_find_line_info);
12953   return found;
12954 }
12955
12956 \f
12957 /* When are writing out the .options or .MIPS.options section,
12958    remember the bytes we are writing out, so that we can install the
12959    GP value in the section_processing routine.  */
12960
12961 bfd_boolean
12962 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
12963                                     const void *location,
12964                                     file_ptr offset, bfd_size_type count)
12965 {
12966   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
12967     {
12968       bfd_byte *c;
12969
12970       if (elf_section_data (section) == NULL)
12971         {
12972           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
12973           section->used_by_bfd = bfd_zalloc (abfd, amt);
12974           if (elf_section_data (section) == NULL)
12975             return FALSE;
12976         }
12977       c = mips_elf_section_data (section)->u.tdata;
12978       if (c == NULL)
12979         {
12980           c = bfd_zalloc (abfd, section->size);
12981           if (c == NULL)
12982             return FALSE;
12983           mips_elf_section_data (section)->u.tdata = c;
12984         }
12985
12986       memcpy (c + offset, location, count);
12987     }
12988
12989   return _bfd_elf_set_section_contents (abfd, section, location, offset,
12990                                         count);
12991 }
12992
12993 /* This is almost identical to bfd_generic_get_... except that some
12994    MIPS relocations need to be handled specially.  Sigh.  */
12995
12996 bfd_byte *
12997 _bfd_elf_mips_get_relocated_section_contents
12998   (bfd *abfd,
12999    struct bfd_link_info *link_info,
13000    struct bfd_link_order *link_order,
13001    bfd_byte *data,
13002    bfd_boolean relocatable,
13003    asymbol **symbols)
13004 {
13005   /* Get enough memory to hold the stuff */
13006   bfd *input_bfd = link_order->u.indirect.section->owner;
13007   asection *input_section = link_order->u.indirect.section;
13008   bfd_size_type sz;
13009
13010   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
13011   arelent **reloc_vector = NULL;
13012   long reloc_count;
13013
13014   if (reloc_size < 0)
13015     goto error_return;
13016
13017   reloc_vector = bfd_malloc (reloc_size);
13018   if (reloc_vector == NULL && reloc_size != 0)
13019     goto error_return;
13020
13021   /* read in the section */
13022   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
13023   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
13024     goto error_return;
13025
13026   reloc_count = bfd_canonicalize_reloc (input_bfd,
13027                                         input_section,
13028                                         reloc_vector,
13029                                         symbols);
13030   if (reloc_count < 0)
13031     goto error_return;
13032
13033   if (reloc_count > 0)
13034     {
13035       arelent **parent;
13036       /* for mips */
13037       int gp_found;
13038       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
13039
13040       {
13041         struct bfd_hash_entry *h;
13042         struct bfd_link_hash_entry *lh;
13043         /* Skip all this stuff if we aren't mixing formats.  */
13044         if (abfd && input_bfd
13045             && abfd->xvec == input_bfd->xvec)
13046           lh = 0;
13047         else
13048           {
13049             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
13050             lh = (struct bfd_link_hash_entry *) h;
13051           }
13052       lookup:
13053         if (lh)
13054           {
13055             switch (lh->type)
13056               {
13057               case bfd_link_hash_undefined:
13058               case bfd_link_hash_undefweak:
13059               case bfd_link_hash_common:
13060                 gp_found = 0;
13061                 break;
13062               case bfd_link_hash_defined:
13063               case bfd_link_hash_defweak:
13064                 gp_found = 1;
13065                 gp = lh->u.def.value;
13066                 break;
13067               case bfd_link_hash_indirect:
13068               case bfd_link_hash_warning:
13069                 lh = lh->u.i.link;
13070                 /* @@FIXME  ignoring warning for now */
13071                 goto lookup;
13072               case bfd_link_hash_new:
13073               default:
13074                 abort ();
13075               }
13076           }
13077         else
13078           gp_found = 0;
13079       }
13080       /* end mips */
13081       for (parent = reloc_vector; *parent != NULL; parent++)
13082         {
13083           char *error_message = NULL;
13084           bfd_reloc_status_type r;
13085
13086           /* Specific to MIPS: Deal with relocation types that require
13087              knowing the gp of the output bfd.  */
13088           asymbol *sym = *(*parent)->sym_ptr_ptr;
13089
13090           /* If we've managed to find the gp and have a special
13091              function for the relocation then go ahead, else default
13092              to the generic handling.  */
13093           if (gp_found
13094               && (*parent)->howto->special_function
13095               == _bfd_mips_elf32_gprel16_reloc)
13096             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
13097                                                input_section, relocatable,
13098                                                data, gp);
13099           else
13100             r = bfd_perform_relocation (input_bfd, *parent, data,
13101                                         input_section,
13102                                         relocatable ? abfd : NULL,
13103                                         &error_message);
13104
13105           if (relocatable)
13106             {
13107               asection *os = input_section->output_section;
13108
13109               /* A partial link, so keep the relocs */
13110               os->orelocation[os->reloc_count] = *parent;
13111               os->reloc_count++;
13112             }
13113
13114           if (r != bfd_reloc_ok)
13115             {
13116               switch (r)
13117                 {
13118                 case bfd_reloc_undefined:
13119                   (*link_info->callbacks->undefined_symbol)
13120                     (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
13121                      input_bfd, input_section, (*parent)->address, TRUE);
13122                   break;
13123                 case bfd_reloc_dangerous:
13124                   BFD_ASSERT (error_message != NULL);
13125                   (*link_info->callbacks->reloc_dangerous)
13126                     (link_info, error_message,
13127                      input_bfd, input_section, (*parent)->address);
13128                   break;
13129                 case bfd_reloc_overflow:
13130                   (*link_info->callbacks->reloc_overflow)
13131                     (link_info, NULL,
13132                      bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
13133                      (*parent)->howto->name, (*parent)->addend,
13134                      input_bfd, input_section, (*parent)->address);
13135                   break;
13136                 case bfd_reloc_outofrange:
13137                 default:
13138                   abort ();
13139                   break;
13140                 }
13141
13142             }
13143         }
13144     }
13145   if (reloc_vector != NULL)
13146     free (reloc_vector);
13147   return data;
13148
13149 error_return:
13150   if (reloc_vector != NULL)
13151     free (reloc_vector);
13152   return NULL;
13153 }
13154 \f
13155 static bfd_boolean
13156 mips_elf_relax_delete_bytes (bfd *abfd,
13157                              asection *sec, bfd_vma addr, int count)
13158 {
13159   Elf_Internal_Shdr *symtab_hdr;
13160   unsigned int sec_shndx;
13161   bfd_byte *contents;
13162   Elf_Internal_Rela *irel, *irelend;
13163   Elf_Internal_Sym *isym;
13164   Elf_Internal_Sym *isymend;
13165   struct elf_link_hash_entry **sym_hashes;
13166   struct elf_link_hash_entry **end_hashes;
13167   struct elf_link_hash_entry **start_hashes;
13168   unsigned int symcount;
13169
13170   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
13171   contents = elf_section_data (sec)->this_hdr.contents;
13172
13173   irel = elf_section_data (sec)->relocs;
13174   irelend = irel + sec->reloc_count;
13175
13176   /* Actually delete the bytes.  */
13177   memmove (contents + addr, contents + addr + count,
13178            (size_t) (sec->size - addr - count));
13179   sec->size -= count;
13180
13181   /* Adjust all the relocs.  */
13182   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
13183     {
13184       /* Get the new reloc address.  */
13185       if (irel->r_offset > addr)
13186         irel->r_offset -= count;
13187     }
13188
13189   BFD_ASSERT (addr % 2 == 0);
13190   BFD_ASSERT (count % 2 == 0);
13191
13192   /* Adjust the local symbols defined in this section.  */
13193   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
13194   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
13195   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
13196     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
13197       isym->st_value -= count;
13198
13199   /* Now adjust the global symbols defined in this section.  */
13200   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
13201               - symtab_hdr->sh_info);
13202   sym_hashes = start_hashes = elf_sym_hashes (abfd);
13203   end_hashes = sym_hashes + symcount;
13204
13205   for (; sym_hashes < end_hashes; sym_hashes++)
13206     {
13207       struct elf_link_hash_entry *sym_hash = *sym_hashes;
13208
13209       if ((sym_hash->root.type == bfd_link_hash_defined
13210            || sym_hash->root.type == bfd_link_hash_defweak)
13211           && sym_hash->root.u.def.section == sec)
13212         {
13213           bfd_vma value = sym_hash->root.u.def.value;
13214
13215           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
13216             value &= MINUS_TWO;
13217           if (value > addr)
13218             sym_hash->root.u.def.value -= count;
13219         }
13220     }
13221
13222   return TRUE;
13223 }
13224
13225
13226 /* Opcodes needed for microMIPS relaxation as found in
13227    opcodes/micromips-opc.c.  */
13228
13229 struct opcode_descriptor {
13230   unsigned long match;
13231   unsigned long mask;
13232 };
13233
13234 /* The $ra register aka $31.  */
13235
13236 #define RA 31
13237
13238 /* 32-bit instruction format register fields.  */
13239
13240 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
13241 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
13242
13243 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
13244
13245 #define OP16_VALID_REG(r) \
13246   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
13247
13248
13249 /* 32-bit and 16-bit branches.  */
13250
13251 static const struct opcode_descriptor b_insns_32[] = {
13252   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
13253   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
13254   { 0, 0 }  /* End marker for find_match().  */
13255 };
13256
13257 static const struct opcode_descriptor bc_insn_32 =
13258   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
13259
13260 static const struct opcode_descriptor bz_insn_32 =
13261   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
13262
13263 static const struct opcode_descriptor bzal_insn_32 =
13264   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
13265
13266 static const struct opcode_descriptor beq_insn_32 =
13267   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
13268
13269 static const struct opcode_descriptor b_insn_16 =
13270   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
13271
13272 static const struct opcode_descriptor bz_insn_16 =
13273   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
13274
13275
13276 /* 32-bit and 16-bit branch EQ and NE zero.  */
13277
13278 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
13279    eq and second the ne.  This convention is used when replacing a
13280    32-bit BEQ/BNE with the 16-bit version.  */
13281
13282 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
13283
13284 static const struct opcode_descriptor bz_rs_insns_32[] = {
13285   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
13286   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
13287   { 0, 0 }  /* End marker for find_match().  */
13288 };
13289
13290 static const struct opcode_descriptor bz_rt_insns_32[] = {
13291   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
13292   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
13293   { 0, 0 }  /* End marker for find_match().  */
13294 };
13295
13296 static const struct opcode_descriptor bzc_insns_32[] = {
13297   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
13298   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
13299   { 0, 0 }  /* End marker for find_match().  */
13300 };
13301
13302 static const struct opcode_descriptor bz_insns_16[] = {
13303   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
13304   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
13305   { 0, 0 }  /* End marker for find_match().  */
13306 };
13307
13308 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
13309
13310 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0xf) + 2)
13311 #define BZ16_REG_FIELD(r) (((r) & 7) << 7)
13312
13313
13314 /* 32-bit instructions with a delay slot.  */
13315
13316 static const struct opcode_descriptor jal_insn_32_bd16 =
13317   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
13318
13319 static const struct opcode_descriptor jal_insn_32_bd32 =
13320   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
13321
13322 static const struct opcode_descriptor jal_x_insn_32_bd32 =
13323   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
13324
13325 static const struct opcode_descriptor j_insn_32 =
13326   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
13327
13328 static const struct opcode_descriptor jalr_insn_32 =
13329   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
13330
13331 /* This table can be compacted, because no opcode replacement is made.  */
13332
13333 static const struct opcode_descriptor ds_insns_32_bd16[] = {
13334   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
13335
13336   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
13337   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
13338
13339   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
13340   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
13341   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
13342   { 0, 0 }  /* End marker for find_match().  */
13343 };
13344
13345 /* This table can be compacted, because no opcode replacement is made.  */
13346
13347 static const struct opcode_descriptor ds_insns_32_bd32[] = {
13348   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
13349
13350   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
13351   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
13352   { 0, 0 }  /* End marker for find_match().  */
13353 };
13354
13355
13356 /* 16-bit instructions with a delay slot.  */
13357
13358 static const struct opcode_descriptor jalr_insn_16_bd16 =
13359   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
13360
13361 static const struct opcode_descriptor jalr_insn_16_bd32 =
13362   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
13363
13364 static const struct opcode_descriptor jr_insn_16 =
13365   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
13366
13367 #define JR16_REG(opcode) ((opcode) & 0x1f)
13368
13369 /* This table can be compacted, because no opcode replacement is made.  */
13370
13371 static const struct opcode_descriptor ds_insns_16_bd16[] = {
13372   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
13373
13374   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
13375   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
13376   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
13377   { 0, 0 }  /* End marker for find_match().  */
13378 };
13379
13380
13381 /* LUI instruction.  */
13382
13383 static const struct opcode_descriptor lui_insn =
13384  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
13385
13386
13387 /* ADDIU instruction.  */
13388
13389 static const struct opcode_descriptor addiu_insn =
13390   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
13391
13392 static const struct opcode_descriptor addiupc_insn =
13393   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
13394
13395 #define ADDIUPC_REG_FIELD(r) \
13396   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
13397
13398
13399 /* Relaxable instructions in a JAL delay slot: MOVE.  */
13400
13401 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
13402    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
13403 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
13404 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
13405
13406 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
13407 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
13408
13409 static const struct opcode_descriptor move_insns_32[] = {
13410   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
13411   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
13412   { 0, 0 }  /* End marker for find_match().  */
13413 };
13414
13415 static const struct opcode_descriptor move_insn_16 =
13416   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
13417
13418
13419 /* NOP instructions.  */
13420
13421 static const struct opcode_descriptor nop_insn_32 =
13422   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
13423
13424 static const struct opcode_descriptor nop_insn_16 =
13425   { /* "nop",   "",             */ 0x0c00,     0xffff };
13426
13427
13428 /* Instruction match support.  */
13429
13430 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
13431
13432 static int
13433 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
13434 {
13435   unsigned long indx;
13436
13437   for (indx = 0; insn[indx].mask != 0; indx++)
13438     if (MATCH (opcode, insn[indx]))
13439       return indx;
13440
13441   return -1;
13442 }
13443
13444
13445 /* Branch and delay slot decoding support.  */
13446
13447 /* If PTR points to what *might* be a 16-bit branch or jump, then
13448    return the minimum length of its delay slot, otherwise return 0.
13449    Non-zero results are not definitive as we might be checking against
13450    the second half of another instruction.  */
13451
13452 static int
13453 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
13454 {
13455   unsigned long opcode;
13456   int bdsize;
13457
13458   opcode = bfd_get_16 (abfd, ptr);
13459   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
13460     /* 16-bit branch/jump with a 32-bit delay slot.  */
13461     bdsize = 4;
13462   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
13463            || find_match (opcode, ds_insns_16_bd16) >= 0)
13464     /* 16-bit branch/jump with a 16-bit delay slot.  */
13465     bdsize = 2;
13466   else
13467     /* No delay slot.  */
13468     bdsize = 0;
13469
13470   return bdsize;
13471 }
13472
13473 /* If PTR points to what *might* be a 32-bit branch or jump, then
13474    return the minimum length of its delay slot, otherwise return 0.
13475    Non-zero results are not definitive as we might be checking against
13476    the second half of another instruction.  */
13477
13478 static int
13479 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
13480 {
13481   unsigned long opcode;
13482   int bdsize;
13483
13484   opcode = bfd_get_micromips_32 (abfd, ptr);
13485   if (find_match (opcode, ds_insns_32_bd32) >= 0)
13486     /* 32-bit branch/jump with a 32-bit delay slot.  */
13487     bdsize = 4;
13488   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
13489     /* 32-bit branch/jump with a 16-bit delay slot.  */
13490     bdsize = 2;
13491   else
13492     /* No delay slot.  */
13493     bdsize = 0;
13494
13495   return bdsize;
13496 }
13497
13498 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
13499    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
13500
13501 static bfd_boolean
13502 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
13503 {
13504   unsigned long opcode;
13505
13506   opcode = bfd_get_16 (abfd, ptr);
13507   if (MATCH (opcode, b_insn_16)
13508                                                 /* B16  */
13509       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
13510                                                 /* JR16  */
13511       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
13512                                                 /* BEQZ16, BNEZ16  */
13513       || (MATCH (opcode, jalr_insn_16_bd32)
13514                                                 /* JALR16  */
13515           && reg != JR16_REG (opcode) && reg != RA))
13516     return TRUE;
13517
13518   return FALSE;
13519 }
13520
13521 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
13522    then return TRUE, otherwise FALSE.  */
13523
13524 static bfd_boolean
13525 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
13526 {
13527   unsigned long opcode;
13528
13529   opcode = bfd_get_micromips_32 (abfd, ptr);
13530   if (MATCH (opcode, j_insn_32)
13531                                                 /* J  */
13532       || MATCH (opcode, bc_insn_32)
13533                                                 /* BC1F, BC1T, BC2F, BC2T  */
13534       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
13535                                                 /* JAL, JALX  */
13536       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
13537                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
13538       || (MATCH (opcode, bzal_insn_32)
13539                                                 /* BGEZAL, BLTZAL  */
13540           && reg != OP32_SREG (opcode) && reg != RA)
13541       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
13542                                                 /* JALR, JALR.HB, BEQ, BNE  */
13543           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
13544     return TRUE;
13545
13546   return FALSE;
13547 }
13548
13549 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
13550    IRELEND) at OFFSET indicate that there must be a compact branch there,
13551    then return TRUE, otherwise FALSE.  */
13552
13553 static bfd_boolean
13554 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
13555                      const Elf_Internal_Rela *internal_relocs,
13556                      const Elf_Internal_Rela *irelend)
13557 {
13558   const Elf_Internal_Rela *irel;
13559   unsigned long opcode;
13560
13561   opcode = bfd_get_micromips_32 (abfd, ptr);
13562   if (find_match (opcode, bzc_insns_32) < 0)
13563     return FALSE;
13564
13565   for (irel = internal_relocs; irel < irelend; irel++)
13566     if (irel->r_offset == offset
13567         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
13568       return TRUE;
13569
13570   return FALSE;
13571 }
13572
13573 /* Bitsize checking.  */
13574 #define IS_BITSIZE(val, N)                                              \
13575   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
13576     - (1ULL << ((N) - 1))) == (val))
13577
13578 \f
13579 bfd_boolean
13580 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
13581                              struct bfd_link_info *link_info,
13582                              bfd_boolean *again)
13583 {
13584   bfd_boolean insn32 = mips_elf_hash_table (link_info)->insn32;
13585   Elf_Internal_Shdr *symtab_hdr;
13586   Elf_Internal_Rela *internal_relocs;
13587   Elf_Internal_Rela *irel, *irelend;
13588   bfd_byte *contents = NULL;
13589   Elf_Internal_Sym *isymbuf = NULL;
13590
13591   /* Assume nothing changes.  */
13592   *again = FALSE;
13593
13594   /* We don't have to do anything for a relocatable link, if
13595      this section does not have relocs, or if this is not a
13596      code section.  */
13597
13598   if (bfd_link_relocatable (link_info)
13599       || (sec->flags & SEC_RELOC) == 0
13600       || sec->reloc_count == 0
13601       || (sec->flags & SEC_CODE) == 0)
13602     return TRUE;
13603
13604   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
13605
13606   /* Get a copy of the native relocations.  */
13607   internal_relocs = (_bfd_elf_link_read_relocs
13608                      (abfd, sec, NULL, (Elf_Internal_Rela *) NULL,
13609                       link_info->keep_memory));
13610   if (internal_relocs == NULL)
13611     goto error_return;
13612
13613   /* Walk through them looking for relaxing opportunities.  */
13614   irelend = internal_relocs + sec->reloc_count;
13615   for (irel = internal_relocs; irel < irelend; irel++)
13616     {
13617       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
13618       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
13619       bfd_boolean target_is_micromips_code_p;
13620       unsigned long opcode;
13621       bfd_vma symval;
13622       bfd_vma pcrval;
13623       bfd_byte *ptr;
13624       int fndopc;
13625
13626       /* The number of bytes to delete for relaxation and from where
13627          to delete these bytes starting at irel->r_offset.  */
13628       int delcnt = 0;
13629       int deloff = 0;
13630
13631       /* If this isn't something that can be relaxed, then ignore
13632          this reloc.  */
13633       if (r_type != R_MICROMIPS_HI16
13634           && r_type != R_MICROMIPS_PC16_S1
13635           && r_type != R_MICROMIPS_26_S1)
13636         continue;
13637
13638       /* Get the section contents if we haven't done so already.  */
13639       if (contents == NULL)
13640         {
13641           /* Get cached copy if it exists.  */
13642           if (elf_section_data (sec)->this_hdr.contents != NULL)
13643             contents = elf_section_data (sec)->this_hdr.contents;
13644           /* Go get them off disk.  */
13645           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
13646             goto error_return;
13647         }
13648       ptr = contents + irel->r_offset;
13649
13650       /* Read this BFD's local symbols if we haven't done so already.  */
13651       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
13652         {
13653           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
13654           if (isymbuf == NULL)
13655             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
13656                                             symtab_hdr->sh_info, 0,
13657                                             NULL, NULL, NULL);
13658           if (isymbuf == NULL)
13659             goto error_return;
13660         }
13661
13662       /* Get the value of the symbol referred to by the reloc.  */
13663       if (r_symndx < symtab_hdr->sh_info)
13664         {
13665           /* A local symbol.  */
13666           Elf_Internal_Sym *isym;
13667           asection *sym_sec;
13668
13669           isym = isymbuf + r_symndx;
13670           if (isym->st_shndx == SHN_UNDEF)
13671             sym_sec = bfd_und_section_ptr;
13672           else if (isym->st_shndx == SHN_ABS)
13673             sym_sec = bfd_abs_section_ptr;
13674           else if (isym->st_shndx == SHN_COMMON)
13675             sym_sec = bfd_com_section_ptr;
13676           else
13677             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
13678           symval = (isym->st_value
13679                     + sym_sec->output_section->vma
13680                     + sym_sec->output_offset);
13681           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
13682         }
13683       else
13684         {
13685           unsigned long indx;
13686           struct elf_link_hash_entry *h;
13687
13688           /* An external symbol.  */
13689           indx = r_symndx - symtab_hdr->sh_info;
13690           h = elf_sym_hashes (abfd)[indx];
13691           BFD_ASSERT (h != NULL);
13692
13693           if (h->root.type != bfd_link_hash_defined
13694               && h->root.type != bfd_link_hash_defweak)
13695             /* This appears to be a reference to an undefined
13696                symbol.  Just ignore it -- it will be caught by the
13697                regular reloc processing.  */
13698             continue;
13699
13700           symval = (h->root.u.def.value
13701                     + h->root.u.def.section->output_section->vma
13702                     + h->root.u.def.section->output_offset);
13703           target_is_micromips_code_p = (!h->needs_plt
13704                                         && ELF_ST_IS_MICROMIPS (h->other));
13705         }
13706
13707
13708       /* For simplicity of coding, we are going to modify the
13709          section contents, the section relocs, and the BFD symbol
13710          table.  We must tell the rest of the code not to free up this
13711          information.  It would be possible to instead create a table
13712          of changes which have to be made, as is done in coff-mips.c;
13713          that would be more work, but would require less memory when
13714          the linker is run.  */
13715
13716       /* Only 32-bit instructions relaxed.  */
13717       if (irel->r_offset + 4 > sec->size)
13718         continue;
13719
13720       opcode = bfd_get_micromips_32 (abfd, ptr);
13721
13722       /* This is the pc-relative distance from the instruction the
13723          relocation is applied to, to the symbol referred.  */
13724       pcrval = (symval
13725                 - (sec->output_section->vma + sec->output_offset)
13726                 - irel->r_offset);
13727
13728       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
13729          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
13730          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
13731
13732            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
13733
13734          where pcrval has first to be adjusted to apply against the LO16
13735          location (we make the adjustment later on, when we have figured
13736          out the offset).  */
13737       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
13738         {
13739           bfd_boolean bzc = FALSE;
13740           unsigned long nextopc;
13741           unsigned long reg;
13742           bfd_vma offset;
13743
13744           /* Give up if the previous reloc was a HI16 against this symbol
13745              too.  */
13746           if (irel > internal_relocs
13747               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
13748               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
13749             continue;
13750
13751           /* Or if the next reloc is not a LO16 against this symbol.  */
13752           if (irel + 1 >= irelend
13753               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
13754               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
13755             continue;
13756
13757           /* Or if the second next reloc is a LO16 against this symbol too.  */
13758           if (irel + 2 >= irelend
13759               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
13760               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
13761             continue;
13762
13763           /* See if the LUI instruction *might* be in a branch delay slot.
13764              We check whether what looks like a 16-bit branch or jump is
13765              actually an immediate argument to a compact branch, and let
13766              it through if so.  */
13767           if (irel->r_offset >= 2
13768               && check_br16_dslot (abfd, ptr - 2)
13769               && !(irel->r_offset >= 4
13770                    && (bzc = check_relocated_bzc (abfd,
13771                                                   ptr - 4, irel->r_offset - 4,
13772                                                   internal_relocs, irelend))))
13773             continue;
13774           if (irel->r_offset >= 4
13775               && !bzc
13776               && check_br32_dslot (abfd, ptr - 4))
13777             continue;
13778
13779           reg = OP32_SREG (opcode);
13780
13781           /* We only relax adjacent instructions or ones separated with
13782              a branch or jump that has a delay slot.  The branch or jump
13783              must not fiddle with the register used to hold the address.
13784              Subtract 4 for the LUI itself.  */
13785           offset = irel[1].r_offset - irel[0].r_offset;
13786           switch (offset - 4)
13787             {
13788             case 0:
13789               break;
13790             case 2:
13791               if (check_br16 (abfd, ptr + 4, reg))
13792                 break;
13793               continue;
13794             case 4:
13795               if (check_br32 (abfd, ptr + 4, reg))
13796                 break;
13797               continue;
13798             default:
13799               continue;
13800             }
13801
13802           nextopc = bfd_get_micromips_32 (abfd, contents + irel[1].r_offset);
13803
13804           /* Give up unless the same register is used with both
13805              relocations.  */
13806           if (OP32_SREG (nextopc) != reg)
13807             continue;
13808
13809           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
13810              and rounding up to take masking of the two LSBs into account.  */
13811           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
13812
13813           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
13814           if (IS_BITSIZE (symval, 16))
13815             {
13816               /* Fix the relocation's type.  */
13817               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
13818
13819               /* Instructions using R_MICROMIPS_LO16 have the base or
13820                  source register in bits 20:16.  This register becomes $0
13821                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
13822               nextopc &= ~0x001f0000;
13823               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
13824                           contents + irel[1].r_offset);
13825             }
13826
13827           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
13828              We add 4 to take LUI deletion into account while checking
13829              the PC-relative distance.  */
13830           else if (symval % 4 == 0
13831                    && IS_BITSIZE (pcrval + 4, 25)
13832                    && MATCH (nextopc, addiu_insn)
13833                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
13834                    && OP16_VALID_REG (OP32_TREG (nextopc)))
13835             {
13836               /* Fix the relocation's type.  */
13837               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
13838
13839               /* Replace ADDIU with the ADDIUPC version.  */
13840               nextopc = (addiupc_insn.match
13841                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
13842
13843               bfd_put_micromips_32 (abfd, nextopc,
13844                                     contents + irel[1].r_offset);
13845             }
13846
13847           /* Can't do anything, give up, sigh...  */
13848           else
13849             continue;
13850
13851           /* Fix the relocation's type.  */
13852           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
13853
13854           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
13855           delcnt = 4;
13856           deloff = 0;
13857         }
13858
13859       /* Compact branch relaxation -- due to the multitude of macros
13860          employed by the compiler/assembler, compact branches are not
13861          always generated.  Obviously, this can/will be fixed elsewhere,
13862          but there is no drawback in double checking it here.  */
13863       else if (r_type == R_MICROMIPS_PC16_S1
13864                && irel->r_offset + 5 < sec->size
13865                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
13866                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
13867                && ((!insn32
13868                     && (delcnt = MATCH (bfd_get_16 (abfd, ptr + 4),
13869                                         nop_insn_16) ? 2 : 0))
13870                    || (irel->r_offset + 7 < sec->size
13871                        && (delcnt = MATCH (bfd_get_micromips_32 (abfd,
13872                                                                  ptr + 4),
13873                                            nop_insn_32) ? 4 : 0))))
13874         {
13875           unsigned long reg;
13876
13877           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
13878
13879           /* Replace BEQZ/BNEZ with the compact version.  */
13880           opcode = (bzc_insns_32[fndopc].match
13881                     | BZC32_REG_FIELD (reg)
13882                     | (opcode & 0xffff));               /* Addend value.  */
13883
13884           bfd_put_micromips_32 (abfd, opcode, ptr);
13885
13886           /* Delete the delay slot NOP: two or four bytes from
13887              irel->offset + 4; delcnt has already been set above.  */
13888           deloff = 4;
13889         }
13890
13891       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
13892          to check the distance from the next instruction, so subtract 2.  */
13893       else if (!insn32
13894                && r_type == R_MICROMIPS_PC16_S1
13895                && IS_BITSIZE (pcrval - 2, 11)
13896                && find_match (opcode, b_insns_32) >= 0)
13897         {
13898           /* Fix the relocation's type.  */
13899           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
13900
13901           /* Replace the 32-bit opcode with a 16-bit opcode.  */
13902           bfd_put_16 (abfd,
13903                       (b_insn_16.match
13904                        | (opcode & 0x3ff)),             /* Addend value.  */
13905                       ptr);
13906
13907           /* Delete 2 bytes from irel->r_offset + 2.  */
13908           delcnt = 2;
13909           deloff = 2;
13910         }
13911
13912       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
13913          to check the distance from the next instruction, so subtract 2.  */
13914       else if (!insn32
13915                && r_type == R_MICROMIPS_PC16_S1
13916                && IS_BITSIZE (pcrval - 2, 8)
13917                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
13918                     && OP16_VALID_REG (OP32_SREG (opcode)))
13919                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
13920                        && OP16_VALID_REG (OP32_TREG (opcode)))))
13921         {
13922           unsigned long reg;
13923
13924           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
13925
13926           /* Fix the relocation's type.  */
13927           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
13928
13929           /* Replace the 32-bit opcode with a 16-bit opcode.  */
13930           bfd_put_16 (abfd,
13931                       (bz_insns_16[fndopc].match
13932                        | BZ16_REG_FIELD (reg)
13933                        | (opcode & 0x7f)),              /* Addend value.  */
13934                       ptr);
13935
13936           /* Delete 2 bytes from irel->r_offset + 2.  */
13937           delcnt = 2;
13938           deloff = 2;
13939         }
13940
13941       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
13942       else if (!insn32
13943                && r_type == R_MICROMIPS_26_S1
13944                && target_is_micromips_code_p
13945                && irel->r_offset + 7 < sec->size
13946                && MATCH (opcode, jal_insn_32_bd32))
13947         {
13948           unsigned long n32opc;
13949           bfd_boolean relaxed = FALSE;
13950
13951           n32opc = bfd_get_micromips_32 (abfd, ptr + 4);
13952
13953           if (MATCH (n32opc, nop_insn_32))
13954             {
13955               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
13956               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
13957
13958               relaxed = TRUE;
13959             }
13960           else if (find_match (n32opc, move_insns_32) >= 0)
13961             {
13962               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
13963               bfd_put_16 (abfd,
13964                           (move_insn_16.match
13965                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
13966                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
13967                           ptr + 4);
13968
13969               relaxed = TRUE;
13970             }
13971           /* Other 32-bit instructions relaxable to 16-bit
13972              instructions will be handled here later.  */
13973
13974           if (relaxed)
13975             {
13976               /* JAL with 32-bit delay slot that is changed to a JALS
13977                  with 16-bit delay slot.  */
13978               bfd_put_micromips_32 (abfd, jal_insn_32_bd16.match, ptr);
13979
13980               /* Delete 2 bytes from irel->r_offset + 6.  */
13981               delcnt = 2;
13982               deloff = 6;
13983             }
13984         }
13985
13986       if (delcnt != 0)
13987         {
13988           /* Note that we've changed the relocs, section contents, etc.  */
13989           elf_section_data (sec)->relocs = internal_relocs;
13990           elf_section_data (sec)->this_hdr.contents = contents;
13991           symtab_hdr->contents = (unsigned char *) isymbuf;
13992
13993           /* Delete bytes depending on the delcnt and deloff.  */
13994           if (!mips_elf_relax_delete_bytes (abfd, sec,
13995                                             irel->r_offset + deloff, delcnt))
13996             goto error_return;
13997
13998           /* That will change things, so we should relax again.
13999              Note that this is not required, and it may be slow.  */
14000           *again = TRUE;
14001         }
14002     }
14003
14004   if (isymbuf != NULL
14005       && symtab_hdr->contents != (unsigned char *) isymbuf)
14006     {
14007       if (! link_info->keep_memory)
14008         free (isymbuf);
14009       else
14010         {
14011           /* Cache the symbols for elf_link_input_bfd.  */
14012           symtab_hdr->contents = (unsigned char *) isymbuf;
14013         }
14014     }
14015
14016   if (contents != NULL
14017       && elf_section_data (sec)->this_hdr.contents != contents)
14018     {
14019       if (! link_info->keep_memory)
14020         free (contents);
14021       else
14022         {
14023           /* Cache the section contents for elf_link_input_bfd.  */
14024           elf_section_data (sec)->this_hdr.contents = contents;
14025         }
14026     }
14027
14028   if (internal_relocs != NULL
14029       && elf_section_data (sec)->relocs != internal_relocs)
14030     free (internal_relocs);
14031
14032   return TRUE;
14033
14034  error_return:
14035   if (isymbuf != NULL
14036       && symtab_hdr->contents != (unsigned char *) isymbuf)
14037     free (isymbuf);
14038   if (contents != NULL
14039       && elf_section_data (sec)->this_hdr.contents != contents)
14040     free (contents);
14041   if (internal_relocs != NULL
14042       && elf_section_data (sec)->relocs != internal_relocs)
14043     free (internal_relocs);
14044
14045   return FALSE;
14046 }
14047 \f
14048 /* Create a MIPS ELF linker hash table.  */
14049
14050 struct bfd_link_hash_table *
14051 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
14052 {
14053   struct mips_elf_link_hash_table *ret;
14054   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
14055
14056   ret = bfd_zmalloc (amt);
14057   if (ret == NULL)
14058     return NULL;
14059
14060   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
14061                                       mips_elf_link_hash_newfunc,
14062                                       sizeof (struct mips_elf_link_hash_entry),
14063                                       MIPS_ELF_DATA))
14064     {
14065       free (ret);
14066       return NULL;
14067     }
14068   ret->root.init_plt_refcount.plist = NULL;
14069   ret->root.init_plt_offset.plist = NULL;
14070
14071   return &ret->root.root;
14072 }
14073
14074 /* Likewise, but indicate that the target is VxWorks.  */
14075
14076 struct bfd_link_hash_table *
14077 _bfd_mips_vxworks_link_hash_table_create (bfd *abfd)
14078 {
14079   struct bfd_link_hash_table *ret;
14080
14081   ret = _bfd_mips_elf_link_hash_table_create (abfd);
14082   if (ret)
14083     {
14084       struct mips_elf_link_hash_table *htab;
14085
14086       htab = (struct mips_elf_link_hash_table *) ret;
14087       htab->use_plts_and_copy_relocs = TRUE;
14088       htab->is_vxworks = TRUE;
14089     }
14090   return ret;
14091 }
14092
14093 /* A function that the linker calls if we are allowed to use PLTs
14094    and copy relocs.  */
14095
14096 void
14097 _bfd_mips_elf_use_plts_and_copy_relocs (struct bfd_link_info *info)
14098 {
14099   mips_elf_hash_table (info)->use_plts_and_copy_relocs = TRUE;
14100 }
14101
14102 /* A function that the linker calls to select between all or only
14103    32-bit microMIPS instructions, and between making or ignoring
14104    branch relocation checks for invalid transitions between ISA modes.  */
14105
14106 void
14107 _bfd_mips_elf_linker_flags (struct bfd_link_info *info, bfd_boolean insn32,
14108                             bfd_boolean ignore_branch_isa)
14109 {
14110   mips_elf_hash_table (info)->insn32 = insn32;
14111   mips_elf_hash_table (info)->ignore_branch_isa = ignore_branch_isa;
14112 }
14113 \f
14114 /* Structure for saying that BFD machine EXTENSION extends BASE.  */
14115
14116 struct mips_mach_extension
14117 {
14118   unsigned long extension, base;
14119 };
14120
14121
14122 /* An array describing how BFD machines relate to one another.  The entries
14123    are ordered topologically with MIPS I extensions listed last.  */
14124
14125 static const struct mips_mach_extension mips_mach_extensions[] =
14126 {
14127   /* MIPS64r2 extensions.  */
14128   { bfd_mach_mips_octeon3, bfd_mach_mips_octeon2 },
14129   { bfd_mach_mips_octeon2, bfd_mach_mips_octeonp },
14130   { bfd_mach_mips_octeonp, bfd_mach_mips_octeon },
14131   { bfd_mach_mips_octeon, bfd_mach_mipsisa64r2 },
14132   { bfd_mach_mips_loongson_3a, bfd_mach_mipsisa64r2 },
14133
14134   /* MIPS64 extensions.  */
14135   { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 },
14136   { bfd_mach_mips_sb1, bfd_mach_mipsisa64 },
14137   { bfd_mach_mips_xlr, bfd_mach_mipsisa64 },
14138
14139   /* MIPS V extensions.  */
14140   { bfd_mach_mipsisa64, bfd_mach_mips5 },
14141
14142   /* R10000 extensions.  */
14143   { bfd_mach_mips12000, bfd_mach_mips10000 },
14144   { bfd_mach_mips14000, bfd_mach_mips10000 },
14145   { bfd_mach_mips16000, bfd_mach_mips10000 },
14146
14147   /* R5000 extensions.  Note: the vr5500 ISA is an extension of the core
14148      vr5400 ISA, but doesn't include the multimedia stuff.  It seems
14149      better to allow vr5400 and vr5500 code to be merged anyway, since
14150      many libraries will just use the core ISA.  Perhaps we could add
14151      some sort of ASE flag if this ever proves a problem.  */
14152   { bfd_mach_mips5500, bfd_mach_mips5400 },
14153   { bfd_mach_mips5400, bfd_mach_mips5000 },
14154
14155   /* MIPS IV extensions.  */
14156   { bfd_mach_mips5, bfd_mach_mips8000 },
14157   { bfd_mach_mips10000, bfd_mach_mips8000 },
14158   { bfd_mach_mips5000, bfd_mach_mips8000 },
14159   { bfd_mach_mips7000, bfd_mach_mips8000 },
14160   { bfd_mach_mips9000, bfd_mach_mips8000 },
14161
14162   /* VR4100 extensions.  */
14163   { bfd_mach_mips4120, bfd_mach_mips4100 },
14164   { bfd_mach_mips4111, bfd_mach_mips4100 },
14165
14166   /* MIPS III extensions.  */
14167   { bfd_mach_mips_loongson_2e, bfd_mach_mips4000 },
14168   { bfd_mach_mips_loongson_2f, bfd_mach_mips4000 },
14169   { bfd_mach_mips8000, bfd_mach_mips4000 },
14170   { bfd_mach_mips4650, bfd_mach_mips4000 },
14171   { bfd_mach_mips4600, bfd_mach_mips4000 },
14172   { bfd_mach_mips4400, bfd_mach_mips4000 },
14173   { bfd_mach_mips4300, bfd_mach_mips4000 },
14174   { bfd_mach_mips4100, bfd_mach_mips4000 },
14175   { bfd_mach_mips4010, bfd_mach_mips4000 },
14176   { bfd_mach_mips5900, bfd_mach_mips4000 },
14177
14178   /* MIPS32 extensions.  */
14179   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
14180
14181   /* MIPS II extensions.  */
14182   { bfd_mach_mips4000, bfd_mach_mips6000 },
14183   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
14184
14185   /* MIPS I extensions.  */
14186   { bfd_mach_mips6000, bfd_mach_mips3000 },
14187   { bfd_mach_mips3900, bfd_mach_mips3000 }
14188 };
14189
14190 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
14191
14192 static bfd_boolean
14193 mips_mach_extends_p (unsigned long base, unsigned long extension)
14194 {
14195   size_t i;
14196
14197   if (extension == base)
14198     return TRUE;
14199
14200   if (base == bfd_mach_mipsisa32
14201       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
14202     return TRUE;
14203
14204   if (base == bfd_mach_mipsisa32r2
14205       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
14206     return TRUE;
14207
14208   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
14209     if (extension == mips_mach_extensions[i].extension)
14210       {
14211         extension = mips_mach_extensions[i].base;
14212         if (extension == base)
14213           return TRUE;
14214       }
14215
14216   return FALSE;
14217 }
14218
14219 /* Return the BFD mach for each .MIPS.abiflags ISA Extension.  */
14220
14221 static unsigned long
14222 bfd_mips_isa_ext_mach (unsigned int isa_ext)
14223 {
14224   switch (isa_ext)
14225     {
14226     case AFL_EXT_3900:        return bfd_mach_mips3900;
14227     case AFL_EXT_4010:        return bfd_mach_mips4010;
14228     case AFL_EXT_4100:        return bfd_mach_mips4100;
14229     case AFL_EXT_4111:        return bfd_mach_mips4111;
14230     case AFL_EXT_4120:        return bfd_mach_mips4120;
14231     case AFL_EXT_4650:        return bfd_mach_mips4650;
14232     case AFL_EXT_5400:        return bfd_mach_mips5400;
14233     case AFL_EXT_5500:        return bfd_mach_mips5500;
14234     case AFL_EXT_5900:        return bfd_mach_mips5900;
14235     case AFL_EXT_10000:       return bfd_mach_mips10000;
14236     case AFL_EXT_LOONGSON_2E: return bfd_mach_mips_loongson_2e;
14237     case AFL_EXT_LOONGSON_2F: return bfd_mach_mips_loongson_2f;
14238     case AFL_EXT_LOONGSON_3A: return bfd_mach_mips_loongson_3a;
14239     case AFL_EXT_SB1:         return bfd_mach_mips_sb1;
14240     case AFL_EXT_OCTEON:      return bfd_mach_mips_octeon;
14241     case AFL_EXT_OCTEONP:     return bfd_mach_mips_octeonp;
14242     case AFL_EXT_OCTEON2:     return bfd_mach_mips_octeon2;
14243     case AFL_EXT_XLR:         return bfd_mach_mips_xlr;
14244     default:                  return bfd_mach_mips3000;
14245     }
14246 }
14247
14248 /* Return the .MIPS.abiflags value representing each ISA Extension.  */
14249
14250 unsigned int
14251 bfd_mips_isa_ext (bfd *abfd)
14252 {
14253   switch (bfd_get_mach (abfd))
14254     {
14255     case bfd_mach_mips3900:         return AFL_EXT_3900;
14256     case bfd_mach_mips4010:         return AFL_EXT_4010;
14257     case bfd_mach_mips4100:         return AFL_EXT_4100;
14258     case bfd_mach_mips4111:         return AFL_EXT_4111;
14259     case bfd_mach_mips4120:         return AFL_EXT_4120;
14260     case bfd_mach_mips4650:         return AFL_EXT_4650;
14261     case bfd_mach_mips5400:         return AFL_EXT_5400;
14262     case bfd_mach_mips5500:         return AFL_EXT_5500;
14263     case bfd_mach_mips5900:         return AFL_EXT_5900;
14264     case bfd_mach_mips10000:        return AFL_EXT_10000;
14265     case bfd_mach_mips_loongson_2e: return AFL_EXT_LOONGSON_2E;
14266     case bfd_mach_mips_loongson_2f: return AFL_EXT_LOONGSON_2F;
14267     case bfd_mach_mips_loongson_3a: return AFL_EXT_LOONGSON_3A;
14268     case bfd_mach_mips_sb1:         return AFL_EXT_SB1;
14269     case bfd_mach_mips_octeon:      return AFL_EXT_OCTEON;
14270     case bfd_mach_mips_octeonp:     return AFL_EXT_OCTEONP;
14271     case bfd_mach_mips_octeon3:     return AFL_EXT_OCTEON3;
14272     case bfd_mach_mips_octeon2:     return AFL_EXT_OCTEON2;
14273     case bfd_mach_mips_xlr:         return AFL_EXT_XLR;
14274     default:                        return 0;
14275     }
14276 }
14277
14278 /* Encode ISA level and revision as a single value.  */
14279 #define LEVEL_REV(LEV,REV) ((LEV) << 3 | (REV))
14280
14281 /* Decode a single value into level and revision.  */
14282 #define ISA_LEVEL(LEVREV)  ((LEVREV) >> 3)
14283 #define ISA_REV(LEVREV)    ((LEVREV) & 0x7)
14284
14285 /* Update the isa_level, isa_rev, isa_ext fields of abiflags.  */
14286
14287 static void
14288 update_mips_abiflags_isa (bfd *abfd, Elf_Internal_ABIFlags_v0 *abiflags)
14289 {
14290   int new_isa = 0;
14291   switch (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH)
14292     {
14293     case E_MIPS_ARCH_1:    new_isa = LEVEL_REV (1, 0); break;
14294     case E_MIPS_ARCH_2:    new_isa = LEVEL_REV (2, 0); break;
14295     case E_MIPS_ARCH_3:    new_isa = LEVEL_REV (3, 0); break;
14296     case E_MIPS_ARCH_4:    new_isa = LEVEL_REV (4, 0); break;
14297     case E_MIPS_ARCH_5:    new_isa = LEVEL_REV (5, 0); break;
14298     case E_MIPS_ARCH_32:   new_isa = LEVEL_REV (32, 1); break;
14299     case E_MIPS_ARCH_32R2: new_isa = LEVEL_REV (32, 2); break;
14300     case E_MIPS_ARCH_32R6: new_isa = LEVEL_REV (32, 6); break;
14301     case E_MIPS_ARCH_64:   new_isa = LEVEL_REV (64, 1); break;
14302     case E_MIPS_ARCH_64R2: new_isa = LEVEL_REV (64, 2); break;
14303     case E_MIPS_ARCH_64R6: new_isa = LEVEL_REV (64, 6); break;
14304     default:
14305       _bfd_error_handler
14306         /* xgettext:c-format */
14307         (_("%B: Unknown architecture %s"),
14308          abfd, bfd_printable_name (abfd));
14309     }
14310
14311   if (new_isa > LEVEL_REV (abiflags->isa_level, abiflags->isa_rev))
14312     {
14313       abiflags->isa_level = ISA_LEVEL (new_isa);
14314       abiflags->isa_rev = ISA_REV (new_isa);
14315     }
14316
14317   /* Update the isa_ext if ABFD describes a further extension.  */
14318   if (mips_mach_extends_p (bfd_mips_isa_ext_mach (abiflags->isa_ext),
14319                            bfd_get_mach (abfd)))
14320     abiflags->isa_ext = bfd_mips_isa_ext (abfd);
14321 }
14322
14323 /* Return true if the given ELF header flags describe a 32-bit binary.  */
14324
14325 static bfd_boolean
14326 mips_32bit_flags_p (flagword flags)
14327 {
14328   return ((flags & EF_MIPS_32BITMODE) != 0
14329           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
14330           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
14331           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
14332           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
14333           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
14334           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2
14335           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R6);
14336 }
14337
14338 /* Infer the content of the ABI flags based on the elf header.  */
14339
14340 static void
14341 infer_mips_abiflags (bfd *abfd, Elf_Internal_ABIFlags_v0* abiflags)
14342 {
14343   obj_attribute *in_attr;
14344
14345   memset (abiflags, 0, sizeof (Elf_Internal_ABIFlags_v0));
14346   update_mips_abiflags_isa (abfd, abiflags);
14347
14348   if (mips_32bit_flags_p (elf_elfheader (abfd)->e_flags))
14349     abiflags->gpr_size = AFL_REG_32;
14350   else
14351     abiflags->gpr_size = AFL_REG_64;
14352
14353   abiflags->cpr1_size = AFL_REG_NONE;
14354
14355   in_attr = elf_known_obj_attributes (abfd)[OBJ_ATTR_GNU];
14356   abiflags->fp_abi = in_attr[Tag_GNU_MIPS_ABI_FP].i;
14357
14358   if (abiflags->fp_abi == Val_GNU_MIPS_ABI_FP_SINGLE
14359       || abiflags->fp_abi == Val_GNU_MIPS_ABI_FP_XX
14360       || (abiflags->fp_abi == Val_GNU_MIPS_ABI_FP_DOUBLE
14361           && abiflags->gpr_size == AFL_REG_32))
14362     abiflags->cpr1_size = AFL_REG_32;
14363   else if (abiflags->fp_abi == Val_GNU_MIPS_ABI_FP_DOUBLE
14364            || abiflags->fp_abi == Val_GNU_MIPS_ABI_FP_64
14365            || abiflags->fp_abi == Val_GNU_MIPS_ABI_FP_64A)
14366     abiflags->cpr1_size = AFL_REG_64;
14367
14368   abiflags->cpr2_size = AFL_REG_NONE;
14369
14370   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
14371     abiflags->ases |= AFL_ASE_MDMX;
14372   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
14373     abiflags->ases |= AFL_ASE_MIPS16;
14374   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
14375     abiflags->ases |= AFL_ASE_MICROMIPS;
14376
14377   if (abiflags->fp_abi != Val_GNU_MIPS_ABI_FP_ANY
14378       && abiflags->fp_abi != Val_GNU_MIPS_ABI_FP_SOFT
14379       && abiflags->fp_abi != Val_GNU_MIPS_ABI_FP_64A
14380       && abiflags->isa_level >= 32
14381       && abiflags->isa_ext != AFL_EXT_LOONGSON_3A)
14382     abiflags->flags1 |= AFL_FLAGS1_ODDSPREG;
14383 }
14384
14385 /* We need to use a special link routine to handle the .reginfo and
14386    the .mdebug sections.  We need to merge all instances of these
14387    sections together, not write them all out sequentially.  */
14388
14389 bfd_boolean
14390 _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info)
14391 {
14392   asection *o;
14393   struct bfd_link_order *p;
14394   asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec;
14395   asection *rtproc_sec, *abiflags_sec;
14396   Elf32_RegInfo reginfo;
14397   struct ecoff_debug_info debug;
14398   struct mips_htab_traverse_info hti;
14399   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14400   const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap;
14401   HDRR *symhdr = &debug.symbolic_header;
14402   void *mdebug_handle = NULL;
14403   asection *s;
14404   EXTR esym;
14405   unsigned int i;
14406   bfd_size_type amt;
14407   struct mips_elf_link_hash_table *htab;
14408
14409   static const char * const secname[] =
14410   {
14411     ".text", ".init", ".fini", ".data",
14412     ".rodata", ".sdata", ".sbss", ".bss"
14413   };
14414   static const int sc[] =
14415   {
14416     scText, scInit, scFini, scData,
14417     scRData, scSData, scSBss, scBss
14418   };
14419
14420   /* Sort the dynamic symbols so that those with GOT entries come after
14421      those without.  */
14422   htab = mips_elf_hash_table (info);
14423   BFD_ASSERT (htab != NULL);
14424
14425   if (!mips_elf_sort_hash_table (abfd, info))
14426     return FALSE;
14427
14428   /* Create any scheduled LA25 stubs.  */
14429   hti.info = info;
14430   hti.output_bfd = abfd;
14431   hti.error = FALSE;
14432   htab_traverse (htab->la25_stubs, mips_elf_create_la25_stub, &hti);
14433   if (hti.error)
14434     return FALSE;
14435
14436   /* Get a value for the GP register.  */
14437   if (elf_gp (abfd) == 0)
14438     {
14439       struct bfd_link_hash_entry *h;
14440
14441       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
14442       if (h != NULL && h->type == bfd_link_hash_defined)
14443         elf_gp (abfd) = (h->u.def.value
14444                          + h->u.def.section->output_section->vma
14445                          + h->u.def.section->output_offset);
14446       else if (htab->is_vxworks
14447                && (h = bfd_link_hash_lookup (info->hash,
14448                                              "_GLOBAL_OFFSET_TABLE_",
14449                                              FALSE, FALSE, TRUE))
14450                && h->type == bfd_link_hash_defined)
14451         elf_gp (abfd) = (h->u.def.section->output_section->vma
14452                          + h->u.def.section->output_offset
14453                          + h->u.def.value);
14454       else if (bfd_link_relocatable (info))
14455         {
14456           bfd_vma lo = MINUS_ONE;
14457
14458           /* Find the GP-relative section with the lowest offset.  */
14459           for (o = abfd->sections; o != NULL; o = o->next)
14460             if (o->vma < lo
14461                 && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL))
14462               lo = o->vma;
14463
14464           /* And calculate GP relative to that.  */
14465           elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (info);
14466         }
14467       else
14468         {
14469           /* If the relocate_section function needs to do a reloc
14470              involving the GP value, it should make a reloc_dangerous
14471              callback to warn that GP is not defined.  */
14472         }
14473     }
14474
14475   /* Go through the sections and collect the .reginfo and .mdebug
14476      information.  */
14477   abiflags_sec = NULL;
14478   reginfo_sec = NULL;
14479   mdebug_sec = NULL;
14480   gptab_data_sec = NULL;
14481   gptab_bss_sec = NULL;
14482   for (o = abfd->sections; o != NULL; o = o->next)
14483     {
14484       if (strcmp (o->name, ".MIPS.abiflags") == 0)
14485         {
14486           /* We have found the .MIPS.abiflags section in the output file.
14487              Look through all the link_orders comprising it and remove them.
14488              The data is merged in _bfd_mips_elf_merge_private_bfd_data.  */
14489           for (p = o->map_head.link_order; p != NULL; p = p->next)
14490             {
14491               asection *input_section;
14492
14493               if (p->type != bfd_indirect_link_order)
14494                 {
14495                   if (p->type == bfd_data_link_order)
14496                     continue;
14497                   abort ();
14498                 }
14499
14500               input_section = p->u.indirect.section;
14501
14502               /* Hack: reset the SEC_HAS_CONTENTS flag so that
14503                  elf_link_input_bfd ignores this section.  */
14504               input_section->flags &= ~SEC_HAS_CONTENTS;
14505             }
14506
14507           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
14508           BFD_ASSERT(o->size == sizeof (Elf_External_ABIFlags_v0));
14509
14510           /* Skip this section later on (I don't think this currently
14511              matters, but someday it might).  */
14512           o->map_head.link_order = NULL;
14513
14514           abiflags_sec = o;
14515         }
14516
14517       if (strcmp (o->name, ".reginfo") == 0)
14518         {
14519           memset (&reginfo, 0, sizeof reginfo);
14520
14521           /* We have found the .reginfo section in the output file.
14522              Look through all the link_orders comprising it and merge
14523              the information together.  */
14524           for (p = o->map_head.link_order; p != NULL; p = p->next)
14525             {
14526               asection *input_section;
14527               bfd *input_bfd;
14528               Elf32_External_RegInfo ext;
14529               Elf32_RegInfo sub;
14530
14531               if (p->type != bfd_indirect_link_order)
14532                 {
14533                   if (p->type == bfd_data_link_order)
14534                     continue;
14535                   abort ();
14536                 }
14537
14538               input_section = p->u.indirect.section;
14539               input_bfd = input_section->owner;
14540
14541               if (! bfd_get_section_contents (input_bfd, input_section,
14542                                               &ext, 0, sizeof ext))
14543                 return FALSE;
14544
14545               bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub);
14546
14547               reginfo.ri_gprmask |= sub.ri_gprmask;
14548               reginfo.ri_cprmask[0] |= sub.ri_cprmask[0];
14549               reginfo.ri_cprmask[1] |= sub.ri_cprmask[1];
14550               reginfo.ri_cprmask[2] |= sub.ri_cprmask[2];
14551               reginfo.ri_cprmask[3] |= sub.ri_cprmask[3];
14552
14553               /* ri_gp_value is set by the function
14554                  mips_elf32_section_processing when the section is
14555                  finally written out.  */
14556
14557               /* Hack: reset the SEC_HAS_CONTENTS flag so that
14558                  elf_link_input_bfd ignores this section.  */
14559               input_section->flags &= ~SEC_HAS_CONTENTS;
14560             }
14561
14562           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
14563           BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo));
14564
14565           /* Skip this section later on (I don't think this currently
14566              matters, but someday it might).  */
14567           o->map_head.link_order = NULL;
14568
14569           reginfo_sec = o;
14570         }
14571
14572       if (strcmp (o->name, ".mdebug") == 0)
14573         {
14574           struct extsym_info einfo;
14575           bfd_vma last;
14576
14577           /* We have found the .mdebug section in the output file.
14578              Look through all the link_orders comprising it and merge
14579              the information together.  */
14580           symhdr->magic = swap->sym_magic;
14581           /* FIXME: What should the version stamp be?  */
14582           symhdr->vstamp = 0;
14583           symhdr->ilineMax = 0;
14584           symhdr->cbLine = 0;
14585           symhdr->idnMax = 0;
14586           symhdr->ipdMax = 0;
14587           symhdr->isymMax = 0;
14588           symhdr->ioptMax = 0;
14589           symhdr->iauxMax = 0;
14590           symhdr->issMax = 0;
14591           symhdr->issExtMax = 0;
14592           symhdr->ifdMax = 0;
14593           symhdr->crfd = 0;
14594           symhdr->iextMax = 0;
14595
14596           /* We accumulate the debugging information itself in the
14597              debug_info structure.  */
14598           debug.line = NULL;
14599           debug.external_dnr = NULL;
14600           debug.external_pdr = NULL;
14601           debug.external_sym = NULL;
14602           debug.external_opt = NULL;
14603           debug.external_aux = NULL;
14604           debug.ss = NULL;
14605           debug.ssext = debug.ssext_end = NULL;
14606           debug.external_fdr = NULL;
14607           debug.external_rfd = NULL;
14608           debug.external_ext = debug.external_ext_end = NULL;
14609
14610           mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info);
14611           if (mdebug_handle == NULL)
14612             return FALSE;
14613
14614           esym.jmptbl = 0;
14615           esym.cobol_main = 0;
14616           esym.weakext = 0;
14617           esym.reserved = 0;
14618           esym.ifd = ifdNil;
14619           esym.asym.iss = issNil;
14620           esym.asym.st = stLocal;
14621           esym.asym.reserved = 0;
14622           esym.asym.index = indexNil;
14623           last = 0;
14624           for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++)
14625             {
14626               esym.asym.sc = sc[i];
14627               s = bfd_get_section_by_name (abfd, secname[i]);
14628               if (s != NULL)
14629                 {
14630                   esym.asym.value = s->vma;
14631                   last = s->vma + s->size;
14632                 }
14633               else
14634                 esym.asym.value = last;
14635               if (!bfd_ecoff_debug_one_external (abfd, &debug, swap,
14636                                                  secname[i], &esym))
14637                 return FALSE;
14638             }
14639
14640           for (p = o->map_head.link_order; p != NULL; p = p->next)
14641             {
14642               asection *input_section;
14643               bfd *input_bfd;
14644               const struct ecoff_debug_swap *input_swap;
14645               struct ecoff_debug_info input_debug;
14646               char *eraw_src;
14647               char *eraw_end;
14648
14649               if (p->type != bfd_indirect_link_order)
14650                 {
14651                   if (p->type == bfd_data_link_order)
14652                     continue;
14653                   abort ();
14654                 }
14655
14656               input_section = p->u.indirect.section;
14657               input_bfd = input_section->owner;
14658
14659               if (!is_mips_elf (input_bfd))
14660                 {
14661                   /* I don't know what a non MIPS ELF bfd would be
14662                      doing with a .mdebug section, but I don't really
14663                      want to deal with it.  */
14664                   continue;
14665                 }
14666
14667               input_swap = (get_elf_backend_data (input_bfd)
14668                             ->elf_backend_ecoff_debug_swap);
14669
14670               BFD_ASSERT (p->size == input_section->size);
14671
14672               /* The ECOFF linking code expects that we have already
14673                  read in the debugging information and set up an
14674                  ecoff_debug_info structure, so we do that now.  */
14675               if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section,
14676                                                    &input_debug))
14677                 return FALSE;
14678
14679               if (! (bfd_ecoff_debug_accumulate
14680                      (mdebug_handle, abfd, &debug, swap, input_bfd,
14681                       &input_debug, input_swap, info)))
14682                 return FALSE;
14683
14684               /* Loop through the external symbols.  For each one with
14685                  interesting information, try to find the symbol in
14686                  the linker global hash table and save the information
14687                  for the output external symbols.  */
14688               eraw_src = input_debug.external_ext;
14689               eraw_end = (eraw_src
14690                           + (input_debug.symbolic_header.iextMax
14691                              * input_swap->external_ext_size));
14692               for (;
14693                    eraw_src < eraw_end;
14694                    eraw_src += input_swap->external_ext_size)
14695                 {
14696                   EXTR ext;
14697                   const char *name;
14698                   struct mips_elf_link_hash_entry *h;
14699
14700                   (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext);
14701                   if (ext.asym.sc == scNil
14702                       || ext.asym.sc == scUndefined
14703                       || ext.asym.sc == scSUndefined)
14704                     continue;
14705
14706                   name = input_debug.ssext + ext.asym.iss;
14707                   h = mips_elf_link_hash_lookup (mips_elf_hash_table (info),
14708                                                  name, FALSE, FALSE, TRUE);
14709                   if (h == NULL || h->esym.ifd != -2)
14710                     continue;
14711
14712                   if (ext.ifd != -1)
14713                     {
14714                       BFD_ASSERT (ext.ifd
14715                                   < input_debug.symbolic_header.ifdMax);
14716                       ext.ifd = input_debug.ifdmap[ext.ifd];
14717                     }
14718
14719                   h->esym = ext;
14720                 }
14721
14722               /* Free up the information we just read.  */
14723               free (input_debug.line);
14724               free (input_debug.external_dnr);
14725               free (input_debug.external_pdr);
14726               free (input_debug.external_sym);
14727               free (input_debug.external_opt);
14728               free (input_debug.external_aux);
14729               free (input_debug.ss);
14730               free (input_debug.ssext);
14731               free (input_debug.external_fdr);
14732               free (input_debug.external_rfd);
14733               free (input_debug.external_ext);
14734
14735               /* Hack: reset the SEC_HAS_CONTENTS flag so that
14736                  elf_link_input_bfd ignores this section.  */
14737               input_section->flags &= ~SEC_HAS_CONTENTS;
14738             }
14739
14740           if (SGI_COMPAT (abfd) && bfd_link_pic (info))
14741             {
14742               /* Create .rtproc section.  */
14743               rtproc_sec = bfd_get_linker_section (abfd, ".rtproc");
14744               if (rtproc_sec == NULL)
14745                 {
14746                   flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
14747                                     | SEC_LINKER_CREATED | SEC_READONLY);
14748
14749                   rtproc_sec = bfd_make_section_anyway_with_flags (abfd,
14750                                                                    ".rtproc",
14751                                                                    flags);
14752                   if (rtproc_sec == NULL
14753                       || ! bfd_set_section_alignment (abfd, rtproc_sec, 4))
14754                     return FALSE;
14755                 }
14756
14757               if (! mips_elf_create_procedure_table (mdebug_handle, abfd,
14758                                                      info, rtproc_sec,
14759                                                      &debug))
14760                 return FALSE;
14761             }
14762
14763           /* Build the external symbol information.  */
14764           einfo.abfd = abfd;
14765           einfo.info = info;
14766           einfo.debug = &debug;
14767           einfo.swap = swap;
14768           einfo.failed = FALSE;
14769           mips_elf_link_hash_traverse (mips_elf_hash_table (info),
14770                                        mips_elf_output_extsym, &einfo);
14771           if (einfo.failed)
14772             return FALSE;
14773
14774           /* Set the size of the .mdebug section.  */
14775           o->size = bfd_ecoff_debug_size (abfd, &debug, swap);
14776
14777           /* Skip this section later on (I don't think this currently
14778              matters, but someday it might).  */
14779           o->map_head.link_order = NULL;
14780
14781           mdebug_sec = o;
14782         }
14783
14784       if (CONST_STRNEQ (o->name, ".gptab."))
14785         {
14786           const char *subname;
14787           unsigned int c;
14788           Elf32_gptab *tab;
14789           Elf32_External_gptab *ext_tab;
14790           unsigned int j;
14791
14792           /* The .gptab.sdata and .gptab.sbss sections hold
14793              information describing how the small data area would
14794              change depending upon the -G switch.  These sections
14795              not used in executables files.  */
14796           if (! bfd_link_relocatable (info))
14797             {
14798               for (p = o->map_head.link_order; p != NULL; p = p->next)
14799                 {
14800                   asection *input_section;
14801
14802                   if (p->type != bfd_indirect_link_order)
14803                     {
14804                       if (p->type == bfd_data_link_order)
14805                         continue;
14806                       abort ();
14807                     }
14808
14809                   input_section = p->u.indirect.section;
14810
14811                   /* Hack: reset the SEC_HAS_CONTENTS flag so that
14812                      elf_link_input_bfd ignores this section.  */
14813                   input_section->flags &= ~SEC_HAS_CONTENTS;
14814                 }
14815
14816               /* Skip this section later on (I don't think this
14817                  currently matters, but someday it might).  */
14818               o->map_head.link_order = NULL;
14819
14820               /* Really remove the section.  */
14821               bfd_section_list_remove (abfd, o);
14822               --abfd->section_count;
14823
14824               continue;
14825             }
14826
14827           /* There is one gptab for initialized data, and one for
14828              uninitialized data.  */
14829           if (strcmp (o->name, ".gptab.sdata") == 0)
14830             gptab_data_sec = o;
14831           else if (strcmp (o->name, ".gptab.sbss") == 0)
14832             gptab_bss_sec = o;
14833           else
14834             {
14835               _bfd_error_handler
14836                 /* xgettext:c-format */
14837                 (_("%s: illegal section name `%s'"),
14838                  bfd_get_filename (abfd), o->name);
14839               bfd_set_error (bfd_error_nonrepresentable_section);
14840               return FALSE;
14841             }
14842
14843           /* The linker script always combines .gptab.data and
14844              .gptab.sdata into .gptab.sdata, and likewise for
14845              .gptab.bss and .gptab.sbss.  It is possible that there is
14846              no .sdata or .sbss section in the output file, in which
14847              case we must change the name of the output section.  */
14848           subname = o->name + sizeof ".gptab" - 1;
14849           if (bfd_get_section_by_name (abfd, subname) == NULL)
14850             {
14851               if (o == gptab_data_sec)
14852                 o->name = ".gptab.data";
14853               else
14854                 o->name = ".gptab.bss";
14855               subname = o->name + sizeof ".gptab" - 1;
14856               BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL);
14857             }
14858
14859           /* Set up the first entry.  */
14860           c = 1;
14861           amt = c * sizeof (Elf32_gptab);
14862           tab = bfd_malloc (amt);
14863           if (tab == NULL)
14864             return FALSE;
14865           tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd);
14866           tab[0].gt_header.gt_unused = 0;
14867
14868           /* Combine the input sections.  */
14869           for (p = o->map_head.link_order; p != NULL; p = p->next)
14870             {
14871               asection *input_section;
14872               bfd *input_bfd;
14873               bfd_size_type size;
14874               unsigned long last;
14875               bfd_size_type gpentry;
14876
14877               if (p->type != bfd_indirect_link_order)
14878                 {
14879                   if (p->type == bfd_data_link_order)
14880                     continue;
14881                   abort ();
14882                 }
14883
14884               input_section = p->u.indirect.section;
14885               input_bfd = input_section->owner;
14886
14887               /* Combine the gptab entries for this input section one
14888                  by one.  We know that the input gptab entries are
14889                  sorted by ascending -G value.  */
14890               size = input_section->size;
14891               last = 0;
14892               for (gpentry = sizeof (Elf32_External_gptab);
14893                    gpentry < size;
14894                    gpentry += sizeof (Elf32_External_gptab))
14895                 {
14896                   Elf32_External_gptab ext_gptab;
14897                   Elf32_gptab int_gptab;
14898                   unsigned long val;
14899                   unsigned long add;
14900                   bfd_boolean exact;
14901                   unsigned int look;
14902
14903                   if (! (bfd_get_section_contents
14904                          (input_bfd, input_section, &ext_gptab, gpentry,
14905                           sizeof (Elf32_External_gptab))))
14906                     {
14907                       free (tab);
14908                       return FALSE;
14909                     }
14910
14911                   bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab,
14912                                                 &int_gptab);
14913                   val = int_gptab.gt_entry.gt_g_value;
14914                   add = int_gptab.gt_entry.gt_bytes - last;
14915
14916                   exact = FALSE;
14917                   for (look = 1; look < c; look++)
14918                     {
14919                       if (tab[look].gt_entry.gt_g_value >= val)
14920                         tab[look].gt_entry.gt_bytes += add;
14921
14922                       if (tab[look].gt_entry.gt_g_value == val)
14923                         exact = TRUE;
14924                     }
14925
14926                   if (! exact)
14927                     {
14928                       Elf32_gptab *new_tab;
14929                       unsigned int max;
14930
14931                       /* We need a new table entry.  */
14932                       amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab);
14933                       new_tab = bfd_realloc (tab, amt);
14934                       if (new_tab == NULL)
14935                         {
14936                           free (tab);
14937                           return FALSE;
14938                         }
14939                       tab = new_tab;
14940                       tab[c].gt_entry.gt_g_value = val;
14941                       tab[c].gt_entry.gt_bytes = add;
14942
14943                       /* Merge in the size for the next smallest -G
14944                          value, since that will be implied by this new
14945                          value.  */
14946                       max = 0;
14947                       for (look = 1; look < c; look++)
14948                         {
14949                           if (tab[look].gt_entry.gt_g_value < val
14950                               && (max == 0
14951                                   || (tab[look].gt_entry.gt_g_value
14952                                       > tab[max].gt_entry.gt_g_value)))
14953                             max = look;
14954                         }
14955                       if (max != 0)
14956                         tab[c].gt_entry.gt_bytes +=
14957                           tab[max].gt_entry.gt_bytes;
14958
14959                       ++c;
14960                     }
14961
14962                   last = int_gptab.gt_entry.gt_bytes;
14963                 }
14964
14965               /* Hack: reset the SEC_HAS_CONTENTS flag so that
14966                  elf_link_input_bfd ignores this section.  */
14967               input_section->flags &= ~SEC_HAS_CONTENTS;
14968             }
14969
14970           /* The table must be sorted by -G value.  */
14971           if (c > 2)
14972             qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare);
14973
14974           /* Swap out the table.  */
14975           amt = (bfd_size_type) c * sizeof (Elf32_External_gptab);
14976           ext_tab = bfd_alloc (abfd, amt);
14977           if (ext_tab == NULL)
14978             {
14979               free (tab);
14980               return FALSE;
14981             }
14982
14983           for (j = 0; j < c; j++)
14984             bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j);
14985           free (tab);
14986
14987           o->size = c * sizeof (Elf32_External_gptab);
14988           o->contents = (bfd_byte *) ext_tab;
14989
14990           /* Skip this section later on (I don't think this currently
14991              matters, but someday it might).  */
14992           o->map_head.link_order = NULL;
14993         }
14994     }
14995
14996   /* Invoke the regular ELF backend linker to do all the work.  */
14997   if (!bfd_elf_final_link (abfd, info))
14998     return FALSE;
14999
15000   /* Now write out the computed sections.  */
15001
15002   if (abiflags_sec != NULL)
15003     {
15004       Elf_External_ABIFlags_v0 ext;
15005       Elf_Internal_ABIFlags_v0 *abiflags;
15006
15007       abiflags = &mips_elf_tdata (abfd)->abiflags;
15008
15009       /* Set up the abiflags if no valid input sections were found.  */
15010       if (!mips_elf_tdata (abfd)->abiflags_valid)
15011         {
15012           infer_mips_abiflags (abfd, abiflags);
15013           mips_elf_tdata (abfd)->abiflags_valid = TRUE;
15014         }
15015       bfd_mips_elf_swap_abiflags_v0_out (abfd, abiflags, &ext);
15016       if (! bfd_set_section_contents (abfd, abiflags_sec, &ext, 0, sizeof ext))
15017         return FALSE;
15018     }
15019
15020   if (reginfo_sec != NULL)
15021     {
15022       Elf32_External_RegInfo ext;
15023
15024       bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext);
15025       if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext))
15026         return FALSE;
15027     }
15028
15029   if (mdebug_sec != NULL)
15030     {
15031       BFD_ASSERT (abfd->output_has_begun);
15032       if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug,
15033                                                swap, info,
15034                                                mdebug_sec->filepos))
15035         return FALSE;
15036
15037       bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info);
15038     }
15039
15040   if (gptab_data_sec != NULL)
15041     {
15042       if (! bfd_set_section_contents (abfd, gptab_data_sec,
15043                                       gptab_data_sec->contents,
15044                                       0, gptab_data_sec->size))
15045         return FALSE;
15046     }
15047
15048   if (gptab_bss_sec != NULL)
15049     {
15050       if (! bfd_set_section_contents (abfd, gptab_bss_sec,
15051                                       gptab_bss_sec->contents,
15052                                       0, gptab_bss_sec->size))
15053         return FALSE;
15054     }
15055
15056   if (SGI_COMPAT (abfd))
15057     {
15058       rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
15059       if (rtproc_sec != NULL)
15060         {
15061           if (! bfd_set_section_contents (abfd, rtproc_sec,
15062                                           rtproc_sec->contents,
15063                                           0, rtproc_sec->size))
15064             return FALSE;
15065         }
15066     }
15067
15068   return TRUE;
15069 }
15070 \f
15071 /* Merge object file header flags from IBFD into OBFD.  Raise an error
15072    if there are conflicting settings.  */
15073
15074 static bfd_boolean
15075 mips_elf_merge_obj_e_flags (bfd *ibfd, struct bfd_link_info *info)
15076 {
15077   bfd *obfd = info->output_bfd;
15078   struct mips_elf_obj_tdata *out_tdata = mips_elf_tdata (obfd);
15079   flagword old_flags;
15080   flagword new_flags;
15081   bfd_boolean ok;
15082
15083   new_flags = elf_elfheader (ibfd)->e_flags;
15084   elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER;
15085   old_flags = elf_elfheader (obfd)->e_flags;
15086
15087   /* Check flag compatibility.  */
15088
15089   new_flags &= ~EF_MIPS_NOREORDER;
15090   old_flags &= ~EF_MIPS_NOREORDER;
15091
15092   /* Some IRIX 6 BSD-compatibility objects have this bit set.  It
15093      doesn't seem to matter.  */
15094   new_flags &= ~EF_MIPS_XGOT;
15095   old_flags &= ~EF_MIPS_XGOT;
15096
15097   /* MIPSpro generates ucode info in n64 objects.  Again, we should
15098      just be able to ignore this.  */
15099   new_flags &= ~EF_MIPS_UCODE;
15100   old_flags &= ~EF_MIPS_UCODE;
15101
15102   /* DSOs should only be linked with CPIC code.  */
15103   if ((ibfd->flags & DYNAMIC) != 0)
15104     new_flags |= EF_MIPS_PIC | EF_MIPS_CPIC;
15105
15106   if (new_flags == old_flags)
15107     return TRUE;
15108
15109   ok = TRUE;
15110
15111   if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)
15112       != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0))
15113     {
15114       _bfd_error_handler
15115         (_("%B: warning: linking abicalls files with non-abicalls files"),
15116          ibfd);
15117       ok = TRUE;
15118     }
15119
15120   if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC))
15121     elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC;
15122   if (! (new_flags & EF_MIPS_PIC))
15123     elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC;
15124
15125   new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
15126   old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
15127
15128   /* Compare the ISAs.  */
15129   if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags))
15130     {
15131       _bfd_error_handler
15132         (_("%B: linking 32-bit code with 64-bit code"),
15133          ibfd);
15134       ok = FALSE;
15135     }
15136   else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd)))
15137     {
15138       /* OBFD's ISA isn't the same as, or an extension of, IBFD's.  */
15139       if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd)))
15140         {
15141           /* Copy the architecture info from IBFD to OBFD.  Also copy
15142              the 32-bit flag (if set) so that we continue to recognise
15143              OBFD as a 32-bit binary.  */
15144           bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd));
15145           elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
15146           elf_elfheader (obfd)->e_flags
15147             |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
15148
15149           /* Update the ABI flags isa_level, isa_rev, isa_ext fields.  */
15150           update_mips_abiflags_isa (obfd, &out_tdata->abiflags);
15151
15152           /* Copy across the ABI flags if OBFD doesn't use them
15153              and if that was what caused us to treat IBFD as 32-bit.  */
15154           if ((old_flags & EF_MIPS_ABI) == 0
15155               && mips_32bit_flags_p (new_flags)
15156               && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI))
15157             elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI;
15158         }
15159       else
15160         {
15161           /* The ISAs aren't compatible.  */
15162           _bfd_error_handler
15163             /* xgettext:c-format */
15164             (_("%B: linking %s module with previous %s modules"),
15165              ibfd,
15166              bfd_printable_name (ibfd),
15167              bfd_printable_name (obfd));
15168           ok = FALSE;
15169         }
15170     }
15171
15172   new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
15173   old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
15174
15175   /* Compare ABIs.  The 64-bit ABI does not use EF_MIPS_ABI.  But, it
15176      does set EI_CLASS differently from any 32-bit ABI.  */
15177   if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI)
15178       || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
15179           != elf_elfheader (obfd)->e_ident[EI_CLASS]))
15180     {
15181       /* Only error if both are set (to different values).  */
15182       if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI))
15183           || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
15184               != elf_elfheader (obfd)->e_ident[EI_CLASS]))
15185         {
15186           _bfd_error_handler
15187             /* xgettext:c-format */
15188             (_("%B: ABI mismatch: linking %s module with previous %s modules"),
15189              ibfd,
15190              elf_mips_abi_name (ibfd),
15191              elf_mips_abi_name (obfd));
15192           ok = FALSE;
15193         }
15194       new_flags &= ~EF_MIPS_ABI;
15195       old_flags &= ~EF_MIPS_ABI;
15196     }
15197
15198   /* Compare ASEs.  Forbid linking MIPS16 and microMIPS ASE modules together
15199      and allow arbitrary mixing of the remaining ASEs (retain the union).  */
15200   if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE))
15201     {
15202       int old_micro = old_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
15203       int new_micro = new_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
15204       int old_m16 = old_flags & EF_MIPS_ARCH_ASE_M16;
15205       int new_m16 = new_flags & EF_MIPS_ARCH_ASE_M16;
15206       int micro_mis = old_m16 && new_micro;
15207       int m16_mis = old_micro && new_m16;
15208
15209       if (m16_mis || micro_mis)
15210         {
15211           _bfd_error_handler
15212             /* xgettext:c-format */
15213             (_("%B: ASE mismatch: linking %s module with previous %s modules"),
15214              ibfd,
15215              m16_mis ? "MIPS16" : "microMIPS",
15216              m16_mis ? "microMIPS" : "MIPS16");
15217           ok = FALSE;
15218         }
15219
15220       elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE;
15221
15222       new_flags &= ~ EF_MIPS_ARCH_ASE;
15223       old_flags &= ~ EF_MIPS_ARCH_ASE;
15224     }
15225
15226   /* Compare NaN encodings.  */
15227   if ((new_flags & EF_MIPS_NAN2008) != (old_flags & EF_MIPS_NAN2008))
15228     {
15229       /* xgettext:c-format */
15230       _bfd_error_handler (_("%B: linking %s module with previous %s modules"),
15231                           ibfd,
15232                           (new_flags & EF_MIPS_NAN2008
15233                            ? "-mnan=2008" : "-mnan=legacy"),
15234                           (old_flags & EF_MIPS_NAN2008
15235                            ? "-mnan=2008" : "-mnan=legacy"));
15236       ok = FALSE;
15237       new_flags &= ~EF_MIPS_NAN2008;
15238       old_flags &= ~EF_MIPS_NAN2008;
15239     }
15240
15241   /* Compare FP64 state.  */
15242   if ((new_flags & EF_MIPS_FP64) != (old_flags & EF_MIPS_FP64))
15243     {
15244       /* xgettext:c-format */
15245       _bfd_error_handler (_("%B: linking %s module with previous %s modules"),
15246                           ibfd,
15247                           (new_flags & EF_MIPS_FP64
15248                            ? "-mfp64" : "-mfp32"),
15249                           (old_flags & EF_MIPS_FP64
15250                            ? "-mfp64" : "-mfp32"));
15251       ok = FALSE;
15252       new_flags &= ~EF_MIPS_FP64;
15253       old_flags &= ~EF_MIPS_FP64;
15254     }
15255
15256   /* Warn about any other mismatches */
15257   if (new_flags != old_flags)
15258     {
15259       /* xgettext:c-format */
15260       _bfd_error_handler
15261         (_("%B: uses different e_flags (0x%lx) fields than previous modules "
15262            "(0x%lx)"),
15263          ibfd, (unsigned long) new_flags,
15264          (unsigned long) old_flags);
15265       ok = FALSE;
15266     }
15267
15268   return ok;
15269 }
15270
15271 /* Merge object attributes from IBFD into OBFD.  Raise an error if
15272    there are conflicting attributes.  */
15273 static bfd_boolean
15274 mips_elf_merge_obj_attributes (bfd *ibfd, struct bfd_link_info *info)
15275 {
15276   bfd *obfd = info->output_bfd;
15277   obj_attribute *in_attr;
15278   obj_attribute *out_attr;
15279   bfd *abi_fp_bfd;
15280   bfd *abi_msa_bfd;
15281
15282   abi_fp_bfd = mips_elf_tdata (obfd)->abi_fp_bfd;
15283   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
15284   if (!abi_fp_bfd && in_attr[Tag_GNU_MIPS_ABI_FP].i != Val_GNU_MIPS_ABI_FP_ANY)
15285     mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
15286
15287   abi_msa_bfd = mips_elf_tdata (obfd)->abi_msa_bfd;
15288   if (!abi_msa_bfd
15289       && in_attr[Tag_GNU_MIPS_ABI_MSA].i != Val_GNU_MIPS_ABI_MSA_ANY)
15290     mips_elf_tdata (obfd)->abi_msa_bfd = ibfd;
15291
15292   if (!elf_known_obj_attributes_proc (obfd)[0].i)
15293     {
15294       /* This is the first object.  Copy the attributes.  */
15295       _bfd_elf_copy_obj_attributes (ibfd, obfd);
15296
15297       /* Use the Tag_null value to indicate the attributes have been
15298          initialized.  */
15299       elf_known_obj_attributes_proc (obfd)[0].i = 1;
15300
15301       return TRUE;
15302     }
15303
15304   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
15305      non-conflicting ones.  */
15306   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
15307   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
15308     {
15309       int out_fp, in_fp;
15310
15311       out_fp = out_attr[Tag_GNU_MIPS_ABI_FP].i;
15312       in_fp = in_attr[Tag_GNU_MIPS_ABI_FP].i;
15313       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
15314       if (out_fp == Val_GNU_MIPS_ABI_FP_ANY)
15315         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_fp;
15316       else if (out_fp == Val_GNU_MIPS_ABI_FP_XX
15317                && (in_fp == Val_GNU_MIPS_ABI_FP_DOUBLE
15318                    || in_fp == Val_GNU_MIPS_ABI_FP_64
15319                    || in_fp == Val_GNU_MIPS_ABI_FP_64A))
15320         {
15321           mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
15322           out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
15323         }
15324       else if (in_fp == Val_GNU_MIPS_ABI_FP_XX
15325                && (out_fp == Val_GNU_MIPS_ABI_FP_DOUBLE
15326                    || out_fp == Val_GNU_MIPS_ABI_FP_64
15327                    || out_fp == Val_GNU_MIPS_ABI_FP_64A))
15328         /* Keep the current setting.  */;
15329       else if (out_fp == Val_GNU_MIPS_ABI_FP_64A
15330                && in_fp == Val_GNU_MIPS_ABI_FP_64)
15331         {
15332           mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
15333           out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
15334         }
15335       else if (in_fp == Val_GNU_MIPS_ABI_FP_64A
15336                && out_fp == Val_GNU_MIPS_ABI_FP_64)
15337         /* Keep the current setting.  */;
15338       else if (in_fp != Val_GNU_MIPS_ABI_FP_ANY)
15339         {
15340           const char *out_string, *in_string;
15341
15342           out_string = _bfd_mips_fp_abi_string (out_fp);
15343           in_string = _bfd_mips_fp_abi_string (in_fp);
15344           /* First warn about cases involving unrecognised ABIs.  */
15345           if (!out_string && !in_string)
15346             /* xgettext:c-format */
15347             _bfd_error_handler
15348               (_("Warning: %B uses unknown floating point ABI %d "
15349                  "(set by %B), %B uses unknown floating point ABI %d"),
15350                obfd, abi_fp_bfd, ibfd, out_fp, in_fp);
15351           else if (!out_string)
15352             _bfd_error_handler
15353               /* xgettext:c-format */
15354               (_("Warning: %B uses unknown floating point ABI %d "
15355                  "(set by %B), %B uses %s"),
15356                obfd, abi_fp_bfd, ibfd, out_fp, in_string);
15357           else if (!in_string)
15358             _bfd_error_handler
15359               /* xgettext:c-format */
15360               (_("Warning: %B uses %s (set by %B), "
15361                  "%B uses unknown floating point ABI %d"),
15362                obfd, abi_fp_bfd, ibfd, out_string, in_fp);
15363           else
15364             {
15365               /* If one of the bfds is soft-float, the other must be
15366                  hard-float.  The exact choice of hard-float ABI isn't
15367                  really relevant to the error message.  */
15368               if (in_fp == Val_GNU_MIPS_ABI_FP_SOFT)
15369                 out_string = "-mhard-float";
15370               else if (out_fp == Val_GNU_MIPS_ABI_FP_SOFT)
15371                 in_string = "-mhard-float";
15372               _bfd_error_handler
15373                 /* xgettext:c-format */
15374                 (_("Warning: %B uses %s (set by %B), %B uses %s"),
15375                  obfd, abi_fp_bfd, ibfd, out_string, in_string);
15376             }
15377         }
15378     }
15379
15380   /* Check for conflicting Tag_GNU_MIPS_ABI_MSA attributes and merge
15381      non-conflicting ones.  */
15382   if (in_attr[Tag_GNU_MIPS_ABI_MSA].i != out_attr[Tag_GNU_MIPS_ABI_MSA].i)
15383     {
15384       out_attr[Tag_GNU_MIPS_ABI_MSA].type = 1;
15385       if (out_attr[Tag_GNU_MIPS_ABI_MSA].i == Val_GNU_MIPS_ABI_MSA_ANY)
15386         out_attr[Tag_GNU_MIPS_ABI_MSA].i = in_attr[Tag_GNU_MIPS_ABI_MSA].i;
15387       else if (in_attr[Tag_GNU_MIPS_ABI_MSA].i != Val_GNU_MIPS_ABI_MSA_ANY)
15388         switch (out_attr[Tag_GNU_MIPS_ABI_MSA].i)
15389           {
15390           case Val_GNU_MIPS_ABI_MSA_128:
15391             _bfd_error_handler
15392               /* xgettext:c-format */
15393               (_("Warning: %B uses %s (set by %B), "
15394                  "%B uses unknown MSA ABI %d"),
15395                obfd, abi_msa_bfd, ibfd,
15396                "-mmsa", in_attr[Tag_GNU_MIPS_ABI_MSA].i);
15397             break;
15398
15399           default:
15400             switch (in_attr[Tag_GNU_MIPS_ABI_MSA].i)
15401               {
15402               case Val_GNU_MIPS_ABI_MSA_128:
15403                 _bfd_error_handler
15404                   /* xgettext:c-format */
15405                   (_("Warning: %B uses unknown MSA ABI %d "
15406                      "(set by %B), %B uses %s"),
15407                      obfd, abi_msa_bfd, ibfd,
15408                      out_attr[Tag_GNU_MIPS_ABI_MSA].i, "-mmsa");
15409                   break;
15410
15411               default:
15412                 _bfd_error_handler
15413                   /* xgettext:c-format */
15414                   (_("Warning: %B uses unknown MSA ABI %d "
15415                      "(set by %B), %B uses unknown MSA ABI %d"),
15416                    obfd, abi_msa_bfd, ibfd,
15417                    out_attr[Tag_GNU_MIPS_ABI_MSA].i,
15418                    in_attr[Tag_GNU_MIPS_ABI_MSA].i);
15419                 break;
15420               }
15421           }
15422     }
15423
15424   /* Merge Tag_compatibility attributes and any common GNU ones.  */
15425   return _bfd_elf_merge_object_attributes (ibfd, info);
15426 }
15427
15428 /* Merge object ABI flags from IBFD into OBFD.  Raise an error if
15429    there are conflicting settings.  */
15430
15431 static bfd_boolean
15432 mips_elf_merge_obj_abiflags (bfd *ibfd, bfd *obfd)
15433 {
15434   obj_attribute *out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
15435   struct mips_elf_obj_tdata *out_tdata = mips_elf_tdata (obfd);
15436   struct mips_elf_obj_tdata *in_tdata = mips_elf_tdata (ibfd);
15437
15438   /* Update the output abiflags fp_abi using the computed fp_abi.  */
15439   out_tdata->abiflags.fp_abi = out_attr[Tag_GNU_MIPS_ABI_FP].i;
15440
15441 #define max(a, b) ((a) > (b) ? (a) : (b))
15442   /* Merge abiflags.  */
15443   out_tdata->abiflags.isa_level = max (out_tdata->abiflags.isa_level,
15444                                        in_tdata->abiflags.isa_level);
15445   out_tdata->abiflags.isa_rev = max (out_tdata->abiflags.isa_rev,
15446                                      in_tdata->abiflags.isa_rev);
15447   out_tdata->abiflags.gpr_size = max (out_tdata->abiflags.gpr_size,
15448                                       in_tdata->abiflags.gpr_size);
15449   out_tdata->abiflags.cpr1_size = max (out_tdata->abiflags.cpr1_size,
15450                                        in_tdata->abiflags.cpr1_size);
15451   out_tdata->abiflags.cpr2_size = max (out_tdata->abiflags.cpr2_size,
15452                                        in_tdata->abiflags.cpr2_size);
15453 #undef max
15454   out_tdata->abiflags.ases |= in_tdata->abiflags.ases;
15455   out_tdata->abiflags.flags1 |= in_tdata->abiflags.flags1;
15456
15457   return TRUE;
15458 }
15459
15460 /* Merge backend specific data from an object file to the output
15461    object file when linking.  */
15462
15463 bfd_boolean
15464 _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, struct bfd_link_info *info)
15465 {
15466   bfd *obfd = info->output_bfd;
15467   struct mips_elf_obj_tdata *out_tdata;
15468   struct mips_elf_obj_tdata *in_tdata;
15469   bfd_boolean null_input_bfd = TRUE;
15470   asection *sec;
15471   bfd_boolean ok;
15472
15473   /* Check if we have the same endianness.  */
15474   if (! _bfd_generic_verify_endian_match (ibfd, info))
15475     {
15476       _bfd_error_handler
15477         (_("%B: endianness incompatible with that of the selected emulation"),
15478          ibfd);
15479       return FALSE;
15480     }
15481
15482   if (!is_mips_elf (ibfd) || !is_mips_elf (obfd))
15483     return TRUE;
15484
15485   in_tdata = mips_elf_tdata (ibfd);
15486   out_tdata = mips_elf_tdata (obfd);
15487
15488   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
15489     {
15490       _bfd_error_handler
15491         (_("%B: ABI is incompatible with that of the selected emulation"),
15492          ibfd);
15493       return FALSE;
15494     }
15495
15496   /* Check to see if the input BFD actually contains any sections.  If not,
15497      then it has no attributes, and its flags may not have been initialized
15498      either, but it cannot actually cause any incompatibility.  */
15499   for (sec = ibfd->sections; sec != NULL; sec = sec->next)
15500     {
15501       /* Ignore synthetic sections and empty .text, .data and .bss sections
15502          which are automatically generated by gas.  Also ignore fake
15503          (s)common sections, since merely defining a common symbol does
15504          not affect compatibility.  */
15505       if ((sec->flags & SEC_IS_COMMON) == 0
15506           && strcmp (sec->name, ".reginfo")
15507           && strcmp (sec->name, ".mdebug")
15508           && (sec->size != 0
15509               || (strcmp (sec->name, ".text")
15510                   && strcmp (sec->name, ".data")
15511                   && strcmp (sec->name, ".bss"))))
15512         {
15513           null_input_bfd = FALSE;
15514           break;
15515         }
15516     }
15517   if (null_input_bfd)
15518     return TRUE;
15519
15520   /* Populate abiflags using existing information.  */
15521   if (in_tdata->abiflags_valid)
15522     {
15523       obj_attribute *in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
15524       Elf_Internal_ABIFlags_v0 in_abiflags;
15525       Elf_Internal_ABIFlags_v0 abiflags;
15526
15527       /* Set up the FP ABI attribute from the abiflags if it is not already
15528          set.  */
15529       if (in_attr[Tag_GNU_MIPS_ABI_FP].i == Val_GNU_MIPS_ABI_FP_ANY)
15530         in_attr[Tag_GNU_MIPS_ABI_FP].i = in_tdata->abiflags.fp_abi;
15531
15532       infer_mips_abiflags (ibfd, &abiflags);
15533       in_abiflags = in_tdata->abiflags;
15534
15535       /* It is not possible to infer the correct ISA revision
15536          for R3 or R5 so drop down to R2 for the checks.  */
15537       if (in_abiflags.isa_rev == 3 || in_abiflags.isa_rev == 5)
15538         in_abiflags.isa_rev = 2;
15539
15540       if (LEVEL_REV (in_abiflags.isa_level, in_abiflags.isa_rev)
15541           < LEVEL_REV (abiflags.isa_level, abiflags.isa_rev))
15542         _bfd_error_handler
15543           (_("%B: warning: Inconsistent ISA between e_flags and "
15544              ".MIPS.abiflags"), ibfd);
15545       if (abiflags.fp_abi != Val_GNU_MIPS_ABI_FP_ANY
15546           && in_abiflags.fp_abi != abiflags.fp_abi)
15547         _bfd_error_handler
15548           (_("%B: warning: Inconsistent FP ABI between .gnu.attributes and "
15549              ".MIPS.abiflags"), ibfd);
15550       if ((in_abiflags.ases & abiflags.ases) != abiflags.ases)
15551         _bfd_error_handler
15552           (_("%B: warning: Inconsistent ASEs between e_flags and "
15553              ".MIPS.abiflags"), ibfd);
15554       /* The isa_ext is allowed to be an extension of what can be inferred
15555          from e_flags.  */
15556       if (!mips_mach_extends_p (bfd_mips_isa_ext_mach (abiflags.isa_ext),
15557                                 bfd_mips_isa_ext_mach (in_abiflags.isa_ext)))
15558         _bfd_error_handler
15559           (_("%B: warning: Inconsistent ISA extensions between e_flags and "
15560              ".MIPS.abiflags"), ibfd);
15561       if (in_abiflags.flags2 != 0)
15562         _bfd_error_handler
15563           (_("%B: warning: Unexpected flag in the flags2 field of "
15564              ".MIPS.abiflags (0x%lx)"), ibfd,
15565            (unsigned long) in_abiflags.flags2);
15566     }
15567   else
15568     {
15569       infer_mips_abiflags (ibfd, &in_tdata->abiflags);
15570       in_tdata->abiflags_valid = TRUE;
15571     }
15572
15573   if (!out_tdata->abiflags_valid)
15574     {
15575       /* Copy input abiflags if output abiflags are not already valid.  */
15576       out_tdata->abiflags = in_tdata->abiflags;
15577       out_tdata->abiflags_valid = TRUE;
15578     }
15579
15580   if (! elf_flags_init (obfd))
15581     {
15582       elf_flags_init (obfd) = TRUE;
15583       elf_elfheader (obfd)->e_flags = elf_elfheader (ibfd)->e_flags;
15584       elf_elfheader (obfd)->e_ident[EI_CLASS]
15585         = elf_elfheader (ibfd)->e_ident[EI_CLASS];
15586
15587       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
15588           && (bfd_get_arch_info (obfd)->the_default
15589               || mips_mach_extends_p (bfd_get_mach (obfd),
15590                                       bfd_get_mach (ibfd))))
15591         {
15592           if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
15593                                    bfd_get_mach (ibfd)))
15594             return FALSE;
15595
15596           /* Update the ABI flags isa_level, isa_rev and isa_ext fields.  */
15597           update_mips_abiflags_isa (obfd, &out_tdata->abiflags);
15598         }
15599
15600       ok = TRUE;
15601     }
15602   else
15603     ok = mips_elf_merge_obj_e_flags (ibfd, info);
15604
15605   ok = mips_elf_merge_obj_attributes (ibfd, info) && ok;
15606
15607   ok = mips_elf_merge_obj_abiflags (ibfd, obfd) && ok;
15608
15609   if (!ok)
15610     {
15611       bfd_set_error (bfd_error_bad_value);
15612       return FALSE;
15613     }
15614
15615   return TRUE;
15616 }
15617
15618 /* Function to keep MIPS specific file flags like as EF_MIPS_PIC.  */
15619
15620 bfd_boolean
15621 _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags)
15622 {
15623   BFD_ASSERT (!elf_flags_init (abfd)
15624               || elf_elfheader (abfd)->e_flags == flags);
15625
15626   elf_elfheader (abfd)->e_flags = flags;
15627   elf_flags_init (abfd) = TRUE;
15628   return TRUE;
15629 }
15630
15631 char *
15632 _bfd_mips_elf_get_target_dtag (bfd_vma dtag)
15633 {
15634   switch (dtag)
15635     {
15636     default: return "";
15637     case DT_MIPS_RLD_VERSION:
15638       return "MIPS_RLD_VERSION";
15639     case DT_MIPS_TIME_STAMP:
15640       return "MIPS_TIME_STAMP";
15641     case DT_MIPS_ICHECKSUM:
15642       return "MIPS_ICHECKSUM";
15643     case DT_MIPS_IVERSION:
15644       return "MIPS_IVERSION";
15645     case DT_MIPS_FLAGS:
15646       return "MIPS_FLAGS";
15647     case DT_MIPS_BASE_ADDRESS:
15648       return "MIPS_BASE_ADDRESS";
15649     case DT_MIPS_MSYM:
15650       return "MIPS_MSYM";
15651     case DT_MIPS_CONFLICT:
15652       return "MIPS_CONFLICT";
15653     case DT_MIPS_LIBLIST:
15654       return "MIPS_LIBLIST";
15655     case DT_MIPS_LOCAL_GOTNO:
15656       return "MIPS_LOCAL_GOTNO";
15657     case DT_MIPS_CONFLICTNO:
15658       return "MIPS_CONFLICTNO";
15659     case DT_MIPS_LIBLISTNO:
15660       return "MIPS_LIBLISTNO";
15661     case DT_MIPS_SYMTABNO:
15662       return "MIPS_SYMTABNO";
15663     case DT_MIPS_UNREFEXTNO:
15664       return "MIPS_UNREFEXTNO";
15665     case DT_MIPS_GOTSYM:
15666       return "MIPS_GOTSYM";
15667     case DT_MIPS_HIPAGENO:
15668       return "MIPS_HIPAGENO";
15669     case DT_MIPS_RLD_MAP:
15670       return "MIPS_RLD_MAP";
15671     case DT_MIPS_RLD_MAP_REL:
15672       return "MIPS_RLD_MAP_REL";
15673     case DT_MIPS_DELTA_CLASS:
15674       return "MIPS_DELTA_CLASS";
15675     case DT_MIPS_DELTA_CLASS_NO:
15676       return "MIPS_DELTA_CLASS_NO";
15677     case DT_MIPS_DELTA_INSTANCE:
15678       return "MIPS_DELTA_INSTANCE";
15679     case DT_MIPS_DELTA_INSTANCE_NO:
15680       return "MIPS_DELTA_INSTANCE_NO";
15681     case DT_MIPS_DELTA_RELOC:
15682       return "MIPS_DELTA_RELOC";
15683     case DT_MIPS_DELTA_RELOC_NO:
15684       return "MIPS_DELTA_RELOC_NO";
15685     case DT_MIPS_DELTA_SYM:
15686       return "MIPS_DELTA_SYM";
15687     case DT_MIPS_DELTA_SYM_NO:
15688       return "MIPS_DELTA_SYM_NO";
15689     case DT_MIPS_DELTA_CLASSSYM:
15690       return "MIPS_DELTA_CLASSSYM";
15691     case DT_MIPS_DELTA_CLASSSYM_NO:
15692       return "MIPS_DELTA_CLASSSYM_NO";
15693     case DT_MIPS_CXX_FLAGS:
15694       return "MIPS_CXX_FLAGS";
15695     case DT_MIPS_PIXIE_INIT:
15696       return "MIPS_PIXIE_INIT";
15697     case DT_MIPS_SYMBOL_LIB:
15698       return "MIPS_SYMBOL_LIB";
15699     case DT_MIPS_LOCALPAGE_GOTIDX:
15700       return "MIPS_LOCALPAGE_GOTIDX";
15701     case DT_MIPS_LOCAL_GOTIDX:
15702       return "MIPS_LOCAL_GOTIDX";
15703     case DT_MIPS_HIDDEN_GOTIDX:
15704       return "MIPS_HIDDEN_GOTIDX";
15705     case DT_MIPS_PROTECTED_GOTIDX:
15706       return "MIPS_PROTECTED_GOT_IDX";
15707     case DT_MIPS_OPTIONS:
15708       return "MIPS_OPTIONS";
15709     case DT_MIPS_INTERFACE:
15710       return "MIPS_INTERFACE";
15711     case DT_MIPS_DYNSTR_ALIGN:
15712       return "DT_MIPS_DYNSTR_ALIGN";
15713     case DT_MIPS_INTERFACE_SIZE:
15714       return "DT_MIPS_INTERFACE_SIZE";
15715     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
15716       return "DT_MIPS_RLD_TEXT_RESOLVE_ADDR";
15717     case DT_MIPS_PERF_SUFFIX:
15718       return "DT_MIPS_PERF_SUFFIX";
15719     case DT_MIPS_COMPACT_SIZE:
15720       return "DT_MIPS_COMPACT_SIZE";
15721     case DT_MIPS_GP_VALUE:
15722       return "DT_MIPS_GP_VALUE";
15723     case DT_MIPS_AUX_DYNAMIC:
15724       return "DT_MIPS_AUX_DYNAMIC";
15725     case DT_MIPS_PLTGOT:
15726       return "DT_MIPS_PLTGOT";
15727     case DT_MIPS_RWPLT:
15728       return "DT_MIPS_RWPLT";
15729     }
15730 }
15731
15732 /* Return the meaning of Tag_GNU_MIPS_ABI_FP value FP, or null if
15733    not known.  */
15734
15735 const char *
15736 _bfd_mips_fp_abi_string (int fp)
15737 {
15738   switch (fp)
15739     {
15740       /* These strings aren't translated because they're simply
15741          option lists.  */
15742     case Val_GNU_MIPS_ABI_FP_DOUBLE:
15743       return "-mdouble-float";
15744
15745     case Val_GNU_MIPS_ABI_FP_SINGLE:
15746       return "-msingle-float";
15747
15748     case Val_GNU_MIPS_ABI_FP_SOFT:
15749       return "-msoft-float";
15750
15751     case Val_GNU_MIPS_ABI_FP_OLD_64:
15752       return _("-mips32r2 -mfp64 (12 callee-saved)");
15753
15754     case Val_GNU_MIPS_ABI_FP_XX:
15755       return "-mfpxx";
15756
15757     case Val_GNU_MIPS_ABI_FP_64:
15758       return "-mgp32 -mfp64";
15759
15760     case Val_GNU_MIPS_ABI_FP_64A:
15761       return "-mgp32 -mfp64 -mno-odd-spreg";
15762
15763     default:
15764       return 0;
15765     }
15766 }
15767
15768 static void
15769 print_mips_ases (FILE *file, unsigned int mask)
15770 {
15771   if (mask & AFL_ASE_DSP)
15772     fputs ("\n\tDSP ASE", file);
15773   if (mask & AFL_ASE_DSPR2)
15774     fputs ("\n\tDSP R2 ASE", file);
15775   if (mask & AFL_ASE_DSPR3)
15776     fputs ("\n\tDSP R3 ASE", file);
15777   if (mask & AFL_ASE_EVA)
15778     fputs ("\n\tEnhanced VA Scheme", file);
15779   if (mask & AFL_ASE_MCU)
15780     fputs ("\n\tMCU (MicroController) ASE", file);
15781   if (mask & AFL_ASE_MDMX)
15782     fputs ("\n\tMDMX ASE", file);
15783   if (mask & AFL_ASE_MIPS3D)
15784     fputs ("\n\tMIPS-3D ASE", file);
15785   if (mask & AFL_ASE_MT)
15786     fputs ("\n\tMT ASE", file);
15787   if (mask & AFL_ASE_SMARTMIPS)
15788     fputs ("\n\tSmartMIPS ASE", file);
15789   if (mask & AFL_ASE_VIRT)
15790     fputs ("\n\tVZ ASE", file);
15791   if (mask & AFL_ASE_MSA)
15792     fputs ("\n\tMSA ASE", file);
15793   if (mask & AFL_ASE_MIPS16)
15794     fputs ("\n\tMIPS16 ASE", file);
15795   if (mask & AFL_ASE_MICROMIPS)
15796     fputs ("\n\tMICROMIPS ASE", file);
15797   if (mask & AFL_ASE_XPA)
15798     fputs ("\n\tXPA ASE", file);
15799   if (mask == 0)
15800     fprintf (file, "\n\t%s", _("None"));
15801   else if ((mask & ~AFL_ASE_MASK) != 0)
15802     fprintf (stdout, "\n\t%s (%x)", _("Unknown"), mask & ~AFL_ASE_MASK);
15803 }
15804
15805 static void
15806 print_mips_isa_ext (FILE *file, unsigned int isa_ext)
15807 {
15808   switch (isa_ext)
15809     {
15810     case 0:
15811       fputs (_("None"), file);
15812       break;
15813     case AFL_EXT_XLR:
15814       fputs ("RMI XLR", file);
15815       break;
15816     case AFL_EXT_OCTEON3:
15817       fputs ("Cavium Networks Octeon3", file);
15818       break;
15819     case AFL_EXT_OCTEON2:
15820       fputs ("Cavium Networks Octeon2", file);
15821       break;
15822     case AFL_EXT_OCTEONP:
15823       fputs ("Cavium Networks OcteonP", file);
15824       break;
15825     case AFL_EXT_LOONGSON_3A:
15826       fputs ("Loongson 3A", file);
15827       break;
15828     case AFL_EXT_OCTEON:
15829       fputs ("Cavium Networks Octeon", file);
15830       break;
15831     case AFL_EXT_5900:
15832       fputs ("Toshiba R5900", file);
15833       break;
15834     case AFL_EXT_4650:
15835       fputs ("MIPS R4650", file);
15836       break;
15837     case AFL_EXT_4010:
15838       fputs ("LSI R4010", file);
15839       break;
15840     case AFL_EXT_4100:
15841       fputs ("NEC VR4100", file);
15842       break;
15843     case AFL_EXT_3900:
15844       fputs ("Toshiba R3900", file);
15845       break;
15846     case AFL_EXT_10000:
15847       fputs ("MIPS R10000", file);
15848       break;
15849     case AFL_EXT_SB1:
15850       fputs ("Broadcom SB-1", file);
15851       break;
15852     case AFL_EXT_4111:
15853       fputs ("NEC VR4111/VR4181", file);
15854       break;
15855     case AFL_EXT_4120:
15856       fputs ("NEC VR4120", file);
15857       break;
15858     case AFL_EXT_5400:
15859       fputs ("NEC VR5400", file);
15860       break;
15861     case AFL_EXT_5500:
15862       fputs ("NEC VR5500", file);
15863       break;
15864     case AFL_EXT_LOONGSON_2E:
15865       fputs ("ST Microelectronics Loongson 2E", file);
15866       break;
15867     case AFL_EXT_LOONGSON_2F:
15868       fputs ("ST Microelectronics Loongson 2F", file);
15869       break;
15870     default:
15871       fprintf (file, "%s (%d)", _("Unknown"), isa_ext);
15872       break;
15873     }
15874 }
15875
15876 static void
15877 print_mips_fp_abi_value (FILE *file, int val)
15878 {
15879   switch (val)
15880     {
15881     case Val_GNU_MIPS_ABI_FP_ANY:
15882       fprintf (file, _("Hard or soft float\n"));
15883       break;
15884     case Val_GNU_MIPS_ABI_FP_DOUBLE:
15885       fprintf (file, _("Hard float (double precision)\n"));
15886       break;
15887     case Val_GNU_MIPS_ABI_FP_SINGLE:
15888       fprintf (file, _("Hard float (single precision)\n"));
15889       break;
15890     case Val_GNU_MIPS_ABI_FP_SOFT:
15891       fprintf (file, _("Soft float\n"));
15892       break;
15893     case Val_GNU_MIPS_ABI_FP_OLD_64:
15894       fprintf (file, _("Hard float (MIPS32r2 64-bit FPU 12 callee-saved)\n"));
15895       break;
15896     case Val_GNU_MIPS_ABI_FP_XX:
15897       fprintf (file, _("Hard float (32-bit CPU, Any FPU)\n"));
15898       break;
15899     case Val_GNU_MIPS_ABI_FP_64:
15900       fprintf (file, _("Hard float (32-bit CPU, 64-bit FPU)\n"));
15901       break;
15902     case Val_GNU_MIPS_ABI_FP_64A:
15903       fprintf (file, _("Hard float compat (32-bit CPU, 64-bit FPU)\n"));
15904       break;
15905     default:
15906       fprintf (file, "??? (%d)\n", val);
15907       break;
15908     }
15909 }
15910
15911 static int
15912 get_mips_reg_size (int reg_size)
15913 {
15914   return (reg_size == AFL_REG_NONE) ? 0
15915          : (reg_size == AFL_REG_32) ? 32
15916          : (reg_size == AFL_REG_64) ? 64
15917          : (reg_size == AFL_REG_128) ? 128
15918          : -1;
15919 }
15920
15921 bfd_boolean
15922 _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr)
15923 {
15924   FILE *file = ptr;
15925
15926   BFD_ASSERT (abfd != NULL && ptr != NULL);
15927
15928   /* Print normal ELF private data.  */
15929   _bfd_elf_print_private_bfd_data (abfd, ptr);
15930
15931   /* xgettext:c-format */
15932   fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
15933
15934   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
15935     fprintf (file, _(" [abi=O32]"));
15936   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64)
15937     fprintf (file, _(" [abi=O64]"));
15938   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32)
15939     fprintf (file, _(" [abi=EABI32]"));
15940   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
15941     fprintf (file, _(" [abi=EABI64]"));
15942   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI))
15943     fprintf (file, _(" [abi unknown]"));
15944   else if (ABI_N32_P (abfd))
15945     fprintf (file, _(" [abi=N32]"));
15946   else if (ABI_64_P (abfd))
15947     fprintf (file, _(" [abi=64]"));
15948   else
15949     fprintf (file, _(" [no abi set]"));
15950
15951   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1)
15952     fprintf (file, " [mips1]");
15953   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2)
15954     fprintf (file, " [mips2]");
15955   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3)
15956     fprintf (file, " [mips3]");
15957   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4)
15958     fprintf (file, " [mips4]");
15959   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5)
15960     fprintf (file, " [mips5]");
15961   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32)
15962     fprintf (file, " [mips32]");
15963   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64)
15964     fprintf (file, " [mips64]");
15965   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2)
15966     fprintf (file, " [mips32r2]");
15967   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2)
15968     fprintf (file, " [mips64r2]");
15969   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R6)
15970     fprintf (file, " [mips32r6]");
15971   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R6)
15972     fprintf (file, " [mips64r6]");
15973   else
15974     fprintf (file, _(" [unknown ISA]"));
15975
15976   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
15977     fprintf (file, " [mdmx]");
15978
15979   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
15980     fprintf (file, " [mips16]");
15981
15982   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
15983     fprintf (file, " [micromips]");
15984
15985   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NAN2008)
15986     fprintf (file, " [nan2008]");
15987
15988   if (elf_elfheader (abfd)->e_flags & EF_MIPS_FP64)
15989     fprintf (file, " [old fp64]");
15990
15991   if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE)
15992     fprintf (file, " [32bitmode]");
15993   else
15994     fprintf (file, _(" [not 32bitmode]"));
15995
15996   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NOREORDER)
15997     fprintf (file, " [noreorder]");
15998
15999   if (elf_elfheader (abfd)->e_flags & EF_MIPS_PIC)
16000     fprintf (file, " [PIC]");
16001
16002   if (elf_elfheader (abfd)->e_flags & EF_MIPS_CPIC)
16003     fprintf (file, " [CPIC]");
16004
16005   if (elf_elfheader (abfd)->e_flags & EF_MIPS_XGOT)
16006     fprintf (file, " [XGOT]");
16007
16008   if (elf_elfheader (abfd)->e_flags & EF_MIPS_UCODE)
16009     fprintf (file, " [UCODE]");
16010
16011   fputc ('\n', file);
16012
16013   if (mips_elf_tdata (abfd)->abiflags_valid)
16014     {
16015       Elf_Internal_ABIFlags_v0 *abiflags = &mips_elf_tdata (abfd)->abiflags;
16016       fprintf (file, "\nMIPS ABI Flags Version: %d\n", abiflags->version);
16017       fprintf (file, "\nISA: MIPS%d", abiflags->isa_level);
16018       if (abiflags->isa_rev > 1)
16019         fprintf (file, "r%d", abiflags->isa_rev);
16020       fprintf (file, "\nGPR size: %d",
16021                get_mips_reg_size (abiflags->gpr_size));
16022       fprintf (file, "\nCPR1 size: %d",
16023                get_mips_reg_size (abiflags->cpr1_size));
16024       fprintf (file, "\nCPR2 size: %d",
16025                get_mips_reg_size (abiflags->cpr2_size));
16026       fputs ("\nFP ABI: ", file);
16027       print_mips_fp_abi_value (file, abiflags->fp_abi);
16028       fputs ("ISA Extension: ", file);
16029       print_mips_isa_ext (file, abiflags->isa_ext);
16030       fputs ("\nASEs:", file);
16031       print_mips_ases (file, abiflags->ases);
16032       fprintf (file, "\nFLAGS 1: %8.8lx", abiflags->flags1);
16033       fprintf (file, "\nFLAGS 2: %8.8lx", abiflags->flags2);
16034       fputc ('\n', file);
16035     }
16036
16037   return TRUE;
16038 }
16039
16040 const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] =
16041 {
16042   { STRING_COMMA_LEN (".lit4"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
16043   { STRING_COMMA_LEN (".lit8"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
16044   { STRING_COMMA_LEN (".mdebug"), 0, SHT_MIPS_DEBUG, 0 },
16045   { STRING_COMMA_LEN (".sbss"),  -2, SHT_NOBITS,     SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
16046   { STRING_COMMA_LEN (".sdata"), -2, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
16047   { STRING_COMMA_LEN (".ucode"),  0, SHT_MIPS_UCODE, 0 },
16048   { NULL,                     0,  0, 0,              0 }
16049 };
16050
16051 /* Merge non visibility st_other attributes.  Ensure that the
16052    STO_OPTIONAL flag is copied into h->other, even if this is not a
16053    definiton of the symbol.  */
16054 void
16055 _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
16056                                       const Elf_Internal_Sym *isym,
16057                                       bfd_boolean definition,
16058                                       bfd_boolean dynamic ATTRIBUTE_UNUSED)
16059 {
16060   if ((isym->st_other & ~ELF_ST_VISIBILITY (-1)) != 0)
16061     {
16062       unsigned char other;
16063
16064       other = (definition ? isym->st_other : h->other);
16065       other &= ~ELF_ST_VISIBILITY (-1);
16066       h->other = other | ELF_ST_VISIBILITY (h->other);
16067     }
16068
16069   if (!definition
16070       && ELF_MIPS_IS_OPTIONAL (isym->st_other))
16071     h->other |= STO_OPTIONAL;
16072 }
16073
16074 /* Decide whether an undefined symbol is special and can be ignored.
16075    This is the case for OPTIONAL symbols on IRIX.  */
16076 bfd_boolean
16077 _bfd_mips_elf_ignore_undef_symbol (struct elf_link_hash_entry *h)
16078 {
16079   return ELF_MIPS_IS_OPTIONAL (h->other) ? TRUE : FALSE;
16080 }
16081
16082 bfd_boolean
16083 _bfd_mips_elf_common_definition (Elf_Internal_Sym *sym)
16084 {
16085   return (sym->st_shndx == SHN_COMMON
16086           || sym->st_shndx == SHN_MIPS_ACOMMON
16087           || sym->st_shndx == SHN_MIPS_SCOMMON);
16088 }
16089
16090 /* Return address for Ith PLT stub in section PLT, for relocation REL
16091    or (bfd_vma) -1 if it should not be included.  */
16092
16093 bfd_vma
16094 _bfd_mips_elf_plt_sym_val (bfd_vma i, const asection *plt,
16095                            const arelent *rel ATTRIBUTE_UNUSED)
16096 {
16097   return (plt->vma
16098           + 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry)
16099           + i * 4 * ARRAY_SIZE (mips_exec_plt_entry));
16100 }
16101
16102 /* Build a table of synthetic symbols to represent the PLT.  As with MIPS16
16103    and microMIPS PLT slots we may have a many-to-one mapping between .plt
16104    and .got.plt and also the slots may be of a different size each we walk
16105    the PLT manually fetching instructions and matching them against known
16106    patterns.  To make things easier standard MIPS slots, if any, always come
16107    first.  As we don't create proper ELF symbols we use the UDATA.I member
16108    of ASYMBOL to carry ISA annotation.  The encoding used is the same as
16109    with the ST_OTHER member of the ELF symbol.  */
16110
16111 long
16112 _bfd_mips_elf_get_synthetic_symtab (bfd *abfd,
16113                                     long symcount ATTRIBUTE_UNUSED,
16114                                     asymbol **syms ATTRIBUTE_UNUSED,
16115                                     long dynsymcount, asymbol **dynsyms,
16116                                     asymbol **ret)
16117 {
16118   static const char pltname[] = "_PROCEDURE_LINKAGE_TABLE_";
16119   static const char microsuffix[] = "@micromipsplt";
16120   static const char m16suffix[] = "@mips16plt";
16121   static const char mipssuffix[] = "@plt";
16122
16123   bfd_boolean (*slurp_relocs) (bfd *, asection *, asymbol **, bfd_boolean);
16124   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
16125   bfd_boolean micromips_p = MICROMIPS_P (abfd);
16126   Elf_Internal_Shdr *hdr;
16127   bfd_byte *plt_data;
16128   bfd_vma plt_offset;
16129   unsigned int other;
16130   bfd_vma entry_size;
16131   bfd_vma plt0_size;
16132   asection *relplt;
16133   bfd_vma opcode;
16134   asection *plt;
16135   asymbol *send;
16136   size_t size;
16137   char *names;
16138   long counti;
16139   arelent *p;
16140   asymbol *s;
16141   char *nend;
16142   long count;
16143   long pi;
16144   long i;
16145   long n;
16146
16147   *ret = NULL;
16148
16149   if ((abfd->flags & (DYNAMIC | EXEC_P)) == 0 || dynsymcount <= 0)
16150     return 0;
16151
16152   relplt = bfd_get_section_by_name (abfd, ".rel.plt");
16153   if (relplt == NULL)
16154     return 0;
16155
16156   hdr = &elf_section_data (relplt)->this_hdr;
16157   if (hdr->sh_link != elf_dynsymtab (abfd) || hdr->sh_type != SHT_REL)
16158     return 0;
16159
16160   plt = bfd_get_section_by_name (abfd, ".plt");
16161   if (plt == NULL)
16162     return 0;
16163
16164   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
16165   if (!(*slurp_relocs) (abfd, relplt, dynsyms, TRUE))
16166     return -1;
16167   p = relplt->relocation;
16168
16169   /* Calculating the exact amount of space required for symbols would
16170      require two passes over the PLT, so just pessimise assuming two
16171      PLT slots per relocation.  */
16172   count = relplt->size / hdr->sh_entsize;
16173   counti = count * bed->s->int_rels_per_ext_rel;
16174   size = 2 * count * sizeof (asymbol);
16175   size += count * (sizeof (mipssuffix) +
16176                    (micromips_p ? sizeof (microsuffix) : sizeof (m16suffix)));
16177   for (pi = 0; pi < counti; pi += bed->s->int_rels_per_ext_rel)
16178     size += 2 * strlen ((*p[pi].sym_ptr_ptr)->name);
16179
16180   /* Add the size of "_PROCEDURE_LINKAGE_TABLE_" too.  */
16181   size += sizeof (asymbol) + sizeof (pltname);
16182
16183   if (!bfd_malloc_and_get_section (abfd, plt, &plt_data))
16184     return -1;
16185
16186   if (plt->size < 16)
16187     return -1;
16188
16189   s = *ret = bfd_malloc (size);
16190   if (s == NULL)
16191     return -1;
16192   send = s + 2 * count + 1;
16193
16194   names = (char *) send;
16195   nend = (char *) s + size;
16196   n = 0;
16197
16198   opcode = bfd_get_micromips_32 (abfd, plt_data + 12);
16199   if (opcode == 0x3302fffe)
16200     {
16201       if (!micromips_p)
16202         return -1;
16203       plt0_size = 2 * ARRAY_SIZE (micromips_o32_exec_plt0_entry);
16204       other = STO_MICROMIPS;
16205     }
16206   else if (opcode == 0x0398c1d0)
16207     {
16208       if (!micromips_p)
16209         return -1;
16210       plt0_size = 2 * ARRAY_SIZE (micromips_insn32_o32_exec_plt0_entry);
16211       other = STO_MICROMIPS;
16212     }
16213   else
16214     {
16215       plt0_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
16216       other = 0;
16217     }
16218
16219   s->the_bfd = abfd;
16220   s->flags = BSF_SYNTHETIC | BSF_FUNCTION | BSF_LOCAL;
16221   s->section = plt;
16222   s->value = 0;
16223   s->name = names;
16224   s->udata.i = other;
16225   memcpy (names, pltname, sizeof (pltname));
16226   names += sizeof (pltname);
16227   ++s, ++n;
16228
16229   pi = 0;
16230   for (plt_offset = plt0_size;
16231        plt_offset + 8 <= plt->size && s < send;
16232        plt_offset += entry_size)
16233     {
16234       bfd_vma gotplt_addr;
16235       const char *suffix;
16236       bfd_vma gotplt_hi;
16237       bfd_vma gotplt_lo;
16238       size_t suffixlen;
16239
16240       opcode = bfd_get_micromips_32 (abfd, plt_data + plt_offset + 4);
16241
16242       /* Check if the second word matches the expected MIPS16 instruction.  */
16243       if (opcode == 0x651aeb00)
16244         {
16245           if (micromips_p)
16246             return -1;
16247           /* Truncated table???  */
16248           if (plt_offset + 16 > plt->size)
16249             break;
16250           gotplt_addr = bfd_get_32 (abfd, plt_data + plt_offset + 12);
16251           entry_size = 2 * ARRAY_SIZE (mips16_o32_exec_plt_entry);
16252           suffixlen = sizeof (m16suffix);
16253           suffix = m16suffix;
16254           other = STO_MIPS16;
16255         }
16256       /* Likewise the expected microMIPS instruction (no insn32 mode).  */
16257       else if (opcode == 0xff220000)
16258         {
16259           if (!micromips_p)
16260             return -1;
16261           gotplt_hi = bfd_get_16 (abfd, plt_data + plt_offset) & 0x7f;
16262           gotplt_lo = bfd_get_16 (abfd, plt_data + plt_offset + 2) & 0xffff;
16263           gotplt_hi = ((gotplt_hi ^ 0x40) - 0x40) << 18;
16264           gotplt_lo <<= 2;
16265           gotplt_addr = gotplt_hi + gotplt_lo;
16266           gotplt_addr += ((plt->vma + plt_offset) | 3) ^ 3;
16267           entry_size = 2 * ARRAY_SIZE (micromips_o32_exec_plt_entry);
16268           suffixlen = sizeof (microsuffix);
16269           suffix = microsuffix;
16270           other = STO_MICROMIPS;
16271         }
16272       /* Likewise the expected microMIPS instruction (insn32 mode).  */
16273       else if ((opcode & 0xffff0000) == 0xff2f0000)
16274         {
16275           gotplt_hi = bfd_get_16 (abfd, plt_data + plt_offset + 2) & 0xffff;
16276           gotplt_lo = bfd_get_16 (abfd, plt_data + plt_offset + 6) & 0xffff;
16277           gotplt_hi = ((gotplt_hi ^ 0x8000) - 0x8000) << 16;
16278           gotplt_lo = (gotplt_lo ^ 0x8000) - 0x8000;
16279           gotplt_addr = gotplt_hi + gotplt_lo;
16280           entry_size = 2 * ARRAY_SIZE (micromips_insn32_o32_exec_plt_entry);
16281           suffixlen = sizeof (microsuffix);
16282           suffix = microsuffix;
16283           other = STO_MICROMIPS;
16284         }
16285       /* Otherwise assume standard MIPS code.  */
16286       else
16287         {
16288           gotplt_hi = bfd_get_32 (abfd, plt_data + plt_offset) & 0xffff;
16289           gotplt_lo = bfd_get_32 (abfd, plt_data + plt_offset + 4) & 0xffff;
16290           gotplt_hi = ((gotplt_hi ^ 0x8000) - 0x8000) << 16;
16291           gotplt_lo = (gotplt_lo ^ 0x8000) - 0x8000;
16292           gotplt_addr = gotplt_hi + gotplt_lo;
16293           entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
16294           suffixlen = sizeof (mipssuffix);
16295           suffix = mipssuffix;
16296           other = 0;
16297         }
16298       /* Truncated table???  */
16299       if (plt_offset + entry_size > plt->size)
16300         break;
16301
16302       for (i = 0;
16303            i < count && p[pi].address != gotplt_addr;
16304            i++, pi = (pi + bed->s->int_rels_per_ext_rel) % counti);
16305
16306       if (i < count)
16307         {
16308           size_t namelen;
16309           size_t len;
16310
16311           *s = **p[pi].sym_ptr_ptr;
16312           /* Undefined syms won't have BSF_LOCAL or BSF_GLOBAL set.  Since
16313              we are defining a symbol, ensure one of them is set.  */
16314           if ((s->flags & BSF_LOCAL) == 0)
16315             s->flags |= BSF_GLOBAL;
16316           s->flags |= BSF_SYNTHETIC;
16317           s->section = plt;
16318           s->value = plt_offset;
16319           s->name = names;
16320           s->udata.i = other;
16321
16322           len = strlen ((*p[pi].sym_ptr_ptr)->name);
16323           namelen = len + suffixlen;
16324           if (names + namelen > nend)
16325             break;
16326
16327           memcpy (names, (*p[pi].sym_ptr_ptr)->name, len);
16328           names += len;
16329           memcpy (names, suffix, suffixlen);
16330           names += suffixlen;
16331
16332           ++s, ++n;
16333           pi = (pi + bed->s->int_rels_per_ext_rel) % counti;
16334         }
16335     }
16336
16337   free (plt_data);
16338
16339   return n;
16340 }
16341
16342 /* Return the ABI flags associated with ABFD if available.  */
16343
16344 Elf_Internal_ABIFlags_v0 *
16345 bfd_mips_elf_get_abiflags (bfd *abfd)
16346 {
16347   struct mips_elf_obj_tdata *tdata = mips_elf_tdata (abfd);
16348
16349   return tdata->abiflags_valid ? &tdata->abiflags : NULL;
16350 }
16351
16352 void
16353 _bfd_mips_post_process_headers (bfd *abfd, struct bfd_link_info *link_info)
16354 {
16355   struct mips_elf_link_hash_table *htab;
16356   Elf_Internal_Ehdr *i_ehdrp;
16357
16358   i_ehdrp = elf_elfheader (abfd);
16359   if (link_info)
16360     {
16361       htab = mips_elf_hash_table (link_info);
16362       BFD_ASSERT (htab != NULL);
16363
16364       if (htab->use_plts_and_copy_relocs && !htab->is_vxworks)
16365         i_ehdrp->e_ident[EI_ABIVERSION] = 1;
16366     }
16367
16368   _bfd_elf_post_process_headers (abfd, link_info);
16369
16370   if (mips_elf_tdata (abfd)->abiflags.fp_abi == Val_GNU_MIPS_ABI_FP_64
16371       || mips_elf_tdata (abfd)->abiflags.fp_abi == Val_GNU_MIPS_ABI_FP_64A)
16372     i_ehdrp->e_ident[EI_ABIVERSION] = 3;
16373 }
16374
16375 int
16376 _bfd_mips_elf_compact_eh_encoding (struct bfd_link_info *link_info ATTRIBUTE_UNUSED)
16377 {
16378   return DW_EH_PE_pcrel | DW_EH_PE_sdata4;
16379 }
16380
16381 /* Return the opcode for can't unwind.  */
16382
16383 int
16384 _bfd_mips_elf_cant_unwind_opcode (struct bfd_link_info *link_info ATTRIBUTE_UNUSED)
16385 {
16386   return COMPACT_EH_CANT_UNWIND_OPCODE;
16387 }