bfd/
[platform/upstream/binutils.git] / bfd / elfxx-mips.c
1 /* MIPS-specific support for ELF
2    Copyright 1993-2013 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
40 /* Get the ECOFF swapping routines.  */
41 #include "coff/sym.h"
42 #include "coff/symconst.h"
43 #include "coff/ecoff.h"
44 #include "coff/mips.h"
45
46 #include "hashtab.h"
47
48 /* Types of TLS GOT entry.  */
49 enum mips_got_tls_type {
50   GOT_TLS_NONE,
51   GOT_TLS_GD,
52   GOT_TLS_LDM,
53   GOT_TLS_IE
54 };
55
56 /* This structure is used to hold information about one GOT entry.
57    There are four types of entry:
58
59       (1) an absolute address
60             requires: abfd == NULL
61             fields: d.address
62
63       (2) a SYMBOL + OFFSET address, where SYMBOL is local to an input bfd
64             requires: abfd != NULL, symndx >= 0, tls_type != GOT_TLS_LDM
65             fields: abfd, symndx, d.addend, tls_type
66
67       (3) a SYMBOL address, where SYMBOL is not local to an input bfd
68             requires: abfd != NULL, symndx == -1
69             fields: d.h, tls_type
70
71       (4) a TLS LDM slot
72             requires: abfd != NULL, symndx == 0, tls_type == GOT_TLS_LDM
73             fields: none; there's only one of these per GOT.  */
74 struct mips_got_entry
75 {
76   /* One input bfd that needs the GOT entry.  */
77   bfd *abfd;
78   /* The index of the symbol, as stored in the relocation r_info, if
79      we have a local symbol; -1 otherwise.  */
80   long symndx;
81   union
82   {
83     /* If abfd == NULL, an address that must be stored in the got.  */
84     bfd_vma address;
85     /* If abfd != NULL && symndx != -1, the addend of the relocation
86        that should be added to the symbol value.  */
87     bfd_vma addend;
88     /* If abfd != NULL && symndx == -1, the hash table entry
89        corresponding to a symbol in the GOT.  The symbol's entry
90        is in the local area if h->global_got_area is GGA_NONE,
91        otherwise it is in the global area.  */
92     struct mips_elf_link_hash_entry *h;
93   } d;
94
95   /* The TLS type of this GOT entry.  An LDM GOT entry will be a local
96      symbol entry with r_symndx == 0.  */
97   unsigned char tls_type;
98
99   /* True if we have filled in the GOT contents for a TLS entry,
100      and created the associated relocations.  */
101   unsigned char tls_initialized;
102
103   /* The offset from the beginning of the .got section to the entry
104      corresponding to this symbol+addend.  If it's a global symbol
105      whose offset is yet to be decided, it's going to be -1.  */
106   long gotidx;
107 };
108
109 /* This structure represents a GOT page reference from an input bfd.
110    Each instance represents a symbol + ADDEND, where the representation
111    of the symbol depends on whether it is local to the input bfd.
112    If it is, then SYMNDX >= 0, and the symbol has index SYMNDX in U.ABFD.
113    Otherwise, SYMNDX < 0 and U.H points to the symbol's hash table entry.
114
115    Page references with SYMNDX >= 0 always become page references
116    in the output.  Page references with SYMNDX < 0 only become page
117    references if the symbol binds locally; in other cases, the page
118    reference decays to a global GOT reference.  */
119 struct mips_got_page_ref
120 {
121   long symndx;
122   union
123   {
124     struct mips_elf_link_hash_entry *h;
125     bfd *abfd;
126   } u;
127   bfd_vma addend;
128 };
129
130 /* This structure describes a range of addends: [MIN_ADDEND, MAX_ADDEND].
131    The structures form a non-overlapping list that is sorted by increasing
132    MIN_ADDEND.  */
133 struct mips_got_page_range
134 {
135   struct mips_got_page_range *next;
136   bfd_signed_vma min_addend;
137   bfd_signed_vma max_addend;
138 };
139
140 /* This structure describes the range of addends that are applied to page
141    relocations against a given section.  */
142 struct mips_got_page_entry
143 {
144   /* The section that these entries are based on.  */
145   asection *sec;
146   /* The ranges for this page entry.  */
147   struct mips_got_page_range *ranges;
148   /* The maximum number of page entries needed for RANGES.  */
149   bfd_vma num_pages;
150 };
151
152 /* This structure is used to hold .got information when linking.  */
153
154 struct mips_got_info
155 {
156   /* The number of global .got entries.  */
157   unsigned int global_gotno;
158   /* The number of global .got entries that are in the GGA_RELOC_ONLY area.  */
159   unsigned int reloc_only_gotno;
160   /* The number of .got slots used for TLS.  */
161   unsigned int tls_gotno;
162   /* The first unused TLS .got entry.  Used only during
163      mips_elf_initialize_tls_index.  */
164   unsigned int tls_assigned_gotno;
165   /* The number of local .got entries, eventually including page entries.  */
166   unsigned int local_gotno;
167   /* The maximum number of page entries needed.  */
168   unsigned int page_gotno;
169   /* The number of relocations needed for the GOT entries.  */
170   unsigned int relocs;
171   /* The number of local .got entries we have used.  */
172   unsigned int assigned_gotno;
173   /* A hash table holding members of the got.  */
174   struct htab *got_entries;
175   /* A hash table holding mips_got_page_ref structures.  */
176   struct htab *got_page_refs;
177   /* A hash table of mips_got_page_entry structures.  */
178   struct htab *got_page_entries;
179   /* In multi-got links, a pointer to the next got (err, rather, most
180      of the time, it points to the previous got).  */
181   struct mips_got_info *next;
182 };
183
184 /* Structure passed when merging bfds' gots.  */
185
186 struct mips_elf_got_per_bfd_arg
187 {
188   /* The output bfd.  */
189   bfd *obfd;
190   /* The link information.  */
191   struct bfd_link_info *info;
192   /* A pointer to the primary got, i.e., the one that's going to get
193      the implicit relocations from DT_MIPS_LOCAL_GOTNO and
194      DT_MIPS_GOTSYM.  */
195   struct mips_got_info *primary;
196   /* A non-primary got we're trying to merge with other input bfd's
197      gots.  */
198   struct mips_got_info *current;
199   /* The maximum number of got entries that can be addressed with a
200      16-bit offset.  */
201   unsigned int max_count;
202   /* The maximum number of page entries needed by each got.  */
203   unsigned int max_pages;
204   /* The total number of global entries which will live in the
205      primary got and be automatically relocated.  This includes
206      those not referenced by the primary GOT but included in
207      the "master" GOT.  */
208   unsigned int global_count;
209 };
210
211 /* A structure used to pass information to htab_traverse callbacks
212    when laying out the GOT.  */
213
214 struct mips_elf_traverse_got_arg
215 {
216   struct bfd_link_info *info;
217   struct mips_got_info *g;
218   int value;
219 };
220
221 struct _mips_elf_section_data
222 {
223   struct bfd_elf_section_data elf;
224   union
225   {
226     bfd_byte *tdata;
227   } u;
228 };
229
230 #define mips_elf_section_data(sec) \
231   ((struct _mips_elf_section_data *) elf_section_data (sec))
232
233 #define is_mips_elf(bfd)                                \
234   (bfd_get_flavour (bfd) == bfd_target_elf_flavour      \
235    && elf_tdata (bfd) != NULL                           \
236    && elf_object_id (bfd) == MIPS_ELF_DATA)
237
238 /* The ABI says that every symbol used by dynamic relocations must have
239    a global GOT entry.  Among other things, this provides the dynamic
240    linker with a free, directly-indexed cache.  The GOT can therefore
241    contain symbols that are not referenced by GOT relocations themselves
242    (in other words, it may have symbols that are not referenced by things
243    like R_MIPS_GOT16 and R_MIPS_GOT_PAGE).
244
245    GOT relocations are less likely to overflow if we put the associated
246    GOT entries towards the beginning.  We therefore divide the global
247    GOT entries into two areas: "normal" and "reloc-only".  Entries in
248    the first area can be used for both dynamic relocations and GP-relative
249    accesses, while those in the "reloc-only" area are for dynamic
250    relocations only.
251
252    These GGA_* ("Global GOT Area") values are organised so that lower
253    values are more general than higher values.  Also, non-GGA_NONE
254    values are ordered by the position of the area in the GOT.  */
255 #define GGA_NORMAL 0
256 #define GGA_RELOC_ONLY 1
257 #define GGA_NONE 2
258
259 /* Information about a non-PIC interface to a PIC function.  There are
260    two ways of creating these interfaces.  The first is to add:
261
262         lui     $25,%hi(func)
263         addiu   $25,$25,%lo(func)
264
265    immediately before a PIC function "func".  The second is to add:
266
267         lui     $25,%hi(func)
268         j       func
269         addiu   $25,$25,%lo(func)
270
271    to a separate trampoline section.
272
273    Stubs of the first kind go in a new section immediately before the
274    target function.  Stubs of the second kind go in a single section
275    pointed to by the hash table's "strampoline" field.  */
276 struct mips_elf_la25_stub {
277   /* The generated section that contains this stub.  */
278   asection *stub_section;
279
280   /* The offset of the stub from the start of STUB_SECTION.  */
281   bfd_vma offset;
282
283   /* One symbol for the original function.  Its location is available
284      in H->root.root.u.def.  */
285   struct mips_elf_link_hash_entry *h;
286 };
287
288 /* Macros for populating a mips_elf_la25_stub.  */
289
290 #define LA25_LUI(VAL) (0x3c190000 | (VAL))      /* lui t9,VAL */
291 #define LA25_J(VAL) (0x08000000 | (((VAL) >> 2) & 0x3ffffff)) /* j VAL */
292 #define LA25_ADDIU(VAL) (0x27390000 | (VAL))    /* addiu t9,t9,VAL */
293 #define LA25_LUI_MICROMIPS(VAL)                                         \
294   (0x41b90000 | (VAL))                          /* lui t9,VAL */
295 #define LA25_J_MICROMIPS(VAL)                                           \
296   (0xd4000000 | (((VAL) >> 1) & 0x3ffffff))     /* j VAL */
297 #define LA25_ADDIU_MICROMIPS(VAL)                                       \
298   (0x33390000 | (VAL))                          /* addiu t9,t9,VAL */
299
300 /* This structure is passed to mips_elf_sort_hash_table_f when sorting
301    the dynamic symbols.  */
302
303 struct mips_elf_hash_sort_data
304 {
305   /* The symbol in the global GOT with the lowest dynamic symbol table
306      index.  */
307   struct elf_link_hash_entry *low;
308   /* The least dynamic symbol table index corresponding to a non-TLS
309      symbol with a GOT entry.  */
310   long min_got_dynindx;
311   /* The greatest dynamic symbol table index corresponding to a symbol
312      with a GOT entry that is not referenced (e.g., a dynamic symbol
313      with dynamic relocations pointing to it from non-primary GOTs).  */
314   long max_unref_got_dynindx;
315   /* The greatest dynamic symbol table index not corresponding to a
316      symbol without a GOT entry.  */
317   long max_non_got_dynindx;
318 };
319
320 /* We make up to two PLT entries if needed, one for standard MIPS code
321    and one for compressed code, either a MIPS16 or microMIPS one.  We
322    keep a separate record of traditional lazy-binding stubs, for easier
323    processing.  */
324
325 struct plt_entry
326 {
327   /* Traditional SVR4 stub offset, or -1 if none.  */
328   bfd_vma stub_offset;
329
330   /* Standard PLT entry offset, or -1 if none.  */
331   bfd_vma mips_offset;
332
333   /* Compressed PLT entry offset, or -1 if none.  */
334   bfd_vma comp_offset;
335
336   /* The corresponding .got.plt index, or -1 if none.  */
337   bfd_vma gotplt_index;
338
339   /* Whether we need a standard PLT entry.  */
340   unsigned int need_mips : 1;
341
342   /* Whether we need a compressed PLT entry.  */
343   unsigned int need_comp : 1;
344 };
345
346 /* The MIPS ELF linker needs additional information for each symbol in
347    the global hash table.  */
348
349 struct mips_elf_link_hash_entry
350 {
351   struct elf_link_hash_entry root;
352
353   /* External symbol information.  */
354   EXTR esym;
355
356   /* The la25 stub we have created for ths symbol, if any.  */
357   struct mips_elf_la25_stub *la25_stub;
358
359   /* Number of R_MIPS_32, R_MIPS_REL32, or R_MIPS_64 relocs against
360      this symbol.  */
361   unsigned int possibly_dynamic_relocs;
362
363   /* If there is a stub that 32 bit functions should use to call this
364      16 bit function, this points to the section containing the stub.  */
365   asection *fn_stub;
366
367   /* If there is a stub that 16 bit functions should use to call this
368      32 bit function, this points to the section containing the stub.  */
369   asection *call_stub;
370
371   /* This is like the call_stub field, but it is used if the function
372      being called returns a floating point value.  */
373   asection *call_fp_stub;
374
375   /* The highest GGA_* value that satisfies all references to this symbol.  */
376   unsigned int global_got_area : 2;
377
378   /* True if all GOT relocations against this symbol are for calls.  This is
379      a looser condition than no_fn_stub below, because there may be other
380      non-call non-GOT relocations against the symbol.  */
381   unsigned int got_only_for_calls : 1;
382
383   /* True if one of the relocations described by possibly_dynamic_relocs
384      is against a readonly section.  */
385   unsigned int readonly_reloc : 1;
386
387   /* True if there is a relocation against this symbol that must be
388      resolved by the static linker (in other words, if the relocation
389      cannot possibly be made dynamic).  */
390   unsigned int has_static_relocs : 1;
391
392   /* True if we must not create a .MIPS.stubs entry for this symbol.
393      This is set, for example, if there are relocations related to
394      taking the function's address, i.e. any but R_MIPS_CALL*16 ones.
395      See "MIPS ABI Supplement, 3rd Edition", p. 4-20.  */
396   unsigned int no_fn_stub : 1;
397
398   /* Whether we need the fn_stub; this is true if this symbol appears
399      in any relocs other than a 16 bit call.  */
400   unsigned int need_fn_stub : 1;
401
402   /* True if this symbol is referenced by branch relocations from
403      any non-PIC input file.  This is used to determine whether an
404      la25 stub is required.  */
405   unsigned int has_nonpic_branches : 1;
406
407   /* Does this symbol need a traditional MIPS lazy-binding stub
408      (as opposed to a PLT entry)?  */
409   unsigned int needs_lazy_stub : 1;
410
411   /* Does this symbol resolve to a PLT entry?  */
412   unsigned int use_plt_entry : 1;
413 };
414
415 /* MIPS ELF linker hash table.  */
416
417 struct mips_elf_link_hash_table
418 {
419   struct elf_link_hash_table root;
420
421   /* The number of .rtproc entries.  */
422   bfd_size_type procedure_count;
423
424   /* The size of the .compact_rel section (if SGI_COMPAT).  */
425   bfd_size_type compact_rel_size;
426
427   /* This flag indicates that the value of DT_MIPS_RLD_MAP dynamic entry
428      is set to the address of __rld_obj_head as in IRIX5 and IRIX6.  */
429   bfd_boolean use_rld_obj_head;
430
431   /* The  __rld_map or __rld_obj_head symbol. */
432   struct elf_link_hash_entry *rld_symbol;
433
434   /* This is set if we see any mips16 stub sections.  */
435   bfd_boolean mips16_stubs_seen;
436
437   /* True if we can generate copy relocs and PLTs.  */
438   bfd_boolean use_plts_and_copy_relocs;
439
440   /* True if we're generating code for VxWorks.  */
441   bfd_boolean is_vxworks;
442
443   /* True if we already reported the small-data section overflow.  */
444   bfd_boolean small_data_overflow_reported;
445
446   /* Shortcuts to some dynamic sections, or NULL if they are not
447      being used.  */
448   asection *srelbss;
449   asection *sdynbss;
450   asection *srelplt;
451   asection *srelplt2;
452   asection *sgotplt;
453   asection *splt;
454   asection *sstubs;
455   asection *sgot;
456
457   /* The master GOT information.  */
458   struct mips_got_info *got_info;
459
460   /* The global symbol in the GOT with the lowest index in the dynamic
461      symbol table.  */
462   struct elf_link_hash_entry *global_gotsym;
463
464   /* The size of the PLT header in bytes.  */
465   bfd_vma plt_header_size;
466
467   /* The size of a standard PLT entry in bytes.  */
468   bfd_vma plt_mips_entry_size;
469
470   /* The size of a compressed PLT entry in bytes.  */
471   bfd_vma plt_comp_entry_size;
472
473   /* The offset of the next standard PLT entry to create.  */
474   bfd_vma plt_mips_offset;
475
476   /* The offset of the next compressed PLT entry to create.  */
477   bfd_vma plt_comp_offset;
478
479   /* The index of the next .got.plt entry to create.  */
480   bfd_vma plt_got_index;
481
482   /* The number of functions that need a lazy-binding stub.  */
483   bfd_vma lazy_stub_count;
484
485   /* The size of a function stub entry in bytes.  */
486   bfd_vma function_stub_size;
487
488   /* The number of reserved entries at the beginning of the GOT.  */
489   unsigned int reserved_gotno;
490
491   /* The section used for mips_elf_la25_stub trampolines.
492      See the comment above that structure for details.  */
493   asection *strampoline;
494
495   /* A table of mips_elf_la25_stubs, indexed by (input_section, offset)
496      pairs.  */
497   htab_t la25_stubs;
498
499   /* A function FN (NAME, IS, OS) that creates a new input section
500      called NAME and links it to output section OS.  If IS is nonnull,
501      the new section should go immediately before it, otherwise it
502      should go at the (current) beginning of OS.
503
504      The function returns the new section on success, otherwise it
505      returns null.  */
506   asection *(*add_stub_section) (const char *, asection *, asection *);
507
508   /* Small local sym cache.  */
509   struct sym_cache sym_cache;
510
511   /* Is the PLT header compressed?  */
512   unsigned int plt_header_is_comp : 1;
513 };
514
515 /* Get the MIPS ELF linker hash table from a link_info structure.  */
516
517 #define mips_elf_hash_table(p) \
518   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
519   == MIPS_ELF_DATA ? ((struct mips_elf_link_hash_table *) ((p)->hash)) : NULL)
520
521 /* A structure used to communicate with htab_traverse callbacks.  */
522 struct mips_htab_traverse_info
523 {
524   /* The usual link-wide information.  */
525   struct bfd_link_info *info;
526   bfd *output_bfd;
527
528   /* Starts off FALSE and is set to TRUE if the link should be aborted.  */
529   bfd_boolean error;
530 };
531
532 /* MIPS ELF private object data.  */
533
534 struct mips_elf_obj_tdata
535 {
536   /* Generic ELF private object data.  */
537   struct elf_obj_tdata root;
538
539   /* Input BFD providing Tag_GNU_MIPS_ABI_FP attribute for output.  */
540   bfd *abi_fp_bfd;
541
542   /* The GOT requirements of input bfds.  */
543   struct mips_got_info *got;
544
545   /* Used by _bfd_mips_elf_find_nearest_line.  The structure could be
546      included directly in this one, but there's no point to wasting
547      the memory just for the infrequently called find_nearest_line.  */
548   struct mips_elf_find_line *find_line_info;
549
550   /* An array of stub sections indexed by symbol number.  */
551   asection **local_stubs;
552   asection **local_call_stubs;
553
554   /* The Irix 5 support uses two virtual sections, which represent
555      text/data symbols defined in dynamic objects.  */
556   asymbol *elf_data_symbol;
557   asymbol *elf_text_symbol;
558   asection *elf_data_section;
559   asection *elf_text_section;
560 };
561
562 /* Get MIPS ELF private object data from BFD's tdata.  */
563
564 #define mips_elf_tdata(bfd) \
565   ((struct mips_elf_obj_tdata *) (bfd)->tdata.any)
566
567 #define TLS_RELOC_P(r_type) \
568   (r_type == R_MIPS_TLS_DTPMOD32                \
569    || r_type == R_MIPS_TLS_DTPMOD64             \
570    || r_type == R_MIPS_TLS_DTPREL32             \
571    || r_type == R_MIPS_TLS_DTPREL64             \
572    || r_type == R_MIPS_TLS_GD                   \
573    || r_type == R_MIPS_TLS_LDM                  \
574    || r_type == R_MIPS_TLS_DTPREL_HI16          \
575    || r_type == R_MIPS_TLS_DTPREL_LO16          \
576    || r_type == R_MIPS_TLS_GOTTPREL             \
577    || r_type == R_MIPS_TLS_TPREL32              \
578    || r_type == R_MIPS_TLS_TPREL64              \
579    || r_type == R_MIPS_TLS_TPREL_HI16           \
580    || r_type == R_MIPS_TLS_TPREL_LO16           \
581    || r_type == R_MIPS16_TLS_GD                 \
582    || r_type == R_MIPS16_TLS_LDM                \
583    || r_type == R_MIPS16_TLS_DTPREL_HI16        \
584    || r_type == R_MIPS16_TLS_DTPREL_LO16        \
585    || r_type == R_MIPS16_TLS_GOTTPREL           \
586    || r_type == R_MIPS16_TLS_TPREL_HI16         \
587    || r_type == R_MIPS16_TLS_TPREL_LO16         \
588    || r_type == R_MICROMIPS_TLS_GD              \
589    || r_type == R_MICROMIPS_TLS_LDM             \
590    || r_type == R_MICROMIPS_TLS_DTPREL_HI16     \
591    || r_type == R_MICROMIPS_TLS_DTPREL_LO16     \
592    || r_type == R_MICROMIPS_TLS_GOTTPREL        \
593    || r_type == R_MICROMIPS_TLS_TPREL_HI16      \
594    || r_type == R_MICROMIPS_TLS_TPREL_LO16)
595
596 /* Structure used to pass information to mips_elf_output_extsym.  */
597
598 struct extsym_info
599 {
600   bfd *abfd;
601   struct bfd_link_info *info;
602   struct ecoff_debug_info *debug;
603   const struct ecoff_debug_swap *swap;
604   bfd_boolean failed;
605 };
606
607 /* The names of the runtime procedure table symbols used on IRIX5.  */
608
609 static const char * const mips_elf_dynsym_rtproc_names[] =
610 {
611   "_procedure_table",
612   "_procedure_string_table",
613   "_procedure_table_size",
614   NULL
615 };
616
617 /* These structures are used to generate the .compact_rel section on
618    IRIX5.  */
619
620 typedef struct
621 {
622   unsigned long id1;            /* Always one?  */
623   unsigned long num;            /* Number of compact relocation entries.  */
624   unsigned long id2;            /* Always two?  */
625   unsigned long offset;         /* The file offset of the first relocation.  */
626   unsigned long reserved0;      /* Zero?  */
627   unsigned long reserved1;      /* Zero?  */
628 } Elf32_compact_rel;
629
630 typedef struct
631 {
632   bfd_byte id1[4];
633   bfd_byte num[4];
634   bfd_byte id2[4];
635   bfd_byte offset[4];
636   bfd_byte reserved0[4];
637   bfd_byte reserved1[4];
638 } Elf32_External_compact_rel;
639
640 typedef struct
641 {
642   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
643   unsigned int rtype : 4;       /* Relocation types. See below.  */
644   unsigned int dist2to : 8;
645   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
646   unsigned long konst;          /* KONST field. See below.  */
647   unsigned long vaddr;          /* VADDR to be relocated.  */
648 } Elf32_crinfo;
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 } Elf32_crinfo2;
658
659 typedef struct
660 {
661   bfd_byte info[4];
662   bfd_byte konst[4];
663   bfd_byte vaddr[4];
664 } Elf32_External_crinfo;
665
666 typedef struct
667 {
668   bfd_byte info[4];
669   bfd_byte konst[4];
670 } Elf32_External_crinfo2;
671
672 /* These are the constants used to swap the bitfields in a crinfo.  */
673
674 #define CRINFO_CTYPE (0x1)
675 #define CRINFO_CTYPE_SH (31)
676 #define CRINFO_RTYPE (0xf)
677 #define CRINFO_RTYPE_SH (27)
678 #define CRINFO_DIST2TO (0xff)
679 #define CRINFO_DIST2TO_SH (19)
680 #define CRINFO_RELVADDR (0x7ffff)
681 #define CRINFO_RELVADDR_SH (0)
682
683 /* A compact relocation info has long (3 words) or short (2 words)
684    formats.  A short format doesn't have VADDR field and relvaddr
685    fields contains ((VADDR - vaddr of the previous entry) >> 2).  */
686 #define CRF_MIPS_LONG                   1
687 #define CRF_MIPS_SHORT                  0
688
689 /* There are 4 types of compact relocation at least. The value KONST
690    has different meaning for each type:
691
692    (type)               (konst)
693    CT_MIPS_REL32        Address in data
694    CT_MIPS_WORD         Address in word (XXX)
695    CT_MIPS_GPHI_LO      GP - vaddr
696    CT_MIPS_JMPAD        Address to jump
697    */
698
699 #define CRT_MIPS_REL32                  0xa
700 #define CRT_MIPS_WORD                   0xb
701 #define CRT_MIPS_GPHI_LO                0xc
702 #define CRT_MIPS_JMPAD                  0xd
703
704 #define mips_elf_set_cr_format(x,format)        ((x).ctype = (format))
705 #define mips_elf_set_cr_type(x,type)            ((x).rtype = (type))
706 #define mips_elf_set_cr_dist2to(x,v)            ((x).dist2to = (v))
707 #define mips_elf_set_cr_relvaddr(x,d)           ((x).relvaddr = (d)<<2)
708 \f
709 /* The structure of the runtime procedure descriptor created by the
710    loader for use by the static exception system.  */
711
712 typedef struct runtime_pdr {
713         bfd_vma adr;            /* Memory address of start of procedure.  */
714         long    regmask;        /* Save register mask.  */
715         long    regoffset;      /* Save register offset.  */
716         long    fregmask;       /* Save floating point register mask.  */
717         long    fregoffset;     /* Save floating point register offset.  */
718         long    frameoffset;    /* Frame size.  */
719         short   framereg;       /* Frame pointer register.  */
720         short   pcreg;          /* Offset or reg of return pc.  */
721         long    irpss;          /* Index into the runtime string table.  */
722         long    reserved;
723         struct exception_info *exception_info;/* Pointer to exception array.  */
724 } RPDR, *pRPDR;
725 #define cbRPDR sizeof (RPDR)
726 #define rpdNil ((pRPDR) 0)
727 \f
728 static struct mips_got_entry *mips_elf_create_local_got_entry
729   (bfd *, struct bfd_link_info *, bfd *, bfd_vma, unsigned long,
730    struct mips_elf_link_hash_entry *, int);
731 static bfd_boolean mips_elf_sort_hash_table_f
732   (struct mips_elf_link_hash_entry *, void *);
733 static bfd_vma mips_elf_high
734   (bfd_vma);
735 static bfd_boolean mips_elf_create_dynamic_relocation
736   (bfd *, struct bfd_link_info *, const Elf_Internal_Rela *,
737    struct mips_elf_link_hash_entry *, asection *, bfd_vma,
738    bfd_vma *, asection *);
739 static bfd_vma mips_elf_adjust_gp
740   (bfd *, struct mips_got_info *, bfd *);
741
742 /* This will be used when we sort the dynamic relocation records.  */
743 static bfd *reldyn_sorting_bfd;
744
745 /* True if ABFD is for CPUs with load interlocking that include
746    non-MIPS1 CPUs and R3900.  */
747 #define LOAD_INTERLOCKS_P(abfd) \
748   (   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) != E_MIPS_ARCH_1) \
749    || ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_3900))
750
751 /* True if ABFD is for CPUs that are faster if JAL is converted to BAL.
752    This should be safe for all architectures.  We enable this predicate
753    for RM9000 for now.  */
754 #define JAL_TO_BAL_P(abfd) \
755   ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_9000)
756
757 /* True if ABFD is for CPUs that are faster if JALR is converted to BAL.
758    This should be safe for all architectures.  We enable this predicate for
759    all CPUs.  */
760 #define JALR_TO_BAL_P(abfd) 1
761
762 /* True if ABFD is for CPUs that are faster if JR is converted to B.
763    This should be safe for all architectures.  We enable this predicate for
764    all CPUs.  */
765 #define JR_TO_B_P(abfd) 1
766
767 /* True if ABFD is a PIC object.  */
768 #define PIC_OBJECT_P(abfd) \
769   ((elf_elfheader (abfd)->e_flags & EF_MIPS_PIC) != 0)
770
771 /* Nonzero if ABFD is using the N32 ABI.  */
772 #define ABI_N32_P(abfd) \
773   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI2) != 0)
774
775 /* Nonzero if ABFD is using the N64 ABI.  */
776 #define ABI_64_P(abfd) \
777   (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS64)
778
779 /* Nonzero if ABFD is using NewABI conventions.  */
780 #define NEWABI_P(abfd) (ABI_N32_P (abfd) || ABI_64_P (abfd))
781
782 /* Nonzero if ABFD has microMIPS code.  */
783 #define MICROMIPS_P(abfd) \
784   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS) != 0)
785
786 /* The IRIX compatibility level we are striving for.  */
787 #define IRIX_COMPAT(abfd) \
788   (get_elf_backend_data (abfd)->elf_backend_mips_irix_compat (abfd))
789
790 /* Whether we are trying to be compatible with IRIX at all.  */
791 #define SGI_COMPAT(abfd) \
792   (IRIX_COMPAT (abfd) != ict_none)
793
794 /* The name of the options section.  */
795 #define MIPS_ELF_OPTIONS_SECTION_NAME(abfd) \
796   (NEWABI_P (abfd) ? ".MIPS.options" : ".options")
797
798 /* True if NAME is the recognized name of any SHT_MIPS_OPTIONS section.
799    Some IRIX system files do not use MIPS_ELF_OPTIONS_SECTION_NAME.  */
800 #define MIPS_ELF_OPTIONS_SECTION_NAME_P(NAME) \
801   (strcmp (NAME, ".MIPS.options") == 0 || strcmp (NAME, ".options") == 0)
802
803 /* Whether the section is readonly.  */
804 #define MIPS_ELF_READONLY_SECTION(sec) \
805   ((sec->flags & (SEC_ALLOC | SEC_LOAD | SEC_READONLY))         \
806    == (SEC_ALLOC | SEC_LOAD | SEC_READONLY))
807
808 /* The name of the stub section.  */
809 #define MIPS_ELF_STUB_SECTION_NAME(abfd) ".MIPS.stubs"
810
811 /* The size of an external REL relocation.  */
812 #define MIPS_ELF_REL_SIZE(abfd) \
813   (get_elf_backend_data (abfd)->s->sizeof_rel)
814
815 /* The size of an external RELA relocation.  */
816 #define MIPS_ELF_RELA_SIZE(abfd) \
817   (get_elf_backend_data (abfd)->s->sizeof_rela)
818
819 /* The size of an external dynamic table entry.  */
820 #define MIPS_ELF_DYN_SIZE(abfd) \
821   (get_elf_backend_data (abfd)->s->sizeof_dyn)
822
823 /* The size of a GOT entry.  */
824 #define MIPS_ELF_GOT_SIZE(abfd) \
825   (get_elf_backend_data (abfd)->s->arch_size / 8)
826
827 /* The size of the .rld_map section. */
828 #define MIPS_ELF_RLD_MAP_SIZE(abfd) \
829   (get_elf_backend_data (abfd)->s->arch_size / 8)
830
831 /* The size of a symbol-table entry.  */
832 #define MIPS_ELF_SYM_SIZE(abfd) \
833   (get_elf_backend_data (abfd)->s->sizeof_sym)
834
835 /* The default alignment for sections, as a power of two.  */
836 #define MIPS_ELF_LOG_FILE_ALIGN(abfd)                           \
837   (get_elf_backend_data (abfd)->s->log_file_align)
838
839 /* Get word-sized data.  */
840 #define MIPS_ELF_GET_WORD(abfd, ptr) \
841   (ABI_64_P (abfd) ? bfd_get_64 (abfd, ptr) : bfd_get_32 (abfd, ptr))
842
843 /* Put out word-sized data.  */
844 #define MIPS_ELF_PUT_WORD(abfd, val, ptr)       \
845   (ABI_64_P (abfd)                              \
846    ? bfd_put_64 (abfd, val, ptr)                \
847    : bfd_put_32 (abfd, val, ptr))
848
849 /* The opcode for word-sized loads (LW or LD).  */
850 #define MIPS_ELF_LOAD_WORD(abfd) \
851   (ABI_64_P (abfd) ? 0xdc000000 : 0x8c000000)
852
853 /* Add a dynamic symbol table-entry.  */
854 #define MIPS_ELF_ADD_DYNAMIC_ENTRY(info, tag, val)      \
855   _bfd_elf_add_dynamic_entry (info, tag, val)
856
857 #define MIPS_ELF_RTYPE_TO_HOWTO(abfd, rtype, rela)                      \
858   (get_elf_backend_data (abfd)->elf_backend_mips_rtype_to_howto (rtype, rela))
859
860 /* The name of the dynamic relocation section.  */
861 #define MIPS_ELF_REL_DYN_NAME(INFO) \
862   (mips_elf_hash_table (INFO)->is_vxworks ? ".rela.dyn" : ".rel.dyn")
863
864 /* In case we're on a 32-bit machine, construct a 64-bit "-1" value
865    from smaller values.  Start with zero, widen, *then* decrement.  */
866 #define MINUS_ONE       (((bfd_vma)0) - 1)
867 #define MINUS_TWO       (((bfd_vma)0) - 2)
868
869 /* The value to write into got[1] for SVR4 targets, to identify it is
870    a GNU object.  The dynamic linker can then use got[1] to store the
871    module pointer.  */
872 #define MIPS_ELF_GNU_GOT1_MASK(abfd) \
873   ((bfd_vma) 1 << (ABI_64_P (abfd) ? 63 : 31))
874
875 /* The offset of $gp from the beginning of the .got section.  */
876 #define ELF_MIPS_GP_OFFSET(INFO) \
877   (mips_elf_hash_table (INFO)->is_vxworks ? 0x0 : 0x7ff0)
878
879 /* The maximum size of the GOT for it to be addressable using 16-bit
880    offsets from $gp.  */
881 #define MIPS_ELF_GOT_MAX_SIZE(INFO) (ELF_MIPS_GP_OFFSET (INFO) + 0x7fff)
882
883 /* Instructions which appear in a stub.  */
884 #define STUB_LW(abfd)                                                   \
885   ((ABI_64_P (abfd)                                                     \
886     ? 0xdf998010                                /* ld t9,0x8010(gp) */  \
887     : 0x8f998010))                              /* lw t9,0x8010(gp) */
888 #define STUB_MOVE(abfd)                                                 \
889    ((ABI_64_P (abfd)                                                    \
890      ? 0x03e0782d                               /* daddu t7,ra */       \
891      : 0x03e07821))                             /* addu t7,ra */
892 #define STUB_LUI(VAL) (0x3c180000 + (VAL))      /* lui t8,VAL */
893 #define STUB_JALR 0x0320f809                    /* jalr t9,ra */
894 #define STUB_ORI(VAL) (0x37180000 + (VAL))      /* ori t8,t8,VAL */
895 #define STUB_LI16U(VAL) (0x34180000 + (VAL))    /* ori t8,zero,VAL unsigned */
896 #define STUB_LI16S(abfd, VAL)                                           \
897    ((ABI_64_P (abfd)                                                    \
898     ? (0x64180000 + (VAL))      /* daddiu t8,zero,VAL sign extended */  \
899     : (0x24180000 + (VAL))))    /* addiu t8,zero,VAL sign extended */
900
901 /* Likewise for the microMIPS ASE.  */
902 #define STUB_LW_MICROMIPS(abfd)                                         \
903   (ABI_64_P (abfd)                                                      \
904    ? 0xdf3c8010                                 /* ld t9,0x8010(gp) */  \
905    : 0xff3c8010)                                /* lw t9,0x8010(gp) */
906 #define STUB_MOVE_MICROMIPS 0x0dff              /* move t7,ra */
907 #define STUB_LUI_MICROMIPS(VAL)                                         \
908    (0x41b80000 + (VAL))                         /* lui t8,VAL */
909 #define STUB_JALR_MICROMIPS 0x45d9              /* jalr t9 */
910 #define STUB_ORI_MICROMIPS(VAL)                                         \
911   (0x53180000 + (VAL))                          /* ori t8,t8,VAL */
912 #define STUB_LI16U_MICROMIPS(VAL)                                       \
913   (0x53000000 + (VAL))                          /* ori t8,zero,VAL unsigned */
914 #define STUB_LI16S_MICROMIPS(abfd, VAL)                                 \
915    (ABI_64_P (abfd)                                                     \
916     ? 0x5f000000 + (VAL)        /* daddiu t8,zero,VAL sign extended */  \
917     : 0x33000000 + (VAL))       /* addiu t8,zero,VAL sign extended */
918
919 #define MIPS_FUNCTION_STUB_NORMAL_SIZE 16
920 #define MIPS_FUNCTION_STUB_BIG_SIZE 20
921 #define MICROMIPS_FUNCTION_STUB_NORMAL_SIZE 12
922 #define MICROMIPS_FUNCTION_STUB_BIG_SIZE 16
923
924 /* The name of the dynamic interpreter.  This is put in the .interp
925    section.  */
926
927 #define ELF_DYNAMIC_INTERPRETER(abfd)           \
928    (ABI_N32_P (abfd) ? "/usr/lib32/libc.so.1"   \
929     : ABI_64_P (abfd) ? "/usr/lib64/libc.so.1"  \
930     : "/usr/lib/libc.so.1")
931
932 #ifdef BFD64
933 #define MNAME(bfd,pre,pos) \
934   (ABI_64_P (bfd) ? CONCAT4 (pre,64,_,pos) : CONCAT4 (pre,32,_,pos))
935 #define ELF_R_SYM(bfd, i)                                       \
936   (ABI_64_P (bfd) ? ELF64_R_SYM (i) : ELF32_R_SYM (i))
937 #define ELF_R_TYPE(bfd, i)                                      \
938   (ABI_64_P (bfd) ? ELF64_MIPS_R_TYPE (i) : ELF32_R_TYPE (i))
939 #define ELF_R_INFO(bfd, s, t)                                   \
940   (ABI_64_P (bfd) ? ELF64_R_INFO (s, t) : ELF32_R_INFO (s, t))
941 #else
942 #define MNAME(bfd,pre,pos) CONCAT4 (pre,32,_,pos)
943 #define ELF_R_SYM(bfd, i)                                       \
944   (ELF32_R_SYM (i))
945 #define ELF_R_TYPE(bfd, i)                                      \
946   (ELF32_R_TYPE (i))
947 #define ELF_R_INFO(bfd, s, t)                                   \
948   (ELF32_R_INFO (s, t))
949 #endif
950 \f
951   /* The mips16 compiler uses a couple of special sections to handle
952      floating point arguments.
953
954      Section names that look like .mips16.fn.FNNAME contain stubs that
955      copy floating point arguments from the fp regs to the gp regs and
956      then jump to FNNAME.  If any 32 bit function calls FNNAME, the
957      call should be redirected to the stub instead.  If no 32 bit
958      function calls FNNAME, the stub should be discarded.  We need to
959      consider any reference to the function, not just a call, because
960      if the address of the function is taken we will need the stub,
961      since the address might be passed to a 32 bit function.
962
963      Section names that look like .mips16.call.FNNAME contain stubs
964      that copy floating point arguments from the gp regs to the fp
965      regs and then jump to FNNAME.  If FNNAME is a 32 bit function,
966      then any 16 bit function that calls FNNAME should be redirected
967      to the stub instead.  If FNNAME is not a 32 bit function, the
968      stub should be discarded.
969
970      .mips16.call.fp.FNNAME sections are similar, but contain stubs
971      which call FNNAME and then copy the return value from the fp regs
972      to the gp regs.  These stubs store the return value in $18 while
973      calling FNNAME; any function which might call one of these stubs
974      must arrange to save $18 around the call.  (This case is not
975      needed for 32 bit functions that call 16 bit functions, because
976      16 bit functions always return floating point values in both
977      $f0/$f1 and $2/$3.)
978
979      Note that in all cases FNNAME might be defined statically.
980      Therefore, FNNAME is not used literally.  Instead, the relocation
981      information will indicate which symbol the section is for.
982
983      We record any stubs that we find in the symbol table.  */
984
985 #define FN_STUB ".mips16.fn."
986 #define CALL_STUB ".mips16.call."
987 #define CALL_FP_STUB ".mips16.call.fp."
988
989 #define FN_STUB_P(name) CONST_STRNEQ (name, FN_STUB)
990 #define CALL_STUB_P(name) CONST_STRNEQ (name, CALL_STUB)
991 #define CALL_FP_STUB_P(name) CONST_STRNEQ (name, CALL_FP_STUB)
992 \f
993 /* The format of the first PLT entry in an O32 executable.  */
994 static const bfd_vma mips_o32_exec_plt0_entry[] =
995 {
996   0x3c1c0000,   /* lui $28, %hi(&GOTPLT[0])                             */
997   0x8f990000,   /* lw $25, %lo(&GOTPLT[0])($28)                         */
998   0x279c0000,   /* addiu $28, $28, %lo(&GOTPLT[0])                      */
999   0x031cc023,   /* subu $24, $24, $28                                   */
1000   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
1001   0x0018c082,   /* srl $24, $24, 2                                      */
1002   0x0320f809,   /* jalr $25                                             */
1003   0x2718fffe    /* subu $24, $24, 2                                     */
1004 };
1005
1006 /* The format of the first PLT entry in an N32 executable.  Different
1007    because gp ($28) is not available; we use t2 ($14) instead.  */
1008 static const bfd_vma mips_n32_exec_plt0_entry[] =
1009 {
1010   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
1011   0x8dd90000,   /* lw $25, %lo(&GOTPLT[0])($14)                         */
1012   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
1013   0x030ec023,   /* subu $24, $24, $14                                   */
1014   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
1015   0x0018c082,   /* srl $24, $24, 2                                      */
1016   0x0320f809,   /* jalr $25                                             */
1017   0x2718fffe    /* subu $24, $24, 2                                     */
1018 };
1019
1020 /* The format of the first PLT entry in an N64 executable.  Different
1021    from N32 because of the increased size of GOT entries.  */
1022 static const bfd_vma mips_n64_exec_plt0_entry[] =
1023 {
1024   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
1025   0xddd90000,   /* ld $25, %lo(&GOTPLT[0])($14)                         */
1026   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
1027   0x030ec023,   /* subu $24, $24, $14                                   */
1028   0x03e0782d,   /* move $15, $31        # 64-bit move (daddu)           */
1029   0x0018c0c2,   /* srl $24, $24, 3                                      */
1030   0x0320f809,   /* jalr $25                                             */
1031   0x2718fffe    /* subu $24, $24, 2                                     */
1032 };
1033
1034 /* The format of the microMIPS first PLT entry in an O32 executable.
1035    We rely on v0 ($2) rather than t8 ($24) to contain the address
1036    of the GOTPLT entry handled, so this stub may only be used when
1037    all the subsequent PLT entries are microMIPS code too.
1038
1039    The trailing NOP is for alignment and correct disassembly only.  */
1040 static const bfd_vma micromips_o32_exec_plt0_entry[] =
1041 {
1042   0x7980, 0x0000,       /* addiupc $3, (&GOTPLT[0]) - .                 */
1043   0xff23, 0x0000,       /* lw $25, 0($3)                                */
1044   0x0535,               /* subu $2, $2, $3                              */
1045   0x2525,               /* srl $2, $2, 2                                */
1046   0x3302, 0xfffe,       /* subu $24, $2, 2                              */
1047   0x0dff,               /* move $15, $31                                */
1048   0x45f9,               /* jalrs $25                                    */
1049   0x0f83,               /* move $28, $3                                 */
1050   0x0c00                /* nop                                          */
1051 };
1052
1053 /* The format of subsequent standard PLT entries.  */
1054 static const bfd_vma mips_exec_plt_entry[] =
1055 {
1056   0x3c0f0000,   /* lui $15, %hi(.got.plt entry)                 */
1057   0x01f90000,   /* l[wd] $25, %lo(.got.plt entry)($15)          */
1058   0x25f80000,   /* addiu $24, $15, %lo(.got.plt entry)          */
1059   0x03200008    /* jr $25                                       */
1060 };
1061
1062 /* The format of subsequent MIPS16 o32 PLT entries.  We use v0 ($2)
1063    and v1 ($3) as temporaries because t8 ($24) and t9 ($25) are not
1064    directly addressable.  */
1065 static const bfd_vma mips16_o32_exec_plt_entry[] =
1066 {
1067   0xb203,               /* lw $2, 12($pc)                       */
1068   0x9a60,               /* lw $3, 0($2)                         */
1069   0x651a,               /* move $24, $2                         */
1070   0xeb00,               /* jr $3                                */
1071   0x653b,               /* move $25, $3                         */
1072   0x6500,               /* nop                                  */
1073   0x0000, 0x0000        /* .word (.got.plt entry)               */
1074 };
1075
1076 /* The format of subsequent microMIPS o32 PLT entries.  We use v0 ($2)
1077    as a temporary because t8 ($24) is not addressable with ADDIUPC.  */
1078 static const bfd_vma micromips_o32_exec_plt_entry[] =
1079 {
1080   0x7900, 0x0000,       /* addiupc $2, (.got.plt entry) - .     */
1081   0xff22, 0x0000,       /* lw $25, 0($2)                        */
1082   0x4599,               /* jr $25                               */
1083   0x0f02                /* move $24, $2                         */
1084 };
1085
1086 /* The format of the first PLT entry in a VxWorks executable.  */
1087 static const bfd_vma mips_vxworks_exec_plt0_entry[] =
1088 {
1089   0x3c190000,   /* lui t9, %hi(_GLOBAL_OFFSET_TABLE_)           */
1090   0x27390000,   /* addiu t9, t9, %lo(_GLOBAL_OFFSET_TABLE_)     */
1091   0x8f390008,   /* lw t9, 8(t9)                                 */
1092   0x00000000,   /* nop                                          */
1093   0x03200008,   /* jr t9                                        */
1094   0x00000000    /* nop                                          */
1095 };
1096
1097 /* The format of subsequent PLT entries.  */
1098 static const bfd_vma mips_vxworks_exec_plt_entry[] =
1099 {
1100   0x10000000,   /* b .PLT_resolver                      */
1101   0x24180000,   /* li t8, <pltindex>                    */
1102   0x3c190000,   /* lui t9, %hi(<.got.plt slot>)         */
1103   0x27390000,   /* addiu t9, t9, %lo(<.got.plt slot>)   */
1104   0x8f390000,   /* lw t9, 0(t9)                         */
1105   0x00000000,   /* nop                                  */
1106   0x03200008,   /* jr t9                                */
1107   0x00000000    /* nop                                  */
1108 };
1109
1110 /* The format of the first PLT entry in a VxWorks shared object.  */
1111 static const bfd_vma mips_vxworks_shared_plt0_entry[] =
1112 {
1113   0x8f990008,   /* lw t9, 8(gp)         */
1114   0x00000000,   /* nop                  */
1115   0x03200008,   /* jr t9                */
1116   0x00000000,   /* nop                  */
1117   0x00000000,   /* nop                  */
1118   0x00000000    /* nop                  */
1119 };
1120
1121 /* The format of subsequent PLT entries.  */
1122 static const bfd_vma mips_vxworks_shared_plt_entry[] =
1123 {
1124   0x10000000,   /* b .PLT_resolver      */
1125   0x24180000    /* li t8, <pltindex>    */
1126 };
1127 \f
1128 /* microMIPS 32-bit opcode helper installer.  */
1129
1130 static void
1131 bfd_put_micromips_32 (const bfd *abfd, bfd_vma opcode, bfd_byte *ptr)
1132 {
1133   bfd_put_16 (abfd, (opcode >> 16) & 0xffff, ptr);
1134   bfd_put_16 (abfd,  opcode        & 0xffff, ptr + 2);
1135 }
1136
1137 /* microMIPS 32-bit opcode helper retriever.  */
1138
1139 static bfd_vma
1140 bfd_get_micromips_32 (const bfd *abfd, const bfd_byte *ptr)
1141 {
1142   return (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
1143 }
1144 \f
1145 /* Look up an entry in a MIPS ELF linker hash table.  */
1146
1147 #define mips_elf_link_hash_lookup(table, string, create, copy, follow)  \
1148   ((struct mips_elf_link_hash_entry *)                                  \
1149    elf_link_hash_lookup (&(table)->root, (string), (create),            \
1150                          (copy), (follow)))
1151
1152 /* Traverse a MIPS ELF linker hash table.  */
1153
1154 #define mips_elf_link_hash_traverse(table, func, info)                  \
1155   (elf_link_hash_traverse                                               \
1156    (&(table)->root,                                                     \
1157     (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func),    \
1158     (info)))
1159
1160 /* Find the base offsets for thread-local storage in this object,
1161    for GD/LD and IE/LE respectively.  */
1162
1163 #define TP_OFFSET 0x7000
1164 #define DTP_OFFSET 0x8000
1165
1166 static bfd_vma
1167 dtprel_base (struct bfd_link_info *info)
1168 {
1169   /* If tls_sec is NULL, we should have signalled an error already.  */
1170   if (elf_hash_table (info)->tls_sec == NULL)
1171     return 0;
1172   return elf_hash_table (info)->tls_sec->vma + DTP_OFFSET;
1173 }
1174
1175 static bfd_vma
1176 tprel_base (struct bfd_link_info *info)
1177 {
1178   /* If tls_sec is NULL, we should have signalled an error already.  */
1179   if (elf_hash_table (info)->tls_sec == NULL)
1180     return 0;
1181   return elf_hash_table (info)->tls_sec->vma + TP_OFFSET;
1182 }
1183
1184 /* Create an entry in a MIPS ELF linker hash table.  */
1185
1186 static struct bfd_hash_entry *
1187 mips_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
1188                             struct bfd_hash_table *table, const char *string)
1189 {
1190   struct mips_elf_link_hash_entry *ret =
1191     (struct mips_elf_link_hash_entry *) entry;
1192
1193   /* Allocate the structure if it has not already been allocated by a
1194      subclass.  */
1195   if (ret == NULL)
1196     ret = bfd_hash_allocate (table, sizeof (struct mips_elf_link_hash_entry));
1197   if (ret == NULL)
1198     return (struct bfd_hash_entry *) ret;
1199
1200   /* Call the allocation method of the superclass.  */
1201   ret = ((struct mips_elf_link_hash_entry *)
1202          _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret,
1203                                      table, string));
1204   if (ret != NULL)
1205     {
1206       /* Set local fields.  */
1207       memset (&ret->esym, 0, sizeof (EXTR));
1208       /* We use -2 as a marker to indicate that the information has
1209          not been set.  -1 means there is no associated ifd.  */
1210       ret->esym.ifd = -2;
1211       ret->la25_stub = 0;
1212       ret->possibly_dynamic_relocs = 0;
1213       ret->fn_stub = NULL;
1214       ret->call_stub = NULL;
1215       ret->call_fp_stub = NULL;
1216       ret->global_got_area = GGA_NONE;
1217       ret->got_only_for_calls = TRUE;
1218       ret->readonly_reloc = FALSE;
1219       ret->has_static_relocs = FALSE;
1220       ret->no_fn_stub = FALSE;
1221       ret->need_fn_stub = FALSE;
1222       ret->has_nonpic_branches = FALSE;
1223       ret->needs_lazy_stub = FALSE;
1224       ret->use_plt_entry = FALSE;
1225     }
1226
1227   return (struct bfd_hash_entry *) ret;
1228 }
1229
1230 /* Allocate MIPS ELF private object data.  */
1231
1232 bfd_boolean
1233 _bfd_mips_elf_mkobject (bfd *abfd)
1234 {
1235   return bfd_elf_allocate_object (abfd, sizeof (struct mips_elf_obj_tdata),
1236                                   MIPS_ELF_DATA);
1237 }
1238
1239 bfd_boolean
1240 _bfd_mips_elf_new_section_hook (bfd *abfd, asection *sec)
1241 {
1242   if (!sec->used_by_bfd)
1243     {
1244       struct _mips_elf_section_data *sdata;
1245       bfd_size_type amt = sizeof (*sdata);
1246
1247       sdata = bfd_zalloc (abfd, amt);
1248       if (sdata == NULL)
1249         return FALSE;
1250       sec->used_by_bfd = sdata;
1251     }
1252
1253   return _bfd_elf_new_section_hook (abfd, sec);
1254 }
1255 \f
1256 /* Read ECOFF debugging information from a .mdebug section into a
1257    ecoff_debug_info structure.  */
1258
1259 bfd_boolean
1260 _bfd_mips_elf_read_ecoff_info (bfd *abfd, asection *section,
1261                                struct ecoff_debug_info *debug)
1262 {
1263   HDRR *symhdr;
1264   const struct ecoff_debug_swap *swap;
1265   char *ext_hdr;
1266
1267   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1268   memset (debug, 0, sizeof (*debug));
1269
1270   ext_hdr = bfd_malloc (swap->external_hdr_size);
1271   if (ext_hdr == NULL && swap->external_hdr_size != 0)
1272     goto error_return;
1273
1274   if (! bfd_get_section_contents (abfd, section, ext_hdr, 0,
1275                                   swap->external_hdr_size))
1276     goto error_return;
1277
1278   symhdr = &debug->symbolic_header;
1279   (*swap->swap_hdr_in) (abfd, ext_hdr, symhdr);
1280
1281   /* The symbolic header contains absolute file offsets and sizes to
1282      read.  */
1283 #define READ(ptr, offset, count, size, type)                            \
1284   if (symhdr->count == 0)                                               \
1285     debug->ptr = NULL;                                                  \
1286   else                                                                  \
1287     {                                                                   \
1288       bfd_size_type amt = (bfd_size_type) size * symhdr->count;         \
1289       debug->ptr = bfd_malloc (amt);                                    \
1290       if (debug->ptr == NULL)                                           \
1291         goto error_return;                                              \
1292       if (bfd_seek (abfd, symhdr->offset, SEEK_SET) != 0                \
1293           || bfd_bread (debug->ptr, amt, abfd) != amt)                  \
1294         goto error_return;                                              \
1295     }
1296
1297   READ (line, cbLineOffset, cbLine, sizeof (unsigned char), unsigned char *);
1298   READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *);
1299   READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *);
1300   READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *);
1301   READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *);
1302   READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext),
1303         union aux_ext *);
1304   READ (ss, cbSsOffset, issMax, sizeof (char), char *);
1305   READ (ssext, cbSsExtOffset, issExtMax, sizeof (char), char *);
1306   READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *);
1307   READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *);
1308   READ (external_ext, cbExtOffset, iextMax, swap->external_ext_size, void *);
1309 #undef READ
1310
1311   debug->fdr = NULL;
1312
1313   return TRUE;
1314
1315  error_return:
1316   if (ext_hdr != NULL)
1317     free (ext_hdr);
1318   if (debug->line != NULL)
1319     free (debug->line);
1320   if (debug->external_dnr != NULL)
1321     free (debug->external_dnr);
1322   if (debug->external_pdr != NULL)
1323     free (debug->external_pdr);
1324   if (debug->external_sym != NULL)
1325     free (debug->external_sym);
1326   if (debug->external_opt != NULL)
1327     free (debug->external_opt);
1328   if (debug->external_aux != NULL)
1329     free (debug->external_aux);
1330   if (debug->ss != NULL)
1331     free (debug->ss);
1332   if (debug->ssext != NULL)
1333     free (debug->ssext);
1334   if (debug->external_fdr != NULL)
1335     free (debug->external_fdr);
1336   if (debug->external_rfd != NULL)
1337     free (debug->external_rfd);
1338   if (debug->external_ext != NULL)
1339     free (debug->external_ext);
1340   return FALSE;
1341 }
1342 \f
1343 /* Swap RPDR (runtime procedure table entry) for output.  */
1344
1345 static void
1346 ecoff_swap_rpdr_out (bfd *abfd, const RPDR *in, struct rpdr_ext *ex)
1347 {
1348   H_PUT_S32 (abfd, in->adr, ex->p_adr);
1349   H_PUT_32 (abfd, in->regmask, ex->p_regmask);
1350   H_PUT_32 (abfd, in->regoffset, ex->p_regoffset);
1351   H_PUT_32 (abfd, in->fregmask, ex->p_fregmask);
1352   H_PUT_32 (abfd, in->fregoffset, ex->p_fregoffset);
1353   H_PUT_32 (abfd, in->frameoffset, ex->p_frameoffset);
1354
1355   H_PUT_16 (abfd, in->framereg, ex->p_framereg);
1356   H_PUT_16 (abfd, in->pcreg, ex->p_pcreg);
1357
1358   H_PUT_32 (abfd, in->irpss, ex->p_irpss);
1359 }
1360
1361 /* Create a runtime procedure table from the .mdebug section.  */
1362
1363 static bfd_boolean
1364 mips_elf_create_procedure_table (void *handle, bfd *abfd,
1365                                  struct bfd_link_info *info, asection *s,
1366                                  struct ecoff_debug_info *debug)
1367 {
1368   const struct ecoff_debug_swap *swap;
1369   HDRR *hdr = &debug->symbolic_header;
1370   RPDR *rpdr, *rp;
1371   struct rpdr_ext *erp;
1372   void *rtproc;
1373   struct pdr_ext *epdr;
1374   struct sym_ext *esym;
1375   char *ss, **sv;
1376   char *str;
1377   bfd_size_type size;
1378   bfd_size_type count;
1379   unsigned long sindex;
1380   unsigned long i;
1381   PDR pdr;
1382   SYMR sym;
1383   const char *no_name_func = _("static procedure (no name)");
1384
1385   epdr = NULL;
1386   rpdr = NULL;
1387   esym = NULL;
1388   ss = NULL;
1389   sv = NULL;
1390
1391   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1392
1393   sindex = strlen (no_name_func) + 1;
1394   count = hdr->ipdMax;
1395   if (count > 0)
1396     {
1397       size = swap->external_pdr_size;
1398
1399       epdr = bfd_malloc (size * count);
1400       if (epdr == NULL)
1401         goto error_return;
1402
1403       if (! _bfd_ecoff_get_accumulated_pdr (handle, (bfd_byte *) epdr))
1404         goto error_return;
1405
1406       size = sizeof (RPDR);
1407       rp = rpdr = bfd_malloc (size * count);
1408       if (rpdr == NULL)
1409         goto error_return;
1410
1411       size = sizeof (char *);
1412       sv = bfd_malloc (size * count);
1413       if (sv == NULL)
1414         goto error_return;
1415
1416       count = hdr->isymMax;
1417       size = swap->external_sym_size;
1418       esym = bfd_malloc (size * count);
1419       if (esym == NULL)
1420         goto error_return;
1421
1422       if (! _bfd_ecoff_get_accumulated_sym (handle, (bfd_byte *) esym))
1423         goto error_return;
1424
1425       count = hdr->issMax;
1426       ss = bfd_malloc (count);
1427       if (ss == NULL)
1428         goto error_return;
1429       if (! _bfd_ecoff_get_accumulated_ss (handle, (bfd_byte *) ss))
1430         goto error_return;
1431
1432       count = hdr->ipdMax;
1433       for (i = 0; i < (unsigned long) count; i++, rp++)
1434         {
1435           (*swap->swap_pdr_in) (abfd, epdr + i, &pdr);
1436           (*swap->swap_sym_in) (abfd, &esym[pdr.isym], &sym);
1437           rp->adr = sym.value;
1438           rp->regmask = pdr.regmask;
1439           rp->regoffset = pdr.regoffset;
1440           rp->fregmask = pdr.fregmask;
1441           rp->fregoffset = pdr.fregoffset;
1442           rp->frameoffset = pdr.frameoffset;
1443           rp->framereg = pdr.framereg;
1444           rp->pcreg = pdr.pcreg;
1445           rp->irpss = sindex;
1446           sv[i] = ss + sym.iss;
1447           sindex += strlen (sv[i]) + 1;
1448         }
1449     }
1450
1451   size = sizeof (struct rpdr_ext) * (count + 2) + sindex;
1452   size = BFD_ALIGN (size, 16);
1453   rtproc = bfd_alloc (abfd, size);
1454   if (rtproc == NULL)
1455     {
1456       mips_elf_hash_table (info)->procedure_count = 0;
1457       goto error_return;
1458     }
1459
1460   mips_elf_hash_table (info)->procedure_count = count + 2;
1461
1462   erp = rtproc;
1463   memset (erp, 0, sizeof (struct rpdr_ext));
1464   erp++;
1465   str = (char *) rtproc + sizeof (struct rpdr_ext) * (count + 2);
1466   strcpy (str, no_name_func);
1467   str += strlen (no_name_func) + 1;
1468   for (i = 0; i < count; i++)
1469     {
1470       ecoff_swap_rpdr_out (abfd, rpdr + i, erp + i);
1471       strcpy (str, sv[i]);
1472       str += strlen (sv[i]) + 1;
1473     }
1474   H_PUT_S32 (abfd, -1, (erp + count)->p_adr);
1475
1476   /* Set the size and contents of .rtproc section.  */
1477   s->size = size;
1478   s->contents = rtproc;
1479
1480   /* Skip this section later on (I don't think this currently
1481      matters, but someday it might).  */
1482   s->map_head.link_order = NULL;
1483
1484   if (epdr != NULL)
1485     free (epdr);
1486   if (rpdr != NULL)
1487     free (rpdr);
1488   if (esym != NULL)
1489     free (esym);
1490   if (ss != NULL)
1491     free (ss);
1492   if (sv != NULL)
1493     free (sv);
1494
1495   return TRUE;
1496
1497  error_return:
1498   if (epdr != NULL)
1499     free (epdr);
1500   if (rpdr != NULL)
1501     free (rpdr);
1502   if (esym != NULL)
1503     free (esym);
1504   if (ss != NULL)
1505     free (ss);
1506   if (sv != NULL)
1507     free (sv);
1508   return FALSE;
1509 }
1510 \f
1511 /* We're going to create a stub for H.  Create a symbol for the stub's
1512    value and size, to help make the disassembly easier to read.  */
1513
1514 static bfd_boolean
1515 mips_elf_create_stub_symbol (struct bfd_link_info *info,
1516                              struct mips_elf_link_hash_entry *h,
1517                              const char *prefix, asection *s, bfd_vma value,
1518                              bfd_vma size)
1519 {
1520   struct bfd_link_hash_entry *bh;
1521   struct elf_link_hash_entry *elfh;
1522   const char *name;
1523
1524   if (ELF_ST_IS_MICROMIPS (h->root.other))
1525     value |= 1;
1526
1527   /* Create a new symbol.  */
1528   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1529   bh = NULL;
1530   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1531                                          BSF_LOCAL, s, value, NULL,
1532                                          TRUE, FALSE, &bh))
1533     return FALSE;
1534
1535   /* Make it a local function.  */
1536   elfh = (struct elf_link_hash_entry *) bh;
1537   elfh->type = ELF_ST_INFO (STB_LOCAL, STT_FUNC);
1538   elfh->size = size;
1539   elfh->forced_local = 1;
1540   return TRUE;
1541 }
1542
1543 /* We're about to redefine H.  Create a symbol to represent H's
1544    current value and size, to help make the disassembly easier
1545    to read.  */
1546
1547 static bfd_boolean
1548 mips_elf_create_shadow_symbol (struct bfd_link_info *info,
1549                                struct mips_elf_link_hash_entry *h,
1550                                const char *prefix)
1551 {
1552   struct bfd_link_hash_entry *bh;
1553   struct elf_link_hash_entry *elfh;
1554   const char *name;
1555   asection *s;
1556   bfd_vma value;
1557
1558   /* Read the symbol's value.  */
1559   BFD_ASSERT (h->root.root.type == bfd_link_hash_defined
1560               || h->root.root.type == bfd_link_hash_defweak);
1561   s = h->root.root.u.def.section;
1562   value = h->root.root.u.def.value;
1563
1564   /* Create a new symbol.  */
1565   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1566   bh = NULL;
1567   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1568                                          BSF_LOCAL, s, value, NULL,
1569                                          TRUE, FALSE, &bh))
1570     return FALSE;
1571
1572   /* Make it local and copy the other attributes from H.  */
1573   elfh = (struct elf_link_hash_entry *) bh;
1574   elfh->type = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (h->root.type));
1575   elfh->other = h->root.other;
1576   elfh->size = h->root.size;
1577   elfh->forced_local = 1;
1578   return TRUE;
1579 }
1580
1581 /* Return TRUE if relocations in SECTION can refer directly to a MIPS16
1582    function rather than to a hard-float stub.  */
1583
1584 static bfd_boolean
1585 section_allows_mips16_refs_p (asection *section)
1586 {
1587   const char *name;
1588
1589   name = bfd_get_section_name (section->owner, section);
1590   return (FN_STUB_P (name)
1591           || CALL_STUB_P (name)
1592           || CALL_FP_STUB_P (name)
1593           || strcmp (name, ".pdr") == 0);
1594 }
1595
1596 /* [RELOCS, RELEND) are the relocations against SEC, which is a MIPS16
1597    stub section of some kind.  Return the R_SYMNDX of the target
1598    function, or 0 if we can't decide which function that is.  */
1599
1600 static unsigned long
1601 mips16_stub_symndx (const struct elf_backend_data *bed,
1602                     asection *sec ATTRIBUTE_UNUSED,
1603                     const Elf_Internal_Rela *relocs,
1604                     const Elf_Internal_Rela *relend)
1605 {
1606   int int_rels_per_ext_rel = bed->s->int_rels_per_ext_rel;
1607   const Elf_Internal_Rela *rel;
1608
1609   /* Trust the first R_MIPS_NONE relocation, if any, but not a subsequent
1610      one in a compound relocation.  */
1611   for (rel = relocs; rel < relend; rel += int_rels_per_ext_rel)
1612     if (ELF_R_TYPE (sec->owner, rel->r_info) == R_MIPS_NONE)
1613       return ELF_R_SYM (sec->owner, rel->r_info);
1614
1615   /* Otherwise trust the first relocation, whatever its kind.  This is
1616      the traditional behavior.  */
1617   if (relocs < relend)
1618     return ELF_R_SYM (sec->owner, relocs->r_info);
1619
1620   return 0;
1621 }
1622
1623 /* Check the mips16 stubs for a particular symbol, and see if we can
1624    discard them.  */
1625
1626 static void
1627 mips_elf_check_mips16_stubs (struct bfd_link_info *info,
1628                              struct mips_elf_link_hash_entry *h)
1629 {
1630   /* Dynamic symbols must use the standard call interface, in case other
1631      objects try to call them.  */
1632   if (h->fn_stub != NULL
1633       && h->root.dynindx != -1)
1634     {
1635       mips_elf_create_shadow_symbol (info, h, ".mips16.");
1636       h->need_fn_stub = TRUE;
1637     }
1638
1639   if (h->fn_stub != NULL
1640       && ! h->need_fn_stub)
1641     {
1642       /* We don't need the fn_stub; the only references to this symbol
1643          are 16 bit calls.  Clobber the size to 0 to prevent it from
1644          being included in the link.  */
1645       h->fn_stub->size = 0;
1646       h->fn_stub->flags &= ~SEC_RELOC;
1647       h->fn_stub->reloc_count = 0;
1648       h->fn_stub->flags |= SEC_EXCLUDE;
1649     }
1650
1651   if (h->call_stub != NULL
1652       && ELF_ST_IS_MIPS16 (h->root.other))
1653     {
1654       /* We don't need the call_stub; this is a 16 bit function, so
1655          calls from other 16 bit functions are OK.  Clobber the size
1656          to 0 to prevent it from being included in the link.  */
1657       h->call_stub->size = 0;
1658       h->call_stub->flags &= ~SEC_RELOC;
1659       h->call_stub->reloc_count = 0;
1660       h->call_stub->flags |= SEC_EXCLUDE;
1661     }
1662
1663   if (h->call_fp_stub != NULL
1664       && ELF_ST_IS_MIPS16 (h->root.other))
1665     {
1666       /* We don't need the call_stub; this is a 16 bit function, so
1667          calls from other 16 bit functions are OK.  Clobber the size
1668          to 0 to prevent it from being included in the link.  */
1669       h->call_fp_stub->size = 0;
1670       h->call_fp_stub->flags &= ~SEC_RELOC;
1671       h->call_fp_stub->reloc_count = 0;
1672       h->call_fp_stub->flags |= SEC_EXCLUDE;
1673     }
1674 }
1675
1676 /* Hashtable callbacks for mips_elf_la25_stubs.  */
1677
1678 static hashval_t
1679 mips_elf_la25_stub_hash (const void *entry_)
1680 {
1681   const struct mips_elf_la25_stub *entry;
1682
1683   entry = (struct mips_elf_la25_stub *) entry_;
1684   return entry->h->root.root.u.def.section->id
1685     + entry->h->root.root.u.def.value;
1686 }
1687
1688 static int
1689 mips_elf_la25_stub_eq (const void *entry1_, const void *entry2_)
1690 {
1691   const struct mips_elf_la25_stub *entry1, *entry2;
1692
1693   entry1 = (struct mips_elf_la25_stub *) entry1_;
1694   entry2 = (struct mips_elf_la25_stub *) entry2_;
1695   return ((entry1->h->root.root.u.def.section
1696            == entry2->h->root.root.u.def.section)
1697           && (entry1->h->root.root.u.def.value
1698               == entry2->h->root.root.u.def.value));
1699 }
1700
1701 /* Called by the linker to set up the la25 stub-creation code.  FN is
1702    the linker's implementation of add_stub_function.  Return true on
1703    success.  */
1704
1705 bfd_boolean
1706 _bfd_mips_elf_init_stubs (struct bfd_link_info *info,
1707                           asection *(*fn) (const char *, asection *,
1708                                            asection *))
1709 {
1710   struct mips_elf_link_hash_table *htab;
1711
1712   htab = mips_elf_hash_table (info);
1713   if (htab == NULL)
1714     return FALSE;
1715
1716   htab->add_stub_section = fn;
1717   htab->la25_stubs = htab_try_create (1, mips_elf_la25_stub_hash,
1718                                       mips_elf_la25_stub_eq, NULL);
1719   if (htab->la25_stubs == NULL)
1720     return FALSE;
1721
1722   return TRUE;
1723 }
1724
1725 /* Return true if H is a locally-defined PIC function, in the sense
1726    that it or its fn_stub might need $25 to be valid on entry.
1727    Note that MIPS16 functions set up $gp using PC-relative instructions,
1728    so they themselves never need $25 to be valid.  Only non-MIPS16
1729    entry points are of interest here.  */
1730
1731 static bfd_boolean
1732 mips_elf_local_pic_function_p (struct mips_elf_link_hash_entry *h)
1733 {
1734   return ((h->root.root.type == bfd_link_hash_defined
1735            || h->root.root.type == bfd_link_hash_defweak)
1736           && h->root.def_regular
1737           && !bfd_is_abs_section (h->root.root.u.def.section)
1738           && (!ELF_ST_IS_MIPS16 (h->root.other)
1739               || (h->fn_stub && h->need_fn_stub))
1740           && (PIC_OBJECT_P (h->root.root.u.def.section->owner)
1741               || ELF_ST_IS_MIPS_PIC (h->root.other)));
1742 }
1743
1744 /* Set *SEC to the input section that contains the target of STUB.
1745    Return the offset of the target from the start of that section.  */
1746
1747 static bfd_vma
1748 mips_elf_get_la25_target (struct mips_elf_la25_stub *stub,
1749                           asection **sec)
1750 {
1751   if (ELF_ST_IS_MIPS16 (stub->h->root.other))
1752     {
1753       BFD_ASSERT (stub->h->need_fn_stub);
1754       *sec = stub->h->fn_stub;
1755       return 0;
1756     }
1757   else
1758     {
1759       *sec = stub->h->root.root.u.def.section;
1760       return stub->h->root.root.u.def.value;
1761     }
1762 }
1763
1764 /* STUB describes an la25 stub that we have decided to implement
1765    by inserting an LUI/ADDIU pair before the target function.
1766    Create the section and redirect the function symbol to it.  */
1767
1768 static bfd_boolean
1769 mips_elf_add_la25_intro (struct mips_elf_la25_stub *stub,
1770                          struct bfd_link_info *info)
1771 {
1772   struct mips_elf_link_hash_table *htab;
1773   char *name;
1774   asection *s, *input_section;
1775   unsigned int align;
1776
1777   htab = mips_elf_hash_table (info);
1778   if (htab == NULL)
1779     return FALSE;
1780
1781   /* Create a unique name for the new section.  */
1782   name = bfd_malloc (11 + sizeof (".text.stub."));
1783   if (name == NULL)
1784     return FALSE;
1785   sprintf (name, ".text.stub.%d", (int) htab_elements (htab->la25_stubs));
1786
1787   /* Create the section.  */
1788   mips_elf_get_la25_target (stub, &input_section);
1789   s = htab->add_stub_section (name, input_section,
1790                               input_section->output_section);
1791   if (s == NULL)
1792     return FALSE;
1793
1794   /* Make sure that any padding goes before the stub.  */
1795   align = input_section->alignment_power;
1796   if (!bfd_set_section_alignment (s->owner, s, align))
1797     return FALSE;
1798   if (align > 3)
1799     s->size = (1 << align) - 8;
1800
1801   /* Create a symbol for the stub.  */
1802   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 8);
1803   stub->stub_section = s;
1804   stub->offset = s->size;
1805
1806   /* Allocate room for it.  */
1807   s->size += 8;
1808   return TRUE;
1809 }
1810
1811 /* STUB describes an la25 stub that we have decided to implement
1812    with a separate trampoline.  Allocate room for it and redirect
1813    the function symbol to it.  */
1814
1815 static bfd_boolean
1816 mips_elf_add_la25_trampoline (struct mips_elf_la25_stub *stub,
1817                               struct bfd_link_info *info)
1818 {
1819   struct mips_elf_link_hash_table *htab;
1820   asection *s;
1821
1822   htab = mips_elf_hash_table (info);
1823   if (htab == NULL)
1824     return FALSE;
1825
1826   /* Create a trampoline section, if we haven't already.  */
1827   s = htab->strampoline;
1828   if (s == NULL)
1829     {
1830       asection *input_section = stub->h->root.root.u.def.section;
1831       s = htab->add_stub_section (".text", NULL,
1832                                   input_section->output_section);
1833       if (s == NULL || !bfd_set_section_alignment (s->owner, s, 4))
1834         return FALSE;
1835       htab->strampoline = s;
1836     }
1837
1838   /* Create a symbol for the stub.  */
1839   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 16);
1840   stub->stub_section = s;
1841   stub->offset = s->size;
1842
1843   /* Allocate room for it.  */
1844   s->size += 16;
1845   return TRUE;
1846 }
1847
1848 /* H describes a symbol that needs an la25 stub.  Make sure that an
1849    appropriate stub exists and point H at it.  */
1850
1851 static bfd_boolean
1852 mips_elf_add_la25_stub (struct bfd_link_info *info,
1853                         struct mips_elf_link_hash_entry *h)
1854 {
1855   struct mips_elf_link_hash_table *htab;
1856   struct mips_elf_la25_stub search, *stub;
1857   bfd_boolean use_trampoline_p;
1858   asection *s;
1859   bfd_vma value;
1860   void **slot;
1861
1862   /* Describe the stub we want.  */
1863   search.stub_section = NULL;
1864   search.offset = 0;
1865   search.h = h;
1866
1867   /* See if we've already created an equivalent stub.  */
1868   htab = mips_elf_hash_table (info);
1869   if (htab == NULL)
1870     return FALSE;
1871
1872   slot = htab_find_slot (htab->la25_stubs, &search, INSERT);
1873   if (slot == NULL)
1874     return FALSE;
1875
1876   stub = (struct mips_elf_la25_stub *) *slot;
1877   if (stub != NULL)
1878     {
1879       /* We can reuse the existing stub.  */
1880       h->la25_stub = stub;
1881       return TRUE;
1882     }
1883
1884   /* Create a permanent copy of ENTRY and add it to the hash table.  */
1885   stub = bfd_malloc (sizeof (search));
1886   if (stub == NULL)
1887     return FALSE;
1888   *stub = search;
1889   *slot = stub;
1890
1891   /* Prefer to use LUI/ADDIU stubs if the function is at the beginning
1892      of the section and if we would need no more than 2 nops.  */
1893   value = mips_elf_get_la25_target (stub, &s);
1894   use_trampoline_p = (value != 0 || s->alignment_power > 4);
1895
1896   h->la25_stub = stub;
1897   return (use_trampoline_p
1898           ? mips_elf_add_la25_trampoline (stub, info)
1899           : mips_elf_add_la25_intro (stub, info));
1900 }
1901
1902 /* A mips_elf_link_hash_traverse callback that is called before sizing
1903    sections.  DATA points to a mips_htab_traverse_info structure.  */
1904
1905 static bfd_boolean
1906 mips_elf_check_symbols (struct mips_elf_link_hash_entry *h, void *data)
1907 {
1908   struct mips_htab_traverse_info *hti;
1909
1910   hti = (struct mips_htab_traverse_info *) data;
1911   if (!hti->info->relocatable)
1912     mips_elf_check_mips16_stubs (hti->info, h);
1913
1914   if (mips_elf_local_pic_function_p (h))
1915     {
1916       /* PR 12845: If H is in a section that has been garbage
1917          collected it will have its output section set to *ABS*.  */
1918       if (bfd_is_abs_section (h->root.root.u.def.section->output_section))
1919         return TRUE;
1920
1921       /* H is a function that might need $25 to be valid on entry.
1922          If we're creating a non-PIC relocatable object, mark H as
1923          being PIC.  If we're creating a non-relocatable object with
1924          non-PIC branches and jumps to H, make sure that H has an la25
1925          stub.  */
1926       if (hti->info->relocatable)
1927         {
1928           if (!PIC_OBJECT_P (hti->output_bfd))
1929             h->root.other = ELF_ST_SET_MIPS_PIC (h->root.other);
1930         }
1931       else if (h->has_nonpic_branches && !mips_elf_add_la25_stub (hti->info, h))
1932         {
1933           hti->error = TRUE;
1934           return FALSE;
1935         }
1936     }
1937   return TRUE;
1938 }
1939 \f
1940 /* R_MIPS16_26 is used for the mips16 jal and jalx instructions.
1941    Most mips16 instructions are 16 bits, but these instructions
1942    are 32 bits.
1943
1944    The format of these instructions is:
1945
1946    +--------------+--------------------------------+
1947    |     JALX     | X|   Imm 20:16  |   Imm 25:21  |
1948    +--------------+--------------------------------+
1949    |                Immediate  15:0                |
1950    +-----------------------------------------------+
1951
1952    JALX is the 5-bit value 00011.  X is 0 for jal, 1 for jalx.
1953    Note that the immediate value in the first word is swapped.
1954
1955    When producing a relocatable object file, R_MIPS16_26 is
1956    handled mostly like R_MIPS_26.  In particular, the addend is
1957    stored as a straight 26-bit value in a 32-bit instruction.
1958    (gas makes life simpler for itself by never adjusting a
1959    R_MIPS16_26 reloc to be against a section, so the addend is
1960    always zero).  However, the 32 bit instruction is stored as 2
1961    16-bit values, rather than a single 32-bit value.  In a
1962    big-endian file, the result is the same; in a little-endian
1963    file, the two 16-bit halves of the 32 bit value are swapped.
1964    This is so that a disassembler can recognize the jal
1965    instruction.
1966
1967    When doing a final link, R_MIPS16_26 is treated as a 32 bit
1968    instruction stored as two 16-bit values.  The addend A is the
1969    contents of the targ26 field.  The calculation is the same as
1970    R_MIPS_26.  When storing the calculated value, reorder the
1971    immediate value as shown above, and don't forget to store the
1972    value as two 16-bit values.
1973
1974    To put it in MIPS ABI terms, the relocation field is T-targ26-16,
1975    defined as
1976
1977    big-endian:
1978    +--------+----------------------+
1979    |        |                      |
1980    |        |    targ26-16         |
1981    |31    26|25                   0|
1982    +--------+----------------------+
1983
1984    little-endian:
1985    +----------+------+-------------+
1986    |          |      |             |
1987    |  sub1    |      |     sub2    |
1988    |0        9|10  15|16         31|
1989    +----------+--------------------+
1990    where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is
1991    ((sub1 << 16) | sub2)).
1992
1993    When producing a relocatable object file, the calculation is
1994    (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1995    When producing a fully linked file, the calculation is
1996    let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1997    ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff)
1998
1999    The table below lists the other MIPS16 instruction relocations.
2000    Each one is calculated in the same way as the non-MIPS16 relocation
2001    given on the right, but using the extended MIPS16 layout of 16-bit
2002    immediate fields:
2003
2004         R_MIPS16_GPREL          R_MIPS_GPREL16
2005         R_MIPS16_GOT16          R_MIPS_GOT16
2006         R_MIPS16_CALL16         R_MIPS_CALL16
2007         R_MIPS16_HI16           R_MIPS_HI16
2008         R_MIPS16_LO16           R_MIPS_LO16
2009
2010    A typical instruction will have a format like this:
2011
2012    +--------------+--------------------------------+
2013    |    EXTEND    |     Imm 10:5    |   Imm 15:11  |
2014    +--------------+--------------------------------+
2015    |    Major     |   rx   |   ry   |   Imm  4:0   |
2016    +--------------+--------------------------------+
2017
2018    EXTEND is the five bit value 11110.  Major is the instruction
2019    opcode.
2020
2021    All we need to do here is shuffle the bits appropriately.
2022    As above, the two 16-bit halves must be swapped on a
2023    little-endian system.  */
2024
2025 static inline bfd_boolean
2026 mips16_reloc_p (int r_type)
2027 {
2028   switch (r_type)
2029     {
2030     case R_MIPS16_26:
2031     case R_MIPS16_GPREL:
2032     case R_MIPS16_GOT16:
2033     case R_MIPS16_CALL16:
2034     case R_MIPS16_HI16:
2035     case R_MIPS16_LO16:
2036     case R_MIPS16_TLS_GD:
2037     case R_MIPS16_TLS_LDM:
2038     case R_MIPS16_TLS_DTPREL_HI16:
2039     case R_MIPS16_TLS_DTPREL_LO16:
2040     case R_MIPS16_TLS_GOTTPREL:
2041     case R_MIPS16_TLS_TPREL_HI16:
2042     case R_MIPS16_TLS_TPREL_LO16:
2043       return TRUE;
2044
2045     default:
2046       return FALSE;
2047     }
2048 }
2049
2050 /* Check if a microMIPS reloc.  */
2051
2052 static inline bfd_boolean
2053 micromips_reloc_p (unsigned int r_type)
2054 {
2055   return r_type >= R_MICROMIPS_min && r_type < R_MICROMIPS_max;
2056 }
2057
2058 /* Similar to MIPS16, the two 16-bit halves in microMIPS must be swapped
2059    on a little-endian system.  This does not apply to R_MICROMIPS_PC7_S1
2060    and R_MICROMIPS_PC10_S1 relocs that apply to 16-bit instructions.  */
2061
2062 static inline bfd_boolean
2063 micromips_reloc_shuffle_p (unsigned int r_type)
2064 {
2065   return (micromips_reloc_p (r_type)
2066           && r_type != R_MICROMIPS_PC7_S1
2067           && r_type != R_MICROMIPS_PC10_S1);
2068 }
2069
2070 static inline bfd_boolean
2071 got16_reloc_p (int r_type)
2072 {
2073   return (r_type == R_MIPS_GOT16
2074           || r_type == R_MIPS16_GOT16
2075           || r_type == R_MICROMIPS_GOT16);
2076 }
2077
2078 static inline bfd_boolean
2079 call16_reloc_p (int r_type)
2080 {
2081   return (r_type == R_MIPS_CALL16
2082           || r_type == R_MIPS16_CALL16
2083           || r_type == R_MICROMIPS_CALL16);
2084 }
2085
2086 static inline bfd_boolean
2087 got_disp_reloc_p (unsigned int r_type)
2088 {
2089   return r_type == R_MIPS_GOT_DISP || r_type == R_MICROMIPS_GOT_DISP;
2090 }
2091
2092 static inline bfd_boolean
2093 got_page_reloc_p (unsigned int r_type)
2094 {
2095   return r_type == R_MIPS_GOT_PAGE || r_type == R_MICROMIPS_GOT_PAGE;
2096 }
2097
2098 static inline bfd_boolean
2099 got_ofst_reloc_p (unsigned int r_type)
2100 {
2101   return r_type == R_MIPS_GOT_OFST || r_type == R_MICROMIPS_GOT_OFST;
2102 }
2103
2104 static inline bfd_boolean
2105 got_hi16_reloc_p (unsigned int r_type)
2106 {
2107   return r_type == R_MIPS_GOT_HI16 || r_type == R_MICROMIPS_GOT_HI16;
2108 }
2109
2110 static inline bfd_boolean
2111 got_lo16_reloc_p (unsigned int r_type)
2112 {
2113   return r_type == R_MIPS_GOT_LO16 || r_type == R_MICROMIPS_GOT_LO16;
2114 }
2115
2116 static inline bfd_boolean
2117 call_hi16_reloc_p (unsigned int r_type)
2118 {
2119   return r_type == R_MIPS_CALL_HI16 || r_type == R_MICROMIPS_CALL_HI16;
2120 }
2121
2122 static inline bfd_boolean
2123 call_lo16_reloc_p (unsigned int r_type)
2124 {
2125   return r_type == R_MIPS_CALL_LO16 || r_type == R_MICROMIPS_CALL_LO16;
2126 }
2127
2128 static inline bfd_boolean
2129 hi16_reloc_p (int r_type)
2130 {
2131   return (r_type == R_MIPS_HI16
2132           || r_type == R_MIPS16_HI16
2133           || r_type == R_MICROMIPS_HI16);
2134 }
2135
2136 static inline bfd_boolean
2137 lo16_reloc_p (int r_type)
2138 {
2139   return (r_type == R_MIPS_LO16
2140           || r_type == R_MIPS16_LO16
2141           || r_type == R_MICROMIPS_LO16);
2142 }
2143
2144 static inline bfd_boolean
2145 mips16_call_reloc_p (int r_type)
2146 {
2147   return r_type == R_MIPS16_26 || r_type == R_MIPS16_CALL16;
2148 }
2149
2150 static inline bfd_boolean
2151 jal_reloc_p (int r_type)
2152 {
2153   return (r_type == R_MIPS_26
2154           || r_type == R_MIPS16_26
2155           || r_type == R_MICROMIPS_26_S1);
2156 }
2157
2158 static inline bfd_boolean
2159 micromips_branch_reloc_p (int r_type)
2160 {
2161   return (r_type == R_MICROMIPS_26_S1
2162           || r_type == R_MICROMIPS_PC16_S1
2163           || r_type == R_MICROMIPS_PC10_S1
2164           || r_type == R_MICROMIPS_PC7_S1);
2165 }
2166
2167 static inline bfd_boolean
2168 tls_gd_reloc_p (unsigned int r_type)
2169 {
2170   return (r_type == R_MIPS_TLS_GD
2171           || r_type == R_MIPS16_TLS_GD
2172           || r_type == R_MICROMIPS_TLS_GD);
2173 }
2174
2175 static inline bfd_boolean
2176 tls_ldm_reloc_p (unsigned int r_type)
2177 {
2178   return (r_type == R_MIPS_TLS_LDM
2179           || r_type == R_MIPS16_TLS_LDM
2180           || r_type == R_MICROMIPS_TLS_LDM);
2181 }
2182
2183 static inline bfd_boolean
2184 tls_gottprel_reloc_p (unsigned int r_type)
2185 {
2186   return (r_type == R_MIPS_TLS_GOTTPREL
2187           || r_type == R_MIPS16_TLS_GOTTPREL
2188           || r_type == R_MICROMIPS_TLS_GOTTPREL);
2189 }
2190
2191 void
2192 _bfd_mips_elf_reloc_unshuffle (bfd *abfd, int r_type,
2193                                bfd_boolean jal_shuffle, bfd_byte *data)
2194 {
2195   bfd_vma first, second, val;
2196
2197   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2198     return;
2199
2200   /* Pick up the first and second halfwords of the instruction.  */
2201   first = bfd_get_16 (abfd, data);
2202   second = bfd_get_16 (abfd, data + 2);
2203   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2204     val = first << 16 | second;
2205   else if (r_type != R_MIPS16_26)
2206     val = (((first & 0xf800) << 16) | ((second & 0xffe0) << 11)
2207            | ((first & 0x1f) << 11) | (first & 0x7e0) | (second & 0x1f));
2208   else
2209     val = (((first & 0xfc00) << 16) | ((first & 0x3e0) << 11)
2210            | ((first & 0x1f) << 21) | second);
2211   bfd_put_32 (abfd, val, data);
2212 }
2213
2214 void
2215 _bfd_mips_elf_reloc_shuffle (bfd *abfd, int r_type,
2216                              bfd_boolean jal_shuffle, bfd_byte *data)
2217 {
2218   bfd_vma first, second, val;
2219
2220   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2221     return;
2222
2223   val = bfd_get_32 (abfd, data);
2224   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2225     {
2226       second = val & 0xffff;
2227       first = val >> 16;
2228     }
2229   else if (r_type != R_MIPS16_26)
2230     {
2231       second = ((val >> 11) & 0xffe0) | (val & 0x1f);
2232       first = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0);
2233     }
2234   else
2235     {
2236       second = val & 0xffff;
2237       first = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0)
2238                | ((val >> 21) & 0x1f);
2239     }
2240   bfd_put_16 (abfd, second, data + 2);
2241   bfd_put_16 (abfd, first, data);
2242 }
2243
2244 bfd_reloc_status_type
2245 _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol,
2246                                arelent *reloc_entry, asection *input_section,
2247                                bfd_boolean relocatable, void *data, bfd_vma gp)
2248 {
2249   bfd_vma relocation;
2250   bfd_signed_vma val;
2251   bfd_reloc_status_type status;
2252
2253   if (bfd_is_com_section (symbol->section))
2254     relocation = 0;
2255   else
2256     relocation = symbol->value;
2257
2258   relocation += symbol->section->output_section->vma;
2259   relocation += symbol->section->output_offset;
2260
2261   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2262     return bfd_reloc_outofrange;
2263
2264   /* Set val to the offset into the section or symbol.  */
2265   val = reloc_entry->addend;
2266
2267   _bfd_mips_elf_sign_extend (val, 16);
2268
2269   /* Adjust val for the final section location and GP value.  If we
2270      are producing relocatable output, we don't want to do this for
2271      an external symbol.  */
2272   if (! relocatable
2273       || (symbol->flags & BSF_SECTION_SYM) != 0)
2274     val += relocation - gp;
2275
2276   if (reloc_entry->howto->partial_inplace)
2277     {
2278       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2279                                        (bfd_byte *) data
2280                                        + reloc_entry->address);
2281       if (status != bfd_reloc_ok)
2282         return status;
2283     }
2284   else
2285     reloc_entry->addend = val;
2286
2287   if (relocatable)
2288     reloc_entry->address += input_section->output_offset;
2289
2290   return bfd_reloc_ok;
2291 }
2292
2293 /* Used to store a REL high-part relocation such as R_MIPS_HI16 or
2294    R_MIPS_GOT16.  REL is the relocation, INPUT_SECTION is the section
2295    that contains the relocation field and DATA points to the start of
2296    INPUT_SECTION.  */
2297
2298 struct mips_hi16
2299 {
2300   struct mips_hi16 *next;
2301   bfd_byte *data;
2302   asection *input_section;
2303   arelent rel;
2304 };
2305
2306 /* FIXME: This should not be a static variable.  */
2307
2308 static struct mips_hi16 *mips_hi16_list;
2309
2310 /* A howto special_function for REL *HI16 relocations.  We can only
2311    calculate the correct value once we've seen the partnering
2312    *LO16 relocation, so just save the information for later.
2313
2314    The ABI requires that the *LO16 immediately follow the *HI16.
2315    However, as a GNU extension, we permit an arbitrary number of
2316    *HI16s to be associated with a single *LO16.  This significantly
2317    simplies the relocation handling in gcc.  */
2318
2319 bfd_reloc_status_type
2320 _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2321                           asymbol *symbol ATTRIBUTE_UNUSED, void *data,
2322                           asection *input_section, bfd *output_bfd,
2323                           char **error_message ATTRIBUTE_UNUSED)
2324 {
2325   struct mips_hi16 *n;
2326
2327   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2328     return bfd_reloc_outofrange;
2329
2330   n = bfd_malloc (sizeof *n);
2331   if (n == NULL)
2332     return bfd_reloc_outofrange;
2333
2334   n->next = mips_hi16_list;
2335   n->data = data;
2336   n->input_section = input_section;
2337   n->rel = *reloc_entry;
2338   mips_hi16_list = n;
2339
2340   if (output_bfd != NULL)
2341     reloc_entry->address += input_section->output_offset;
2342
2343   return bfd_reloc_ok;
2344 }
2345
2346 /* A howto special_function for REL R_MIPS*_GOT16 relocations.  This is just
2347    like any other 16-bit relocation when applied to global symbols, but is
2348    treated in the same as R_MIPS_HI16 when applied to local symbols.  */
2349
2350 bfd_reloc_status_type
2351 _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2352                            void *data, asection *input_section,
2353                            bfd *output_bfd, char **error_message)
2354 {
2355   if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2356       || bfd_is_und_section (bfd_get_section (symbol))
2357       || bfd_is_com_section (bfd_get_section (symbol)))
2358     /* The relocation is against a global symbol.  */
2359     return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2360                                         input_section, output_bfd,
2361                                         error_message);
2362
2363   return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
2364                                    input_section, output_bfd, error_message);
2365 }
2366
2367 /* A howto special_function for REL *LO16 relocations.  The *LO16 itself
2368    is a straightforward 16 bit inplace relocation, but we must deal with
2369    any partnering high-part relocations as well.  */
2370
2371 bfd_reloc_status_type
2372 _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2373                           void *data, asection *input_section,
2374                           bfd *output_bfd, char **error_message)
2375 {
2376   bfd_vma vallo;
2377   bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2378
2379   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2380     return bfd_reloc_outofrange;
2381
2382   _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2383                                  location);
2384   vallo = bfd_get_32 (abfd, location);
2385   _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2386                                location);
2387
2388   while (mips_hi16_list != NULL)
2389     {
2390       bfd_reloc_status_type ret;
2391       struct mips_hi16 *hi;
2392
2393       hi = mips_hi16_list;
2394
2395       /* R_MIPS*_GOT16 relocations are something of a special case.  We
2396          want to install the addend in the same way as for a R_MIPS*_HI16
2397          relocation (with a rightshift of 16).  However, since GOT16
2398          relocations can also be used with global symbols, their howto
2399          has a rightshift of 0.  */
2400       if (hi->rel.howto->type == R_MIPS_GOT16)
2401         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE);
2402       else if (hi->rel.howto->type == R_MIPS16_GOT16)
2403         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS16_HI16, FALSE);
2404       else if (hi->rel.howto->type == R_MICROMIPS_GOT16)
2405         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MICROMIPS_HI16, FALSE);
2406
2407       /* VALLO is a signed 16-bit number.  Bias it by 0x8000 so that any
2408          carry or borrow will induce a change of +1 or -1 in the high part.  */
2409       hi->rel.addend += (vallo + 0x8000) & 0xffff;
2410
2411       ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data,
2412                                          hi->input_section, output_bfd,
2413                                          error_message);
2414       if (ret != bfd_reloc_ok)
2415         return ret;
2416
2417       mips_hi16_list = hi->next;
2418       free (hi);
2419     }
2420
2421   return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2422                                       input_section, output_bfd,
2423                                       error_message);
2424 }
2425
2426 /* A generic howto special_function.  This calculates and installs the
2427    relocation itself, thus avoiding the oft-discussed problems in
2428    bfd_perform_relocation and bfd_install_relocation.  */
2429
2430 bfd_reloc_status_type
2431 _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2432                              asymbol *symbol, void *data ATTRIBUTE_UNUSED,
2433                              asection *input_section, bfd *output_bfd,
2434                              char **error_message ATTRIBUTE_UNUSED)
2435 {
2436   bfd_signed_vma val;
2437   bfd_reloc_status_type status;
2438   bfd_boolean relocatable;
2439
2440   relocatable = (output_bfd != NULL);
2441
2442   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2443     return bfd_reloc_outofrange;
2444
2445   /* Build up the field adjustment in VAL.  */
2446   val = 0;
2447   if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)
2448     {
2449       /* Either we're calculating the final field value or we have a
2450          relocation against a section symbol.  Add in the section's
2451          offset or address.  */
2452       val += symbol->section->output_section->vma;
2453       val += symbol->section->output_offset;
2454     }
2455
2456   if (!relocatable)
2457     {
2458       /* We're calculating the final field value.  Add in the symbol's value
2459          and, if pc-relative, subtract the address of the field itself.  */
2460       val += symbol->value;
2461       if (reloc_entry->howto->pc_relative)
2462         {
2463           val -= input_section->output_section->vma;
2464           val -= input_section->output_offset;
2465           val -= reloc_entry->address;
2466         }
2467     }
2468
2469   /* VAL is now the final adjustment.  If we're keeping this relocation
2470      in the output file, and if the relocation uses a separate addend,
2471      we just need to add VAL to that addend.  Otherwise we need to add
2472      VAL to the relocation field itself.  */
2473   if (relocatable && !reloc_entry->howto->partial_inplace)
2474     reloc_entry->addend += val;
2475   else
2476     {
2477       bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2478
2479       /* Add in the separate addend, if any.  */
2480       val += reloc_entry->addend;
2481
2482       /* Add VAL to the relocation field.  */
2483       _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2484                                      location);
2485       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2486                                        location);
2487       _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2488                                    location);
2489
2490       if (status != bfd_reloc_ok)
2491         return status;
2492     }
2493
2494   if (relocatable)
2495     reloc_entry->address += input_section->output_offset;
2496
2497   return bfd_reloc_ok;
2498 }
2499 \f
2500 /* Swap an entry in a .gptab section.  Note that these routines rely
2501    on the equivalence of the two elements of the union.  */
2502
2503 static void
2504 bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex,
2505                               Elf32_gptab *in)
2506 {
2507   in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value);
2508   in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes);
2509 }
2510
2511 static void
2512 bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in,
2513                                Elf32_External_gptab *ex)
2514 {
2515   H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value);
2516   H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes);
2517 }
2518
2519 static void
2520 bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in,
2521                                 Elf32_External_compact_rel *ex)
2522 {
2523   H_PUT_32 (abfd, in->id1, ex->id1);
2524   H_PUT_32 (abfd, in->num, ex->num);
2525   H_PUT_32 (abfd, in->id2, ex->id2);
2526   H_PUT_32 (abfd, in->offset, ex->offset);
2527   H_PUT_32 (abfd, in->reserved0, ex->reserved0);
2528   H_PUT_32 (abfd, in->reserved1, ex->reserved1);
2529 }
2530
2531 static void
2532 bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in,
2533                            Elf32_External_crinfo *ex)
2534 {
2535   unsigned long l;
2536
2537   l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH)
2538        | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH)
2539        | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH)
2540        | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH));
2541   H_PUT_32 (abfd, l, ex->info);
2542   H_PUT_32 (abfd, in->konst, ex->konst);
2543   H_PUT_32 (abfd, in->vaddr, ex->vaddr);
2544 }
2545 \f
2546 /* A .reginfo section holds a single Elf32_RegInfo structure.  These
2547    routines swap this structure in and out.  They are used outside of
2548    BFD, so they are globally visible.  */
2549
2550 void
2551 bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex,
2552                                 Elf32_RegInfo *in)
2553 {
2554   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2555   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2556   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2557   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2558   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2559   in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value);
2560 }
2561
2562 void
2563 bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in,
2564                                  Elf32_External_RegInfo *ex)
2565 {
2566   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2567   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2568   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2569   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2570   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2571   H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value);
2572 }
2573
2574 /* In the 64 bit ABI, the .MIPS.options section holds register
2575    information in an Elf64_Reginfo structure.  These routines swap
2576    them in and out.  They are globally visible because they are used
2577    outside of BFD.  These routines are here so that gas can call them
2578    without worrying about whether the 64 bit ABI has been included.  */
2579
2580 void
2581 bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex,
2582                                 Elf64_Internal_RegInfo *in)
2583 {
2584   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2585   in->ri_pad = H_GET_32 (abfd, ex->ri_pad);
2586   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2587   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2588   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2589   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2590   in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value);
2591 }
2592
2593 void
2594 bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in,
2595                                  Elf64_External_RegInfo *ex)
2596 {
2597   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2598   H_PUT_32 (abfd, in->ri_pad, ex->ri_pad);
2599   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2600   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2601   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2602   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2603   H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value);
2604 }
2605
2606 /* Swap in an options header.  */
2607
2608 void
2609 bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex,
2610                               Elf_Internal_Options *in)
2611 {
2612   in->kind = H_GET_8 (abfd, ex->kind);
2613   in->size = H_GET_8 (abfd, ex->size);
2614   in->section = H_GET_16 (abfd, ex->section);
2615   in->info = H_GET_32 (abfd, ex->info);
2616 }
2617
2618 /* Swap out an options header.  */
2619
2620 void
2621 bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in,
2622                                Elf_External_Options *ex)
2623 {
2624   H_PUT_8 (abfd, in->kind, ex->kind);
2625   H_PUT_8 (abfd, in->size, ex->size);
2626   H_PUT_16 (abfd, in->section, ex->section);
2627   H_PUT_32 (abfd, in->info, ex->info);
2628 }
2629 \f
2630 /* This function is called via qsort() to sort the dynamic relocation
2631    entries by increasing r_symndx value.  */
2632
2633 static int
2634 sort_dynamic_relocs (const void *arg1, const void *arg2)
2635 {
2636   Elf_Internal_Rela int_reloc1;
2637   Elf_Internal_Rela int_reloc2;
2638   int diff;
2639
2640   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
2641   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
2642
2643   diff = ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info);
2644   if (diff != 0)
2645     return diff;
2646
2647   if (int_reloc1.r_offset < int_reloc2.r_offset)
2648     return -1;
2649   if (int_reloc1.r_offset > int_reloc2.r_offset)
2650     return 1;
2651   return 0;
2652 }
2653
2654 /* Like sort_dynamic_relocs, but used for elf64 relocations.  */
2655
2656 static int
2657 sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED,
2658                         const void *arg2 ATTRIBUTE_UNUSED)
2659 {
2660 #ifdef BFD64
2661   Elf_Internal_Rela int_reloc1[3];
2662   Elf_Internal_Rela int_reloc2[3];
2663
2664   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2665     (reldyn_sorting_bfd, arg1, int_reloc1);
2666   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2667     (reldyn_sorting_bfd, arg2, int_reloc2);
2668
2669   if (ELF64_R_SYM (int_reloc1[0].r_info) < ELF64_R_SYM (int_reloc2[0].r_info))
2670     return -1;
2671   if (ELF64_R_SYM (int_reloc1[0].r_info) > ELF64_R_SYM (int_reloc2[0].r_info))
2672     return 1;
2673
2674   if (int_reloc1[0].r_offset < int_reloc2[0].r_offset)
2675     return -1;
2676   if (int_reloc1[0].r_offset > int_reloc2[0].r_offset)
2677     return 1;
2678   return 0;
2679 #else
2680   abort ();
2681 #endif
2682 }
2683
2684
2685 /* This routine is used to write out ECOFF debugging external symbol
2686    information.  It is called via mips_elf_link_hash_traverse.  The
2687    ECOFF external symbol information must match the ELF external
2688    symbol information.  Unfortunately, at this point we don't know
2689    whether a symbol is required by reloc information, so the two
2690    tables may wind up being different.  We must sort out the external
2691    symbol information before we can set the final size of the .mdebug
2692    section, and we must set the size of the .mdebug section before we
2693    can relocate any sections, and we can't know which symbols are
2694    required by relocation until we relocate the sections.
2695    Fortunately, it is relatively unlikely that any symbol will be
2696    stripped but required by a reloc.  In particular, it can not happen
2697    when generating a final executable.  */
2698
2699 static bfd_boolean
2700 mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data)
2701 {
2702   struct extsym_info *einfo = data;
2703   bfd_boolean strip;
2704   asection *sec, *output_section;
2705
2706   if (h->root.indx == -2)
2707     strip = FALSE;
2708   else if ((h->root.def_dynamic
2709             || h->root.ref_dynamic
2710             || h->root.type == bfd_link_hash_new)
2711            && !h->root.def_regular
2712            && !h->root.ref_regular)
2713     strip = TRUE;
2714   else if (einfo->info->strip == strip_all
2715            || (einfo->info->strip == strip_some
2716                && bfd_hash_lookup (einfo->info->keep_hash,
2717                                    h->root.root.root.string,
2718                                    FALSE, FALSE) == NULL))
2719     strip = TRUE;
2720   else
2721     strip = FALSE;
2722
2723   if (strip)
2724     return TRUE;
2725
2726   if (h->esym.ifd == -2)
2727     {
2728       h->esym.jmptbl = 0;
2729       h->esym.cobol_main = 0;
2730       h->esym.weakext = 0;
2731       h->esym.reserved = 0;
2732       h->esym.ifd = ifdNil;
2733       h->esym.asym.value = 0;
2734       h->esym.asym.st = stGlobal;
2735
2736       if (h->root.root.type == bfd_link_hash_undefined
2737           || h->root.root.type == bfd_link_hash_undefweak)
2738         {
2739           const char *name;
2740
2741           /* Use undefined class.  Also, set class and type for some
2742              special symbols.  */
2743           name = h->root.root.root.string;
2744           if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
2745               || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
2746             {
2747               h->esym.asym.sc = scData;
2748               h->esym.asym.st = stLabel;
2749               h->esym.asym.value = 0;
2750             }
2751           else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
2752             {
2753               h->esym.asym.sc = scAbs;
2754               h->esym.asym.st = stLabel;
2755               h->esym.asym.value =
2756                 mips_elf_hash_table (einfo->info)->procedure_count;
2757             }
2758           else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd))
2759             {
2760               h->esym.asym.sc = scAbs;
2761               h->esym.asym.st = stLabel;
2762               h->esym.asym.value = elf_gp (einfo->abfd);
2763             }
2764           else
2765             h->esym.asym.sc = scUndefined;
2766         }
2767       else if (h->root.root.type != bfd_link_hash_defined
2768           && h->root.root.type != bfd_link_hash_defweak)
2769         h->esym.asym.sc = scAbs;
2770       else
2771         {
2772           const char *name;
2773
2774           sec = h->root.root.u.def.section;
2775           output_section = sec->output_section;
2776
2777           /* When making a shared library and symbol h is the one from
2778              the another shared library, OUTPUT_SECTION may be null.  */
2779           if (output_section == NULL)
2780             h->esym.asym.sc = scUndefined;
2781           else
2782             {
2783               name = bfd_section_name (output_section->owner, output_section);
2784
2785               if (strcmp (name, ".text") == 0)
2786                 h->esym.asym.sc = scText;
2787               else if (strcmp (name, ".data") == 0)
2788                 h->esym.asym.sc = scData;
2789               else if (strcmp (name, ".sdata") == 0)
2790                 h->esym.asym.sc = scSData;
2791               else if (strcmp (name, ".rodata") == 0
2792                        || strcmp (name, ".rdata") == 0)
2793                 h->esym.asym.sc = scRData;
2794               else if (strcmp (name, ".bss") == 0)
2795                 h->esym.asym.sc = scBss;
2796               else if (strcmp (name, ".sbss") == 0)
2797                 h->esym.asym.sc = scSBss;
2798               else if (strcmp (name, ".init") == 0)
2799                 h->esym.asym.sc = scInit;
2800               else if (strcmp (name, ".fini") == 0)
2801                 h->esym.asym.sc = scFini;
2802               else
2803                 h->esym.asym.sc = scAbs;
2804             }
2805         }
2806
2807       h->esym.asym.reserved = 0;
2808       h->esym.asym.index = indexNil;
2809     }
2810
2811   if (h->root.root.type == bfd_link_hash_common)
2812     h->esym.asym.value = h->root.root.u.c.size;
2813   else if (h->root.root.type == bfd_link_hash_defined
2814            || h->root.root.type == bfd_link_hash_defweak)
2815     {
2816       if (h->esym.asym.sc == scCommon)
2817         h->esym.asym.sc = scBss;
2818       else if (h->esym.asym.sc == scSCommon)
2819         h->esym.asym.sc = scSBss;
2820
2821       sec = h->root.root.u.def.section;
2822       output_section = sec->output_section;
2823       if (output_section != NULL)
2824         h->esym.asym.value = (h->root.root.u.def.value
2825                               + sec->output_offset
2826                               + output_section->vma);
2827       else
2828         h->esym.asym.value = 0;
2829     }
2830   else
2831     {
2832       struct mips_elf_link_hash_entry *hd = h;
2833
2834       while (hd->root.root.type == bfd_link_hash_indirect)
2835         hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link;
2836
2837       if (hd->needs_lazy_stub)
2838         {
2839           BFD_ASSERT (hd->root.plt.plist != NULL);
2840           BFD_ASSERT (hd->root.plt.plist->stub_offset != MINUS_ONE);
2841           /* Set type and value for a symbol with a function stub.  */
2842           h->esym.asym.st = stProc;
2843           sec = hd->root.root.u.def.section;
2844           if (sec == NULL)
2845             h->esym.asym.value = 0;
2846           else
2847             {
2848               output_section = sec->output_section;
2849               if (output_section != NULL)
2850                 h->esym.asym.value = (hd->root.plt.plist->stub_offset
2851                                       + sec->output_offset
2852                                       + output_section->vma);
2853               else
2854                 h->esym.asym.value = 0;
2855             }
2856         }
2857     }
2858
2859   if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap,
2860                                       h->root.root.root.string,
2861                                       &h->esym))
2862     {
2863       einfo->failed = TRUE;
2864       return FALSE;
2865     }
2866
2867   return TRUE;
2868 }
2869
2870 /* A comparison routine used to sort .gptab entries.  */
2871
2872 static int
2873 gptab_compare (const void *p1, const void *p2)
2874 {
2875   const Elf32_gptab *a1 = p1;
2876   const Elf32_gptab *a2 = p2;
2877
2878   return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value;
2879 }
2880 \f
2881 /* Functions to manage the got entry hash table.  */
2882
2883 /* Use all 64 bits of a bfd_vma for the computation of a 32-bit
2884    hash number.  */
2885
2886 static INLINE hashval_t
2887 mips_elf_hash_bfd_vma (bfd_vma addr)
2888 {
2889 #ifdef BFD64
2890   return addr + (addr >> 32);
2891 #else
2892   return addr;
2893 #endif
2894 }
2895
2896 static hashval_t
2897 mips_elf_got_entry_hash (const void *entry_)
2898 {
2899   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2900
2901   return (entry->symndx
2902           + ((entry->tls_type == GOT_TLS_LDM) << 18)
2903           + (entry->tls_type == GOT_TLS_LDM ? 0
2904              : !entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address)
2905              : entry->symndx >= 0 ? (entry->abfd->id
2906                                      + mips_elf_hash_bfd_vma (entry->d.addend))
2907              : entry->d.h->root.root.root.hash));
2908 }
2909
2910 static int
2911 mips_elf_got_entry_eq (const void *entry1, const void *entry2)
2912 {
2913   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2914   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2915
2916   return (e1->symndx == e2->symndx
2917           && e1->tls_type == e2->tls_type
2918           && (e1->tls_type == GOT_TLS_LDM ? TRUE
2919               : !e1->abfd ? !e2->abfd && e1->d.address == e2->d.address
2920               : e1->symndx >= 0 ? (e1->abfd == e2->abfd
2921                                    && e1->d.addend == e2->d.addend)
2922               : e2->abfd && e1->d.h == e2->d.h));
2923 }
2924
2925 static hashval_t
2926 mips_got_page_ref_hash (const void *ref_)
2927 {
2928   const struct mips_got_page_ref *ref;
2929
2930   ref = (const struct mips_got_page_ref *) ref_;
2931   return ((ref->symndx >= 0
2932            ? (hashval_t) (ref->u.abfd->id + ref->symndx)
2933            : ref->u.h->root.root.root.hash)
2934           + mips_elf_hash_bfd_vma (ref->addend));
2935 }
2936
2937 static int
2938 mips_got_page_ref_eq (const void *ref1_, const void *ref2_)
2939 {
2940   const struct mips_got_page_ref *ref1, *ref2;
2941
2942   ref1 = (const struct mips_got_page_ref *) ref1_;
2943   ref2 = (const struct mips_got_page_ref *) ref2_;
2944   return (ref1->symndx == ref2->symndx
2945           && (ref1->symndx < 0
2946               ? ref1->u.h == ref2->u.h
2947               : ref1->u.abfd == ref2->u.abfd)
2948           && ref1->addend == ref2->addend);
2949 }
2950
2951 static hashval_t
2952 mips_got_page_entry_hash (const void *entry_)
2953 {
2954   const struct mips_got_page_entry *entry;
2955
2956   entry = (const struct mips_got_page_entry *) entry_;
2957   return entry->sec->id;
2958 }
2959
2960 static int
2961 mips_got_page_entry_eq (const void *entry1_, const void *entry2_)
2962 {
2963   const struct mips_got_page_entry *entry1, *entry2;
2964
2965   entry1 = (const struct mips_got_page_entry *) entry1_;
2966   entry2 = (const struct mips_got_page_entry *) entry2_;
2967   return entry1->sec == entry2->sec;
2968 }
2969 \f
2970 /* Create and return a new mips_got_info structure.  */
2971
2972 static struct mips_got_info *
2973 mips_elf_create_got_info (bfd *abfd)
2974 {
2975   struct mips_got_info *g;
2976
2977   g = bfd_zalloc (abfd, sizeof (struct mips_got_info));
2978   if (g == NULL)
2979     return NULL;
2980
2981   g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
2982                                     mips_elf_got_entry_eq, NULL);
2983   if (g->got_entries == NULL)
2984     return NULL;
2985
2986   g->got_page_refs = htab_try_create (1, mips_got_page_ref_hash,
2987                                       mips_got_page_ref_eq, NULL);
2988   if (g->got_page_refs == NULL)
2989     return NULL;
2990
2991   return g;
2992 }
2993
2994 /* Return the GOT info for input bfd ABFD, trying to create a new one if
2995    CREATE_P and if ABFD doesn't already have a GOT.  */
2996
2997 static struct mips_got_info *
2998 mips_elf_bfd_got (bfd *abfd, bfd_boolean create_p)
2999 {
3000   struct mips_elf_obj_tdata *tdata;
3001
3002   if (!is_mips_elf (abfd))
3003     return NULL;
3004
3005   tdata = mips_elf_tdata (abfd);
3006   if (!tdata->got && create_p)
3007     tdata->got = mips_elf_create_got_info (abfd);
3008   return tdata->got;
3009 }
3010
3011 /* Record that ABFD should use output GOT G.  */
3012
3013 static void
3014 mips_elf_replace_bfd_got (bfd *abfd, struct mips_got_info *g)
3015 {
3016   struct mips_elf_obj_tdata *tdata;
3017
3018   BFD_ASSERT (is_mips_elf (abfd));
3019   tdata = mips_elf_tdata (abfd);
3020   if (tdata->got)
3021     {
3022       /* The GOT structure itself and the hash table entries are
3023          allocated to a bfd, but the hash tables aren't.  */
3024       htab_delete (tdata->got->got_entries);
3025       htab_delete (tdata->got->got_page_refs);
3026       if (tdata->got->got_page_entries)
3027         htab_delete (tdata->got->got_page_entries);
3028     }
3029   tdata->got = g;
3030 }
3031
3032 /* Return the dynamic relocation section.  If it doesn't exist, try to
3033    create a new it if CREATE_P, otherwise return NULL.  Also return NULL
3034    if creation fails.  */
3035
3036 static asection *
3037 mips_elf_rel_dyn_section (struct bfd_link_info *info, bfd_boolean create_p)
3038 {
3039   const char *dname;
3040   asection *sreloc;
3041   bfd *dynobj;
3042
3043   dname = MIPS_ELF_REL_DYN_NAME (info);
3044   dynobj = elf_hash_table (info)->dynobj;
3045   sreloc = bfd_get_linker_section (dynobj, dname);
3046   if (sreloc == NULL && create_p)
3047     {
3048       sreloc = bfd_make_section_anyway_with_flags (dynobj, dname,
3049                                                    (SEC_ALLOC
3050                                                     | SEC_LOAD
3051                                                     | SEC_HAS_CONTENTS
3052                                                     | SEC_IN_MEMORY
3053                                                     | SEC_LINKER_CREATED
3054                                                     | SEC_READONLY));
3055       if (sreloc == NULL
3056           || ! bfd_set_section_alignment (dynobj, sreloc,
3057                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
3058         return NULL;
3059     }
3060   return sreloc;
3061 }
3062
3063 /* Return the GOT_TLS_* type required by relocation type R_TYPE.  */
3064
3065 static int
3066 mips_elf_reloc_tls_type (unsigned int r_type)
3067 {
3068   if (tls_gd_reloc_p (r_type))
3069     return GOT_TLS_GD;
3070
3071   if (tls_ldm_reloc_p (r_type))
3072     return GOT_TLS_LDM;
3073
3074   if (tls_gottprel_reloc_p (r_type))
3075     return GOT_TLS_IE;
3076
3077   return GOT_TLS_NONE;
3078 }
3079
3080 /* Return the number of GOT slots needed for GOT TLS type TYPE.  */
3081
3082 static int
3083 mips_tls_got_entries (unsigned int type)
3084 {
3085   switch (type)
3086     {
3087     case GOT_TLS_GD:
3088     case GOT_TLS_LDM:
3089       return 2;
3090
3091     case GOT_TLS_IE:
3092       return 1;
3093
3094     case GOT_TLS_NONE:
3095       return 0;
3096     }
3097   abort ();
3098 }
3099
3100 /* Count the number of relocations needed for a TLS GOT entry, with
3101    access types from TLS_TYPE, and symbol H (or a local symbol if H
3102    is NULL).  */
3103
3104 static int
3105 mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type,
3106                      struct elf_link_hash_entry *h)
3107 {
3108   int indx = 0;
3109   bfd_boolean need_relocs = FALSE;
3110   bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3111
3112   if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, h)
3113       && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, h)))
3114     indx = h->dynindx;
3115
3116   if ((info->shared || indx != 0)
3117       && (h == NULL
3118           || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
3119           || h->root.type != bfd_link_hash_undefweak))
3120     need_relocs = TRUE;
3121
3122   if (!need_relocs)
3123     return 0;
3124
3125   switch (tls_type)
3126     {
3127     case GOT_TLS_GD:
3128       return indx != 0 ? 2 : 1;
3129
3130     case GOT_TLS_IE:
3131       return 1;
3132
3133     case GOT_TLS_LDM:
3134       return info->shared ? 1 : 0;
3135
3136     default:
3137       return 0;
3138     }
3139 }
3140
3141 /* Add the number of GOT entries and TLS relocations required by ENTRY
3142    to G.  */
3143
3144 static void
3145 mips_elf_count_got_entry (struct bfd_link_info *info,
3146                           struct mips_got_info *g,
3147                           struct mips_got_entry *entry)
3148 {
3149   if (entry->tls_type)
3150     {
3151       g->tls_gotno += mips_tls_got_entries (entry->tls_type);
3152       g->relocs += mips_tls_got_relocs (info, entry->tls_type,
3153                                         entry->symndx < 0
3154                                         ? &entry->d.h->root : NULL);
3155     }
3156   else if (entry->symndx >= 0 || entry->d.h->global_got_area == GGA_NONE)
3157     g->local_gotno += 1;
3158   else
3159     g->global_gotno += 1;
3160 }
3161
3162 /* Output a simple dynamic relocation into SRELOC.  */
3163
3164 static void
3165 mips_elf_output_dynamic_relocation (bfd *output_bfd,
3166                                     asection *sreloc,
3167                                     unsigned long reloc_index,
3168                                     unsigned long indx,
3169                                     int r_type,
3170                                     bfd_vma offset)
3171 {
3172   Elf_Internal_Rela rel[3];
3173
3174   memset (rel, 0, sizeof (rel));
3175
3176   rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type);
3177   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
3178
3179   if (ABI_64_P (output_bfd))
3180     {
3181       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
3182         (output_bfd, &rel[0],
3183          (sreloc->contents
3184           + reloc_index * sizeof (Elf64_Mips_External_Rel)));
3185     }
3186   else
3187     bfd_elf32_swap_reloc_out
3188       (output_bfd, &rel[0],
3189        (sreloc->contents
3190         + reloc_index * sizeof (Elf32_External_Rel)));
3191 }
3192
3193 /* Initialize a set of TLS GOT entries for one symbol.  */
3194
3195 static void
3196 mips_elf_initialize_tls_slots (bfd *abfd, struct bfd_link_info *info,
3197                                struct mips_got_entry *entry,
3198                                struct mips_elf_link_hash_entry *h,
3199                                bfd_vma value)
3200 {
3201   struct mips_elf_link_hash_table *htab;
3202   int indx;
3203   asection *sreloc, *sgot;
3204   bfd_vma got_offset, got_offset2;
3205   bfd_boolean need_relocs = FALSE;
3206
3207   htab = mips_elf_hash_table (info);
3208   if (htab == NULL)
3209     return;
3210
3211   sgot = htab->sgot;
3212
3213   indx = 0;
3214   if (h != NULL)
3215     {
3216       bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3217
3218       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, &h->root)
3219           && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3220         indx = h->root.dynindx;
3221     }
3222
3223   if (entry->tls_initialized)
3224     return;
3225
3226   if ((info->shared || indx != 0)
3227       && (h == NULL
3228           || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT
3229           || h->root.type != bfd_link_hash_undefweak))
3230     need_relocs = TRUE;
3231
3232   /* MINUS_ONE means the symbol is not defined in this object.  It may not
3233      be defined at all; assume that the value doesn't matter in that
3234      case.  Otherwise complain if we would use the value.  */
3235   BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs)
3236               || h->root.root.type == bfd_link_hash_undefweak);
3237
3238   /* Emit necessary relocations.  */
3239   sreloc = mips_elf_rel_dyn_section (info, FALSE);
3240   got_offset = entry->gotidx;
3241
3242   switch (entry->tls_type)
3243     {
3244     case GOT_TLS_GD:
3245       /* General Dynamic.  */
3246       got_offset2 = got_offset + MIPS_ELF_GOT_SIZE (abfd);
3247
3248       if (need_relocs)
3249         {
3250           mips_elf_output_dynamic_relocation
3251             (abfd, sreloc, sreloc->reloc_count++, indx,
3252              ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3253              sgot->output_offset + sgot->output_section->vma + got_offset);
3254
3255           if (indx)
3256             mips_elf_output_dynamic_relocation
3257               (abfd, sreloc, sreloc->reloc_count++, indx,
3258                ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32,
3259                sgot->output_offset + sgot->output_section->vma + got_offset2);
3260           else
3261             MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3262                                sgot->contents + got_offset2);
3263         }
3264       else
3265         {
3266           MIPS_ELF_PUT_WORD (abfd, 1,
3267                              sgot->contents + got_offset);
3268           MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3269                              sgot->contents + got_offset2);
3270         }
3271       break;
3272
3273     case GOT_TLS_IE:
3274       /* Initial Exec model.  */
3275       if (need_relocs)
3276         {
3277           if (indx == 0)
3278             MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma,
3279                                sgot->contents + got_offset);
3280           else
3281             MIPS_ELF_PUT_WORD (abfd, 0,
3282                                sgot->contents + got_offset);
3283
3284           mips_elf_output_dynamic_relocation
3285             (abfd, sreloc, sreloc->reloc_count++, indx,
3286              ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32,
3287              sgot->output_offset + sgot->output_section->vma + got_offset);
3288         }
3289       else
3290         MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info),
3291                            sgot->contents + got_offset);
3292       break;
3293
3294     case GOT_TLS_LDM:
3295       /* The initial offset is zero, and the LD offsets will include the
3296          bias by DTP_OFFSET.  */
3297       MIPS_ELF_PUT_WORD (abfd, 0,
3298                          sgot->contents + got_offset
3299                          + MIPS_ELF_GOT_SIZE (abfd));
3300
3301       if (!info->shared)
3302         MIPS_ELF_PUT_WORD (abfd, 1,
3303                            sgot->contents + got_offset);
3304       else
3305         mips_elf_output_dynamic_relocation
3306           (abfd, sreloc, sreloc->reloc_count++, indx,
3307            ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3308            sgot->output_offset + sgot->output_section->vma + got_offset);
3309       break;
3310
3311     default:
3312       abort ();
3313     }
3314
3315   entry->tls_initialized = TRUE;
3316 }
3317
3318 /* Return the offset from _GLOBAL_OFFSET_TABLE_ of the .got.plt entry
3319    for global symbol H.  .got.plt comes before the GOT, so the offset
3320    will be negative.  */
3321
3322 static bfd_vma
3323 mips_elf_gotplt_index (struct bfd_link_info *info,
3324                        struct elf_link_hash_entry *h)
3325 {
3326   bfd_vma got_address, got_value;
3327   struct mips_elf_link_hash_table *htab;
3328
3329   htab = mips_elf_hash_table (info);
3330   BFD_ASSERT (htab != NULL);
3331
3332   BFD_ASSERT (h->plt.plist != NULL);
3333   BFD_ASSERT (h->plt.plist->gotplt_index != MINUS_ONE);
3334
3335   /* Calculate the address of the associated .got.plt entry.  */
3336   got_address = (htab->sgotplt->output_section->vma
3337                  + htab->sgotplt->output_offset
3338                  + (h->plt.plist->gotplt_index
3339                     * MIPS_ELF_GOT_SIZE (info->output_bfd)));
3340
3341   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
3342   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
3343                + htab->root.hgot->root.u.def.section->output_offset
3344                + htab->root.hgot->root.u.def.value);
3345
3346   return got_address - got_value;
3347 }
3348
3349 /* Return the GOT offset for address VALUE.   If there is not yet a GOT
3350    entry for this value, create one.  If R_SYMNDX refers to a TLS symbol,
3351    create a TLS GOT entry instead.  Return -1 if no satisfactory GOT
3352    offset can be found.  */
3353
3354 static bfd_vma
3355 mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3356                           bfd_vma value, unsigned long r_symndx,
3357                           struct mips_elf_link_hash_entry *h, int r_type)
3358 {
3359   struct mips_elf_link_hash_table *htab;
3360   struct mips_got_entry *entry;
3361
3362   htab = mips_elf_hash_table (info);
3363   BFD_ASSERT (htab != NULL);
3364
3365   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value,
3366                                            r_symndx, h, r_type);
3367   if (!entry)
3368     return MINUS_ONE;
3369
3370   if (entry->tls_type)
3371     mips_elf_initialize_tls_slots (abfd, info, entry, h, value);
3372   return entry->gotidx;
3373 }
3374
3375 /* Return the GOT index of global symbol H in the primary GOT.  */
3376
3377 static bfd_vma
3378 mips_elf_primary_global_got_index (bfd *obfd, struct bfd_link_info *info,
3379                                    struct elf_link_hash_entry *h)
3380 {
3381   struct mips_elf_link_hash_table *htab;
3382   long global_got_dynindx;
3383   struct mips_got_info *g;
3384   bfd_vma got_index;
3385
3386   htab = mips_elf_hash_table (info);
3387   BFD_ASSERT (htab != NULL);
3388
3389   global_got_dynindx = 0;
3390   if (htab->global_gotsym != NULL)
3391     global_got_dynindx = htab->global_gotsym->dynindx;
3392
3393   /* Once we determine the global GOT entry with the lowest dynamic
3394      symbol table index, we must put all dynamic symbols with greater
3395      indices into the primary GOT.  That makes it easy to calculate the
3396      GOT offset.  */
3397   BFD_ASSERT (h->dynindx >= global_got_dynindx);
3398   g = mips_elf_bfd_got (obfd, FALSE);
3399   got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3400                * MIPS_ELF_GOT_SIZE (obfd));
3401   BFD_ASSERT (got_index < htab->sgot->size);
3402
3403   return got_index;
3404 }
3405
3406 /* Return the GOT index for the global symbol indicated by H, which is
3407    referenced by a relocation of type R_TYPE in IBFD.  */
3408
3409 static bfd_vma
3410 mips_elf_global_got_index (bfd *obfd, struct bfd_link_info *info, bfd *ibfd,
3411                            struct elf_link_hash_entry *h, int r_type)
3412 {
3413   struct mips_elf_link_hash_table *htab;
3414   struct mips_got_info *g;
3415   struct mips_got_entry lookup, *entry;
3416   bfd_vma gotidx;
3417
3418   htab = mips_elf_hash_table (info);
3419   BFD_ASSERT (htab != NULL);
3420
3421   g = mips_elf_bfd_got (ibfd, FALSE);
3422   BFD_ASSERT (g);
3423
3424   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3425   if (!lookup.tls_type && g == mips_elf_bfd_got (obfd, FALSE))
3426     return mips_elf_primary_global_got_index (obfd, info, h);
3427
3428   lookup.abfd = ibfd;
3429   lookup.symndx = -1;
3430   lookup.d.h = (struct mips_elf_link_hash_entry *) h;
3431   entry = htab_find (g->got_entries, &lookup);
3432   BFD_ASSERT (entry);
3433
3434   gotidx = entry->gotidx;
3435   BFD_ASSERT (gotidx > 0 && gotidx < htab->sgot->size);
3436
3437   if (lookup.tls_type)
3438     {
3439       bfd_vma value = MINUS_ONE;
3440
3441       if ((h->root.type == bfd_link_hash_defined
3442            || h->root.type == bfd_link_hash_defweak)
3443           && h->root.u.def.section->output_section)
3444         value = (h->root.u.def.value
3445                  + h->root.u.def.section->output_offset
3446                  + h->root.u.def.section->output_section->vma);
3447
3448       mips_elf_initialize_tls_slots (obfd, info, entry, lookup.d.h, value);
3449     }
3450   return gotidx;
3451 }
3452
3453 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3454    entries are supposed to be placed at small offsets in the GOT, i.e.,
3455    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3456    entry could be created.  If OFFSETP is nonnull, use it to return the
3457    offset of the GOT entry from VALUE.  */
3458
3459 static bfd_vma
3460 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3461                    bfd_vma value, bfd_vma *offsetp)
3462 {
3463   bfd_vma page, got_index;
3464   struct mips_got_entry *entry;
3465
3466   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3467   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3468                                            NULL, R_MIPS_GOT_PAGE);
3469
3470   if (!entry)
3471     return MINUS_ONE;
3472
3473   got_index = entry->gotidx;
3474
3475   if (offsetp)
3476     *offsetp = value - entry->d.address;
3477
3478   return got_index;
3479 }
3480
3481 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3482    EXTERNAL is true if the relocation was originally against a global
3483    symbol that binds locally.  */
3484
3485 static bfd_vma
3486 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3487                       bfd_vma value, bfd_boolean external)
3488 {
3489   struct mips_got_entry *entry;
3490
3491   /* GOT16 relocations against local symbols are followed by a LO16
3492      relocation; those against global symbols are not.  Thus if the
3493      symbol was originally local, the GOT16 relocation should load the
3494      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3495   if (! external)
3496     value = mips_elf_high (value) << 16;
3497
3498   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3499      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3500      same in all cases.  */
3501   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3502                                            NULL, R_MIPS_GOT16);
3503   if (entry)
3504     return entry->gotidx;
3505   else
3506     return MINUS_ONE;
3507 }
3508
3509 /* Returns the offset for the entry at the INDEXth position
3510    in the GOT.  */
3511
3512 static bfd_vma
3513 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3514                                 bfd *input_bfd, bfd_vma got_index)
3515 {
3516   struct mips_elf_link_hash_table *htab;
3517   asection *sgot;
3518   bfd_vma gp;
3519
3520   htab = mips_elf_hash_table (info);
3521   BFD_ASSERT (htab != NULL);
3522
3523   sgot = htab->sgot;
3524   gp = _bfd_get_gp_value (output_bfd)
3525     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3526
3527   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3528 }
3529
3530 /* Create and return a local GOT entry for VALUE, which was calculated
3531    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3532    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3533    instead.  */
3534
3535 static struct mips_got_entry *
3536 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3537                                  bfd *ibfd, bfd_vma value,
3538                                  unsigned long r_symndx,
3539                                  struct mips_elf_link_hash_entry *h,
3540                                  int r_type)
3541 {
3542   struct mips_got_entry lookup, *entry;
3543   void **loc;
3544   struct mips_got_info *g;
3545   struct mips_elf_link_hash_table *htab;
3546   bfd_vma gotidx;
3547
3548   htab = mips_elf_hash_table (info);
3549   BFD_ASSERT (htab != NULL);
3550
3551   g = mips_elf_bfd_got (ibfd, FALSE);
3552   if (g == NULL)
3553     {
3554       g = mips_elf_bfd_got (abfd, FALSE);
3555       BFD_ASSERT (g != NULL);
3556     }
3557
3558   /* This function shouldn't be called for symbols that live in the global
3559      area of the GOT.  */
3560   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3561
3562   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3563   if (lookup.tls_type)
3564     {
3565       lookup.abfd = ibfd;
3566       if (tls_ldm_reloc_p (r_type))
3567         {
3568           lookup.symndx = 0;
3569           lookup.d.addend = 0;
3570         }
3571       else if (h == NULL)
3572         {
3573           lookup.symndx = r_symndx;
3574           lookup.d.addend = 0;
3575         }
3576       else
3577         {
3578           lookup.symndx = -1;
3579           lookup.d.h = h;
3580         }
3581
3582       entry = (struct mips_got_entry *) htab_find (g->got_entries, &lookup);
3583       BFD_ASSERT (entry);
3584
3585       gotidx = entry->gotidx;
3586       BFD_ASSERT (gotidx > 0 && gotidx < htab->sgot->size);
3587
3588       return entry;
3589     }
3590
3591   lookup.abfd = NULL;
3592   lookup.symndx = -1;
3593   lookup.d.address = value;
3594   loc = htab_find_slot (g->got_entries, &lookup, INSERT);
3595   if (!loc)
3596     return NULL;
3597
3598   entry = (struct mips_got_entry *) *loc;
3599   if (entry)
3600     return entry;
3601
3602   if (g->assigned_gotno >= g->local_gotno)
3603     {
3604       /* We didn't allocate enough space in the GOT.  */
3605       (*_bfd_error_handler)
3606         (_("not enough GOT space for local GOT entries"));
3607       bfd_set_error (bfd_error_bad_value);
3608       return NULL;
3609     }
3610
3611   entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3612   if (!entry)
3613     return NULL;
3614
3615   lookup.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_gotno++;
3616   *entry = lookup;
3617   *loc = entry;
3618
3619   MIPS_ELF_PUT_WORD (abfd, value, htab->sgot->contents + entry->gotidx);
3620
3621   /* These GOT entries need a dynamic relocation on VxWorks.  */
3622   if (htab->is_vxworks)
3623     {
3624       Elf_Internal_Rela outrel;
3625       asection *s;
3626       bfd_byte *rloc;
3627       bfd_vma got_address;
3628
3629       s = mips_elf_rel_dyn_section (info, FALSE);
3630       got_address = (htab->sgot->output_section->vma
3631                      + htab->sgot->output_offset
3632                      + entry->gotidx);
3633
3634       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3635       outrel.r_offset = got_address;
3636       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3637       outrel.r_addend = value;
3638       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3639     }
3640
3641   return entry;
3642 }
3643
3644 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3645    The number might be exact or a worst-case estimate, depending on how
3646    much information is available to elf_backend_omit_section_dynsym at
3647    the current linking stage.  */
3648
3649 static bfd_size_type
3650 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3651 {
3652   bfd_size_type count;
3653
3654   count = 0;
3655   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
3656     {
3657       asection *p;
3658       const struct elf_backend_data *bed;
3659
3660       bed = get_elf_backend_data (output_bfd);
3661       for (p = output_bfd->sections; p ; p = p->next)
3662         if ((p->flags & SEC_EXCLUDE) == 0
3663             && (p->flags & SEC_ALLOC) != 0
3664             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3665           ++count;
3666     }
3667   return count;
3668 }
3669
3670 /* Sort the dynamic symbol table so that symbols that need GOT entries
3671    appear towards the end.  */
3672
3673 static bfd_boolean
3674 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3675 {
3676   struct mips_elf_link_hash_table *htab;
3677   struct mips_elf_hash_sort_data hsd;
3678   struct mips_got_info *g;
3679
3680   if (elf_hash_table (info)->dynsymcount == 0)
3681     return TRUE;
3682
3683   htab = mips_elf_hash_table (info);
3684   BFD_ASSERT (htab != NULL);
3685
3686   g = htab->got_info;
3687   if (g == NULL)
3688     return TRUE;
3689
3690   hsd.low = NULL;
3691   hsd.max_unref_got_dynindx
3692     = hsd.min_got_dynindx
3693     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3694   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3695   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3696                                 elf_hash_table (info)),
3697                                mips_elf_sort_hash_table_f,
3698                                &hsd);
3699
3700   /* There should have been enough room in the symbol table to
3701      accommodate both the GOT and non-GOT symbols.  */
3702   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3703   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3704               == elf_hash_table (info)->dynsymcount);
3705   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3706               == g->global_gotno);
3707
3708   /* Now we know which dynamic symbol has the lowest dynamic symbol
3709      table index in the GOT.  */
3710   htab->global_gotsym = hsd.low;
3711
3712   return TRUE;
3713 }
3714
3715 /* If H needs a GOT entry, assign it the highest available dynamic
3716    index.  Otherwise, assign it the lowest available dynamic
3717    index.  */
3718
3719 static bfd_boolean
3720 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3721 {
3722   struct mips_elf_hash_sort_data *hsd = data;
3723
3724   /* Symbols without dynamic symbol table entries aren't interesting
3725      at all.  */
3726   if (h->root.dynindx == -1)
3727     return TRUE;
3728
3729   switch (h->global_got_area)
3730     {
3731     case GGA_NONE:
3732       h->root.dynindx = hsd->max_non_got_dynindx++;
3733       break;
3734
3735     case GGA_NORMAL:
3736       h->root.dynindx = --hsd->min_got_dynindx;
3737       hsd->low = (struct elf_link_hash_entry *) h;
3738       break;
3739
3740     case GGA_RELOC_ONLY:
3741       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3742         hsd->low = (struct elf_link_hash_entry *) h;
3743       h->root.dynindx = hsd->max_unref_got_dynindx++;
3744       break;
3745     }
3746
3747   return TRUE;
3748 }
3749
3750 /* Record that input bfd ABFD requires a GOT entry like *LOOKUP
3751    (which is owned by the caller and shouldn't be added to the
3752    hash table directly).  */
3753
3754 static bfd_boolean
3755 mips_elf_record_got_entry (struct bfd_link_info *info, bfd *abfd,
3756                            struct mips_got_entry *lookup)
3757 {
3758   struct mips_elf_link_hash_table *htab;
3759   struct mips_got_entry *entry;
3760   struct mips_got_info *g;
3761   void **loc, **bfd_loc;
3762
3763   /* Make sure there's a slot for this entry in the master GOT.  */
3764   htab = mips_elf_hash_table (info);
3765   g = htab->got_info;
3766   loc = htab_find_slot (g->got_entries, lookup, INSERT);
3767   if (!loc)
3768     return FALSE;
3769
3770   /* Populate the entry if it isn't already.  */
3771   entry = (struct mips_got_entry *) *loc;
3772   if (!entry)
3773     {
3774       entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3775       if (!entry)
3776         return FALSE;
3777
3778       lookup->tls_initialized = FALSE;
3779       lookup->gotidx = -1;
3780       *entry = *lookup;
3781       *loc = entry;
3782     }
3783
3784   /* Reuse the same GOT entry for the BFD's GOT.  */
3785   g = mips_elf_bfd_got (abfd, TRUE);
3786   if (!g)
3787     return FALSE;
3788
3789   bfd_loc = htab_find_slot (g->got_entries, lookup, INSERT);
3790   if (!bfd_loc)
3791     return FALSE;
3792
3793   if (!*bfd_loc)
3794     *bfd_loc = entry;
3795   return TRUE;
3796 }
3797
3798 /* ABFD has a GOT relocation of type R_TYPE against H.  Reserve a GOT
3799    entry for it.  FOR_CALL is true if the caller is only interested in
3800    using the GOT entry for calls.  */
3801
3802 static bfd_boolean
3803 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3804                                    bfd *abfd, struct bfd_link_info *info,
3805                                    bfd_boolean for_call, int r_type)
3806 {
3807   struct mips_elf_link_hash_table *htab;
3808   struct mips_elf_link_hash_entry *hmips;
3809   struct mips_got_entry entry;
3810   unsigned char tls_type;
3811
3812   htab = mips_elf_hash_table (info);
3813   BFD_ASSERT (htab != NULL);
3814
3815   hmips = (struct mips_elf_link_hash_entry *) h;
3816   if (!for_call)
3817     hmips->got_only_for_calls = FALSE;
3818
3819   /* A global symbol in the GOT must also be in the dynamic symbol
3820      table.  */
3821   if (h->dynindx == -1)
3822     {
3823       switch (ELF_ST_VISIBILITY (h->other))
3824         {
3825         case STV_INTERNAL:
3826         case STV_HIDDEN:
3827           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3828           break;
3829         }
3830       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3831         return FALSE;
3832     }
3833
3834   tls_type = mips_elf_reloc_tls_type (r_type);
3835   if (tls_type == GOT_TLS_NONE && hmips->global_got_area > GGA_NORMAL)
3836     hmips->global_got_area = GGA_NORMAL;
3837
3838   entry.abfd = abfd;
3839   entry.symndx = -1;
3840   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3841   entry.tls_type = tls_type;
3842   return mips_elf_record_got_entry (info, abfd, &entry);
3843 }
3844
3845 /* ABFD has a GOT relocation of type R_TYPE against symbol SYMNDX + ADDEND,
3846    where SYMNDX is a local symbol.  Reserve a GOT entry for it.  */
3847
3848 static bfd_boolean
3849 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
3850                                   struct bfd_link_info *info, int r_type)
3851 {
3852   struct mips_elf_link_hash_table *htab;
3853   struct mips_got_info *g;
3854   struct mips_got_entry entry;
3855
3856   htab = mips_elf_hash_table (info);
3857   BFD_ASSERT (htab != NULL);
3858
3859   g = htab->got_info;
3860   BFD_ASSERT (g != NULL);
3861
3862   entry.abfd = abfd;
3863   entry.symndx = symndx;
3864   entry.d.addend = addend;
3865   entry.tls_type = mips_elf_reloc_tls_type (r_type);
3866   return mips_elf_record_got_entry (info, abfd, &entry);
3867 }
3868
3869 /* Record that ABFD has a page relocation against SYMNDX + ADDEND.
3870    H is the symbol's hash table entry, or null if SYMNDX is local
3871    to ABFD.  */
3872
3873 static bfd_boolean
3874 mips_elf_record_got_page_ref (struct bfd_link_info *info, bfd *abfd,
3875                               long symndx, struct elf_link_hash_entry *h,
3876                               bfd_signed_vma addend)
3877 {
3878   struct mips_elf_link_hash_table *htab;
3879   struct mips_got_info *g1, *g2;
3880   struct mips_got_page_ref lookup, *entry;
3881   void **loc, **bfd_loc;
3882
3883   htab = mips_elf_hash_table (info);
3884   BFD_ASSERT (htab != NULL);
3885
3886   g1 = htab->got_info;
3887   BFD_ASSERT (g1 != NULL);
3888
3889   if (h)
3890     {
3891       lookup.symndx = -1;
3892       lookup.u.h = (struct mips_elf_link_hash_entry *) h;
3893     }
3894   else
3895     {
3896       lookup.symndx = symndx;
3897       lookup.u.abfd = abfd;
3898     }
3899   lookup.addend = addend;
3900   loc = htab_find_slot (g1->got_page_refs, &lookup, INSERT);
3901   if (loc == NULL)
3902     return FALSE;
3903
3904   entry = (struct mips_got_page_ref *) *loc;
3905   if (!entry)
3906     {
3907       entry = bfd_alloc (abfd, sizeof (*entry));
3908       if (!entry)
3909         return FALSE;
3910
3911       *entry = lookup;
3912       *loc = entry;
3913     }
3914
3915   /* Add the same entry to the BFD's GOT.  */
3916   g2 = mips_elf_bfd_got (abfd, TRUE);
3917   if (!g2)
3918     return FALSE;
3919
3920   bfd_loc = htab_find_slot (g2->got_page_refs, &lookup, INSERT);
3921   if (!bfd_loc)
3922     return FALSE;
3923
3924   if (!*bfd_loc)
3925     *bfd_loc = entry;
3926
3927   return TRUE;
3928 }
3929
3930 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
3931
3932 static void
3933 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
3934                                        unsigned int n)
3935 {
3936   asection *s;
3937   struct mips_elf_link_hash_table *htab;
3938
3939   htab = mips_elf_hash_table (info);
3940   BFD_ASSERT (htab != NULL);
3941
3942   s = mips_elf_rel_dyn_section (info, FALSE);
3943   BFD_ASSERT (s != NULL);
3944
3945   if (htab->is_vxworks)
3946     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
3947   else
3948     {
3949       if (s->size == 0)
3950         {
3951           /* Make room for a null element.  */
3952           s->size += MIPS_ELF_REL_SIZE (abfd);
3953           ++s->reloc_count;
3954         }
3955       s->size += n * MIPS_ELF_REL_SIZE (abfd);
3956     }
3957 }
3958 \f
3959 /* A htab_traverse callback for GOT entries, with DATA pointing to a
3960    mips_elf_traverse_got_arg structure.  Count the number of GOT
3961    entries and TLS relocs.  Set DATA->value to true if we need
3962    to resolve indirect or warning symbols and then recreate the GOT.  */
3963
3964 static int
3965 mips_elf_check_recreate_got (void **entryp, void *data)
3966 {
3967   struct mips_got_entry *entry;
3968   struct mips_elf_traverse_got_arg *arg;
3969
3970   entry = (struct mips_got_entry *) *entryp;
3971   arg = (struct mips_elf_traverse_got_arg *) data;
3972   if (entry->abfd != NULL && entry->symndx == -1)
3973     {
3974       struct mips_elf_link_hash_entry *h;
3975
3976       h = entry->d.h;
3977       if (h->root.root.type == bfd_link_hash_indirect
3978           || h->root.root.type == bfd_link_hash_warning)
3979         {
3980           arg->value = TRUE;
3981           return 0;
3982         }
3983     }
3984   mips_elf_count_got_entry (arg->info, arg->g, entry);
3985   return 1;
3986 }
3987
3988 /* A htab_traverse callback for GOT entries, with DATA pointing to a
3989    mips_elf_traverse_got_arg structure.  Add all entries to DATA->g,
3990    converting entries for indirect and warning symbols into entries
3991    for the target symbol.  Set DATA->g to null on error.  */
3992
3993 static int
3994 mips_elf_recreate_got (void **entryp, void *data)
3995 {
3996   struct mips_got_entry new_entry, *entry;
3997   struct mips_elf_traverse_got_arg *arg;
3998   void **slot;
3999
4000   entry = (struct mips_got_entry *) *entryp;
4001   arg = (struct mips_elf_traverse_got_arg *) data;
4002   if (entry->abfd != NULL
4003       && entry->symndx == -1
4004       && (entry->d.h->root.root.type == bfd_link_hash_indirect
4005           || entry->d.h->root.root.type == bfd_link_hash_warning))
4006     {
4007       struct mips_elf_link_hash_entry *h;
4008
4009       new_entry = *entry;
4010       entry = &new_entry;
4011       h = entry->d.h;
4012       do
4013         {
4014           BFD_ASSERT (h->global_got_area == GGA_NONE);
4015           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
4016         }
4017       while (h->root.root.type == bfd_link_hash_indirect
4018              || h->root.root.type == bfd_link_hash_warning);
4019       entry->d.h = h;
4020     }
4021   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
4022   if (slot == NULL)
4023     {
4024       arg->g = NULL;
4025       return 0;
4026     }
4027   if (*slot == NULL)
4028     {
4029       if (entry == &new_entry)
4030         {
4031           entry = bfd_alloc (entry->abfd, sizeof (*entry));
4032           if (!entry)
4033             {
4034               arg->g = NULL;
4035               return 0;
4036             }
4037           *entry = new_entry;
4038         }
4039       *slot = entry;
4040       mips_elf_count_got_entry (arg->info, arg->g, entry);
4041     }
4042   return 1;
4043 }
4044
4045 /* Return the maximum number of GOT page entries required for RANGE.  */
4046
4047 static bfd_vma
4048 mips_elf_pages_for_range (const struct mips_got_page_range *range)
4049 {
4050   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
4051 }
4052
4053 /* Record that G requires a page entry that can reach SEC + ADDEND.  */
4054
4055 static bfd_boolean
4056 mips_elf_record_got_page_entry (struct mips_got_info *g,
4057                                 asection *sec, bfd_signed_vma addend)
4058 {
4059   struct mips_got_page_entry lookup, *entry;
4060   struct mips_got_page_range **range_ptr, *range;
4061   bfd_vma old_pages, new_pages;
4062   void **loc;
4063
4064   /* Find the mips_got_page_entry hash table entry for this section.  */
4065   lookup.sec = sec;
4066   loc = htab_find_slot (g->got_page_entries, &lookup, INSERT);
4067   if (loc == NULL)
4068     return FALSE;
4069
4070   /* Create a mips_got_page_entry if this is the first time we've
4071      seen the section.  */
4072   entry = (struct mips_got_page_entry *) *loc;
4073   if (!entry)
4074     {
4075       entry = bfd_zalloc (sec->owner, sizeof (*entry));
4076       if (!entry)
4077         return FALSE;
4078
4079       entry->sec = sec;
4080       *loc = entry;
4081     }
4082
4083   /* Skip over ranges whose maximum extent cannot share a page entry
4084      with ADDEND.  */
4085   range_ptr = &entry->ranges;
4086   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
4087     range_ptr = &(*range_ptr)->next;
4088
4089   /* If we scanned to the end of the list, or found a range whose
4090      minimum extent cannot share a page entry with ADDEND, create
4091      a new singleton range.  */
4092   range = *range_ptr;
4093   if (!range || addend < range->min_addend - 0xffff)
4094     {
4095       range = bfd_zalloc (sec->owner, sizeof (*range));
4096       if (!range)
4097         return FALSE;
4098
4099       range->next = *range_ptr;
4100       range->min_addend = addend;
4101       range->max_addend = addend;
4102
4103       *range_ptr = range;
4104       entry->num_pages++;
4105       g->page_gotno++;
4106       return TRUE;
4107     }
4108
4109   /* Remember how many pages the old range contributed.  */
4110   old_pages = mips_elf_pages_for_range (range);
4111
4112   /* Update the ranges.  */
4113   if (addend < range->min_addend)
4114     range->min_addend = addend;
4115   else if (addend > range->max_addend)
4116     {
4117       if (range->next && addend >= range->next->min_addend - 0xffff)
4118         {
4119           old_pages += mips_elf_pages_for_range (range->next);
4120           range->max_addend = range->next->max_addend;
4121           range->next = range->next->next;
4122         }
4123       else
4124         range->max_addend = addend;
4125     }
4126
4127   /* Record any change in the total estimate.  */
4128   new_pages = mips_elf_pages_for_range (range);
4129   if (old_pages != new_pages)
4130     {
4131       entry->num_pages += new_pages - old_pages;
4132       g->page_gotno += new_pages - old_pages;
4133     }
4134
4135   return TRUE;
4136 }
4137
4138 /* A htab_traverse callback for which *REFP points to a mips_got_page_ref
4139    and for which DATA points to a mips_elf_traverse_got_arg.  Work out
4140    whether the page reference described by *REFP needs a GOT page entry,
4141    and record that entry in DATA->g if so.  Set DATA->g to null on failure.  */
4142
4143 static bfd_boolean
4144 mips_elf_resolve_got_page_ref (void **refp, void *data)
4145 {
4146   struct mips_got_page_ref *ref;
4147   struct mips_elf_traverse_got_arg *arg;
4148   struct mips_elf_link_hash_table *htab;
4149   asection *sec;
4150   bfd_vma addend;
4151
4152   ref = (struct mips_got_page_ref *) *refp;
4153   arg = (struct mips_elf_traverse_got_arg *) data;
4154   htab = mips_elf_hash_table (arg->info);
4155
4156   if (ref->symndx < 0)
4157     {
4158       struct mips_elf_link_hash_entry *h;
4159
4160       /* Global GOT_PAGEs decay to GOT_DISP and so don't need page entries.  */
4161       h = ref->u.h;
4162       if (!SYMBOL_REFERENCES_LOCAL (arg->info, &h->root))
4163         return 1;
4164
4165       /* Ignore undefined symbols; we'll issue an error later if
4166          appropriate.  */
4167       if (!((h->root.root.type == bfd_link_hash_defined
4168              || h->root.root.type == bfd_link_hash_defweak)
4169             && h->root.root.u.def.section))
4170         return 1;
4171
4172       sec = h->root.root.u.def.section;
4173       addend = h->root.root.u.def.value + ref->addend;
4174     }
4175   else
4176     {
4177       Elf_Internal_Sym *isym;
4178
4179       /* Read in the symbol.  */
4180       isym = bfd_sym_from_r_symndx (&htab->sym_cache, ref->u.abfd,
4181                                     ref->symndx);
4182       if (isym == NULL)
4183         {
4184           arg->g = NULL;
4185           return 0;
4186         }
4187
4188       /* Get the associated input section.  */
4189       sec = bfd_section_from_elf_index (ref->u.abfd, isym->st_shndx);
4190       if (sec == NULL)
4191         {
4192           arg->g = NULL;
4193           return 0;
4194         }
4195
4196       /* If this is a mergable section, work out the section and offset
4197          of the merged data.  For section symbols, the addend specifies
4198          of the offset _of_ the first byte in the data, otherwise it
4199          specifies the offset _from_ the first byte.  */
4200       if (sec->flags & SEC_MERGE)
4201         {
4202           void *secinfo;
4203
4204           secinfo = elf_section_data (sec)->sec_info;
4205           if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
4206             addend = _bfd_merged_section_offset (ref->u.abfd, &sec, secinfo,
4207                                                  isym->st_value + ref->addend);
4208           else
4209             addend = _bfd_merged_section_offset (ref->u.abfd, &sec, secinfo,
4210                                                  isym->st_value) + ref->addend;
4211         }
4212       else
4213         addend = isym->st_value + ref->addend;
4214     }
4215   if (!mips_elf_record_got_page_entry (arg->g, sec, addend))
4216     {
4217       arg->g = NULL;
4218       return 0;
4219     }
4220   return 1;
4221 }
4222
4223 /* If any entries in G->got_entries are for indirect or warning symbols,
4224    replace them with entries for the target symbol.  Convert g->got_page_refs
4225    into got_page_entry structures and estimate the number of page entries
4226    that they require.  */
4227
4228 static bfd_boolean
4229 mips_elf_resolve_final_got_entries (struct bfd_link_info *info,
4230                                     struct mips_got_info *g)
4231 {
4232   struct mips_elf_traverse_got_arg tga;
4233   struct mips_got_info oldg;
4234
4235   oldg = *g;
4236
4237   tga.info = info;
4238   tga.g = g;
4239   tga.value = FALSE;
4240   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &tga);
4241   if (tga.value)
4242     {
4243       *g = oldg;
4244       g->got_entries = htab_create (htab_size (oldg.got_entries),
4245                                     mips_elf_got_entry_hash,
4246                                     mips_elf_got_entry_eq, NULL);
4247       if (!g->got_entries)
4248         return FALSE;
4249
4250       htab_traverse (oldg.got_entries, mips_elf_recreate_got, &tga);
4251       if (!tga.g)
4252         return FALSE;
4253
4254       htab_delete (oldg.got_entries);
4255     }
4256
4257   g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4258                                          mips_got_page_entry_eq, NULL);
4259   if (g->got_page_entries == NULL)
4260     return FALSE;
4261
4262   tga.info = info;
4263   tga.g = g;
4264   htab_traverse (g->got_page_refs, mips_elf_resolve_got_page_ref, &tga);
4265
4266   return TRUE;
4267 }
4268
4269 /* A mips_elf_link_hash_traverse callback for which DATA points to the
4270    link_info structure.  Decide whether the hash entry needs an entry in
4271    the global part of the primary GOT, setting global_got_area accordingly.
4272    Count the number of global symbols that are in the primary GOT only
4273    because they have relocations against them (reloc_only_gotno).  */
4274
4275 static int
4276 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
4277 {
4278   struct bfd_link_info *info;
4279   struct mips_elf_link_hash_table *htab;
4280   struct mips_got_info *g;
4281
4282   info = (struct bfd_link_info *) data;
4283   htab = mips_elf_hash_table (info);
4284   g = htab->got_info;
4285   if (h->global_got_area != GGA_NONE)
4286     {
4287       /* Make a final decision about whether the symbol belongs in the
4288          local or global GOT.  Symbols that bind locally can (and in the
4289          case of forced-local symbols, must) live in the local GOT.
4290          Those that are aren't in the dynamic symbol table must also
4291          live in the local GOT.
4292
4293          Note that the former condition does not always imply the
4294          latter: symbols do not bind locally if they are completely
4295          undefined.  We'll report undefined symbols later if appropriate.  */
4296       if (h->root.dynindx == -1
4297           || (h->got_only_for_calls
4298               ? SYMBOL_CALLS_LOCAL (info, &h->root)
4299               : SYMBOL_REFERENCES_LOCAL (info, &h->root)))
4300         /* The symbol belongs in the local GOT.  We no longer need this
4301            entry if it was only used for relocations; those relocations
4302            will be against the null or section symbol instead of H.  */
4303         h->global_got_area = GGA_NONE;
4304       else if (htab->is_vxworks
4305                && h->got_only_for_calls
4306                && h->root.plt.plist->mips_offset != MINUS_ONE)
4307         /* On VxWorks, calls can refer directly to the .got.plt entry;
4308            they don't need entries in the regular GOT.  .got.plt entries
4309            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4310         h->global_got_area = GGA_NONE;
4311       else if (h->global_got_area == GGA_RELOC_ONLY)
4312         {
4313           g->reloc_only_gotno++;
4314           g->global_gotno++;
4315         }
4316     }
4317   return 1;
4318 }
4319 \f
4320 /* A htab_traverse callback for GOT entries.  Add each one to the GOT
4321    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4322
4323 static int
4324 mips_elf_add_got_entry (void **entryp, void *data)
4325 {
4326   struct mips_got_entry *entry;
4327   struct mips_elf_traverse_got_arg *arg;
4328   void **slot;
4329
4330   entry = (struct mips_got_entry *) *entryp;
4331   arg = (struct mips_elf_traverse_got_arg *) data;
4332   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
4333   if (!slot)
4334     {
4335       arg->g = NULL;
4336       return 0;
4337     }
4338   if (!*slot)
4339     {
4340       *slot = entry;
4341       mips_elf_count_got_entry (arg->info, arg->g, entry);
4342     }
4343   return 1;
4344 }
4345
4346 /* A htab_traverse callback for GOT page entries.  Add each one to the GOT
4347    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4348
4349 static int
4350 mips_elf_add_got_page_entry (void **entryp, void *data)
4351 {
4352   struct mips_got_page_entry *entry;
4353   struct mips_elf_traverse_got_arg *arg;
4354   void **slot;
4355
4356   entry = (struct mips_got_page_entry *) *entryp;
4357   arg = (struct mips_elf_traverse_got_arg *) data;
4358   slot = htab_find_slot (arg->g->got_page_entries, entry, INSERT);
4359   if (!slot)
4360     {
4361       arg->g = NULL;
4362       return 0;
4363     }
4364   if (!*slot)
4365     {
4366       *slot = entry;
4367       arg->g->page_gotno += entry->num_pages;
4368     }
4369   return 1;
4370 }
4371
4372 /* Consider merging FROM, which is ABFD's GOT, into TO.  Return -1 if
4373    this would lead to overflow, 1 if they were merged successfully,
4374    and 0 if a merge failed due to lack of memory.  (These values are chosen
4375    so that nonnegative return values can be returned by a htab_traverse
4376    callback.)  */
4377
4378 static int
4379 mips_elf_merge_got_with (bfd *abfd, struct mips_got_info *from,
4380                          struct mips_got_info *to,
4381                          struct mips_elf_got_per_bfd_arg *arg)
4382 {
4383   struct mips_elf_traverse_got_arg tga;
4384   unsigned int estimate;
4385
4386   /* Work out how many page entries we would need for the combined GOT.  */
4387   estimate = arg->max_pages;
4388   if (estimate >= from->page_gotno + to->page_gotno)
4389     estimate = from->page_gotno + to->page_gotno;
4390
4391   /* And conservatively estimate how many local and TLS entries
4392      would be needed.  */
4393   estimate += from->local_gotno + to->local_gotno;
4394   estimate += from->tls_gotno + to->tls_gotno;
4395
4396   /* If we're merging with the primary got, any TLS relocations will
4397      come after the full set of global entries.  Otherwise estimate those
4398      conservatively as well.  */
4399   if (to == arg->primary && from->tls_gotno + to->tls_gotno)
4400     estimate += arg->global_count;
4401   else
4402     estimate += from->global_gotno + to->global_gotno;
4403
4404   /* Bail out if the combined GOT might be too big.  */
4405   if (estimate > arg->max_count)
4406     return -1;
4407
4408   /* Transfer the bfd's got information from FROM to TO.  */
4409   tga.info = arg->info;
4410   tga.g = to;
4411   htab_traverse (from->got_entries, mips_elf_add_got_entry, &tga);
4412   if (!tga.g)
4413     return 0;
4414
4415   htab_traverse (from->got_page_entries, mips_elf_add_got_page_entry, &tga);
4416   if (!tga.g)
4417     return 0;
4418
4419   mips_elf_replace_bfd_got (abfd, to);
4420   return 1;
4421 }
4422
4423 /* Attempt to merge GOT G, which belongs to ABFD.  Try to use as much
4424    as possible of the primary got, since it doesn't require explicit
4425    dynamic relocations, but don't use bfds that would reference global
4426    symbols out of the addressable range.  Failing the primary got,
4427    attempt to merge with the current got, or finish the current got
4428    and then make make the new got current.  */
4429
4430 static bfd_boolean
4431 mips_elf_merge_got (bfd *abfd, struct mips_got_info *g,
4432                     struct mips_elf_got_per_bfd_arg *arg)
4433 {
4434   unsigned int estimate;
4435   int result;
4436
4437   if (!mips_elf_resolve_final_got_entries (arg->info, g))
4438     return FALSE;
4439
4440   /* Work out the number of page, local and TLS entries.  */
4441   estimate = arg->max_pages;
4442   if (estimate > g->page_gotno)
4443     estimate = g->page_gotno;
4444   estimate += g->local_gotno + g->tls_gotno;
4445
4446   /* We place TLS GOT entries after both locals and globals.  The globals
4447      for the primary GOT may overflow the normal GOT size limit, so be
4448      sure not to merge a GOT which requires TLS with the primary GOT in that
4449      case.  This doesn't affect non-primary GOTs.  */
4450   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4451
4452   if (estimate <= arg->max_count)
4453     {
4454       /* If we don't have a primary GOT, use it as
4455          a starting point for the primary GOT.  */
4456       if (!arg->primary)
4457         {
4458           arg->primary = g;
4459           return TRUE;
4460         }
4461
4462       /* Try merging with the primary GOT.  */
4463       result = mips_elf_merge_got_with (abfd, g, arg->primary, arg);
4464       if (result >= 0)
4465         return result;
4466     }
4467
4468   /* If we can merge with the last-created got, do it.  */
4469   if (arg->current)
4470     {
4471       result = mips_elf_merge_got_with (abfd, g, arg->current, arg);
4472       if (result >= 0)
4473         return result;
4474     }
4475
4476   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4477      fits; if it turns out that it doesn't, we'll get relocation
4478      overflows anyway.  */
4479   g->next = arg->current;
4480   arg->current = g;
4481
4482   return TRUE;
4483 }
4484
4485 /* ENTRYP is a hash table entry for a mips_got_entry.  Set its gotidx
4486    to GOTIDX, duplicating the entry if it has already been assigned
4487    an index in a different GOT.  */
4488
4489 static bfd_boolean
4490 mips_elf_set_gotidx (void **entryp, long gotidx)
4491 {
4492   struct mips_got_entry *entry;
4493
4494   entry = (struct mips_got_entry *) *entryp;
4495   if (entry->gotidx > 0)
4496     {
4497       struct mips_got_entry *new_entry;
4498
4499       new_entry = bfd_alloc (entry->abfd, sizeof (*entry));
4500       if (!new_entry)
4501         return FALSE;
4502
4503       *new_entry = *entry;
4504       *entryp = new_entry;
4505       entry = new_entry;
4506     }
4507   entry->gotidx = gotidx;
4508   return TRUE;
4509 }
4510
4511 /* Set the TLS GOT index for the GOT entry in ENTRYP.  DATA points to a
4512    mips_elf_traverse_got_arg in which DATA->value is the size of one
4513    GOT entry.  Set DATA->g to null on failure.  */
4514
4515 static int
4516 mips_elf_initialize_tls_index (void **entryp, void *data)
4517 {
4518   struct mips_got_entry *entry;
4519   struct mips_elf_traverse_got_arg *arg;
4520
4521   /* We're only interested in TLS symbols.  */
4522   entry = (struct mips_got_entry *) *entryp;
4523   if (entry->tls_type == GOT_TLS_NONE)
4524     return 1;
4525
4526   arg = (struct mips_elf_traverse_got_arg *) data;
4527   if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->tls_assigned_gotno))
4528     {
4529       arg->g = NULL;
4530       return 0;
4531     }
4532
4533   /* Account for the entries we've just allocated.  */
4534   arg->g->tls_assigned_gotno += mips_tls_got_entries (entry->tls_type);
4535   return 1;
4536 }
4537
4538 /* A htab_traverse callback for GOT entries, where DATA points to a
4539    mips_elf_traverse_got_arg.  Set the global_got_area of each global
4540    symbol to DATA->value.  */
4541
4542 static int
4543 mips_elf_set_global_got_area (void **entryp, void *data)
4544 {
4545   struct mips_got_entry *entry;
4546   struct mips_elf_traverse_got_arg *arg;
4547
4548   entry = (struct mips_got_entry *) *entryp;
4549   arg = (struct mips_elf_traverse_got_arg *) data;
4550   if (entry->abfd != NULL
4551       && entry->symndx == -1
4552       && entry->d.h->global_got_area != GGA_NONE)
4553     entry->d.h->global_got_area = arg->value;
4554   return 1;
4555 }
4556
4557 /* A htab_traverse callback for secondary GOT entries, where DATA points
4558    to a mips_elf_traverse_got_arg.  Assign GOT indices to global entries
4559    and record the number of relocations they require.  DATA->value is
4560    the size of one GOT entry.  Set DATA->g to null on failure.  */
4561
4562 static int
4563 mips_elf_set_global_gotidx (void **entryp, void *data)
4564 {
4565   struct mips_got_entry *entry;
4566   struct mips_elf_traverse_got_arg *arg;
4567
4568   entry = (struct mips_got_entry *) *entryp;
4569   arg = (struct mips_elf_traverse_got_arg *) data;
4570   if (entry->abfd != NULL
4571       && entry->symndx == -1
4572       && entry->d.h->global_got_area != GGA_NONE)
4573     {
4574       if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->assigned_gotno))
4575         {
4576           arg->g = NULL;
4577           return 0;
4578         }
4579       arg->g->assigned_gotno += 1;
4580
4581       if (arg->info->shared
4582           || (elf_hash_table (arg->info)->dynamic_sections_created
4583               && entry->d.h->root.def_dynamic
4584               && !entry->d.h->root.def_regular))
4585         arg->g->relocs += 1;
4586     }
4587
4588   return 1;
4589 }
4590
4591 /* A htab_traverse callback for GOT entries for which DATA is the
4592    bfd_link_info.  Forbid any global symbols from having traditional
4593    lazy-binding stubs.  */
4594
4595 static int
4596 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4597 {
4598   struct bfd_link_info *info;
4599   struct mips_elf_link_hash_table *htab;
4600   struct mips_got_entry *entry;
4601
4602   entry = (struct mips_got_entry *) *entryp;
4603   info = (struct bfd_link_info *) data;
4604   htab = mips_elf_hash_table (info);
4605   BFD_ASSERT (htab != NULL);
4606
4607   if (entry->abfd != NULL
4608       && entry->symndx == -1
4609       && entry->d.h->needs_lazy_stub)
4610     {
4611       entry->d.h->needs_lazy_stub = FALSE;
4612       htab->lazy_stub_count--;
4613     }
4614
4615   return 1;
4616 }
4617
4618 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4619    the primary GOT.  */
4620 static bfd_vma
4621 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4622 {
4623   if (!g->next)
4624     return 0;
4625
4626   g = mips_elf_bfd_got (ibfd, FALSE);
4627   if (! g)
4628     return 0;
4629
4630   BFD_ASSERT (g->next);
4631
4632   g = g->next;
4633
4634   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4635     * MIPS_ELF_GOT_SIZE (abfd);
4636 }
4637
4638 /* Turn a single GOT that is too big for 16-bit addressing into
4639    a sequence of GOTs, each one 16-bit addressable.  */
4640
4641 static bfd_boolean
4642 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4643                     asection *got, bfd_size_type pages)
4644 {
4645   struct mips_elf_link_hash_table *htab;
4646   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4647   struct mips_elf_traverse_got_arg tga;
4648   struct mips_got_info *g, *gg;
4649   unsigned int assign, needed_relocs;
4650   bfd *dynobj, *ibfd;
4651
4652   dynobj = elf_hash_table (info)->dynobj;
4653   htab = mips_elf_hash_table (info);
4654   BFD_ASSERT (htab != NULL);
4655
4656   g = htab->got_info;
4657
4658   got_per_bfd_arg.obfd = abfd;
4659   got_per_bfd_arg.info = info;
4660   got_per_bfd_arg.current = NULL;
4661   got_per_bfd_arg.primary = NULL;
4662   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4663                                 / MIPS_ELF_GOT_SIZE (abfd))
4664                                - htab->reserved_gotno);
4665   got_per_bfd_arg.max_pages = pages;
4666   /* The number of globals that will be included in the primary GOT.
4667      See the calls to mips_elf_set_global_got_area below for more
4668      information.  */
4669   got_per_bfd_arg.global_count = g->global_gotno;
4670
4671   /* Try to merge the GOTs of input bfds together, as long as they
4672      don't seem to exceed the maximum GOT size, choosing one of them
4673      to be the primary GOT.  */
4674   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
4675     {
4676       gg = mips_elf_bfd_got (ibfd, FALSE);
4677       if (gg && !mips_elf_merge_got (ibfd, gg, &got_per_bfd_arg))
4678         return FALSE;
4679     }
4680
4681   /* If we do not find any suitable primary GOT, create an empty one.  */
4682   if (got_per_bfd_arg.primary == NULL)
4683     g->next = mips_elf_create_got_info (abfd);
4684   else
4685     g->next = got_per_bfd_arg.primary;
4686   g->next->next = got_per_bfd_arg.current;
4687
4688   /* GG is now the master GOT, and G is the primary GOT.  */
4689   gg = g;
4690   g = g->next;
4691
4692   /* Map the output bfd to the primary got.  That's what we're going
4693      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4694      didn't mark in check_relocs, and we want a quick way to find it.
4695      We can't just use gg->next because we're going to reverse the
4696      list.  */
4697   mips_elf_replace_bfd_got (abfd, g);
4698
4699   /* Every symbol that is referenced in a dynamic relocation must be
4700      present in the primary GOT, so arrange for them to appear after
4701      those that are actually referenced.  */
4702   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4703   g->global_gotno = gg->global_gotno;
4704
4705   tga.info = info;
4706   tga.value = GGA_RELOC_ONLY;
4707   htab_traverse (gg->got_entries, mips_elf_set_global_got_area, &tga);
4708   tga.value = GGA_NORMAL;
4709   htab_traverse (g->got_entries, mips_elf_set_global_got_area, &tga);
4710
4711   /* Now go through the GOTs assigning them offset ranges.
4712      [assigned_gotno, local_gotno[ will be set to the range of local
4713      entries in each GOT.  We can then compute the end of a GOT by
4714      adding local_gotno to global_gotno.  We reverse the list and make
4715      it circular since then we'll be able to quickly compute the
4716      beginning of a GOT, by computing the end of its predecessor.  To
4717      avoid special cases for the primary GOT, while still preserving
4718      assertions that are valid for both single- and multi-got links,
4719      we arrange for the main got struct to have the right number of
4720      global entries, but set its local_gotno such that the initial
4721      offset of the primary GOT is zero.  Remember that the primary GOT
4722      will become the last item in the circular linked list, so it
4723      points back to the master GOT.  */
4724   gg->local_gotno = -g->global_gotno;
4725   gg->global_gotno = g->global_gotno;
4726   gg->tls_gotno = 0;
4727   assign = 0;
4728   gg->next = gg;
4729
4730   do
4731     {
4732       struct mips_got_info *gn;
4733
4734       assign += htab->reserved_gotno;
4735       g->assigned_gotno = assign;
4736       g->local_gotno += assign;
4737       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4738       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4739
4740       /* Take g out of the direct list, and push it onto the reversed
4741          list that gg points to.  g->next is guaranteed to be nonnull after
4742          this operation, as required by mips_elf_initialize_tls_index. */
4743       gn = g->next;
4744       g->next = gg->next;
4745       gg->next = g;
4746
4747       /* Set up any TLS entries.  We always place the TLS entries after
4748          all non-TLS entries.  */
4749       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4750       tga.g = g;
4751       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4752       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
4753       if (!tga.g)
4754         return FALSE;
4755       BFD_ASSERT (g->tls_assigned_gotno == assign);
4756
4757       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4758       g = gn;
4759
4760       /* Forbid global symbols in every non-primary GOT from having
4761          lazy-binding stubs.  */
4762       if (g)
4763         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4764     }
4765   while (g);
4766
4767   got->size = assign * MIPS_ELF_GOT_SIZE (abfd);
4768
4769   needed_relocs = 0;
4770   for (g = gg->next; g && g->next != gg; g = g->next)
4771     {
4772       unsigned int save_assign;
4773
4774       /* Assign offsets to global GOT entries and count how many
4775          relocations they need.  */
4776       save_assign = g->assigned_gotno;
4777       g->assigned_gotno = g->local_gotno;
4778       tga.info = info;
4779       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4780       tga.g = g;
4781       htab_traverse (g->got_entries, mips_elf_set_global_gotidx, &tga);
4782       if (!tga.g)
4783         return FALSE;
4784       BFD_ASSERT (g->assigned_gotno == g->local_gotno + g->global_gotno);
4785       g->assigned_gotno = save_assign;
4786
4787       if (info->shared)
4788         {
4789           g->relocs += g->local_gotno - g->assigned_gotno;
4790           BFD_ASSERT (g->assigned_gotno == g->next->local_gotno
4791                       + g->next->global_gotno
4792                       + g->next->tls_gotno
4793                       + htab->reserved_gotno);
4794         }
4795       needed_relocs += g->relocs;
4796     }
4797   needed_relocs += g->relocs;
4798
4799   if (needed_relocs)
4800     mips_elf_allocate_dynamic_relocations (dynobj, info,
4801                                            needed_relocs);
4802
4803   return TRUE;
4804 }
4805
4806 \f
4807 /* Returns the first relocation of type r_type found, beginning with
4808    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4809
4810 static const Elf_Internal_Rela *
4811 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4812                           const Elf_Internal_Rela *relocation,
4813                           const Elf_Internal_Rela *relend)
4814 {
4815   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4816
4817   while (relocation < relend)
4818     {
4819       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4820           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4821         return relocation;
4822
4823       ++relocation;
4824     }
4825
4826   /* We didn't find it.  */
4827   return NULL;
4828 }
4829
4830 /* Return whether an input relocation is against a local symbol.  */
4831
4832 static bfd_boolean
4833 mips_elf_local_relocation_p (bfd *input_bfd,
4834                              const Elf_Internal_Rela *relocation,
4835                              asection **local_sections)
4836 {
4837   unsigned long r_symndx;
4838   Elf_Internal_Shdr *symtab_hdr;
4839   size_t extsymoff;
4840
4841   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4842   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4843   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
4844
4845   if (r_symndx < extsymoff)
4846     return TRUE;
4847   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
4848     return TRUE;
4849
4850   return FALSE;
4851 }
4852 \f
4853 /* Sign-extend VALUE, which has the indicated number of BITS.  */
4854
4855 bfd_vma
4856 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
4857 {
4858   if (value & ((bfd_vma) 1 << (bits - 1)))
4859     /* VALUE is negative.  */
4860     value |= ((bfd_vma) - 1) << bits;
4861
4862   return value;
4863 }
4864
4865 /* Return non-zero if the indicated VALUE has overflowed the maximum
4866    range expressible by a signed number with the indicated number of
4867    BITS.  */
4868
4869 static bfd_boolean
4870 mips_elf_overflow_p (bfd_vma value, int bits)
4871 {
4872   bfd_signed_vma svalue = (bfd_signed_vma) value;
4873
4874   if (svalue > (1 << (bits - 1)) - 1)
4875     /* The value is too big.  */
4876     return TRUE;
4877   else if (svalue < -(1 << (bits - 1)))
4878     /* The value is too small.  */
4879     return TRUE;
4880
4881   /* All is well.  */
4882   return FALSE;
4883 }
4884
4885 /* Calculate the %high function.  */
4886
4887 static bfd_vma
4888 mips_elf_high (bfd_vma value)
4889 {
4890   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
4891 }
4892
4893 /* Calculate the %higher function.  */
4894
4895 static bfd_vma
4896 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
4897 {
4898 #ifdef BFD64
4899   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
4900 #else
4901   abort ();
4902   return MINUS_ONE;
4903 #endif
4904 }
4905
4906 /* Calculate the %highest function.  */
4907
4908 static bfd_vma
4909 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
4910 {
4911 #ifdef BFD64
4912   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
4913 #else
4914   abort ();
4915   return MINUS_ONE;
4916 #endif
4917 }
4918 \f
4919 /* Create the .compact_rel section.  */
4920
4921 static bfd_boolean
4922 mips_elf_create_compact_rel_section
4923   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
4924 {
4925   flagword flags;
4926   register asection *s;
4927
4928   if (bfd_get_linker_section (abfd, ".compact_rel") == NULL)
4929     {
4930       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
4931                | SEC_READONLY);
4932
4933       s = bfd_make_section_anyway_with_flags (abfd, ".compact_rel", flags);
4934       if (s == NULL
4935           || ! bfd_set_section_alignment (abfd, s,
4936                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
4937         return FALSE;
4938
4939       s->size = sizeof (Elf32_External_compact_rel);
4940     }
4941
4942   return TRUE;
4943 }
4944
4945 /* Create the .got section to hold the global offset table.  */
4946
4947 static bfd_boolean
4948 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
4949 {
4950   flagword flags;
4951   register asection *s;
4952   struct elf_link_hash_entry *h;
4953   struct bfd_link_hash_entry *bh;
4954   struct mips_elf_link_hash_table *htab;
4955
4956   htab = mips_elf_hash_table (info);
4957   BFD_ASSERT (htab != NULL);
4958
4959   /* This function may be called more than once.  */
4960   if (htab->sgot)
4961     return TRUE;
4962
4963   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
4964            | SEC_LINKER_CREATED);
4965
4966   /* We have to use an alignment of 2**4 here because this is hardcoded
4967      in the function stub generation and in the linker script.  */
4968   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
4969   if (s == NULL
4970       || ! bfd_set_section_alignment (abfd, s, 4))
4971     return FALSE;
4972   htab->sgot = s;
4973
4974   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
4975      linker script because we don't want to define the symbol if we
4976      are not creating a global offset table.  */
4977   bh = NULL;
4978   if (! (_bfd_generic_link_add_one_symbol
4979          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
4980           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
4981     return FALSE;
4982
4983   h = (struct elf_link_hash_entry *) bh;
4984   h->non_elf = 0;
4985   h->def_regular = 1;
4986   h->type = STT_OBJECT;
4987   elf_hash_table (info)->hgot = h;
4988
4989   if (info->shared
4990       && ! bfd_elf_link_record_dynamic_symbol (info, h))
4991     return FALSE;
4992
4993   htab->got_info = mips_elf_create_got_info (abfd);
4994   mips_elf_section_data (s)->elf.this_hdr.sh_flags
4995     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
4996
4997   /* We also need a .got.plt section when generating PLTs.  */
4998   s = bfd_make_section_anyway_with_flags (abfd, ".got.plt",
4999                                           SEC_ALLOC | SEC_LOAD
5000                                           | SEC_HAS_CONTENTS
5001                                           | SEC_IN_MEMORY
5002                                           | SEC_LINKER_CREATED);
5003   if (s == NULL)
5004     return FALSE;
5005   htab->sgotplt = s;
5006
5007   return TRUE;
5008 }
5009 \f
5010 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
5011    __GOTT_INDEX__ symbols.  These symbols are only special for
5012    shared objects; they are not used in executables.  */
5013
5014 static bfd_boolean
5015 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
5016 {
5017   return (mips_elf_hash_table (info)->is_vxworks
5018           && info->shared
5019           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
5020               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
5021 }
5022
5023 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
5024    require an la25 stub.  See also mips_elf_local_pic_function_p,
5025    which determines whether the destination function ever requires a
5026    stub.  */
5027
5028 static bfd_boolean
5029 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type,
5030                                      bfd_boolean target_is_16_bit_code_p)
5031 {
5032   /* We specifically ignore branches and jumps from EF_PIC objects,
5033      where the onus is on the compiler or programmer to perform any
5034      necessary initialization of $25.  Sometimes such initialization
5035      is unnecessary; for example, -mno-shared functions do not use
5036      the incoming value of $25, and may therefore be called directly.  */
5037   if (PIC_OBJECT_P (input_bfd))
5038     return FALSE;
5039
5040   switch (r_type)
5041     {
5042     case R_MIPS_26:
5043     case R_MIPS_PC16:
5044     case R_MICROMIPS_26_S1:
5045     case R_MICROMIPS_PC7_S1:
5046     case R_MICROMIPS_PC10_S1:
5047     case R_MICROMIPS_PC16_S1:
5048     case R_MICROMIPS_PC23_S2:
5049       return TRUE;
5050
5051     case R_MIPS16_26:
5052       return !target_is_16_bit_code_p;
5053
5054     default:
5055       return FALSE;
5056     }
5057 }
5058 \f
5059 /* Calculate the value produced by the RELOCATION (which comes from
5060    the INPUT_BFD).  The ADDEND is the addend to use for this
5061    RELOCATION; RELOCATION->R_ADDEND is ignored.
5062
5063    The result of the relocation calculation is stored in VALUEP.
5064    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
5065    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5066
5067    This function returns bfd_reloc_continue if the caller need take no
5068    further action regarding this relocation, bfd_reloc_notsupported if
5069    something goes dramatically wrong, bfd_reloc_overflow if an
5070    overflow occurs, and bfd_reloc_ok to indicate success.  */
5071
5072 static bfd_reloc_status_type
5073 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
5074                                asection *input_section,
5075                                struct bfd_link_info *info,
5076                                const Elf_Internal_Rela *relocation,
5077                                bfd_vma addend, reloc_howto_type *howto,
5078                                Elf_Internal_Sym *local_syms,
5079                                asection **local_sections, bfd_vma *valuep,
5080                                const char **namep,
5081                                bfd_boolean *cross_mode_jump_p,
5082                                bfd_boolean save_addend)
5083 {
5084   /* The eventual value we will return.  */
5085   bfd_vma value;
5086   /* The address of the symbol against which the relocation is
5087      occurring.  */
5088   bfd_vma symbol = 0;
5089   /* The final GP value to be used for the relocatable, executable, or
5090      shared object file being produced.  */
5091   bfd_vma gp;
5092   /* The place (section offset or address) of the storage unit being
5093      relocated.  */
5094   bfd_vma p;
5095   /* The value of GP used to create the relocatable object.  */
5096   bfd_vma gp0;
5097   /* The offset into the global offset table at which the address of
5098      the relocation entry symbol, adjusted by the addend, resides
5099      during execution.  */
5100   bfd_vma g = MINUS_ONE;
5101   /* The section in which the symbol referenced by the relocation is
5102      located.  */
5103   asection *sec = NULL;
5104   struct mips_elf_link_hash_entry *h = NULL;
5105   /* TRUE if the symbol referred to by this relocation is a local
5106      symbol.  */
5107   bfd_boolean local_p, was_local_p;
5108   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
5109   bfd_boolean gp_disp_p = FALSE;
5110   /* TRUE if the symbol referred to by this relocation is
5111      "__gnu_local_gp".  */
5112   bfd_boolean gnu_local_gp_p = FALSE;
5113   Elf_Internal_Shdr *symtab_hdr;
5114   size_t extsymoff;
5115   unsigned long r_symndx;
5116   int r_type;
5117   /* TRUE if overflow occurred during the calculation of the
5118      relocation value.  */
5119   bfd_boolean overflowed_p;
5120   /* TRUE if this relocation refers to a MIPS16 function.  */
5121   bfd_boolean target_is_16_bit_code_p = FALSE;
5122   bfd_boolean target_is_micromips_code_p = FALSE;
5123   struct mips_elf_link_hash_table *htab;
5124   bfd *dynobj;
5125
5126   dynobj = elf_hash_table (info)->dynobj;
5127   htab = mips_elf_hash_table (info);
5128   BFD_ASSERT (htab != NULL);
5129
5130   /* Parse the relocation.  */
5131   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
5132   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5133   p = (input_section->output_section->vma
5134        + input_section->output_offset
5135        + relocation->r_offset);
5136
5137   /* Assume that there will be no overflow.  */
5138   overflowed_p = FALSE;
5139
5140   /* Figure out whether or not the symbol is local, and get the offset
5141      used in the array of hash table entries.  */
5142   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
5143   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
5144                                          local_sections);
5145   was_local_p = local_p;
5146   if (! elf_bad_symtab (input_bfd))
5147     extsymoff = symtab_hdr->sh_info;
5148   else
5149     {
5150       /* The symbol table does not follow the rule that local symbols
5151          must come before globals.  */
5152       extsymoff = 0;
5153     }
5154
5155   /* Figure out the value of the symbol.  */
5156   if (local_p)
5157     {
5158       Elf_Internal_Sym *sym;
5159
5160       sym = local_syms + r_symndx;
5161       sec = local_sections[r_symndx];
5162
5163       symbol = sec->output_section->vma + sec->output_offset;
5164       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION
5165           || (sec->flags & SEC_MERGE))
5166         symbol += sym->st_value;
5167       if ((sec->flags & SEC_MERGE)
5168           && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
5169         {
5170           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
5171           addend -= symbol;
5172           addend += sec->output_section->vma + sec->output_offset;
5173         }
5174
5175       /* MIPS16/microMIPS text labels should be treated as odd.  */
5176       if (ELF_ST_IS_COMPRESSED (sym->st_other))
5177         ++symbol;
5178
5179       /* Record the name of this symbol, for our caller.  */
5180       *namep = bfd_elf_string_from_elf_section (input_bfd,
5181                                                 symtab_hdr->sh_link,
5182                                                 sym->st_name);
5183       if (*namep == '\0')
5184         *namep = bfd_section_name (input_bfd, sec);
5185
5186       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
5187       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
5188     }
5189   else
5190     {
5191       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
5192
5193       /* For global symbols we look up the symbol in the hash-table.  */
5194       h = ((struct mips_elf_link_hash_entry *)
5195            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
5196       /* Find the real hash-table entry for this symbol.  */
5197       while (h->root.root.type == bfd_link_hash_indirect
5198              || h->root.root.type == bfd_link_hash_warning)
5199         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
5200
5201       /* Record the name of this symbol, for our caller.  */
5202       *namep = h->root.root.root.string;
5203
5204       /* See if this is the special _gp_disp symbol.  Note that such a
5205          symbol must always be a global symbol.  */
5206       if (strcmp (*namep, "_gp_disp") == 0
5207           && ! NEWABI_P (input_bfd))
5208         {
5209           /* Relocations against _gp_disp are permitted only with
5210              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
5211           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
5212             return bfd_reloc_notsupported;
5213
5214           gp_disp_p = TRUE;
5215         }
5216       /* See if this is the special _gp symbol.  Note that such a
5217          symbol must always be a global symbol.  */
5218       else if (strcmp (*namep, "__gnu_local_gp") == 0)
5219         gnu_local_gp_p = TRUE;
5220
5221
5222       /* If this symbol is defined, calculate its address.  Note that
5223          _gp_disp is a magic symbol, always implicitly defined by the
5224          linker, so it's inappropriate to check to see whether or not
5225          its defined.  */
5226       else if ((h->root.root.type == bfd_link_hash_defined
5227                 || h->root.root.type == bfd_link_hash_defweak)
5228                && h->root.root.u.def.section)
5229         {
5230           sec = h->root.root.u.def.section;
5231           if (sec->output_section)
5232             symbol = (h->root.root.u.def.value
5233                       + sec->output_section->vma
5234                       + sec->output_offset);
5235           else
5236             symbol = h->root.root.u.def.value;
5237         }
5238       else if (h->root.root.type == bfd_link_hash_undefweak)
5239         /* We allow relocations against undefined weak symbols, giving
5240            it the value zero, so that you can undefined weak functions
5241            and check to see if they exist by looking at their
5242            addresses.  */
5243         symbol = 0;
5244       else if (info->unresolved_syms_in_objects == RM_IGNORE
5245                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5246         symbol = 0;
5247       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
5248                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
5249         {
5250           /* If this is a dynamic link, we should have created a
5251              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
5252              in in _bfd_mips_elf_create_dynamic_sections.
5253              Otherwise, we should define the symbol with a value of 0.
5254              FIXME: It should probably get into the symbol table
5255              somehow as well.  */
5256           BFD_ASSERT (! info->shared);
5257           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
5258           symbol = 0;
5259         }
5260       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
5261         {
5262           /* This is an optional symbol - an Irix specific extension to the
5263              ELF spec.  Ignore it for now.
5264              XXX - FIXME - there is more to the spec for OPTIONAL symbols
5265              than simply ignoring them, but we do not handle this for now.
5266              For information see the "64-bit ELF Object File Specification"
5267              which is available from here:
5268              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
5269           symbol = 0;
5270         }
5271       else if ((*info->callbacks->undefined_symbol)
5272                (info, h->root.root.root.string, input_bfd,
5273                 input_section, relocation->r_offset,
5274                 (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
5275                  || ELF_ST_VISIBILITY (h->root.other)))
5276         {
5277           return bfd_reloc_undefined;
5278         }
5279       else
5280         {
5281           return bfd_reloc_notsupported;
5282         }
5283
5284       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
5285       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (h->root.other);
5286     }
5287
5288   /* If this is a reference to a 16-bit function with a stub, we need
5289      to redirect the relocation to the stub unless:
5290
5291      (a) the relocation is for a MIPS16 JAL;
5292
5293      (b) the relocation is for a MIPS16 PIC call, and there are no
5294          non-MIPS16 uses of the GOT slot; or
5295
5296      (c) the section allows direct references to MIPS16 functions.  */
5297   if (r_type != R_MIPS16_26
5298       && !info->relocatable
5299       && ((h != NULL
5300            && h->fn_stub != NULL
5301            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5302           || (local_p
5303               && mips_elf_tdata (input_bfd)->local_stubs != NULL
5304               && mips_elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5305       && !section_allows_mips16_refs_p (input_section))
5306     {
5307       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5308          have already noticed that we were going to need the
5309          stub.  */
5310       if (local_p)
5311         {
5312           sec = mips_elf_tdata (input_bfd)->local_stubs[r_symndx];
5313           value = 0;
5314         }
5315       else
5316         {
5317           BFD_ASSERT (h->need_fn_stub);
5318           if (h->la25_stub)
5319             {
5320               /* If a LA25 header for the stub itself exists, point to the
5321                  prepended LUI/ADDIU sequence.  */
5322               sec = h->la25_stub->stub_section;
5323               value = h->la25_stub->offset;
5324             }
5325           else
5326             {
5327               sec = h->fn_stub;
5328               value = 0;
5329             }
5330         }
5331
5332       symbol = sec->output_section->vma + sec->output_offset + value;
5333       /* The target is 16-bit, but the stub isn't.  */
5334       target_is_16_bit_code_p = FALSE;
5335     }
5336   /* If this is a MIPS16 call with a stub, that is made through the PLT or
5337      to a standard MIPS function, we need to redirect the call to the stub.
5338      Note that we specifically exclude R_MIPS16_CALL16 from this behavior;
5339      indirect calls should use an indirect stub instead.  */
5340   else if (r_type == R_MIPS16_26 && !info->relocatable
5341            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5342                || (local_p
5343                    && mips_elf_tdata (input_bfd)->local_call_stubs != NULL
5344                    && mips_elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5345            && ((h != NULL && h->use_plt_entry) || !target_is_16_bit_code_p))
5346     {
5347       if (local_p)
5348         sec = mips_elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5349       else
5350         {
5351           /* If both call_stub and call_fp_stub are defined, we can figure
5352              out which one to use by checking which one appears in the input
5353              file.  */
5354           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5355             {
5356               asection *o;
5357
5358               sec = NULL;
5359               for (o = input_bfd->sections; o != NULL; o = o->next)
5360                 {
5361                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5362                     {
5363                       sec = h->call_fp_stub;
5364                       break;
5365                     }
5366                 }
5367               if (sec == NULL)
5368                 sec = h->call_stub;
5369             }
5370           else if (h->call_stub != NULL)
5371             sec = h->call_stub;
5372           else
5373             sec = h->call_fp_stub;
5374         }
5375
5376       BFD_ASSERT (sec->size > 0);
5377       symbol = sec->output_section->vma + sec->output_offset;
5378     }
5379   /* If this is a direct call to a PIC function, redirect to the
5380      non-PIC stub.  */
5381   else if (h != NULL && h->la25_stub
5382            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type,
5383                                                    target_is_16_bit_code_p))
5384     symbol = (h->la25_stub->stub_section->output_section->vma
5385               + h->la25_stub->stub_section->output_offset
5386               + h->la25_stub->offset);
5387   /* For direct MIPS16 and microMIPS calls make sure the compressed PLT
5388      entry is used if a standard PLT entry has also been made.  In this
5389      case the symbol will have been set by mips_elf_set_plt_sym_value
5390      to point to the standard PLT entry, so redirect to the compressed
5391      one.  */
5392   else if ((r_type == R_MIPS16_26 || r_type == R_MICROMIPS_26_S1)
5393            && !info->relocatable
5394            && h != NULL
5395            && h->use_plt_entry
5396            && h->root.plt.plist->comp_offset != MINUS_ONE
5397            && h->root.plt.plist->mips_offset != MINUS_ONE)
5398     {
5399       bfd_boolean micromips_p = MICROMIPS_P (abfd);
5400
5401       sec = htab->splt;
5402       symbol = (sec->output_section->vma
5403                 + sec->output_offset
5404                 + htab->plt_header_size
5405                 + htab->plt_mips_offset
5406                 + h->root.plt.plist->comp_offset
5407                 + 1);
5408
5409       target_is_16_bit_code_p = !micromips_p;
5410       target_is_micromips_code_p = micromips_p;
5411     }
5412
5413   /* Make sure MIPS16 and microMIPS are not used together.  */
5414   if ((r_type == R_MIPS16_26 && target_is_micromips_code_p)
5415       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5416    {
5417       (*_bfd_error_handler)
5418         (_("MIPS16 and microMIPS functions cannot call each other"));
5419       return bfd_reloc_notsupported;
5420    }
5421
5422   /* Calls from 16-bit code to 32-bit code and vice versa require the
5423      mode change.  However, we can ignore calls to undefined weak symbols,
5424      which should never be executed at runtime.  This exception is important
5425      because the assembly writer may have "known" that any definition of the
5426      symbol would be 16-bit code, and that direct jumps were therefore
5427      acceptable.  */
5428   *cross_mode_jump_p = (!info->relocatable
5429                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5430                         && ((r_type == R_MIPS16_26 && !target_is_16_bit_code_p)
5431                             || (r_type == R_MICROMIPS_26_S1
5432                                 && !target_is_micromips_code_p)
5433                             || ((r_type == R_MIPS_26 || r_type == R_MIPS_JALR)
5434                                 && (target_is_16_bit_code_p
5435                                     || target_is_micromips_code_p))));
5436
5437   local_p = (h == NULL
5438              || (h->got_only_for_calls
5439                  ? SYMBOL_CALLS_LOCAL (info, &h->root)
5440                  : SYMBOL_REFERENCES_LOCAL (info, &h->root)));
5441
5442   gp0 = _bfd_get_gp_value (input_bfd);
5443   gp = _bfd_get_gp_value (abfd);
5444   if (htab->got_info)
5445     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5446
5447   if (gnu_local_gp_p)
5448     symbol = gp;
5449
5450   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5451      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5452      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5453   if (got_page_reloc_p (r_type) && !local_p)
5454     {
5455       r_type = (micromips_reloc_p (r_type)
5456                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5457       addend = 0;
5458     }
5459
5460   /* If we haven't already determined the GOT offset, and we're going
5461      to need it, get it now.  */
5462   switch (r_type)
5463     {
5464     case R_MIPS16_CALL16:
5465     case R_MIPS16_GOT16:
5466     case R_MIPS_CALL16:
5467     case R_MIPS_GOT16:
5468     case R_MIPS_GOT_DISP:
5469     case R_MIPS_GOT_HI16:
5470     case R_MIPS_CALL_HI16:
5471     case R_MIPS_GOT_LO16:
5472     case R_MIPS_CALL_LO16:
5473     case R_MICROMIPS_CALL16:
5474     case R_MICROMIPS_GOT16:
5475     case R_MICROMIPS_GOT_DISP:
5476     case R_MICROMIPS_GOT_HI16:
5477     case R_MICROMIPS_CALL_HI16:
5478     case R_MICROMIPS_GOT_LO16:
5479     case R_MICROMIPS_CALL_LO16:
5480     case R_MIPS_TLS_GD:
5481     case R_MIPS_TLS_GOTTPREL:
5482     case R_MIPS_TLS_LDM:
5483     case R_MIPS16_TLS_GD:
5484     case R_MIPS16_TLS_GOTTPREL:
5485     case R_MIPS16_TLS_LDM:
5486     case R_MICROMIPS_TLS_GD:
5487     case R_MICROMIPS_TLS_GOTTPREL:
5488     case R_MICROMIPS_TLS_LDM:
5489       /* Find the index into the GOT where this value is located.  */
5490       if (tls_ldm_reloc_p (r_type))
5491         {
5492           g = mips_elf_local_got_index (abfd, input_bfd, info,
5493                                         0, 0, NULL, r_type);
5494           if (g == MINUS_ONE)
5495             return bfd_reloc_outofrange;
5496         }
5497       else if (!local_p)
5498         {
5499           /* On VxWorks, CALL relocations should refer to the .got.plt
5500              entry, which is initialized to point at the PLT stub.  */
5501           if (htab->is_vxworks
5502               && (call_hi16_reloc_p (r_type)
5503                   || call_lo16_reloc_p (r_type)
5504                   || call16_reloc_p (r_type)))
5505             {
5506               BFD_ASSERT (addend == 0);
5507               BFD_ASSERT (h->root.needs_plt);
5508               g = mips_elf_gotplt_index (info, &h->root);
5509             }
5510           else
5511             {
5512               BFD_ASSERT (addend == 0);
5513               g = mips_elf_global_got_index (abfd, info, input_bfd,
5514                                              &h->root, r_type);
5515               if (!TLS_RELOC_P (r_type)
5516                   && !elf_hash_table (info)->dynamic_sections_created)
5517                 /* This is a static link.  We must initialize the GOT entry.  */
5518                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->sgot->contents + g);
5519             }
5520         }
5521       else if (!htab->is_vxworks
5522                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5523         /* The calculation below does not involve "g".  */
5524         break;
5525       else
5526         {
5527           g = mips_elf_local_got_index (abfd, input_bfd, info,
5528                                         symbol + addend, r_symndx, h, r_type);
5529           if (g == MINUS_ONE)
5530             return bfd_reloc_outofrange;
5531         }
5532
5533       /* Convert GOT indices to actual offsets.  */
5534       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5535       break;
5536     }
5537
5538   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5539      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5540   if (h != NULL && is_gott_symbol (info, &h->root))
5541     {
5542       Elf_Internal_Rela outrel;
5543       bfd_byte *loc;
5544       asection *s;
5545
5546       s = mips_elf_rel_dyn_section (info, FALSE);
5547       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5548
5549       outrel.r_offset = (input_section->output_section->vma
5550                          + input_section->output_offset
5551                          + relocation->r_offset);
5552       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5553       outrel.r_addend = addend;
5554       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5555
5556       /* If we've written this relocation for a readonly section,
5557          we need to set DF_TEXTREL again, so that we do not delete the
5558          DT_TEXTREL tag.  */
5559       if (MIPS_ELF_READONLY_SECTION (input_section))
5560         info->flags |= DF_TEXTREL;
5561
5562       *valuep = 0;
5563       return bfd_reloc_ok;
5564     }
5565
5566   /* Figure out what kind of relocation is being performed.  */
5567   switch (r_type)
5568     {
5569     case R_MIPS_NONE:
5570       return bfd_reloc_continue;
5571
5572     case R_MIPS_16:
5573       value = symbol + _bfd_mips_elf_sign_extend (addend, 16);
5574       overflowed_p = mips_elf_overflow_p (value, 16);
5575       break;
5576
5577     case R_MIPS_32:
5578     case R_MIPS_REL32:
5579     case R_MIPS_64:
5580       if ((info->shared
5581            || (htab->root.dynamic_sections_created
5582                && h != NULL
5583                && h->root.def_dynamic
5584                && !h->root.def_regular
5585                && !h->has_static_relocs))
5586           && r_symndx != STN_UNDEF
5587           && (h == NULL
5588               || h->root.root.type != bfd_link_hash_undefweak
5589               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5590           && (input_section->flags & SEC_ALLOC) != 0)
5591         {
5592           /* If we're creating a shared library, then we can't know
5593              where the symbol will end up.  So, we create a relocation
5594              record in the output, and leave the job up to the dynamic
5595              linker.  We must do the same for executable references to
5596              shared library symbols, unless we've decided to use copy
5597              relocs or PLTs instead.  */
5598           value = addend;
5599           if (!mips_elf_create_dynamic_relocation (abfd,
5600                                                    info,
5601                                                    relocation,
5602                                                    h,
5603                                                    sec,
5604                                                    symbol,
5605                                                    &value,
5606                                                    input_section))
5607             return bfd_reloc_undefined;
5608         }
5609       else
5610         {
5611           if (r_type != R_MIPS_REL32)
5612             value = symbol + addend;
5613           else
5614             value = addend;
5615         }
5616       value &= howto->dst_mask;
5617       break;
5618
5619     case R_MIPS_PC32:
5620       value = symbol + addend - p;
5621       value &= howto->dst_mask;
5622       break;
5623
5624     case R_MIPS16_26:
5625       /* The calculation for R_MIPS16_26 is just the same as for an
5626          R_MIPS_26.  It's only the storage of the relocated field into
5627          the output file that's different.  That's handled in
5628          mips_elf_perform_relocation.  So, we just fall through to the
5629          R_MIPS_26 case here.  */
5630     case R_MIPS_26:
5631     case R_MICROMIPS_26_S1:
5632       {
5633         unsigned int shift;
5634
5635         /* Make sure the target of JALX is word-aligned.  Bit 0 must be
5636            the correct ISA mode selector and bit 1 must be 0.  */
5637         if (*cross_mode_jump_p && (symbol & 3) != (r_type == R_MIPS_26))
5638           return bfd_reloc_outofrange;
5639
5640         /* Shift is 2, unusually, for microMIPS JALX.  */
5641         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5642
5643         if (was_local_p)
5644           value = addend | ((p + 4) & (0xfc000000 << shift));
5645         else
5646           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5647         value = (value + symbol) >> shift;
5648         if (!was_local_p && h->root.root.type != bfd_link_hash_undefweak)
5649           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5650         value &= howto->dst_mask;
5651       }
5652       break;
5653
5654     case R_MIPS_TLS_DTPREL_HI16:
5655     case R_MIPS16_TLS_DTPREL_HI16:
5656     case R_MICROMIPS_TLS_DTPREL_HI16:
5657       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5658                & howto->dst_mask);
5659       break;
5660
5661     case R_MIPS_TLS_DTPREL_LO16:
5662     case R_MIPS_TLS_DTPREL32:
5663     case R_MIPS_TLS_DTPREL64:
5664     case R_MIPS16_TLS_DTPREL_LO16:
5665     case R_MICROMIPS_TLS_DTPREL_LO16:
5666       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5667       break;
5668
5669     case R_MIPS_TLS_TPREL_HI16:
5670     case R_MIPS16_TLS_TPREL_HI16:
5671     case R_MICROMIPS_TLS_TPREL_HI16:
5672       value = (mips_elf_high (addend + symbol - tprel_base (info))
5673                & howto->dst_mask);
5674       break;
5675
5676     case R_MIPS_TLS_TPREL_LO16:
5677     case R_MIPS_TLS_TPREL32:
5678     case R_MIPS_TLS_TPREL64:
5679     case R_MIPS16_TLS_TPREL_LO16:
5680     case R_MICROMIPS_TLS_TPREL_LO16:
5681       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5682       break;
5683
5684     case R_MIPS_HI16:
5685     case R_MIPS16_HI16:
5686     case R_MICROMIPS_HI16:
5687       if (!gp_disp_p)
5688         {
5689           value = mips_elf_high (addend + symbol);
5690           value &= howto->dst_mask;
5691         }
5692       else
5693         {
5694           /* For MIPS16 ABI code we generate this sequence
5695                 0: li      $v0,%hi(_gp_disp)
5696                 4: addiupc $v1,%lo(_gp_disp)
5697                 8: sll     $v0,16
5698                12: addu    $v0,$v1
5699                14: move    $gp,$v0
5700              So the offsets of hi and lo relocs are the same, but the
5701              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5702              ADDIUPC clears the low two bits of the instruction address,
5703              so the base is ($t9 + 4) & ~3.  */
5704           if (r_type == R_MIPS16_HI16)
5705             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5706           /* The microMIPS .cpload sequence uses the same assembly
5707              instructions as the traditional psABI version, but the
5708              incoming $t9 has the low bit set.  */
5709           else if (r_type == R_MICROMIPS_HI16)
5710             value = mips_elf_high (addend + gp - p - 1);
5711           else
5712             value = mips_elf_high (addend + gp - p);
5713           overflowed_p = mips_elf_overflow_p (value, 16);
5714         }
5715       break;
5716
5717     case R_MIPS_LO16:
5718     case R_MIPS16_LO16:
5719     case R_MICROMIPS_LO16:
5720     case R_MICROMIPS_HI0_LO16:
5721       if (!gp_disp_p)
5722         value = (symbol + addend) & howto->dst_mask;
5723       else
5724         {
5725           /* See the comment for R_MIPS16_HI16 above for the reason
5726              for this conditional.  */
5727           if (r_type == R_MIPS16_LO16)
5728             value = addend + gp - (p & ~(bfd_vma) 0x3);
5729           else if (r_type == R_MICROMIPS_LO16
5730                    || r_type == R_MICROMIPS_HI0_LO16)
5731             value = addend + gp - p + 3;
5732           else
5733             value = addend + gp - p + 4;
5734           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5735              for overflow.  But, on, say, IRIX5, relocations against
5736              _gp_disp are normally generated from the .cpload
5737              pseudo-op.  It generates code that normally looks like
5738              this:
5739
5740                lui    $gp,%hi(_gp_disp)
5741                addiu  $gp,$gp,%lo(_gp_disp)
5742                addu   $gp,$gp,$t9
5743
5744              Here $t9 holds the address of the function being called,
5745              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5746              relocation can easily overflow in this situation, but the
5747              R_MIPS_HI16 relocation will handle the overflow.
5748              Therefore, we consider this a bug in the MIPS ABI, and do
5749              not check for overflow here.  */
5750         }
5751       break;
5752
5753     case R_MIPS_LITERAL:
5754     case R_MICROMIPS_LITERAL:
5755       /* Because we don't merge literal sections, we can handle this
5756          just like R_MIPS_GPREL16.  In the long run, we should merge
5757          shared literals, and then we will need to additional work
5758          here.  */
5759
5760       /* Fall through.  */
5761
5762     case R_MIPS16_GPREL:
5763       /* The R_MIPS16_GPREL performs the same calculation as
5764          R_MIPS_GPREL16, but stores the relocated bits in a different
5765          order.  We don't need to do anything special here; the
5766          differences are handled in mips_elf_perform_relocation.  */
5767     case R_MIPS_GPREL16:
5768     case R_MICROMIPS_GPREL7_S2:
5769     case R_MICROMIPS_GPREL16:
5770       /* Only sign-extend the addend if it was extracted from the
5771          instruction.  If the addend was separate, leave it alone,
5772          otherwise we may lose significant bits.  */
5773       if (howto->partial_inplace)
5774         addend = _bfd_mips_elf_sign_extend (addend, 16);
5775       value = symbol + addend - gp;
5776       /* If the symbol was local, any earlier relocatable links will
5777          have adjusted its addend with the gp offset, so compensate
5778          for that now.  Don't do it for symbols forced local in this
5779          link, though, since they won't have had the gp offset applied
5780          to them before.  */
5781       if (was_local_p)
5782         value += gp0;
5783       overflowed_p = mips_elf_overflow_p (value, 16);
5784       break;
5785
5786     case R_MIPS16_GOT16:
5787     case R_MIPS16_CALL16:
5788     case R_MIPS_GOT16:
5789     case R_MIPS_CALL16:
5790     case R_MICROMIPS_GOT16:
5791     case R_MICROMIPS_CALL16:
5792       /* VxWorks does not have separate local and global semantics for
5793          R_MIPS*_GOT16; every relocation evaluates to "G".  */
5794       if (!htab->is_vxworks && local_p)
5795         {
5796           value = mips_elf_got16_entry (abfd, input_bfd, info,
5797                                         symbol + addend, !was_local_p);
5798           if (value == MINUS_ONE)
5799             return bfd_reloc_outofrange;
5800           value
5801             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5802           overflowed_p = mips_elf_overflow_p (value, 16);
5803           break;
5804         }
5805
5806       /* Fall through.  */
5807
5808     case R_MIPS_TLS_GD:
5809     case R_MIPS_TLS_GOTTPREL:
5810     case R_MIPS_TLS_LDM:
5811     case R_MIPS_GOT_DISP:
5812     case R_MIPS16_TLS_GD:
5813     case R_MIPS16_TLS_GOTTPREL:
5814     case R_MIPS16_TLS_LDM:
5815     case R_MICROMIPS_TLS_GD:
5816     case R_MICROMIPS_TLS_GOTTPREL:
5817     case R_MICROMIPS_TLS_LDM:
5818     case R_MICROMIPS_GOT_DISP:
5819       value = g;
5820       overflowed_p = mips_elf_overflow_p (value, 16);
5821       break;
5822
5823     case R_MIPS_GPREL32:
5824       value = (addend + symbol + gp0 - gp);
5825       if (!save_addend)
5826         value &= howto->dst_mask;
5827       break;
5828
5829     case R_MIPS_PC16:
5830     case R_MIPS_GNU_REL16_S2:
5831       value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p;
5832       overflowed_p = mips_elf_overflow_p (value, 18);
5833       value >>= howto->rightshift;
5834       value &= howto->dst_mask;
5835       break;
5836
5837     case R_MICROMIPS_PC7_S1:
5838       value = symbol + _bfd_mips_elf_sign_extend (addend, 8) - p;
5839       overflowed_p = mips_elf_overflow_p (value, 8);
5840       value >>= howto->rightshift;
5841       value &= howto->dst_mask;
5842       break;
5843
5844     case R_MICROMIPS_PC10_S1:
5845       value = symbol + _bfd_mips_elf_sign_extend (addend, 11) - p;
5846       overflowed_p = mips_elf_overflow_p (value, 11);
5847       value >>= howto->rightshift;
5848       value &= howto->dst_mask;
5849       break;
5850
5851     case R_MICROMIPS_PC16_S1:
5852       value = symbol + _bfd_mips_elf_sign_extend (addend, 17) - p;
5853       overflowed_p = mips_elf_overflow_p (value, 17);
5854       value >>= howto->rightshift;
5855       value &= howto->dst_mask;
5856       break;
5857
5858     case R_MICROMIPS_PC23_S2:
5859       value = symbol + _bfd_mips_elf_sign_extend (addend, 25) - ((p | 3) ^ 3);
5860       overflowed_p = mips_elf_overflow_p (value, 25);
5861       value >>= howto->rightshift;
5862       value &= howto->dst_mask;
5863       break;
5864
5865     case R_MIPS_GOT_HI16:
5866     case R_MIPS_CALL_HI16:
5867     case R_MICROMIPS_GOT_HI16:
5868     case R_MICROMIPS_CALL_HI16:
5869       /* We're allowed to handle these two relocations identically.
5870          The dynamic linker is allowed to handle the CALL relocations
5871          differently by creating a lazy evaluation stub.  */
5872       value = g;
5873       value = mips_elf_high (value);
5874       value &= howto->dst_mask;
5875       break;
5876
5877     case R_MIPS_GOT_LO16:
5878     case R_MIPS_CALL_LO16:
5879     case R_MICROMIPS_GOT_LO16:
5880     case R_MICROMIPS_CALL_LO16:
5881       value = g & howto->dst_mask;
5882       break;
5883
5884     case R_MIPS_GOT_PAGE:
5885     case R_MICROMIPS_GOT_PAGE:
5886       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
5887       if (value == MINUS_ONE)
5888         return bfd_reloc_outofrange;
5889       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5890       overflowed_p = mips_elf_overflow_p (value, 16);
5891       break;
5892
5893     case R_MIPS_GOT_OFST:
5894     case R_MICROMIPS_GOT_OFST:
5895       if (local_p)
5896         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
5897       else
5898         value = addend;
5899       overflowed_p = mips_elf_overflow_p (value, 16);
5900       break;
5901
5902     case R_MIPS_SUB:
5903     case R_MICROMIPS_SUB:
5904       value = symbol - addend;
5905       value &= howto->dst_mask;
5906       break;
5907
5908     case R_MIPS_HIGHER:
5909     case R_MICROMIPS_HIGHER:
5910       value = mips_elf_higher (addend + symbol);
5911       value &= howto->dst_mask;
5912       break;
5913
5914     case R_MIPS_HIGHEST:
5915     case R_MICROMIPS_HIGHEST:
5916       value = mips_elf_highest (addend + symbol);
5917       value &= howto->dst_mask;
5918       break;
5919
5920     case R_MIPS_SCN_DISP:
5921     case R_MICROMIPS_SCN_DISP:
5922       value = symbol + addend - sec->output_offset;
5923       value &= howto->dst_mask;
5924       break;
5925
5926     case R_MIPS_JALR:
5927     case R_MICROMIPS_JALR:
5928       /* This relocation is only a hint.  In some cases, we optimize
5929          it into a bal instruction.  But we don't try to optimize
5930          when the symbol does not resolve locally.  */
5931       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
5932         return bfd_reloc_continue;
5933       value = symbol + addend;
5934       break;
5935
5936     case R_MIPS_PJUMP:
5937     case R_MIPS_GNU_VTINHERIT:
5938     case R_MIPS_GNU_VTENTRY:
5939       /* We don't do anything with these at present.  */
5940       return bfd_reloc_continue;
5941
5942     default:
5943       /* An unrecognized relocation type.  */
5944       return bfd_reloc_notsupported;
5945     }
5946
5947   /* Store the VALUE for our caller.  */
5948   *valuep = value;
5949   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
5950 }
5951
5952 /* Obtain the field relocated by RELOCATION.  */
5953
5954 static bfd_vma
5955 mips_elf_obtain_contents (reloc_howto_type *howto,
5956                           const Elf_Internal_Rela *relocation,
5957                           bfd *input_bfd, bfd_byte *contents)
5958 {
5959   bfd_vma x;
5960   bfd_byte *location = contents + relocation->r_offset;
5961
5962   /* Obtain the bytes.  */
5963   x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location);
5964
5965   return x;
5966 }
5967
5968 /* It has been determined that the result of the RELOCATION is the
5969    VALUE.  Use HOWTO to place VALUE into the output file at the
5970    appropriate position.  The SECTION is the section to which the
5971    relocation applies.
5972    CROSS_MODE_JUMP_P is true if the relocation field
5973    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5974
5975    Returns FALSE if anything goes wrong.  */
5976
5977 static bfd_boolean
5978 mips_elf_perform_relocation (struct bfd_link_info *info,
5979                              reloc_howto_type *howto,
5980                              const Elf_Internal_Rela *relocation,
5981                              bfd_vma value, bfd *input_bfd,
5982                              asection *input_section, bfd_byte *contents,
5983                              bfd_boolean cross_mode_jump_p)
5984 {
5985   bfd_vma x;
5986   bfd_byte *location;
5987   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5988
5989   /* Figure out where the relocation is occurring.  */
5990   location = contents + relocation->r_offset;
5991
5992   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
5993
5994   /* Obtain the current value.  */
5995   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
5996
5997   /* Clear the field we are setting.  */
5998   x &= ~howto->dst_mask;
5999
6000   /* Set the field.  */
6001   x |= (value & howto->dst_mask);
6002
6003   /* If required, turn JAL into JALX.  */
6004   if (cross_mode_jump_p && jal_reloc_p (r_type))
6005     {
6006       bfd_boolean ok;
6007       bfd_vma opcode = x >> 26;
6008       bfd_vma jalx_opcode;
6009
6010       /* Check to see if the opcode is already JAL or JALX.  */
6011       if (r_type == R_MIPS16_26)
6012         {
6013           ok = ((opcode == 0x6) || (opcode == 0x7));
6014           jalx_opcode = 0x7;
6015         }
6016       else if (r_type == R_MICROMIPS_26_S1)
6017         {
6018           ok = ((opcode == 0x3d) || (opcode == 0x3c));
6019           jalx_opcode = 0x3c;
6020         }
6021       else
6022         {
6023           ok = ((opcode == 0x3) || (opcode == 0x1d));
6024           jalx_opcode = 0x1d;
6025         }
6026
6027       /* If the opcode is not JAL or JALX, there's a problem.  We cannot
6028          convert J or JALS to JALX.  */
6029       if (!ok)
6030         {
6031           (*_bfd_error_handler)
6032             (_("%B: %A+0x%lx: Unsupported jump between ISA modes; consider recompiling with interlinking enabled."),
6033              input_bfd,
6034              input_section,
6035              (unsigned long) relocation->r_offset);
6036           bfd_set_error (bfd_error_bad_value);
6037           return FALSE;
6038         }
6039
6040       /* Make this the JALX opcode.  */
6041       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
6042     }
6043
6044   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
6045      range.  */
6046   if (!info->relocatable
6047       && !cross_mode_jump_p
6048       && ((JAL_TO_BAL_P (input_bfd)
6049            && r_type == R_MIPS_26
6050            && (x >> 26) == 0x3)         /* jal addr */
6051           || (JALR_TO_BAL_P (input_bfd)
6052               && r_type == R_MIPS_JALR
6053               && x == 0x0320f809)       /* jalr t9 */
6054           || (JR_TO_B_P (input_bfd)
6055               && r_type == R_MIPS_JALR
6056               && x == 0x03200008)))     /* jr t9 */
6057     {
6058       bfd_vma addr;
6059       bfd_vma dest;
6060       bfd_signed_vma off;
6061
6062       addr = (input_section->output_section->vma
6063               + input_section->output_offset
6064               + relocation->r_offset
6065               + 4);
6066       if (r_type == R_MIPS_26)
6067         dest = (value << 2) | ((addr >> 28) << 28);
6068       else
6069         dest = value;
6070       off = dest - addr;
6071       if (off <= 0x1ffff && off >= -0x20000)
6072         {
6073           if (x == 0x03200008)  /* jr t9 */
6074             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
6075           else
6076             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
6077         }
6078     }
6079
6080   /* Put the value into the output.  */
6081   bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location);
6082
6083   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !info->relocatable,
6084                                location);
6085
6086   return TRUE;
6087 }
6088 \f
6089 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
6090    is the original relocation, which is now being transformed into a
6091    dynamic relocation.  The ADDENDP is adjusted if necessary; the
6092    caller should store the result in place of the original addend.  */
6093
6094 static bfd_boolean
6095 mips_elf_create_dynamic_relocation (bfd *output_bfd,
6096                                     struct bfd_link_info *info,
6097                                     const Elf_Internal_Rela *rel,
6098                                     struct mips_elf_link_hash_entry *h,
6099                                     asection *sec, bfd_vma symbol,
6100                                     bfd_vma *addendp, asection *input_section)
6101 {
6102   Elf_Internal_Rela outrel[3];
6103   asection *sreloc;
6104   bfd *dynobj;
6105   int r_type;
6106   long indx;
6107   bfd_boolean defined_p;
6108   struct mips_elf_link_hash_table *htab;
6109
6110   htab = mips_elf_hash_table (info);
6111   BFD_ASSERT (htab != NULL);
6112
6113   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
6114   dynobj = elf_hash_table (info)->dynobj;
6115   sreloc = mips_elf_rel_dyn_section (info, FALSE);
6116   BFD_ASSERT (sreloc != NULL);
6117   BFD_ASSERT (sreloc->contents != NULL);
6118   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
6119               < sreloc->size);
6120
6121   outrel[0].r_offset =
6122     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
6123   if (ABI_64_P (output_bfd))
6124     {
6125       outrel[1].r_offset =
6126         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
6127       outrel[2].r_offset =
6128         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
6129     }
6130
6131   if (outrel[0].r_offset == MINUS_ONE)
6132     /* The relocation field has been deleted.  */
6133     return TRUE;
6134
6135   if (outrel[0].r_offset == MINUS_TWO)
6136     {
6137       /* The relocation field has been converted into a relative value of
6138          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
6139          the field to be fully relocated, so add in the symbol's value.  */
6140       *addendp += symbol;
6141       return TRUE;
6142     }
6143
6144   /* We must now calculate the dynamic symbol table index to use
6145      in the relocation.  */
6146   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
6147     {
6148       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
6149       indx = h->root.dynindx;
6150       if (SGI_COMPAT (output_bfd))
6151         defined_p = h->root.def_regular;
6152       else
6153         /* ??? glibc's ld.so just adds the final GOT entry to the
6154            relocation field.  It therefore treats relocs against
6155            defined symbols in the same way as relocs against
6156            undefined symbols.  */
6157         defined_p = FALSE;
6158     }
6159   else
6160     {
6161       if (sec != NULL && bfd_is_abs_section (sec))
6162         indx = 0;
6163       else if (sec == NULL || sec->owner == NULL)
6164         {
6165           bfd_set_error (bfd_error_bad_value);
6166           return FALSE;
6167         }
6168       else
6169         {
6170           indx = elf_section_data (sec->output_section)->dynindx;
6171           if (indx == 0)
6172             {
6173               asection *osec = htab->root.text_index_section;
6174               indx = elf_section_data (osec)->dynindx;
6175             }
6176           if (indx == 0)
6177             abort ();
6178         }
6179
6180       /* Instead of generating a relocation using the section
6181          symbol, we may as well make it a fully relative
6182          relocation.  We want to avoid generating relocations to
6183          local symbols because we used to generate them
6184          incorrectly, without adding the original symbol value,
6185          which is mandated by the ABI for section symbols.  In
6186          order to give dynamic loaders and applications time to
6187          phase out the incorrect use, we refrain from emitting
6188          section-relative relocations.  It's not like they're
6189          useful, after all.  This should be a bit more efficient
6190          as well.  */
6191       /* ??? Although this behavior is compatible with glibc's ld.so,
6192          the ABI says that relocations against STN_UNDEF should have
6193          a symbol value of 0.  Irix rld honors this, so relocations
6194          against STN_UNDEF have no effect.  */
6195       if (!SGI_COMPAT (output_bfd))
6196         indx = 0;
6197       defined_p = TRUE;
6198     }
6199
6200   /* If the relocation was previously an absolute relocation and
6201      this symbol will not be referred to by the relocation, we must
6202      adjust it by the value we give it in the dynamic symbol table.
6203      Otherwise leave the job up to the dynamic linker.  */
6204   if (defined_p && r_type != R_MIPS_REL32)
6205     *addendp += symbol;
6206
6207   if (htab->is_vxworks)
6208     /* VxWorks uses non-relative relocations for this.  */
6209     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
6210   else
6211     /* The relocation is always an REL32 relocation because we don't
6212        know where the shared library will wind up at load-time.  */
6213     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
6214                                    R_MIPS_REL32);
6215
6216   /* For strict adherence to the ABI specification, we should
6217      generate a R_MIPS_64 relocation record by itself before the
6218      _REL32/_64 record as well, such that the addend is read in as
6219      a 64-bit value (REL32 is a 32-bit relocation, after all).
6220      However, since none of the existing ELF64 MIPS dynamic
6221      loaders seems to care, we don't waste space with these
6222      artificial relocations.  If this turns out to not be true,
6223      mips_elf_allocate_dynamic_relocation() should be tweaked so
6224      as to make room for a pair of dynamic relocations per
6225      invocation if ABI_64_P, and here we should generate an
6226      additional relocation record with R_MIPS_64 by itself for a
6227      NULL symbol before this relocation record.  */
6228   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
6229                                  ABI_64_P (output_bfd)
6230                                  ? R_MIPS_64
6231                                  : R_MIPS_NONE);
6232   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
6233
6234   /* Adjust the output offset of the relocation to reference the
6235      correct location in the output file.  */
6236   outrel[0].r_offset += (input_section->output_section->vma
6237                          + input_section->output_offset);
6238   outrel[1].r_offset += (input_section->output_section->vma
6239                          + input_section->output_offset);
6240   outrel[2].r_offset += (input_section->output_section->vma
6241                          + input_section->output_offset);
6242
6243   /* Put the relocation back out.  We have to use the special
6244      relocation outputter in the 64-bit case since the 64-bit
6245      relocation format is non-standard.  */
6246   if (ABI_64_P (output_bfd))
6247     {
6248       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
6249         (output_bfd, &outrel[0],
6250          (sreloc->contents
6251           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
6252     }
6253   else if (htab->is_vxworks)
6254     {
6255       /* VxWorks uses RELA rather than REL dynamic relocations.  */
6256       outrel[0].r_addend = *addendp;
6257       bfd_elf32_swap_reloca_out
6258         (output_bfd, &outrel[0],
6259          (sreloc->contents
6260           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
6261     }
6262   else
6263     bfd_elf32_swap_reloc_out
6264       (output_bfd, &outrel[0],
6265        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
6266
6267   /* We've now added another relocation.  */
6268   ++sreloc->reloc_count;
6269
6270   /* Make sure the output section is writable.  The dynamic linker
6271      will be writing to it.  */
6272   elf_section_data (input_section->output_section)->this_hdr.sh_flags
6273     |= SHF_WRITE;
6274
6275   /* On IRIX5, make an entry of compact relocation info.  */
6276   if (IRIX_COMPAT (output_bfd) == ict_irix5)
6277     {
6278       asection *scpt = bfd_get_linker_section (dynobj, ".compact_rel");
6279       bfd_byte *cr;
6280
6281       if (scpt)
6282         {
6283           Elf32_crinfo cptrel;
6284
6285           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
6286           cptrel.vaddr = (rel->r_offset
6287                           + input_section->output_section->vma
6288                           + input_section->output_offset);
6289           if (r_type == R_MIPS_REL32)
6290             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
6291           else
6292             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
6293           mips_elf_set_cr_dist2to (cptrel, 0);
6294           cptrel.konst = *addendp;
6295
6296           cr = (scpt->contents
6297                 + sizeof (Elf32_External_compact_rel));
6298           mips_elf_set_cr_relvaddr (cptrel, 0);
6299           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
6300                                      ((Elf32_External_crinfo *) cr
6301                                       + scpt->reloc_count));
6302           ++scpt->reloc_count;
6303         }
6304     }
6305
6306   /* If we've written this relocation for a readonly section,
6307      we need to set DF_TEXTREL again, so that we do not delete the
6308      DT_TEXTREL tag.  */
6309   if (MIPS_ELF_READONLY_SECTION (input_section))
6310     info->flags |= DF_TEXTREL;
6311
6312   return TRUE;
6313 }
6314 \f
6315 /* Return the MACH for a MIPS e_flags value.  */
6316
6317 unsigned long
6318 _bfd_elf_mips_mach (flagword flags)
6319 {
6320   switch (flags & EF_MIPS_MACH)
6321     {
6322     case E_MIPS_MACH_3900:
6323       return bfd_mach_mips3900;
6324
6325     case E_MIPS_MACH_4010:
6326       return bfd_mach_mips4010;
6327
6328     case E_MIPS_MACH_4100:
6329       return bfd_mach_mips4100;
6330
6331     case E_MIPS_MACH_4111:
6332       return bfd_mach_mips4111;
6333
6334     case E_MIPS_MACH_4120:
6335       return bfd_mach_mips4120;
6336
6337     case E_MIPS_MACH_4650:
6338       return bfd_mach_mips4650;
6339
6340     case E_MIPS_MACH_5400:
6341       return bfd_mach_mips5400;
6342
6343     case E_MIPS_MACH_5500:
6344       return bfd_mach_mips5500;
6345
6346     case E_MIPS_MACH_5900:
6347       return bfd_mach_mips5900;
6348
6349     case E_MIPS_MACH_9000:
6350       return bfd_mach_mips9000;
6351
6352     case E_MIPS_MACH_SB1:
6353       return bfd_mach_mips_sb1;
6354
6355     case E_MIPS_MACH_LS2E:
6356       return bfd_mach_mips_loongson_2e;
6357
6358     case E_MIPS_MACH_LS2F:
6359       return bfd_mach_mips_loongson_2f;
6360
6361     case E_MIPS_MACH_LS3A:
6362       return bfd_mach_mips_loongson_3a;
6363
6364     case E_MIPS_MACH_OCTEON2:
6365       return bfd_mach_mips_octeon2;
6366
6367     case E_MIPS_MACH_OCTEON:
6368       return bfd_mach_mips_octeon;
6369
6370     case E_MIPS_MACH_XLR:
6371       return bfd_mach_mips_xlr;
6372
6373     default:
6374       switch (flags & EF_MIPS_ARCH)
6375         {
6376         default:
6377         case E_MIPS_ARCH_1:
6378           return bfd_mach_mips3000;
6379
6380         case E_MIPS_ARCH_2:
6381           return bfd_mach_mips6000;
6382
6383         case E_MIPS_ARCH_3:
6384           return bfd_mach_mips4000;
6385
6386         case E_MIPS_ARCH_4:
6387           return bfd_mach_mips8000;
6388
6389         case E_MIPS_ARCH_5:
6390           return bfd_mach_mips5;
6391
6392         case E_MIPS_ARCH_32:
6393           return bfd_mach_mipsisa32;
6394
6395         case E_MIPS_ARCH_64:
6396           return bfd_mach_mipsisa64;
6397
6398         case E_MIPS_ARCH_32R2:
6399           return bfd_mach_mipsisa32r2;
6400
6401         case E_MIPS_ARCH_64R2:
6402           return bfd_mach_mipsisa64r2;
6403         }
6404     }
6405
6406   return 0;
6407 }
6408
6409 /* Return printable name for ABI.  */
6410
6411 static INLINE char *
6412 elf_mips_abi_name (bfd *abfd)
6413 {
6414   flagword flags;
6415
6416   flags = elf_elfheader (abfd)->e_flags;
6417   switch (flags & EF_MIPS_ABI)
6418     {
6419     case 0:
6420       if (ABI_N32_P (abfd))
6421         return "N32";
6422       else if (ABI_64_P (abfd))
6423         return "64";
6424       else
6425         return "none";
6426     case E_MIPS_ABI_O32:
6427       return "O32";
6428     case E_MIPS_ABI_O64:
6429       return "O64";
6430     case E_MIPS_ABI_EABI32:
6431       return "EABI32";
6432     case E_MIPS_ABI_EABI64:
6433       return "EABI64";
6434     default:
6435       return "unknown abi";
6436     }
6437 }
6438 \f
6439 /* MIPS ELF uses two common sections.  One is the usual one, and the
6440    other is for small objects.  All the small objects are kept
6441    together, and then referenced via the gp pointer, which yields
6442    faster assembler code.  This is what we use for the small common
6443    section.  This approach is copied from ecoff.c.  */
6444 static asection mips_elf_scom_section;
6445 static asymbol mips_elf_scom_symbol;
6446 static asymbol *mips_elf_scom_symbol_ptr;
6447
6448 /* MIPS ELF also uses an acommon section, which represents an
6449    allocated common symbol which may be overridden by a
6450    definition in a shared library.  */
6451 static asection mips_elf_acom_section;
6452 static asymbol mips_elf_acom_symbol;
6453 static asymbol *mips_elf_acom_symbol_ptr;
6454
6455 /* This is used for both the 32-bit and the 64-bit ABI.  */
6456
6457 void
6458 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6459 {
6460   elf_symbol_type *elfsym;
6461
6462   /* Handle the special MIPS section numbers that a symbol may use.  */
6463   elfsym = (elf_symbol_type *) asym;
6464   switch (elfsym->internal_elf_sym.st_shndx)
6465     {
6466     case SHN_MIPS_ACOMMON:
6467       /* This section is used in a dynamically linked executable file.
6468          It is an allocated common section.  The dynamic linker can
6469          either resolve these symbols to something in a shared
6470          library, or it can just leave them here.  For our purposes,
6471          we can consider these symbols to be in a new section.  */
6472       if (mips_elf_acom_section.name == NULL)
6473         {
6474           /* Initialize the acommon section.  */
6475           mips_elf_acom_section.name = ".acommon";
6476           mips_elf_acom_section.flags = SEC_ALLOC;
6477           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6478           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6479           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6480           mips_elf_acom_symbol.name = ".acommon";
6481           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6482           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6483           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6484         }
6485       asym->section = &mips_elf_acom_section;
6486       break;
6487
6488     case SHN_COMMON:
6489       /* Common symbols less than the GP size are automatically
6490          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6491       if (asym->value > elf_gp_size (abfd)
6492           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6493           || IRIX_COMPAT (abfd) == ict_irix6)
6494         break;
6495       /* Fall through.  */
6496     case SHN_MIPS_SCOMMON:
6497       if (mips_elf_scom_section.name == NULL)
6498         {
6499           /* Initialize the small common section.  */
6500           mips_elf_scom_section.name = ".scommon";
6501           mips_elf_scom_section.flags = SEC_IS_COMMON;
6502           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6503           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6504           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6505           mips_elf_scom_symbol.name = ".scommon";
6506           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6507           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6508           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6509         }
6510       asym->section = &mips_elf_scom_section;
6511       asym->value = elfsym->internal_elf_sym.st_size;
6512       break;
6513
6514     case SHN_MIPS_SUNDEFINED:
6515       asym->section = bfd_und_section_ptr;
6516       break;
6517
6518     case SHN_MIPS_TEXT:
6519       {
6520         asection *section = bfd_get_section_by_name (abfd, ".text");
6521
6522         if (section != NULL)
6523           {
6524             asym->section = section;
6525             /* MIPS_TEXT is a bit special, the address is not an offset
6526                to the base of the .text section.  So substract the section
6527                base address to make it an offset.  */
6528             asym->value -= section->vma;
6529           }
6530       }
6531       break;
6532
6533     case SHN_MIPS_DATA:
6534       {
6535         asection *section = bfd_get_section_by_name (abfd, ".data");
6536
6537         if (section != NULL)
6538           {
6539             asym->section = section;
6540             /* MIPS_DATA is a bit special, the address is not an offset
6541                to the base of the .data section.  So substract the section
6542                base address to make it an offset.  */
6543             asym->value -= section->vma;
6544           }
6545       }
6546       break;
6547     }
6548
6549   /* If this is an odd-valued function symbol, assume it's a MIPS16
6550      or microMIPS one.  */
6551   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6552       && (asym->value & 1) != 0)
6553     {
6554       asym->value--;
6555       if (MICROMIPS_P (abfd))
6556         elfsym->internal_elf_sym.st_other
6557           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6558       else
6559         elfsym->internal_elf_sym.st_other
6560           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6561     }
6562 }
6563 \f
6564 /* Implement elf_backend_eh_frame_address_size.  This differs from
6565    the default in the way it handles EABI64.
6566
6567    EABI64 was originally specified as an LP64 ABI, and that is what
6568    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6569    historically accepted the combination of -mabi=eabi and -mlong32,
6570    and this ILP32 variation has become semi-official over time.
6571    Both forms use elf32 and have pointer-sized FDE addresses.
6572
6573    If an EABI object was generated by GCC 4.0 or above, it will have
6574    an empty .gcc_compiled_longXX section, where XX is the size of longs
6575    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6576    have no special marking to distinguish them from LP64 objects.
6577
6578    We don't want users of the official LP64 ABI to be punished for the
6579    existence of the ILP32 variant, but at the same time, we don't want
6580    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6581    We therefore take the following approach:
6582
6583       - If ABFD contains a .gcc_compiled_longXX section, use it to
6584         determine the pointer size.
6585
6586       - Otherwise check the type of the first relocation.  Assume that
6587         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
6588
6589       - Otherwise punt.
6590
6591    The second check is enough to detect LP64 objects generated by pre-4.0
6592    compilers because, in the kind of output generated by those compilers,
6593    the first relocation will be associated with either a CIE personality
6594    routine or an FDE start address.  Furthermore, the compilers never
6595    used a special (non-pointer) encoding for this ABI.
6596
6597    Checking the relocation type should also be safe because there is no
6598    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
6599    did so.  */
6600
6601 unsigned int
6602 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
6603 {
6604   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
6605     return 8;
6606   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
6607     {
6608       bfd_boolean long32_p, long64_p;
6609
6610       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
6611       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
6612       if (long32_p && long64_p)
6613         return 0;
6614       if (long32_p)
6615         return 4;
6616       if (long64_p)
6617         return 8;
6618
6619       if (sec->reloc_count > 0
6620           && elf_section_data (sec)->relocs != NULL
6621           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
6622               == R_MIPS_64))
6623         return 8;
6624
6625       return 0;
6626     }
6627   return 4;
6628 }
6629 \f
6630 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
6631    relocations against two unnamed section symbols to resolve to the
6632    same address.  For example, if we have code like:
6633
6634         lw      $4,%got_disp(.data)($gp)
6635         lw      $25,%got_disp(.text)($gp)
6636         jalr    $25
6637
6638    then the linker will resolve both relocations to .data and the program
6639    will jump there rather than to .text.
6640
6641    We can work around this problem by giving names to local section symbols.
6642    This is also what the MIPSpro tools do.  */
6643
6644 bfd_boolean
6645 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
6646 {
6647   return SGI_COMPAT (abfd);
6648 }
6649 \f
6650 /* Work over a section just before writing it out.  This routine is
6651    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
6652    sections that need the SHF_MIPS_GPREL flag by name; there has to be
6653    a better way.  */
6654
6655 bfd_boolean
6656 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
6657 {
6658   if (hdr->sh_type == SHT_MIPS_REGINFO
6659       && hdr->sh_size > 0)
6660     {
6661       bfd_byte buf[4];
6662
6663       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
6664       BFD_ASSERT (hdr->contents == NULL);
6665
6666       if (bfd_seek (abfd,
6667                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
6668                     SEEK_SET) != 0)
6669         return FALSE;
6670       H_PUT_32 (abfd, elf_gp (abfd), buf);
6671       if (bfd_bwrite (buf, 4, abfd) != 4)
6672         return FALSE;
6673     }
6674
6675   if (hdr->sh_type == SHT_MIPS_OPTIONS
6676       && hdr->bfd_section != NULL
6677       && mips_elf_section_data (hdr->bfd_section) != NULL
6678       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
6679     {
6680       bfd_byte *contents, *l, *lend;
6681
6682       /* We stored the section contents in the tdata field in the
6683          set_section_contents routine.  We save the section contents
6684          so that we don't have to read them again.
6685          At this point we know that elf_gp is set, so we can look
6686          through the section contents to see if there is an
6687          ODK_REGINFO structure.  */
6688
6689       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
6690       l = contents;
6691       lend = contents + hdr->sh_size;
6692       while (l + sizeof (Elf_External_Options) <= lend)
6693         {
6694           Elf_Internal_Options intopt;
6695
6696           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6697                                         &intopt);
6698           if (intopt.size < sizeof (Elf_External_Options))
6699             {
6700               (*_bfd_error_handler)
6701                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6702                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6703               break;
6704             }
6705           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6706             {
6707               bfd_byte buf[8];
6708
6709               if (bfd_seek (abfd,
6710                             (hdr->sh_offset
6711                              + (l - contents)
6712                              + sizeof (Elf_External_Options)
6713                              + (sizeof (Elf64_External_RegInfo) - 8)),
6714                              SEEK_SET) != 0)
6715                 return FALSE;
6716               H_PUT_64 (abfd, elf_gp (abfd), buf);
6717               if (bfd_bwrite (buf, 8, abfd) != 8)
6718                 return FALSE;
6719             }
6720           else if (intopt.kind == ODK_REGINFO)
6721             {
6722               bfd_byte buf[4];
6723
6724               if (bfd_seek (abfd,
6725                             (hdr->sh_offset
6726                              + (l - contents)
6727                              + sizeof (Elf_External_Options)
6728                              + (sizeof (Elf32_External_RegInfo) - 4)),
6729                             SEEK_SET) != 0)
6730                 return FALSE;
6731               H_PUT_32 (abfd, elf_gp (abfd), buf);
6732               if (bfd_bwrite (buf, 4, abfd) != 4)
6733                 return FALSE;
6734             }
6735           l += intopt.size;
6736         }
6737     }
6738
6739   if (hdr->bfd_section != NULL)
6740     {
6741       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
6742
6743       /* .sbss is not handled specially here because the GNU/Linux
6744          prelinker can convert .sbss from NOBITS to PROGBITS and
6745          changing it back to NOBITS breaks the binary.  The entry in
6746          _bfd_mips_elf_special_sections will ensure the correct flags
6747          are set on .sbss if BFD creates it without reading it from an
6748          input file, and without special handling here the flags set
6749          on it in an input file will be followed.  */
6750       if (strcmp (name, ".sdata") == 0
6751           || strcmp (name, ".lit8") == 0
6752           || strcmp (name, ".lit4") == 0)
6753         {
6754           hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
6755           hdr->sh_type = SHT_PROGBITS;
6756         }
6757       else if (strcmp (name, ".srdata") == 0)
6758         {
6759           hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
6760           hdr->sh_type = SHT_PROGBITS;
6761         }
6762       else if (strcmp (name, ".compact_rel") == 0)
6763         {
6764           hdr->sh_flags = 0;
6765           hdr->sh_type = SHT_PROGBITS;
6766         }
6767       else if (strcmp (name, ".rtproc") == 0)
6768         {
6769           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
6770             {
6771               unsigned int adjust;
6772
6773               adjust = hdr->sh_size % hdr->sh_addralign;
6774               if (adjust != 0)
6775                 hdr->sh_size += hdr->sh_addralign - adjust;
6776             }
6777         }
6778     }
6779
6780   return TRUE;
6781 }
6782
6783 /* Handle a MIPS specific section when reading an object file.  This
6784    is called when elfcode.h finds a section with an unknown type.
6785    This routine supports both the 32-bit and 64-bit ELF ABI.
6786
6787    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
6788    how to.  */
6789
6790 bfd_boolean
6791 _bfd_mips_elf_section_from_shdr (bfd *abfd,
6792                                  Elf_Internal_Shdr *hdr,
6793                                  const char *name,
6794                                  int shindex)
6795 {
6796   flagword flags = 0;
6797
6798   /* There ought to be a place to keep ELF backend specific flags, but
6799      at the moment there isn't one.  We just keep track of the
6800      sections by their name, instead.  Fortunately, the ABI gives
6801      suggested names for all the MIPS specific sections, so we will
6802      probably get away with this.  */
6803   switch (hdr->sh_type)
6804     {
6805     case SHT_MIPS_LIBLIST:
6806       if (strcmp (name, ".liblist") != 0)
6807         return FALSE;
6808       break;
6809     case SHT_MIPS_MSYM:
6810       if (strcmp (name, ".msym") != 0)
6811         return FALSE;
6812       break;
6813     case SHT_MIPS_CONFLICT:
6814       if (strcmp (name, ".conflict") != 0)
6815         return FALSE;
6816       break;
6817     case SHT_MIPS_GPTAB:
6818       if (! CONST_STRNEQ (name, ".gptab."))
6819         return FALSE;
6820       break;
6821     case SHT_MIPS_UCODE:
6822       if (strcmp (name, ".ucode") != 0)
6823         return FALSE;
6824       break;
6825     case SHT_MIPS_DEBUG:
6826       if (strcmp (name, ".mdebug") != 0)
6827         return FALSE;
6828       flags = SEC_DEBUGGING;
6829       break;
6830     case SHT_MIPS_REGINFO:
6831       if (strcmp (name, ".reginfo") != 0
6832           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
6833         return FALSE;
6834       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6835       break;
6836     case SHT_MIPS_IFACE:
6837       if (strcmp (name, ".MIPS.interfaces") != 0)
6838         return FALSE;
6839       break;
6840     case SHT_MIPS_CONTENT:
6841       if (! CONST_STRNEQ (name, ".MIPS.content"))
6842         return FALSE;
6843       break;
6844     case SHT_MIPS_OPTIONS:
6845       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6846         return FALSE;
6847       break;
6848     case SHT_MIPS_DWARF:
6849       if (! CONST_STRNEQ (name, ".debug_")
6850           && ! CONST_STRNEQ (name, ".zdebug_"))
6851         return FALSE;
6852       break;
6853     case SHT_MIPS_SYMBOL_LIB:
6854       if (strcmp (name, ".MIPS.symlib") != 0)
6855         return FALSE;
6856       break;
6857     case SHT_MIPS_EVENTS:
6858       if (! CONST_STRNEQ (name, ".MIPS.events")
6859           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
6860         return FALSE;
6861       break;
6862     default:
6863       break;
6864     }
6865
6866   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
6867     return FALSE;
6868
6869   if (flags)
6870     {
6871       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
6872                                    (bfd_get_section_flags (abfd,
6873                                                            hdr->bfd_section)
6874                                     | flags)))
6875         return FALSE;
6876     }
6877
6878   /* FIXME: We should record sh_info for a .gptab section.  */
6879
6880   /* For a .reginfo section, set the gp value in the tdata information
6881      from the contents of this section.  We need the gp value while
6882      processing relocs, so we just get it now.  The .reginfo section
6883      is not used in the 64-bit MIPS ELF ABI.  */
6884   if (hdr->sh_type == SHT_MIPS_REGINFO)
6885     {
6886       Elf32_External_RegInfo ext;
6887       Elf32_RegInfo s;
6888
6889       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
6890                                       &ext, 0, sizeof ext))
6891         return FALSE;
6892       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
6893       elf_gp (abfd) = s.ri_gp_value;
6894     }
6895
6896   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
6897      set the gp value based on what we find.  We may see both
6898      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
6899      they should agree.  */
6900   if (hdr->sh_type == SHT_MIPS_OPTIONS)
6901     {
6902       bfd_byte *contents, *l, *lend;
6903
6904       contents = bfd_malloc (hdr->sh_size);
6905       if (contents == NULL)
6906         return FALSE;
6907       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
6908                                       0, hdr->sh_size))
6909         {
6910           free (contents);
6911           return FALSE;
6912         }
6913       l = contents;
6914       lend = contents + hdr->sh_size;
6915       while (l + sizeof (Elf_External_Options) <= lend)
6916         {
6917           Elf_Internal_Options intopt;
6918
6919           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6920                                         &intopt);
6921           if (intopt.size < sizeof (Elf_External_Options))
6922             {
6923               (*_bfd_error_handler)
6924                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6925                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6926               break;
6927             }
6928           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6929             {
6930               Elf64_Internal_RegInfo intreg;
6931
6932               bfd_mips_elf64_swap_reginfo_in
6933                 (abfd,
6934                  ((Elf64_External_RegInfo *)
6935                   (l + sizeof (Elf_External_Options))),
6936                  &intreg);
6937               elf_gp (abfd) = intreg.ri_gp_value;
6938             }
6939           else if (intopt.kind == ODK_REGINFO)
6940             {
6941               Elf32_RegInfo intreg;
6942
6943               bfd_mips_elf32_swap_reginfo_in
6944                 (abfd,
6945                  ((Elf32_External_RegInfo *)
6946                   (l + sizeof (Elf_External_Options))),
6947                  &intreg);
6948               elf_gp (abfd) = intreg.ri_gp_value;
6949             }
6950           l += intopt.size;
6951         }
6952       free (contents);
6953     }
6954
6955   return TRUE;
6956 }
6957
6958 /* Set the correct type for a MIPS ELF section.  We do this by the
6959    section name, which is a hack, but ought to work.  This routine is
6960    used by both the 32-bit and the 64-bit ABI.  */
6961
6962 bfd_boolean
6963 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
6964 {
6965   const char *name = bfd_get_section_name (abfd, sec);
6966
6967   if (strcmp (name, ".liblist") == 0)
6968     {
6969       hdr->sh_type = SHT_MIPS_LIBLIST;
6970       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
6971       /* The sh_link field is set in final_write_processing.  */
6972     }
6973   else if (strcmp (name, ".conflict") == 0)
6974     hdr->sh_type = SHT_MIPS_CONFLICT;
6975   else if (CONST_STRNEQ (name, ".gptab."))
6976     {
6977       hdr->sh_type = SHT_MIPS_GPTAB;
6978       hdr->sh_entsize = sizeof (Elf32_External_gptab);
6979       /* The sh_info field is set in final_write_processing.  */
6980     }
6981   else if (strcmp (name, ".ucode") == 0)
6982     hdr->sh_type = SHT_MIPS_UCODE;
6983   else if (strcmp (name, ".mdebug") == 0)
6984     {
6985       hdr->sh_type = SHT_MIPS_DEBUG;
6986       /* In a shared object on IRIX 5.3, the .mdebug section has an
6987          entsize of 0.  FIXME: Does this matter?  */
6988       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
6989         hdr->sh_entsize = 0;
6990       else
6991         hdr->sh_entsize = 1;
6992     }
6993   else if (strcmp (name, ".reginfo") == 0)
6994     {
6995       hdr->sh_type = SHT_MIPS_REGINFO;
6996       /* In a shared object on IRIX 5.3, the .reginfo section has an
6997          entsize of 0x18.  FIXME: Does this matter?  */
6998       if (SGI_COMPAT (abfd))
6999         {
7000           if ((abfd->flags & DYNAMIC) != 0)
7001             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
7002           else
7003             hdr->sh_entsize = 1;
7004         }
7005       else
7006         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
7007     }
7008   else if (SGI_COMPAT (abfd)
7009            && (strcmp (name, ".hash") == 0
7010                || strcmp (name, ".dynamic") == 0
7011                || strcmp (name, ".dynstr") == 0))
7012     {
7013       if (SGI_COMPAT (abfd))
7014         hdr->sh_entsize = 0;
7015 #if 0
7016       /* This isn't how the IRIX6 linker behaves.  */
7017       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
7018 #endif
7019     }
7020   else if (strcmp (name, ".got") == 0
7021            || strcmp (name, ".srdata") == 0
7022            || strcmp (name, ".sdata") == 0
7023            || strcmp (name, ".sbss") == 0
7024            || strcmp (name, ".lit4") == 0
7025            || strcmp (name, ".lit8") == 0)
7026     hdr->sh_flags |= SHF_MIPS_GPREL;
7027   else if (strcmp (name, ".MIPS.interfaces") == 0)
7028     {
7029       hdr->sh_type = SHT_MIPS_IFACE;
7030       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7031     }
7032   else if (CONST_STRNEQ (name, ".MIPS.content"))
7033     {
7034       hdr->sh_type = SHT_MIPS_CONTENT;
7035       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7036       /* The sh_info field is set in final_write_processing.  */
7037     }
7038   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
7039     {
7040       hdr->sh_type = SHT_MIPS_OPTIONS;
7041       hdr->sh_entsize = 1;
7042       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7043     }
7044   else if (CONST_STRNEQ (name, ".debug_")
7045            || CONST_STRNEQ (name, ".zdebug_"))
7046     {
7047       hdr->sh_type = SHT_MIPS_DWARF;
7048
7049       /* Irix facilities such as libexc expect a single .debug_frame
7050          per executable, the system ones have NOSTRIP set and the linker
7051          doesn't merge sections with different flags so ...  */
7052       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
7053         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7054     }
7055   else if (strcmp (name, ".MIPS.symlib") == 0)
7056     {
7057       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
7058       /* The sh_link and sh_info fields are set in
7059          final_write_processing.  */
7060     }
7061   else if (CONST_STRNEQ (name, ".MIPS.events")
7062            || CONST_STRNEQ (name, ".MIPS.post_rel"))
7063     {
7064       hdr->sh_type = SHT_MIPS_EVENTS;
7065       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7066       /* The sh_link field is set in final_write_processing.  */
7067     }
7068   else if (strcmp (name, ".msym") == 0)
7069     {
7070       hdr->sh_type = SHT_MIPS_MSYM;
7071       hdr->sh_flags |= SHF_ALLOC;
7072       hdr->sh_entsize = 8;
7073     }
7074
7075   /* The generic elf_fake_sections will set up REL_HDR using the default
7076    kind of relocations.  We used to set up a second header for the
7077    non-default kind of relocations here, but only NewABI would use
7078    these, and the IRIX ld doesn't like resulting empty RELA sections.
7079    Thus we create those header only on demand now.  */
7080
7081   return TRUE;
7082 }
7083
7084 /* Given a BFD section, try to locate the corresponding ELF section
7085    index.  This is used by both the 32-bit and the 64-bit ABI.
7086    Actually, it's not clear to me that the 64-bit ABI supports these,
7087    but for non-PIC objects we will certainly want support for at least
7088    the .scommon section.  */
7089
7090 bfd_boolean
7091 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
7092                                         asection *sec, int *retval)
7093 {
7094   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
7095     {
7096       *retval = SHN_MIPS_SCOMMON;
7097       return TRUE;
7098     }
7099   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
7100     {
7101       *retval = SHN_MIPS_ACOMMON;
7102       return TRUE;
7103     }
7104   return FALSE;
7105 }
7106 \f
7107 /* Hook called by the linker routine which adds symbols from an object
7108    file.  We must handle the special MIPS section numbers here.  */
7109
7110 bfd_boolean
7111 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
7112                                Elf_Internal_Sym *sym, const char **namep,
7113                                flagword *flagsp ATTRIBUTE_UNUSED,
7114                                asection **secp, bfd_vma *valp)
7115 {
7116   if (SGI_COMPAT (abfd)
7117       && (abfd->flags & DYNAMIC) != 0
7118       && strcmp (*namep, "_rld_new_interface") == 0)
7119     {
7120       /* Skip IRIX5 rld entry name.  */
7121       *namep = NULL;
7122       return TRUE;
7123     }
7124
7125   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
7126      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
7127      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
7128      a magic symbol resolved by the linker, we ignore this bogus definition
7129      of _gp_disp.  New ABI objects do not suffer from this problem so this
7130      is not done for them. */
7131   if (!NEWABI_P(abfd)
7132       && (sym->st_shndx == SHN_ABS)
7133       && (strcmp (*namep, "_gp_disp") == 0))
7134     {
7135       *namep = NULL;
7136       return TRUE;
7137     }
7138
7139   switch (sym->st_shndx)
7140     {
7141     case SHN_COMMON:
7142       /* Common symbols less than the GP size are automatically
7143          treated as SHN_MIPS_SCOMMON symbols.  */
7144       if (sym->st_size > elf_gp_size (abfd)
7145           || ELF_ST_TYPE (sym->st_info) == STT_TLS
7146           || IRIX_COMPAT (abfd) == ict_irix6)
7147         break;
7148       /* Fall through.  */
7149     case SHN_MIPS_SCOMMON:
7150       *secp = bfd_make_section_old_way (abfd, ".scommon");
7151       (*secp)->flags |= SEC_IS_COMMON;
7152       *valp = sym->st_size;
7153       break;
7154
7155     case SHN_MIPS_TEXT:
7156       /* This section is used in a shared object.  */
7157       if (mips_elf_tdata (abfd)->elf_text_section == NULL)
7158         {
7159           asymbol *elf_text_symbol;
7160           asection *elf_text_section;
7161           bfd_size_type amt = sizeof (asection);
7162
7163           elf_text_section = bfd_zalloc (abfd, amt);
7164           if (elf_text_section == NULL)
7165             return FALSE;
7166
7167           amt = sizeof (asymbol);
7168           elf_text_symbol = bfd_zalloc (abfd, amt);
7169           if (elf_text_symbol == NULL)
7170             return FALSE;
7171
7172           /* Initialize the section.  */
7173
7174           mips_elf_tdata (abfd)->elf_text_section = elf_text_section;
7175           mips_elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
7176
7177           elf_text_section->symbol = elf_text_symbol;
7178           elf_text_section->symbol_ptr_ptr = &mips_elf_tdata (abfd)->elf_text_symbol;
7179
7180           elf_text_section->name = ".text";
7181           elf_text_section->flags = SEC_NO_FLAGS;
7182           elf_text_section->output_section = NULL;
7183           elf_text_section->owner = abfd;
7184           elf_text_symbol->name = ".text";
7185           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7186           elf_text_symbol->section = elf_text_section;
7187         }
7188       /* This code used to do *secp = bfd_und_section_ptr if
7189          info->shared.  I don't know why, and that doesn't make sense,
7190          so I took it out.  */
7191       *secp = mips_elf_tdata (abfd)->elf_text_section;
7192       break;
7193
7194     case SHN_MIPS_ACOMMON:
7195       /* Fall through. XXX Can we treat this as allocated data?  */
7196     case SHN_MIPS_DATA:
7197       /* This section is used in a shared object.  */
7198       if (mips_elf_tdata (abfd)->elf_data_section == NULL)
7199         {
7200           asymbol *elf_data_symbol;
7201           asection *elf_data_section;
7202           bfd_size_type amt = sizeof (asection);
7203
7204           elf_data_section = bfd_zalloc (abfd, amt);
7205           if (elf_data_section == NULL)
7206             return FALSE;
7207
7208           amt = sizeof (asymbol);
7209           elf_data_symbol = bfd_zalloc (abfd, amt);
7210           if (elf_data_symbol == NULL)
7211             return FALSE;
7212
7213           /* Initialize the section.  */
7214
7215           mips_elf_tdata (abfd)->elf_data_section = elf_data_section;
7216           mips_elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
7217
7218           elf_data_section->symbol = elf_data_symbol;
7219           elf_data_section->symbol_ptr_ptr = &mips_elf_tdata (abfd)->elf_data_symbol;
7220
7221           elf_data_section->name = ".data";
7222           elf_data_section->flags = SEC_NO_FLAGS;
7223           elf_data_section->output_section = NULL;
7224           elf_data_section->owner = abfd;
7225           elf_data_symbol->name = ".data";
7226           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7227           elf_data_symbol->section = elf_data_section;
7228         }
7229       /* This code used to do *secp = bfd_und_section_ptr if
7230          info->shared.  I don't know why, and that doesn't make sense,
7231          so I took it out.  */
7232       *secp = mips_elf_tdata (abfd)->elf_data_section;
7233       break;
7234
7235     case SHN_MIPS_SUNDEFINED:
7236       *secp = bfd_und_section_ptr;
7237       break;
7238     }
7239
7240   if (SGI_COMPAT (abfd)
7241       && ! info->shared
7242       && info->output_bfd->xvec == abfd->xvec
7243       && strcmp (*namep, "__rld_obj_head") == 0)
7244     {
7245       struct elf_link_hash_entry *h;
7246       struct bfd_link_hash_entry *bh;
7247
7248       /* Mark __rld_obj_head as dynamic.  */
7249       bh = NULL;
7250       if (! (_bfd_generic_link_add_one_symbol
7251              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
7252               get_elf_backend_data (abfd)->collect, &bh)))
7253         return FALSE;
7254
7255       h = (struct elf_link_hash_entry *) bh;
7256       h->non_elf = 0;
7257       h->def_regular = 1;
7258       h->type = STT_OBJECT;
7259
7260       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7261         return FALSE;
7262
7263       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
7264       mips_elf_hash_table (info)->rld_symbol = h;
7265     }
7266
7267   /* If this is a mips16 text symbol, add 1 to the value to make it
7268      odd.  This will cause something like .word SYM to come up with
7269      the right value when it is loaded into the PC.  */
7270   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7271     ++*valp;
7272
7273   return TRUE;
7274 }
7275
7276 /* This hook function is called before the linker writes out a global
7277    symbol.  We mark symbols as small common if appropriate.  This is
7278    also where we undo the increment of the value for a mips16 symbol.  */
7279
7280 int
7281 _bfd_mips_elf_link_output_symbol_hook
7282   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
7283    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
7284    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
7285 {
7286   /* If we see a common symbol, which implies a relocatable link, then
7287      if a symbol was small common in an input file, mark it as small
7288      common in the output file.  */
7289   if (sym->st_shndx == SHN_COMMON
7290       && strcmp (input_sec->name, ".scommon") == 0)
7291     sym->st_shndx = SHN_MIPS_SCOMMON;
7292
7293   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7294     sym->st_value &= ~1;
7295
7296   return 1;
7297 }
7298 \f
7299 /* Functions for the dynamic linker.  */
7300
7301 /* Create dynamic sections when linking against a dynamic object.  */
7302
7303 bfd_boolean
7304 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
7305 {
7306   struct elf_link_hash_entry *h;
7307   struct bfd_link_hash_entry *bh;
7308   flagword flags;
7309   register asection *s;
7310   const char * const *namep;
7311   struct mips_elf_link_hash_table *htab;
7312
7313   htab = mips_elf_hash_table (info);
7314   BFD_ASSERT (htab != NULL);
7315
7316   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
7317            | SEC_LINKER_CREATED | SEC_READONLY);
7318
7319   /* The psABI requires a read-only .dynamic section, but the VxWorks
7320      EABI doesn't.  */
7321   if (!htab->is_vxworks)
7322     {
7323       s = bfd_get_linker_section (abfd, ".dynamic");
7324       if (s != NULL)
7325         {
7326           if (! bfd_set_section_flags (abfd, s, flags))
7327             return FALSE;
7328         }
7329     }
7330
7331   /* We need to create .got section.  */
7332   if (!mips_elf_create_got_section (abfd, info))
7333     return FALSE;
7334
7335   if (! mips_elf_rel_dyn_section (info, TRUE))
7336     return FALSE;
7337
7338   /* Create .stub section.  */
7339   s = bfd_make_section_anyway_with_flags (abfd,
7340                                           MIPS_ELF_STUB_SECTION_NAME (abfd),
7341                                           flags | SEC_CODE);
7342   if (s == NULL
7343       || ! bfd_set_section_alignment (abfd, s,
7344                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7345     return FALSE;
7346   htab->sstubs = s;
7347
7348   if (!mips_elf_hash_table (info)->use_rld_obj_head
7349       && !info->shared
7350       && bfd_get_linker_section (abfd, ".rld_map") == NULL)
7351     {
7352       s = bfd_make_section_anyway_with_flags (abfd, ".rld_map",
7353                                               flags &~ (flagword) SEC_READONLY);
7354       if (s == NULL
7355           || ! bfd_set_section_alignment (abfd, s,
7356                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7357         return FALSE;
7358     }
7359
7360   /* On IRIX5, we adjust add some additional symbols and change the
7361      alignments of several sections.  There is no ABI documentation
7362      indicating that this is necessary on IRIX6, nor any evidence that
7363      the linker takes such action.  */
7364   if (IRIX_COMPAT (abfd) == ict_irix5)
7365     {
7366       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7367         {
7368           bh = NULL;
7369           if (! (_bfd_generic_link_add_one_symbol
7370                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7371                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7372             return FALSE;
7373
7374           h = (struct elf_link_hash_entry *) bh;
7375           h->non_elf = 0;
7376           h->def_regular = 1;
7377           h->type = STT_SECTION;
7378
7379           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7380             return FALSE;
7381         }
7382
7383       /* We need to create a .compact_rel section.  */
7384       if (SGI_COMPAT (abfd))
7385         {
7386           if (!mips_elf_create_compact_rel_section (abfd, info))
7387             return FALSE;
7388         }
7389
7390       /* Change alignments of some sections.  */
7391       s = bfd_get_linker_section (abfd, ".hash");
7392       if (s != NULL)
7393         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7394
7395       s = bfd_get_linker_section (abfd, ".dynsym");
7396       if (s != NULL)
7397         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7398
7399       s = bfd_get_linker_section (abfd, ".dynstr");
7400       if (s != NULL)
7401         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7402
7403       /* ??? */
7404       s = bfd_get_section_by_name (abfd, ".reginfo");
7405       if (s != NULL)
7406         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7407
7408       s = bfd_get_linker_section (abfd, ".dynamic");
7409       if (s != NULL)
7410         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7411     }
7412
7413   if (!info->shared)
7414     {
7415       const char *name;
7416
7417       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7418       bh = NULL;
7419       if (!(_bfd_generic_link_add_one_symbol
7420             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7421              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7422         return FALSE;
7423
7424       h = (struct elf_link_hash_entry *) bh;
7425       h->non_elf = 0;
7426       h->def_regular = 1;
7427       h->type = STT_SECTION;
7428
7429       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7430         return FALSE;
7431
7432       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7433         {
7434           /* __rld_map is a four byte word located in the .data section
7435              and is filled in by the rtld to contain a pointer to
7436              the _r_debug structure. Its symbol value will be set in
7437              _bfd_mips_elf_finish_dynamic_symbol.  */
7438           s = bfd_get_linker_section (abfd, ".rld_map");
7439           BFD_ASSERT (s != NULL);
7440
7441           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7442           bh = NULL;
7443           if (!(_bfd_generic_link_add_one_symbol
7444                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7445                  get_elf_backend_data (abfd)->collect, &bh)))
7446             return FALSE;
7447
7448           h = (struct elf_link_hash_entry *) bh;
7449           h->non_elf = 0;
7450           h->def_regular = 1;
7451           h->type = STT_OBJECT;
7452
7453           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7454             return FALSE;
7455           mips_elf_hash_table (info)->rld_symbol = h;
7456         }
7457     }
7458
7459   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7460      Also, on VxWorks, create the _PROCEDURE_LINKAGE_TABLE_ symbol.  */
7461   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7462     return FALSE;
7463
7464   /* Cache the sections created above.  */
7465   htab->splt = bfd_get_linker_section (abfd, ".plt");
7466   htab->sdynbss = bfd_get_linker_section (abfd, ".dynbss");
7467   if (htab->is_vxworks)
7468     {
7469       htab->srelbss = bfd_get_linker_section (abfd, ".rela.bss");
7470       htab->srelplt = bfd_get_linker_section (abfd, ".rela.plt");
7471     }
7472   else
7473     htab->srelplt = bfd_get_linker_section (abfd, ".rel.plt");
7474   if (!htab->sdynbss
7475       || (htab->is_vxworks && !htab->srelbss && !info->shared)
7476       || !htab->srelplt
7477       || !htab->splt)
7478     abort ();
7479
7480   /* Do the usual VxWorks handling.  */
7481   if (htab->is_vxworks
7482       && !elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7483     return FALSE;
7484
7485   return TRUE;
7486 }
7487 \f
7488 /* Return true if relocation REL against section SEC is a REL rather than
7489    RELA relocation.  RELOCS is the first relocation in the section and
7490    ABFD is the bfd that contains SEC.  */
7491
7492 static bfd_boolean
7493 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7494                            const Elf_Internal_Rela *relocs,
7495                            const Elf_Internal_Rela *rel)
7496 {
7497   Elf_Internal_Shdr *rel_hdr;
7498   const struct elf_backend_data *bed;
7499
7500   /* To determine which flavor of relocation this is, we depend on the
7501      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7502   rel_hdr = elf_section_data (sec)->rel.hdr;
7503   if (rel_hdr == NULL)
7504     return FALSE;
7505   bed = get_elf_backend_data (abfd);
7506   return ((size_t) (rel - relocs)
7507           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7508 }
7509
7510 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7511    HOWTO is the relocation's howto and CONTENTS points to the contents
7512    of the section that REL is against.  */
7513
7514 static bfd_vma
7515 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7516                           reloc_howto_type *howto, bfd_byte *contents)
7517 {
7518   bfd_byte *location;
7519   unsigned int r_type;
7520   bfd_vma addend;
7521
7522   r_type = ELF_R_TYPE (abfd, rel->r_info);
7523   location = contents + rel->r_offset;
7524
7525   /* Get the addend, which is stored in the input file.  */
7526   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7527   addend = mips_elf_obtain_contents (howto, rel, abfd, contents);
7528   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7529
7530   return addend & howto->src_mask;
7531 }
7532
7533 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7534    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7535    and update *ADDEND with the final addend.  Return true on success
7536    or false if the LO16 could not be found.  RELEND is the exclusive
7537    upper bound on the relocations for REL's section.  */
7538
7539 static bfd_boolean
7540 mips_elf_add_lo16_rel_addend (bfd *abfd,
7541                               const Elf_Internal_Rela *rel,
7542                               const Elf_Internal_Rela *relend,
7543                               bfd_byte *contents, bfd_vma *addend)
7544 {
7545   unsigned int r_type, lo16_type;
7546   const Elf_Internal_Rela *lo16_relocation;
7547   reloc_howto_type *lo16_howto;
7548   bfd_vma l;
7549
7550   r_type = ELF_R_TYPE (abfd, rel->r_info);
7551   if (mips16_reloc_p (r_type))
7552     lo16_type = R_MIPS16_LO16;
7553   else if (micromips_reloc_p (r_type))
7554     lo16_type = R_MICROMIPS_LO16;
7555   else
7556     lo16_type = R_MIPS_LO16;
7557
7558   /* The combined value is the sum of the HI16 addend, left-shifted by
7559      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7560      code does a `lui' of the HI16 value, and then an `addiu' of the
7561      LO16 value.)
7562
7563      Scan ahead to find a matching LO16 relocation.
7564
7565      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7566      be immediately following.  However, for the IRIX6 ABI, the next
7567      relocation may be a composed relocation consisting of several
7568      relocations for the same address.  In that case, the R_MIPS_LO16
7569      relocation may occur as one of these.  We permit a similar
7570      extension in general, as that is useful for GCC.
7571
7572      In some cases GCC dead code elimination removes the LO16 but keeps
7573      the corresponding HI16.  This is strictly speaking a violation of
7574      the ABI but not immediately harmful.  */
7575   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
7576   if (lo16_relocation == NULL)
7577     return FALSE;
7578
7579   /* Obtain the addend kept there.  */
7580   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
7581   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
7582
7583   l <<= lo16_howto->rightshift;
7584   l = _bfd_mips_elf_sign_extend (l, 16);
7585
7586   *addend <<= 16;
7587   *addend += l;
7588   return TRUE;
7589 }
7590
7591 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
7592    store the contents in *CONTENTS on success.  Assume that *CONTENTS
7593    already holds the contents if it is nonull on entry.  */
7594
7595 static bfd_boolean
7596 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
7597 {
7598   if (*contents)
7599     return TRUE;
7600
7601   /* Get cached copy if it exists.  */
7602   if (elf_section_data (sec)->this_hdr.contents != NULL)
7603     {
7604       *contents = elf_section_data (sec)->this_hdr.contents;
7605       return TRUE;
7606     }
7607
7608   return bfd_malloc_and_get_section (abfd, sec, contents);
7609 }
7610
7611 /* Make a new PLT record to keep internal data.  */
7612
7613 static struct plt_entry *
7614 mips_elf_make_plt_record (bfd *abfd)
7615 {
7616   struct plt_entry *entry;
7617
7618   entry = bfd_zalloc (abfd, sizeof (*entry));
7619   if (entry == NULL)
7620     return NULL;
7621
7622   entry->stub_offset = MINUS_ONE;
7623   entry->mips_offset = MINUS_ONE;
7624   entry->comp_offset = MINUS_ONE;
7625   entry->gotplt_index = MINUS_ONE;
7626   return entry;
7627 }
7628
7629 /* Look through the relocs for a section during the first phase, and
7630    allocate space in the global offset table and record the need for
7631    standard MIPS and compressed procedure linkage table entries.  */
7632
7633 bfd_boolean
7634 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
7635                             asection *sec, const Elf_Internal_Rela *relocs)
7636 {
7637   const char *name;
7638   bfd *dynobj;
7639   Elf_Internal_Shdr *symtab_hdr;
7640   struct elf_link_hash_entry **sym_hashes;
7641   size_t extsymoff;
7642   const Elf_Internal_Rela *rel;
7643   const Elf_Internal_Rela *rel_end;
7644   asection *sreloc;
7645   const struct elf_backend_data *bed;
7646   struct mips_elf_link_hash_table *htab;
7647   bfd_byte *contents;
7648   bfd_vma addend;
7649   reloc_howto_type *howto;
7650
7651   if (info->relocatable)
7652     return TRUE;
7653
7654   htab = mips_elf_hash_table (info);
7655   BFD_ASSERT (htab != NULL);
7656
7657   dynobj = elf_hash_table (info)->dynobj;
7658   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7659   sym_hashes = elf_sym_hashes (abfd);
7660   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
7661
7662   bed = get_elf_backend_data (abfd);
7663   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
7664
7665   /* Check for the mips16 stub sections.  */
7666
7667   name = bfd_get_section_name (abfd, sec);
7668   if (FN_STUB_P (name))
7669     {
7670       unsigned long r_symndx;
7671
7672       /* Look at the relocation information to figure out which symbol
7673          this is for.  */
7674
7675       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7676       if (r_symndx == 0)
7677         {
7678           (*_bfd_error_handler)
7679             (_("%B: Warning: cannot determine the target function for"
7680                " stub section `%s'"),
7681              abfd, name);
7682           bfd_set_error (bfd_error_bad_value);
7683           return FALSE;
7684         }
7685
7686       if (r_symndx < extsymoff
7687           || sym_hashes[r_symndx - extsymoff] == NULL)
7688         {
7689           asection *o;
7690
7691           /* This stub is for a local symbol.  This stub will only be
7692              needed if there is some relocation in this BFD, other
7693              than a 16 bit function call, which refers to this symbol.  */
7694           for (o = abfd->sections; o != NULL; o = o->next)
7695             {
7696               Elf_Internal_Rela *sec_relocs;
7697               const Elf_Internal_Rela *r, *rend;
7698
7699               /* We can ignore stub sections when looking for relocs.  */
7700               if ((o->flags & SEC_RELOC) == 0
7701                   || o->reloc_count == 0
7702                   || section_allows_mips16_refs_p (o))
7703                 continue;
7704
7705               sec_relocs
7706                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7707                                              info->keep_memory);
7708               if (sec_relocs == NULL)
7709                 return FALSE;
7710
7711               rend = sec_relocs + o->reloc_count;
7712               for (r = sec_relocs; r < rend; r++)
7713                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7714                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
7715                   break;
7716
7717               if (elf_section_data (o)->relocs != sec_relocs)
7718                 free (sec_relocs);
7719
7720               if (r < rend)
7721                 break;
7722             }
7723
7724           if (o == NULL)
7725             {
7726               /* There is no non-call reloc for this stub, so we do
7727                  not need it.  Since this function is called before
7728                  the linker maps input sections to output sections, we
7729                  can easily discard it by setting the SEC_EXCLUDE
7730                  flag.  */
7731               sec->flags |= SEC_EXCLUDE;
7732               return TRUE;
7733             }
7734
7735           /* Record this stub in an array of local symbol stubs for
7736              this BFD.  */
7737           if (mips_elf_tdata (abfd)->local_stubs == NULL)
7738             {
7739               unsigned long symcount;
7740               asection **n;
7741               bfd_size_type amt;
7742
7743               if (elf_bad_symtab (abfd))
7744                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7745               else
7746                 symcount = symtab_hdr->sh_info;
7747               amt = symcount * sizeof (asection *);
7748               n = bfd_zalloc (abfd, amt);
7749               if (n == NULL)
7750                 return FALSE;
7751               mips_elf_tdata (abfd)->local_stubs = n;
7752             }
7753
7754           sec->flags |= SEC_KEEP;
7755           mips_elf_tdata (abfd)->local_stubs[r_symndx] = sec;
7756
7757           /* We don't need to set mips16_stubs_seen in this case.
7758              That flag is used to see whether we need to look through
7759              the global symbol table for stubs.  We don't need to set
7760              it here, because we just have a local stub.  */
7761         }
7762       else
7763         {
7764           struct mips_elf_link_hash_entry *h;
7765
7766           h = ((struct mips_elf_link_hash_entry *)
7767                sym_hashes[r_symndx - extsymoff]);
7768
7769           while (h->root.root.type == bfd_link_hash_indirect
7770                  || h->root.root.type == bfd_link_hash_warning)
7771             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
7772
7773           /* H is the symbol this stub is for.  */
7774
7775           /* If we already have an appropriate stub for this function, we
7776              don't need another one, so we can discard this one.  Since
7777              this function is called before the linker maps input sections
7778              to output sections, we can easily discard it by setting the
7779              SEC_EXCLUDE flag.  */
7780           if (h->fn_stub != NULL)
7781             {
7782               sec->flags |= SEC_EXCLUDE;
7783               return TRUE;
7784             }
7785
7786           sec->flags |= SEC_KEEP;
7787           h->fn_stub = sec;
7788           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7789         }
7790     }
7791   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
7792     {
7793       unsigned long r_symndx;
7794       struct mips_elf_link_hash_entry *h;
7795       asection **loc;
7796
7797       /* Look at the relocation information to figure out which symbol
7798          this is for.  */
7799
7800       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7801       if (r_symndx == 0)
7802         {
7803           (*_bfd_error_handler)
7804             (_("%B: Warning: cannot determine the target function for"
7805                " stub section `%s'"),
7806              abfd, name);
7807           bfd_set_error (bfd_error_bad_value);
7808           return FALSE;
7809         }
7810
7811       if (r_symndx < extsymoff
7812           || sym_hashes[r_symndx - extsymoff] == NULL)
7813         {
7814           asection *o;
7815
7816           /* This stub is for a local symbol.  This stub will only be
7817              needed if there is some relocation (R_MIPS16_26) in this BFD
7818              that refers to this symbol.  */
7819           for (o = abfd->sections; o != NULL; o = o->next)
7820             {
7821               Elf_Internal_Rela *sec_relocs;
7822               const Elf_Internal_Rela *r, *rend;
7823
7824               /* We can ignore stub sections when looking for relocs.  */
7825               if ((o->flags & SEC_RELOC) == 0
7826                   || o->reloc_count == 0
7827                   || section_allows_mips16_refs_p (o))
7828                 continue;
7829
7830               sec_relocs
7831                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7832                                              info->keep_memory);
7833               if (sec_relocs == NULL)
7834                 return FALSE;
7835
7836               rend = sec_relocs + o->reloc_count;
7837               for (r = sec_relocs; r < rend; r++)
7838                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7839                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
7840                     break;
7841
7842               if (elf_section_data (o)->relocs != sec_relocs)
7843                 free (sec_relocs);
7844
7845               if (r < rend)
7846                 break;
7847             }
7848
7849           if (o == NULL)
7850             {
7851               /* There is no non-call reloc for this stub, so we do
7852                  not need it.  Since this function is called before
7853                  the linker maps input sections to output sections, we
7854                  can easily discard it by setting the SEC_EXCLUDE
7855                  flag.  */
7856               sec->flags |= SEC_EXCLUDE;
7857               return TRUE;
7858             }
7859
7860           /* Record this stub in an array of local symbol call_stubs for
7861              this BFD.  */
7862           if (mips_elf_tdata (abfd)->local_call_stubs == NULL)
7863             {
7864               unsigned long symcount;
7865               asection **n;
7866               bfd_size_type amt;
7867
7868               if (elf_bad_symtab (abfd))
7869                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7870               else
7871                 symcount = symtab_hdr->sh_info;
7872               amt = symcount * sizeof (asection *);
7873               n = bfd_zalloc (abfd, amt);
7874               if (n == NULL)
7875                 return FALSE;
7876               mips_elf_tdata (abfd)->local_call_stubs = n;
7877             }
7878
7879           sec->flags |= SEC_KEEP;
7880           mips_elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
7881
7882           /* We don't need to set mips16_stubs_seen in this case.
7883              That flag is used to see whether we need to look through
7884              the global symbol table for stubs.  We don't need to set
7885              it here, because we just have a local stub.  */
7886         }
7887       else
7888         {
7889           h = ((struct mips_elf_link_hash_entry *)
7890                sym_hashes[r_symndx - extsymoff]);
7891
7892           /* H is the symbol this stub is for.  */
7893
7894           if (CALL_FP_STUB_P (name))
7895             loc = &h->call_fp_stub;
7896           else
7897             loc = &h->call_stub;
7898
7899           /* If we already have an appropriate stub for this function, we
7900              don't need another one, so we can discard this one.  Since
7901              this function is called before the linker maps input sections
7902              to output sections, we can easily discard it by setting the
7903              SEC_EXCLUDE flag.  */
7904           if (*loc != NULL)
7905             {
7906               sec->flags |= SEC_EXCLUDE;
7907               return TRUE;
7908             }
7909
7910           sec->flags |= SEC_KEEP;
7911           *loc = sec;
7912           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7913         }
7914     }
7915
7916   sreloc = NULL;
7917   contents = NULL;
7918   for (rel = relocs; rel < rel_end; ++rel)
7919     {
7920       unsigned long r_symndx;
7921       unsigned int r_type;
7922       struct elf_link_hash_entry *h;
7923       bfd_boolean can_make_dynamic_p;
7924
7925       r_symndx = ELF_R_SYM (abfd, rel->r_info);
7926       r_type = ELF_R_TYPE (abfd, rel->r_info);
7927
7928       if (r_symndx < extsymoff)
7929         h = NULL;
7930       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
7931         {
7932           (*_bfd_error_handler)
7933             (_("%B: Malformed reloc detected for section %s"),
7934              abfd, name);
7935           bfd_set_error (bfd_error_bad_value);
7936           return FALSE;
7937         }
7938       else
7939         {
7940           h = sym_hashes[r_symndx - extsymoff];
7941           if (h != NULL)
7942             {
7943               while (h->root.type == bfd_link_hash_indirect
7944                      || h->root.type == bfd_link_hash_warning)
7945                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
7946
7947               /* PR15323, ref flags aren't set for references in the
7948                  same object.  */
7949               h->root.non_ir_ref = 1;
7950             }
7951         }
7952
7953       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
7954          relocation into a dynamic one.  */
7955       can_make_dynamic_p = FALSE;
7956       switch (r_type)
7957         {
7958         case R_MIPS_GOT16:
7959         case R_MIPS_CALL16:
7960         case R_MIPS_CALL_HI16:
7961         case R_MIPS_CALL_LO16:
7962         case R_MIPS_GOT_HI16:
7963         case R_MIPS_GOT_LO16:
7964         case R_MIPS_GOT_PAGE:
7965         case R_MIPS_GOT_OFST:
7966         case R_MIPS_GOT_DISP:
7967         case R_MIPS_TLS_GOTTPREL:
7968         case R_MIPS_TLS_GD:
7969         case R_MIPS_TLS_LDM:
7970         case R_MIPS16_GOT16:
7971         case R_MIPS16_CALL16:
7972         case R_MIPS16_TLS_GOTTPREL:
7973         case R_MIPS16_TLS_GD:
7974         case R_MIPS16_TLS_LDM:
7975         case R_MICROMIPS_GOT16:
7976         case R_MICROMIPS_CALL16:
7977         case R_MICROMIPS_CALL_HI16:
7978         case R_MICROMIPS_CALL_LO16:
7979         case R_MICROMIPS_GOT_HI16:
7980         case R_MICROMIPS_GOT_LO16:
7981         case R_MICROMIPS_GOT_PAGE:
7982         case R_MICROMIPS_GOT_OFST:
7983         case R_MICROMIPS_GOT_DISP:
7984         case R_MICROMIPS_TLS_GOTTPREL:
7985         case R_MICROMIPS_TLS_GD:
7986         case R_MICROMIPS_TLS_LDM:
7987           if (dynobj == NULL)
7988             elf_hash_table (info)->dynobj = dynobj = abfd;
7989           if (!mips_elf_create_got_section (dynobj, info))
7990             return FALSE;
7991           if (htab->is_vxworks && !info->shared)
7992             {
7993               (*_bfd_error_handler)
7994                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
7995                  abfd, (unsigned long) rel->r_offset);
7996               bfd_set_error (bfd_error_bad_value);
7997               return FALSE;
7998             }
7999           break;
8000
8001           /* This is just a hint; it can safely be ignored.  Don't set
8002              has_static_relocs for the corresponding symbol.  */
8003         case R_MIPS_JALR:
8004         case R_MICROMIPS_JALR:
8005           break;
8006
8007         case R_MIPS_32:
8008         case R_MIPS_REL32:
8009         case R_MIPS_64:
8010           /* In VxWorks executables, references to external symbols
8011              must be handled using copy relocs or PLT entries; it is not
8012              possible to convert this relocation into a dynamic one.
8013
8014              For executables that use PLTs and copy-relocs, we have a
8015              choice between converting the relocation into a dynamic
8016              one or using copy relocations or PLT entries.  It is
8017              usually better to do the former, unless the relocation is
8018              against a read-only section.  */
8019           if ((info->shared
8020                || (h != NULL
8021                    && !htab->is_vxworks
8022                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
8023                    && !(!info->nocopyreloc
8024                         && !PIC_OBJECT_P (abfd)
8025                         && MIPS_ELF_READONLY_SECTION (sec))))
8026               && (sec->flags & SEC_ALLOC) != 0)
8027             {
8028               can_make_dynamic_p = TRUE;
8029               if (dynobj == NULL)
8030                 elf_hash_table (info)->dynobj = dynobj = abfd;
8031               break;
8032             }
8033           /* For sections that are not SEC_ALLOC a copy reloc would be
8034              output if possible (implying questionable semantics for
8035              read-only data objects) or otherwise the final link would
8036              fail as ld.so will not process them and could not therefore
8037              handle any outstanding dynamic relocations.
8038
8039              For such sections that are also SEC_DEBUGGING, we can avoid
8040              these problems by simply ignoring any relocs as these
8041              sections have a predefined use and we know it is safe to do
8042              so.
8043
8044              This is needed in cases such as a global symbol definition
8045              in a shared library causing a common symbol from an object
8046              file to be converted to an undefined reference.  If that
8047              happens, then all the relocations against this symbol from
8048              SEC_DEBUGGING sections in the object file will resolve to
8049              nil.  */
8050           if ((sec->flags & SEC_DEBUGGING) != 0)
8051             break;
8052           /* Fall through.  */
8053
8054         default:
8055           /* Most static relocations require pointer equality, except
8056              for branches.  */
8057           if (h)
8058             h->pointer_equality_needed = TRUE;
8059           /* Fall through.  */
8060
8061         case R_MIPS_26:
8062         case R_MIPS_PC16:
8063         case R_MIPS16_26:
8064         case R_MICROMIPS_26_S1:
8065         case R_MICROMIPS_PC7_S1:
8066         case R_MICROMIPS_PC10_S1:
8067         case R_MICROMIPS_PC16_S1:
8068         case R_MICROMIPS_PC23_S2:
8069           if (h)
8070             ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = TRUE;
8071           break;
8072         }
8073
8074       if (h)
8075         {
8076           /* Relocations against the special VxWorks __GOTT_BASE__ and
8077              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
8078              room for them in .rela.dyn.  */
8079           if (is_gott_symbol (info, h))
8080             {
8081               if (sreloc == NULL)
8082                 {
8083                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8084                   if (sreloc == NULL)
8085                     return FALSE;
8086                 }
8087               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8088               if (MIPS_ELF_READONLY_SECTION (sec))
8089                 /* We tell the dynamic linker that there are
8090                    relocations against the text segment.  */
8091                 info->flags |= DF_TEXTREL;
8092             }
8093         }
8094       else if (call_lo16_reloc_p (r_type)
8095                || got_lo16_reloc_p (r_type)
8096                || got_disp_reloc_p (r_type)
8097                || (got16_reloc_p (r_type) && htab->is_vxworks))
8098         {
8099           /* We may need a local GOT entry for this relocation.  We
8100              don't count R_MIPS_GOT_PAGE because we can estimate the
8101              maximum number of pages needed by looking at the size of
8102              the segment.  Similar comments apply to R_MIPS*_GOT16 and
8103              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
8104              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
8105              R_MIPS_CALL_HI16 because these are always followed by an
8106              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
8107           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8108                                                  rel->r_addend, info, r_type))
8109             return FALSE;
8110         }
8111
8112       if (h != NULL
8113           && mips_elf_relocation_needs_la25_stub (abfd, r_type,
8114                                                   ELF_ST_IS_MIPS16 (h->other)))
8115         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
8116
8117       switch (r_type)
8118         {
8119         case R_MIPS_CALL16:
8120         case R_MIPS16_CALL16:
8121         case R_MICROMIPS_CALL16:
8122           if (h == NULL)
8123             {
8124               (*_bfd_error_handler)
8125                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
8126                  abfd, (unsigned long) rel->r_offset);
8127               bfd_set_error (bfd_error_bad_value);
8128               return FALSE;
8129             }
8130           /* Fall through.  */
8131
8132         case R_MIPS_CALL_HI16:
8133         case R_MIPS_CALL_LO16:
8134         case R_MICROMIPS_CALL_HI16:
8135         case R_MICROMIPS_CALL_LO16:
8136           if (h != NULL)
8137             {
8138               /* Make sure there is room in the regular GOT to hold the
8139                  function's address.  We may eliminate it in favour of
8140                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
8141               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE,
8142                                                       r_type))
8143                 return FALSE;
8144
8145               /* We need a stub, not a plt entry for the undefined
8146                  function.  But we record it as if it needs plt.  See
8147                  _bfd_elf_adjust_dynamic_symbol.  */
8148               h->needs_plt = 1;
8149               h->type = STT_FUNC;
8150             }
8151           break;
8152
8153         case R_MIPS_GOT_PAGE:
8154         case R_MICROMIPS_GOT_PAGE:
8155         case R_MIPS16_GOT16:
8156         case R_MIPS_GOT16:
8157         case R_MIPS_GOT_HI16:
8158         case R_MIPS_GOT_LO16:
8159         case R_MICROMIPS_GOT16:
8160         case R_MICROMIPS_GOT_HI16:
8161         case R_MICROMIPS_GOT_LO16:
8162           if (!h || got_page_reloc_p (r_type))
8163             {
8164               /* This relocation needs (or may need, if h != NULL) a
8165                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
8166                  know for sure until we know whether the symbol is
8167                  preemptible.  */
8168               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
8169                 {
8170                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
8171                     return FALSE;
8172                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8173                   addend = mips_elf_read_rel_addend (abfd, rel,
8174                                                      howto, contents);
8175                   if (got16_reloc_p (r_type))
8176                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
8177                                                   contents, &addend);
8178                   else
8179                     addend <<= howto->rightshift;
8180                 }
8181               else
8182                 addend = rel->r_addend;
8183               if (!mips_elf_record_got_page_ref (info, abfd, r_symndx,
8184                                                  h, addend))
8185                 return FALSE;
8186
8187               if (h)
8188                 {
8189                   struct mips_elf_link_hash_entry *hmips =
8190                     (struct mips_elf_link_hash_entry *) h;
8191
8192                   /* This symbol is definitely not overridable.  */
8193                   if (hmips->root.def_regular
8194                       && ! (info->shared && ! info->symbolic
8195                             && ! hmips->root.forced_local))
8196                     h = NULL;
8197                 }
8198             }
8199           /* If this is a global, overridable symbol, GOT_PAGE will
8200              decay to GOT_DISP, so we'll need a GOT entry for it.  */
8201           /* Fall through.  */
8202
8203         case R_MIPS_GOT_DISP:
8204         case R_MICROMIPS_GOT_DISP:
8205           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8206                                                        FALSE, r_type))
8207             return FALSE;
8208           break;
8209
8210         case R_MIPS_TLS_GOTTPREL:
8211         case R_MIPS16_TLS_GOTTPREL:
8212         case R_MICROMIPS_TLS_GOTTPREL:
8213           if (info->shared)
8214             info->flags |= DF_STATIC_TLS;
8215           /* Fall through */
8216
8217         case R_MIPS_TLS_LDM:
8218         case R_MIPS16_TLS_LDM:
8219         case R_MICROMIPS_TLS_LDM:
8220           if (tls_ldm_reloc_p (r_type))
8221             {
8222               r_symndx = STN_UNDEF;
8223               h = NULL;
8224             }
8225           /* Fall through */
8226
8227         case R_MIPS_TLS_GD:
8228         case R_MIPS16_TLS_GD:
8229         case R_MICROMIPS_TLS_GD:
8230           /* This symbol requires a global offset table entry, or two
8231              for TLS GD relocations.  */
8232           if (h != NULL)
8233             {
8234               if (!mips_elf_record_global_got_symbol (h, abfd, info,
8235                                                       FALSE, r_type))
8236                 return FALSE;
8237             }
8238           else
8239             {
8240               if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8241                                                      rel->r_addend,
8242                                                      info, r_type))
8243                 return FALSE;
8244             }
8245           break;
8246
8247         case R_MIPS_32:
8248         case R_MIPS_REL32:
8249         case R_MIPS_64:
8250           /* In VxWorks executables, references to external symbols
8251              are handled using copy relocs or PLT stubs, so there's
8252              no need to add a .rela.dyn entry for this relocation.  */
8253           if (can_make_dynamic_p)
8254             {
8255               if (sreloc == NULL)
8256                 {
8257                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8258                   if (sreloc == NULL)
8259                     return FALSE;
8260                 }
8261               if (info->shared && h == NULL)
8262                 {
8263                   /* When creating a shared object, we must copy these
8264                      reloc types into the output file as R_MIPS_REL32
8265                      relocs.  Make room for this reloc in .rel(a).dyn.  */
8266                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8267                   if (MIPS_ELF_READONLY_SECTION (sec))
8268                     /* We tell the dynamic linker that there are
8269                        relocations against the text segment.  */
8270                     info->flags |= DF_TEXTREL;
8271                 }
8272               else
8273                 {
8274                   struct mips_elf_link_hash_entry *hmips;
8275
8276                   /* For a shared object, we must copy this relocation
8277                      unless the symbol turns out to be undefined and
8278                      weak with non-default visibility, in which case
8279                      it will be left as zero.
8280
8281                      We could elide R_MIPS_REL32 for locally binding symbols
8282                      in shared libraries, but do not yet do so.
8283
8284                      For an executable, we only need to copy this
8285                      reloc if the symbol is defined in a dynamic
8286                      object.  */
8287                   hmips = (struct mips_elf_link_hash_entry *) h;
8288                   ++hmips->possibly_dynamic_relocs;
8289                   if (MIPS_ELF_READONLY_SECTION (sec))
8290                     /* We need it to tell the dynamic linker if there
8291                        are relocations against the text segment.  */
8292                     hmips->readonly_reloc = TRUE;
8293                 }
8294             }
8295
8296           if (SGI_COMPAT (abfd))
8297             mips_elf_hash_table (info)->compact_rel_size +=
8298               sizeof (Elf32_External_crinfo);
8299           break;
8300
8301         case R_MIPS_26:
8302         case R_MIPS_GPREL16:
8303         case R_MIPS_LITERAL:
8304         case R_MIPS_GPREL32:
8305         case R_MICROMIPS_26_S1:
8306         case R_MICROMIPS_GPREL16:
8307         case R_MICROMIPS_LITERAL:
8308         case R_MICROMIPS_GPREL7_S2:
8309           if (SGI_COMPAT (abfd))
8310             mips_elf_hash_table (info)->compact_rel_size +=
8311               sizeof (Elf32_External_crinfo);
8312           break;
8313
8314           /* This relocation describes the C++ object vtable hierarchy.
8315              Reconstruct it for later use during GC.  */
8316         case R_MIPS_GNU_VTINHERIT:
8317           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
8318             return FALSE;
8319           break;
8320
8321           /* This relocation describes which C++ vtable entries are actually
8322              used.  Record for later use during GC.  */
8323         case R_MIPS_GNU_VTENTRY:
8324           BFD_ASSERT (h != NULL);
8325           if (h != NULL
8326               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
8327             return FALSE;
8328           break;
8329
8330         default:
8331           break;
8332         }
8333
8334       /* Record the need for a PLT entry.  At this point we don't know
8335          yet if we are going to create a PLT in the first place, but
8336          we only record whether the relocation requires a standard MIPS
8337          or a compressed code entry anyway.  If we don't make a PLT after
8338          all, then we'll just ignore these arrangements.  Likewise if
8339          a PLT entry is not created because the symbol is satisfied
8340          locally.  */
8341       if (h != NULL
8342           && jal_reloc_p (r_type)
8343           && !SYMBOL_CALLS_LOCAL (info, h))
8344         {
8345           if (h->plt.plist == NULL)
8346             h->plt.plist = mips_elf_make_plt_record (abfd);
8347           if (h->plt.plist == NULL)
8348             return FALSE;
8349
8350           if (r_type == R_MIPS_26)
8351             h->plt.plist->need_mips = TRUE;
8352           else
8353             h->plt.plist->need_comp = TRUE;
8354         }
8355
8356       /* We must not create a stub for a symbol that has relocations
8357          related to taking the function's address.  This doesn't apply to
8358          VxWorks, where CALL relocs refer to a .got.plt entry instead of
8359          a normal .got entry.  */
8360       if (!htab->is_vxworks && h != NULL)
8361         switch (r_type)
8362           {
8363           default:
8364             ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8365             break;
8366           case R_MIPS16_CALL16:
8367           case R_MIPS_CALL16:
8368           case R_MIPS_CALL_HI16:
8369           case R_MIPS_CALL_LO16:
8370           case R_MIPS_JALR:
8371           case R_MICROMIPS_CALL16:
8372           case R_MICROMIPS_CALL_HI16:
8373           case R_MICROMIPS_CALL_LO16:
8374           case R_MICROMIPS_JALR:
8375             break;
8376           }
8377
8378       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8379          if there is one.  We only need to handle global symbols here;
8380          we decide whether to keep or delete stubs for local symbols
8381          when processing the stub's relocations.  */
8382       if (h != NULL
8383           && !mips16_call_reloc_p (r_type)
8384           && !section_allows_mips16_refs_p (sec))
8385         {
8386           struct mips_elf_link_hash_entry *mh;
8387
8388           mh = (struct mips_elf_link_hash_entry *) h;
8389           mh->need_fn_stub = TRUE;
8390         }
8391
8392       /* Refuse some position-dependent relocations when creating a
8393          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8394          not PIC, but we can create dynamic relocations and the result
8395          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8396          combined with R_MIPS_GOT16.  */
8397       if (info->shared)
8398         {
8399           switch (r_type)
8400             {
8401             case R_MIPS16_HI16:
8402             case R_MIPS_HI16:
8403             case R_MIPS_HIGHER:
8404             case R_MIPS_HIGHEST:
8405             case R_MICROMIPS_HI16:
8406             case R_MICROMIPS_HIGHER:
8407             case R_MICROMIPS_HIGHEST:
8408               /* Don't refuse a high part relocation if it's against
8409                  no symbol (e.g. part of a compound relocation).  */
8410               if (r_symndx == STN_UNDEF)
8411                 break;
8412
8413               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8414                  and has a special meaning.  */
8415               if (!NEWABI_P (abfd) && h != NULL
8416                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8417                 break;
8418
8419               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8420               if (is_gott_symbol (info, h))
8421                 break;
8422
8423               /* FALLTHROUGH */
8424
8425             case R_MIPS16_26:
8426             case R_MIPS_26:
8427             case R_MICROMIPS_26_S1:
8428               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8429               (*_bfd_error_handler)
8430                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8431                  abfd, howto->name,
8432                  (h) ? h->root.root.string : "a local symbol");
8433               bfd_set_error (bfd_error_bad_value);
8434               return FALSE;
8435             default:
8436               break;
8437             }
8438         }
8439     }
8440
8441   return TRUE;
8442 }
8443 \f
8444 bfd_boolean
8445 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8446                          struct bfd_link_info *link_info,
8447                          bfd_boolean *again)
8448 {
8449   Elf_Internal_Rela *internal_relocs;
8450   Elf_Internal_Rela *irel, *irelend;
8451   Elf_Internal_Shdr *symtab_hdr;
8452   bfd_byte *contents = NULL;
8453   size_t extsymoff;
8454   bfd_boolean changed_contents = FALSE;
8455   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8456   Elf_Internal_Sym *isymbuf = NULL;
8457
8458   /* We are not currently changing any sizes, so only one pass.  */
8459   *again = FALSE;
8460
8461   if (link_info->relocatable)
8462     return TRUE;
8463
8464   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8465                                                link_info->keep_memory);
8466   if (internal_relocs == NULL)
8467     return TRUE;
8468
8469   irelend = internal_relocs + sec->reloc_count
8470     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8471   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8472   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8473
8474   for (irel = internal_relocs; irel < irelend; irel++)
8475     {
8476       bfd_vma symval;
8477       bfd_signed_vma sym_offset;
8478       unsigned int r_type;
8479       unsigned long r_symndx;
8480       asection *sym_sec;
8481       unsigned long instruction;
8482
8483       /* Turn jalr into bgezal, and jr into beq, if they're marked
8484          with a JALR relocation, that indicate where they jump to.
8485          This saves some pipeline bubbles.  */
8486       r_type = ELF_R_TYPE (abfd, irel->r_info);
8487       if (r_type != R_MIPS_JALR)
8488         continue;
8489
8490       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8491       /* Compute the address of the jump target.  */
8492       if (r_symndx >= extsymoff)
8493         {
8494           struct mips_elf_link_hash_entry *h
8495             = ((struct mips_elf_link_hash_entry *)
8496                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8497
8498           while (h->root.root.type == bfd_link_hash_indirect
8499                  || h->root.root.type == bfd_link_hash_warning)
8500             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8501
8502           /* If a symbol is undefined, or if it may be overridden,
8503              skip it.  */
8504           if (! ((h->root.root.type == bfd_link_hash_defined
8505                   || h->root.root.type == bfd_link_hash_defweak)
8506                  && h->root.root.u.def.section)
8507               || (link_info->shared && ! link_info->symbolic
8508                   && !h->root.forced_local))
8509             continue;
8510
8511           sym_sec = h->root.root.u.def.section;
8512           if (sym_sec->output_section)
8513             symval = (h->root.root.u.def.value
8514                       + sym_sec->output_section->vma
8515                       + sym_sec->output_offset);
8516           else
8517             symval = h->root.root.u.def.value;
8518         }
8519       else
8520         {
8521           Elf_Internal_Sym *isym;
8522
8523           /* Read this BFD's symbols if we haven't done so already.  */
8524           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8525             {
8526               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8527               if (isymbuf == NULL)
8528                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8529                                                 symtab_hdr->sh_info, 0,
8530                                                 NULL, NULL, NULL);
8531               if (isymbuf == NULL)
8532                 goto relax_return;
8533             }
8534
8535           isym = isymbuf + r_symndx;
8536           if (isym->st_shndx == SHN_UNDEF)
8537             continue;
8538           else if (isym->st_shndx == SHN_ABS)
8539             sym_sec = bfd_abs_section_ptr;
8540           else if (isym->st_shndx == SHN_COMMON)
8541             sym_sec = bfd_com_section_ptr;
8542           else
8543             sym_sec
8544               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8545           symval = isym->st_value
8546             + sym_sec->output_section->vma
8547             + sym_sec->output_offset;
8548         }
8549
8550       /* Compute branch offset, from delay slot of the jump to the
8551          branch target.  */
8552       sym_offset = (symval + irel->r_addend)
8553         - (sec_start + irel->r_offset + 4);
8554
8555       /* Branch offset must be properly aligned.  */
8556       if ((sym_offset & 3) != 0)
8557         continue;
8558
8559       sym_offset >>= 2;
8560
8561       /* Check that it's in range.  */
8562       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
8563         continue;
8564
8565       /* Get the section contents if we haven't done so already.  */
8566       if (!mips_elf_get_section_contents (abfd, sec, &contents))
8567         goto relax_return;
8568
8569       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
8570
8571       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
8572       if ((instruction & 0xfc1fffff) == 0x0000f809)
8573         instruction = 0x04110000;
8574       /* If it was jr <reg>, turn it into b <target>.  */
8575       else if ((instruction & 0xfc1fffff) == 0x00000008)
8576         instruction = 0x10000000;
8577       else
8578         continue;
8579
8580       instruction |= (sym_offset & 0xffff);
8581       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
8582       changed_contents = TRUE;
8583     }
8584
8585   if (contents != NULL
8586       && elf_section_data (sec)->this_hdr.contents != contents)
8587     {
8588       if (!changed_contents && !link_info->keep_memory)
8589         free (contents);
8590       else
8591         {
8592           /* Cache the section contents for elf_link_input_bfd.  */
8593           elf_section_data (sec)->this_hdr.contents = contents;
8594         }
8595     }
8596   return TRUE;
8597
8598  relax_return:
8599   if (contents != NULL
8600       && elf_section_data (sec)->this_hdr.contents != contents)
8601     free (contents);
8602   return FALSE;
8603 }
8604 \f
8605 /* Allocate space for global sym dynamic relocs.  */
8606
8607 static bfd_boolean
8608 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
8609 {
8610   struct bfd_link_info *info = inf;
8611   bfd *dynobj;
8612   struct mips_elf_link_hash_entry *hmips;
8613   struct mips_elf_link_hash_table *htab;
8614
8615   htab = mips_elf_hash_table (info);
8616   BFD_ASSERT (htab != NULL);
8617
8618   dynobj = elf_hash_table (info)->dynobj;
8619   hmips = (struct mips_elf_link_hash_entry *) h;
8620
8621   /* VxWorks executables are handled elsewhere; we only need to
8622      allocate relocations in shared objects.  */
8623   if (htab->is_vxworks && !info->shared)
8624     return TRUE;
8625
8626   /* Ignore indirect symbols.  All relocations against such symbols
8627      will be redirected to the target symbol.  */
8628   if (h->root.type == bfd_link_hash_indirect)
8629     return TRUE;
8630
8631   /* If this symbol is defined in a dynamic object, or we are creating
8632      a shared library, we will need to copy any R_MIPS_32 or
8633      R_MIPS_REL32 relocs against it into the output file.  */
8634   if (! info->relocatable
8635       && hmips->possibly_dynamic_relocs != 0
8636       && (h->root.type == bfd_link_hash_defweak
8637           || (!h->def_regular && !ELF_COMMON_DEF_P (h))
8638           || info->shared))
8639     {
8640       bfd_boolean do_copy = TRUE;
8641
8642       if (h->root.type == bfd_link_hash_undefweak)
8643         {
8644           /* Do not copy relocations for undefined weak symbols with
8645              non-default visibility.  */
8646           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
8647             do_copy = FALSE;
8648
8649           /* Make sure undefined weak symbols are output as a dynamic
8650              symbol in PIEs.  */
8651           else if (h->dynindx == -1 && !h->forced_local)
8652             {
8653               if (! bfd_elf_link_record_dynamic_symbol (info, h))
8654                 return FALSE;
8655             }
8656         }
8657
8658       if (do_copy)
8659         {
8660           /* Even though we don't directly need a GOT entry for this symbol,
8661              the SVR4 psABI requires it to have a dynamic symbol table
8662              index greater that DT_MIPS_GOTSYM if there are dynamic
8663              relocations against it.
8664
8665              VxWorks does not enforce the same mapping between the GOT
8666              and the symbol table, so the same requirement does not
8667              apply there.  */
8668           if (!htab->is_vxworks)
8669             {
8670               if (hmips->global_got_area > GGA_RELOC_ONLY)
8671                 hmips->global_got_area = GGA_RELOC_ONLY;
8672               hmips->got_only_for_calls = FALSE;
8673             }
8674
8675           mips_elf_allocate_dynamic_relocations
8676             (dynobj, info, hmips->possibly_dynamic_relocs);
8677           if (hmips->readonly_reloc)
8678             /* We tell the dynamic linker that there are relocations
8679                against the text segment.  */
8680             info->flags |= DF_TEXTREL;
8681         }
8682     }
8683
8684   return TRUE;
8685 }
8686
8687 /* Adjust a symbol defined by a dynamic object and referenced by a
8688    regular object.  The current definition is in some section of the
8689    dynamic object, but we're not including those sections.  We have to
8690    change the definition to something the rest of the link can
8691    understand.  */
8692
8693 bfd_boolean
8694 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
8695                                      struct elf_link_hash_entry *h)
8696 {
8697   bfd *dynobj;
8698   struct mips_elf_link_hash_entry *hmips;
8699   struct mips_elf_link_hash_table *htab;
8700
8701   htab = mips_elf_hash_table (info);
8702   BFD_ASSERT (htab != NULL);
8703
8704   dynobj = elf_hash_table (info)->dynobj;
8705   hmips = (struct mips_elf_link_hash_entry *) h;
8706
8707   /* Make sure we know what is going on here.  */
8708   BFD_ASSERT (dynobj != NULL
8709               && (h->needs_plt
8710                   || h->u.weakdef != NULL
8711                   || (h->def_dynamic
8712                       && h->ref_regular
8713                       && !h->def_regular)));
8714
8715   hmips = (struct mips_elf_link_hash_entry *) h;
8716
8717   /* If there are call relocations against an externally-defined symbol,
8718      see whether we can create a MIPS lazy-binding stub for it.  We can
8719      only do this if all references to the function are through call
8720      relocations, and in that case, the traditional lazy-binding stubs
8721      are much more efficient than PLT entries.
8722
8723      Traditional stubs are only available on SVR4 psABI-based systems;
8724      VxWorks always uses PLTs instead.  */
8725   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
8726     {
8727       if (! elf_hash_table (info)->dynamic_sections_created)
8728         return TRUE;
8729
8730       /* If this symbol is not defined in a regular file, then set
8731          the symbol to the stub location.  This is required to make
8732          function pointers compare as equal between the normal
8733          executable and the shared library.  */
8734       if (!h->def_regular)
8735         {
8736           hmips->needs_lazy_stub = TRUE;
8737           htab->lazy_stub_count++;
8738           return TRUE;
8739         }
8740     }
8741   /* As above, VxWorks requires PLT entries for externally-defined
8742      functions that are only accessed through call relocations.
8743
8744      Both VxWorks and non-VxWorks targets also need PLT entries if there
8745      are static-only relocations against an externally-defined function.
8746      This can technically occur for shared libraries if there are
8747      branches to the symbol, although it is unlikely that this will be
8748      used in practice due to the short ranges involved.  It can occur
8749      for any relative or absolute relocation in executables; in that
8750      case, the PLT entry becomes the function's canonical address.  */
8751   else if (((h->needs_plt && !hmips->no_fn_stub)
8752             || (h->type == STT_FUNC && hmips->has_static_relocs))
8753            && htab->use_plts_and_copy_relocs
8754            && !SYMBOL_CALLS_LOCAL (info, h)
8755            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
8756                 && h->root.type == bfd_link_hash_undefweak))
8757     {
8758       bfd_boolean micromips_p = MICROMIPS_P (info->output_bfd);
8759       bfd_boolean newabi_p = NEWABI_P (info->output_bfd);
8760
8761       /* If this is the first symbol to need a PLT entry, then make some
8762          basic setup.  Also work out PLT entry sizes.  We'll need them
8763          for PLT offset calculations.  */
8764       if (htab->plt_mips_offset + htab->plt_comp_offset == 0)
8765         {
8766           BFD_ASSERT (htab->sgotplt->size == 0);
8767           BFD_ASSERT (htab->plt_got_index == 0);
8768
8769           /* If we're using the PLT additions to the psABI, each PLT
8770              entry is 16 bytes and the PLT0 entry is 32 bytes.
8771              Encourage better cache usage by aligning.  We do this
8772              lazily to avoid pessimizing traditional objects.  */
8773           if (!htab->is_vxworks
8774               && !bfd_set_section_alignment (dynobj, htab->splt, 5))
8775             return FALSE;
8776
8777           /* Make sure that .got.plt is word-aligned.  We do this lazily
8778              for the same reason as above.  */
8779           if (!bfd_set_section_alignment (dynobj, htab->sgotplt,
8780                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
8781             return FALSE;
8782
8783           /* On non-VxWorks targets, the first two entries in .got.plt
8784              are reserved.  */
8785           if (!htab->is_vxworks)
8786             htab->plt_got_index
8787               += (get_elf_backend_data (dynobj)->got_header_size
8788                   / MIPS_ELF_GOT_SIZE (dynobj));
8789
8790           /* On VxWorks, also allocate room for the header's
8791              .rela.plt.unloaded entries.  */
8792           if (htab->is_vxworks && !info->shared)
8793             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
8794
8795           /* Now work out the sizes of individual PLT entries.  */
8796           if (htab->is_vxworks && info->shared)
8797             htab->plt_mips_entry_size
8798               = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
8799           else if (htab->is_vxworks)
8800             htab->plt_mips_entry_size
8801               = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
8802           else if (newabi_p)
8803             htab->plt_mips_entry_size
8804               = 4 * ARRAY_SIZE (mips_exec_plt_entry);
8805           else if (micromips_p)
8806             {
8807               htab->plt_mips_entry_size
8808                 = 4 * ARRAY_SIZE (mips_exec_plt_entry);
8809               htab->plt_comp_entry_size
8810                 = 2 * ARRAY_SIZE (micromips_o32_exec_plt_entry);
8811             }
8812           else
8813             {
8814               htab->plt_mips_entry_size
8815                 = 4 * ARRAY_SIZE (mips_exec_plt_entry);
8816               htab->plt_comp_entry_size
8817                 = 2 * ARRAY_SIZE (mips16_o32_exec_plt_entry);
8818             }
8819         }
8820
8821       if (h->plt.plist == NULL)
8822         h->plt.plist = mips_elf_make_plt_record (dynobj);
8823       if (h->plt.plist == NULL)
8824         return FALSE;
8825
8826       /* There are no defined MIPS16 or microMIPS PLT entries for VxWorks,
8827          n32 or n64, so always use a standard entry there.
8828
8829          If the symbol has a MIPS16 call stub and gets a PLT entry, then
8830          all MIPS16 calls will go via that stub, and there is no benefit
8831          to having a MIPS16 entry.  And in the case of call_stub a
8832          standard entry actually has to be used as the stub ends with a J
8833          instruction.  */
8834       if (newabi_p
8835           || htab->is_vxworks
8836           || hmips->call_stub
8837           || hmips->call_fp_stub)
8838         {
8839           h->plt.plist->need_mips = TRUE;
8840           h->plt.plist->need_comp = FALSE;
8841         }
8842
8843       /* Otherwise, if there are no direct calls to the function, we
8844          have a free choice of whether to use standard or compressed
8845          entries.  Prefer microMIPS entries if the object is known to
8846          contain microMIPS code, so that it becomes possible to create
8847          pure microMIPS binaries.  Prefer standard entries otherwise,
8848          because MIPS16 ones are no smaller and are usually slower.  */
8849       if (!h->plt.plist->need_mips && !h->plt.plist->need_comp)
8850         {
8851           if (micromips_p)
8852             h->plt.plist->need_comp = TRUE;
8853           else
8854             h->plt.plist->need_mips = TRUE;
8855         }
8856
8857       if (h->plt.plist->need_mips)
8858         {
8859           h->plt.plist->mips_offset = htab->plt_mips_offset;
8860           htab->plt_mips_offset += htab->plt_mips_entry_size;
8861         }
8862       if (h->plt.plist->need_comp)
8863         {
8864           h->plt.plist->comp_offset = htab->plt_comp_offset;
8865           htab->plt_comp_offset += htab->plt_comp_entry_size;
8866         }
8867
8868       /* Reserve the corresponding .got.plt entry now too.  */
8869       h->plt.plist->gotplt_index = htab->plt_got_index++;
8870
8871       /* If the output file has no definition of the symbol, set the
8872          symbol's value to the address of the stub.  */
8873       if (!info->shared && !h->def_regular)
8874         hmips->use_plt_entry = TRUE;
8875
8876       /* Make room for the R_MIPS_JUMP_SLOT relocation.  */
8877       htab->srelplt->size += (htab->is_vxworks
8878                               ? MIPS_ELF_RELA_SIZE (dynobj)
8879                               : MIPS_ELF_REL_SIZE (dynobj));
8880
8881       /* Make room for the .rela.plt.unloaded relocations.  */
8882       if (htab->is_vxworks && !info->shared)
8883         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
8884
8885       /* All relocations against this symbol that could have been made
8886          dynamic will now refer to the PLT entry instead.  */
8887       hmips->possibly_dynamic_relocs = 0;
8888
8889       return TRUE;
8890     }
8891
8892   /* If this is a weak symbol, and there is a real definition, the
8893      processor independent code will have arranged for us to see the
8894      real definition first, and we can just use the same value.  */
8895   if (h->u.weakdef != NULL)
8896     {
8897       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
8898                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
8899       h->root.u.def.section = h->u.weakdef->root.u.def.section;
8900       h->root.u.def.value = h->u.weakdef->root.u.def.value;
8901       return TRUE;
8902     }
8903
8904   /* Otherwise, there is nothing further to do for symbols defined
8905      in regular objects.  */
8906   if (h->def_regular)
8907     return TRUE;
8908
8909   /* There's also nothing more to do if we'll convert all relocations
8910      against this symbol into dynamic relocations.  */
8911   if (!hmips->has_static_relocs)
8912     return TRUE;
8913
8914   /* We're now relying on copy relocations.  Complain if we have
8915      some that we can't convert.  */
8916   if (!htab->use_plts_and_copy_relocs || info->shared)
8917     {
8918       (*_bfd_error_handler) (_("non-dynamic relocations refer to "
8919                                "dynamic symbol %s"),
8920                              h->root.root.string);
8921       bfd_set_error (bfd_error_bad_value);
8922       return FALSE;
8923     }
8924
8925   /* We must allocate the symbol in our .dynbss section, which will
8926      become part of the .bss section of the executable.  There will be
8927      an entry for this symbol in the .dynsym section.  The dynamic
8928      object will contain position independent code, so all references
8929      from the dynamic object to this symbol will go through the global
8930      offset table.  The dynamic linker will use the .dynsym entry to
8931      determine the address it must put in the global offset table, so
8932      both the dynamic object and the regular object will refer to the
8933      same memory location for the variable.  */
8934
8935   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
8936     {
8937       if (htab->is_vxworks)
8938         htab->srelbss->size += sizeof (Elf32_External_Rela);
8939       else
8940         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8941       h->needs_copy = 1;
8942     }
8943
8944   /* All relocations against this symbol that could have been made
8945      dynamic will now refer to the local copy instead.  */
8946   hmips->possibly_dynamic_relocs = 0;
8947
8948   return _bfd_elf_adjust_dynamic_copy (h, htab->sdynbss);
8949 }
8950 \f
8951 /* This function is called after all the input files have been read,
8952    and the input sections have been assigned to output sections.  We
8953    check for any mips16 stub sections that we can discard.  */
8954
8955 bfd_boolean
8956 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
8957                                     struct bfd_link_info *info)
8958 {
8959   asection *ri;
8960   struct mips_elf_link_hash_table *htab;
8961   struct mips_htab_traverse_info hti;
8962
8963   htab = mips_elf_hash_table (info);
8964   BFD_ASSERT (htab != NULL);
8965
8966   /* The .reginfo section has a fixed size.  */
8967   ri = bfd_get_section_by_name (output_bfd, ".reginfo");
8968   if (ri != NULL)
8969     bfd_set_section_size (output_bfd, ri, sizeof (Elf32_External_RegInfo));
8970
8971   hti.info = info;
8972   hti.output_bfd = output_bfd;
8973   hti.error = FALSE;
8974   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
8975                                mips_elf_check_symbols, &hti);
8976   if (hti.error)
8977     return FALSE;
8978
8979   return TRUE;
8980 }
8981
8982 /* If the link uses a GOT, lay it out and work out its size.  */
8983
8984 static bfd_boolean
8985 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
8986 {
8987   bfd *dynobj;
8988   asection *s;
8989   struct mips_got_info *g;
8990   bfd_size_type loadable_size = 0;
8991   bfd_size_type page_gotno;
8992   bfd *ibfd;
8993   struct mips_elf_traverse_got_arg tga;
8994   struct mips_elf_link_hash_table *htab;
8995
8996   htab = mips_elf_hash_table (info);
8997   BFD_ASSERT (htab != NULL);
8998
8999   s = htab->sgot;
9000   if (s == NULL)
9001     return TRUE;
9002
9003   dynobj = elf_hash_table (info)->dynobj;
9004   g = htab->got_info;
9005
9006   /* Allocate room for the reserved entries.  VxWorks always reserves
9007      3 entries; other objects only reserve 2 entries.  */
9008   BFD_ASSERT (g->assigned_gotno == 0);
9009   if (htab->is_vxworks)
9010     htab->reserved_gotno = 3;
9011   else
9012     htab->reserved_gotno = 2;
9013   g->local_gotno += htab->reserved_gotno;
9014   g->assigned_gotno = htab->reserved_gotno;
9015
9016   /* Decide which symbols need to go in the global part of the GOT and
9017      count the number of reloc-only GOT symbols.  */
9018   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
9019
9020   if (!mips_elf_resolve_final_got_entries (info, g))
9021     return FALSE;
9022
9023   /* Calculate the total loadable size of the output.  That
9024      will give us the maximum number of GOT_PAGE entries
9025      required.  */
9026   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
9027     {
9028       asection *subsection;
9029
9030       for (subsection = ibfd->sections;
9031            subsection;
9032            subsection = subsection->next)
9033         {
9034           if ((subsection->flags & SEC_ALLOC) == 0)
9035             continue;
9036           loadable_size += ((subsection->size + 0xf)
9037                             &~ (bfd_size_type) 0xf);
9038         }
9039     }
9040
9041   if (htab->is_vxworks)
9042     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
9043        relocations against local symbols evaluate to "G", and the EABI does
9044        not include R_MIPS_GOT_PAGE.  */
9045     page_gotno = 0;
9046   else
9047     /* Assume there are two loadable segments consisting of contiguous
9048        sections.  Is 5 enough?  */
9049     page_gotno = (loadable_size >> 16) + 5;
9050
9051   /* Choose the smaller of the two page estimates; both are intended to be
9052      conservative.  */
9053   if (page_gotno > g->page_gotno)
9054     page_gotno = g->page_gotno;
9055
9056   g->local_gotno += page_gotno;
9057
9058   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
9059   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
9060   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
9061
9062   /* VxWorks does not support multiple GOTs.  It initializes $gp to
9063      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
9064      dynamic loader.  */
9065   if (!htab->is_vxworks && s->size > MIPS_ELF_GOT_MAX_SIZE (info))
9066     {
9067       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
9068         return FALSE;
9069     }
9070   else
9071     {
9072       /* Record that all bfds use G.  This also has the effect of freeing
9073          the per-bfd GOTs, which we no longer need.  */
9074       for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
9075         if (mips_elf_bfd_got (ibfd, FALSE))
9076           mips_elf_replace_bfd_got (ibfd, g);
9077       mips_elf_replace_bfd_got (output_bfd, g);
9078
9079       /* Set up TLS entries.  */
9080       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
9081       tga.info = info;
9082       tga.g = g;
9083       tga.value = MIPS_ELF_GOT_SIZE (output_bfd);
9084       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
9085       if (!tga.g)
9086         return FALSE;
9087       BFD_ASSERT (g->tls_assigned_gotno
9088                   == g->global_gotno + g->local_gotno + g->tls_gotno);
9089
9090       /* Each VxWorks GOT entry needs an explicit relocation.  */
9091       if (htab->is_vxworks && info->shared)
9092         g->relocs += g->global_gotno + g->local_gotno - htab->reserved_gotno;
9093
9094       /* Allocate room for the TLS relocations.  */
9095       if (g->relocs)
9096         mips_elf_allocate_dynamic_relocations (dynobj, info, g->relocs);
9097     }
9098
9099   return TRUE;
9100 }
9101
9102 /* Estimate the size of the .MIPS.stubs section.  */
9103
9104 static void
9105 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
9106 {
9107   struct mips_elf_link_hash_table *htab;
9108   bfd_size_type dynsymcount;
9109
9110   htab = mips_elf_hash_table (info);
9111   BFD_ASSERT (htab != NULL);
9112
9113   if (htab->lazy_stub_count == 0)
9114     return;
9115
9116   /* IRIX rld assumes that a function stub isn't at the end of the .text
9117      section, so add a dummy entry to the end.  */
9118   htab->lazy_stub_count++;
9119
9120   /* Get a worst-case estimate of the number of dynamic symbols needed.
9121      At this point, dynsymcount does not account for section symbols
9122      and count_section_dynsyms may overestimate the number that will
9123      be needed.  */
9124   dynsymcount = (elf_hash_table (info)->dynsymcount
9125                  + count_section_dynsyms (output_bfd, info));
9126
9127   /* Determine the size of one stub entry.  There's no disadvantage
9128      from using microMIPS code here, so for the sake of pure-microMIPS
9129      binaries we prefer it whenever there's any microMIPS code in
9130      output produced at all.  This has a benefit of stubs being
9131      shorter by 4 bytes each too.  */
9132   if (MICROMIPS_P (output_bfd))
9133     htab->function_stub_size = (dynsymcount > 0x10000
9134                                 ? MICROMIPS_FUNCTION_STUB_BIG_SIZE
9135                                 : MICROMIPS_FUNCTION_STUB_NORMAL_SIZE);
9136   else
9137     htab->function_stub_size = (dynsymcount > 0x10000
9138                                 ? MIPS_FUNCTION_STUB_BIG_SIZE
9139                                 : MIPS_FUNCTION_STUB_NORMAL_SIZE);
9140
9141   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
9142 }
9143
9144 /* A mips_elf_link_hash_traverse callback for which DATA points to a
9145    mips_htab_traverse_info.  If H needs a traditional MIPS lazy-binding
9146    stub, allocate an entry in the stubs section.  */
9147
9148 static bfd_boolean
9149 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void *data)
9150 {
9151   struct mips_htab_traverse_info *hti = data;
9152   struct mips_elf_link_hash_table *htab;
9153   struct bfd_link_info *info;
9154   bfd *output_bfd;
9155
9156   info = hti->info;
9157   output_bfd = hti->output_bfd;
9158   htab = mips_elf_hash_table (info);
9159   BFD_ASSERT (htab != NULL);
9160
9161   if (h->needs_lazy_stub)
9162     {
9163       bfd_boolean micromips_p = MICROMIPS_P (output_bfd);
9164       unsigned int other = micromips_p ? STO_MICROMIPS : 0;
9165       bfd_vma isa_bit = micromips_p;
9166
9167       BFD_ASSERT (htab->root.dynobj != NULL);
9168       if (h->root.plt.plist == NULL)
9169         h->root.plt.plist = mips_elf_make_plt_record (htab->sstubs->owner);
9170       if (h->root.plt.plist == NULL)
9171         {
9172           hti->error = TRUE;
9173           return FALSE;
9174         }
9175       h->root.root.u.def.section = htab->sstubs;
9176       h->root.root.u.def.value = htab->sstubs->size + isa_bit;
9177       h->root.plt.plist->stub_offset = htab->sstubs->size;
9178       h->root.other = other;
9179       htab->sstubs->size += htab->function_stub_size;
9180     }
9181   return TRUE;
9182 }
9183
9184 /* Allocate offsets in the stubs section to each symbol that needs one.
9185    Set the final size of the .MIPS.stub section.  */
9186
9187 static bfd_boolean
9188 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
9189 {
9190   bfd *output_bfd = info->output_bfd;
9191   bfd_boolean micromips_p = MICROMIPS_P (output_bfd);
9192   unsigned int other = micromips_p ? STO_MICROMIPS : 0;
9193   bfd_vma isa_bit = micromips_p;
9194   struct mips_elf_link_hash_table *htab;
9195   struct mips_htab_traverse_info hti;
9196   struct elf_link_hash_entry *h;
9197   bfd *dynobj;
9198
9199   htab = mips_elf_hash_table (info);
9200   BFD_ASSERT (htab != NULL);
9201
9202   if (htab->lazy_stub_count == 0)
9203     return TRUE;
9204
9205   htab->sstubs->size = 0;
9206   hti.info = info;
9207   hti.output_bfd = output_bfd;
9208   hti.error = FALSE;
9209   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, &hti);
9210   if (hti.error)
9211     return FALSE;
9212   htab->sstubs->size += htab->function_stub_size;
9213   BFD_ASSERT (htab->sstubs->size
9214               == htab->lazy_stub_count * htab->function_stub_size);
9215
9216   dynobj = elf_hash_table (info)->dynobj;
9217   BFD_ASSERT (dynobj != NULL);
9218   h = _bfd_elf_define_linkage_sym (dynobj, info, htab->sstubs, "_MIPS_STUBS_");
9219   if (h == NULL)
9220     return FALSE;
9221   h->root.u.def.value = isa_bit;
9222   h->other = other;
9223   h->type = STT_FUNC;
9224
9225   return TRUE;
9226 }
9227
9228 /* A mips_elf_link_hash_traverse callback for which DATA points to a
9229    bfd_link_info.  If H uses the address of a PLT entry as the value
9230    of the symbol, then set the entry in the symbol table now.  Prefer
9231    a standard MIPS PLT entry.  */
9232
9233 static bfd_boolean
9234 mips_elf_set_plt_sym_value (struct mips_elf_link_hash_entry *h, void *data)
9235 {
9236   struct bfd_link_info *info = data;
9237   bfd_boolean micromips_p = MICROMIPS_P (info->output_bfd);
9238   struct mips_elf_link_hash_table *htab;
9239   unsigned int other;
9240   bfd_vma isa_bit;
9241   bfd_vma val;
9242
9243   htab = mips_elf_hash_table (info);
9244   BFD_ASSERT (htab != NULL);
9245
9246   if (h->use_plt_entry)
9247     {
9248       BFD_ASSERT (h->root.plt.plist != NULL);
9249       BFD_ASSERT (h->root.plt.plist->mips_offset != MINUS_ONE
9250                   || h->root.plt.plist->comp_offset != MINUS_ONE);
9251
9252       val = htab->plt_header_size;
9253       if (h->root.plt.plist->mips_offset != MINUS_ONE)
9254         {
9255           isa_bit = 0;
9256           val += h->root.plt.plist->mips_offset;
9257           other = 0;
9258         }
9259       else
9260         {
9261           isa_bit = 1;
9262           val += htab->plt_mips_offset + h->root.plt.plist->comp_offset;
9263           other = micromips_p ? STO_MICROMIPS : STO_MIPS16;
9264         }
9265       val += isa_bit;
9266       /* For VxWorks, point at the PLT load stub rather than the lazy
9267          resolution stub; this stub will become the canonical function
9268          address.  */
9269       if (htab->is_vxworks)
9270         val += 8;
9271
9272       h->root.root.u.def.section = htab->splt;
9273       h->root.root.u.def.value = val;
9274       h->root.other = other;
9275     }
9276
9277   return TRUE;
9278 }
9279
9280 /* Set the sizes of the dynamic sections.  */
9281
9282 bfd_boolean
9283 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
9284                                      struct bfd_link_info *info)
9285 {
9286   bfd *dynobj;
9287   asection *s, *sreldyn;
9288   bfd_boolean reltext;
9289   struct mips_elf_link_hash_table *htab;
9290
9291   htab = mips_elf_hash_table (info);
9292   BFD_ASSERT (htab != NULL);
9293   dynobj = elf_hash_table (info)->dynobj;
9294   BFD_ASSERT (dynobj != NULL);
9295
9296   if (elf_hash_table (info)->dynamic_sections_created)
9297     {
9298       /* Set the contents of the .interp section to the interpreter.  */
9299       if (info->executable)
9300         {
9301           s = bfd_get_linker_section (dynobj, ".interp");
9302           BFD_ASSERT (s != NULL);
9303           s->size
9304             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
9305           s->contents
9306             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
9307         }
9308
9309       /* Figure out the size of the PLT header if we know that we
9310          are using it.  For the sake of cache alignment always use
9311          a standard header whenever any standard entries are present
9312          even if microMIPS entries are present as well.  This also
9313          lets the microMIPS header rely on the value of $v0 only set
9314          by microMIPS entries, for a small size reduction.
9315
9316          Set symbol table entry values for symbols that use the
9317          address of their PLT entry now that we can calculate it.
9318
9319          Also create the _PROCEDURE_LINKAGE_TABLE_ symbol if we
9320          haven't already in _bfd_elf_create_dynamic_sections.  */
9321       if (htab->splt && htab->plt_mips_offset + htab->plt_comp_offset != 0)
9322         {
9323           bfd_boolean micromips_p = (MICROMIPS_P (output_bfd)
9324                                      && !htab->plt_mips_offset);
9325           unsigned int other = micromips_p ? STO_MICROMIPS : 0;
9326           bfd_vma isa_bit = micromips_p;
9327           struct elf_link_hash_entry *h;
9328           bfd_vma size;
9329
9330           BFD_ASSERT (htab->use_plts_and_copy_relocs);
9331           BFD_ASSERT (htab->sgotplt->size == 0);
9332           BFD_ASSERT (htab->splt->size == 0);
9333
9334           if (htab->is_vxworks && info->shared)
9335             size = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
9336           else if (htab->is_vxworks)
9337             size = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
9338           else if (ABI_64_P (output_bfd))
9339             size = 4 * ARRAY_SIZE (mips_n64_exec_plt0_entry);
9340           else if (ABI_N32_P (output_bfd))
9341             size = 4 * ARRAY_SIZE (mips_n32_exec_plt0_entry);
9342           else if (!micromips_p)
9343             size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
9344           else
9345             size = 2 * ARRAY_SIZE (micromips_o32_exec_plt0_entry);
9346
9347           htab->plt_header_is_comp = micromips_p;
9348           htab->plt_header_size = size;
9349           htab->splt->size = (size
9350                               + htab->plt_mips_offset
9351                               + htab->plt_comp_offset);
9352           htab->sgotplt->size = (htab->plt_got_index
9353                                  * MIPS_ELF_GOT_SIZE (dynobj));
9354
9355           mips_elf_link_hash_traverse (htab, mips_elf_set_plt_sym_value, info);
9356
9357           if (htab->root.hplt == NULL)
9358             {
9359               h = _bfd_elf_define_linkage_sym (dynobj, info, htab->splt,
9360                                                "_PROCEDURE_LINKAGE_TABLE_");
9361               htab->root.hplt = h;
9362               if (h == NULL)
9363                 return FALSE;
9364             }
9365
9366           h = htab->root.hplt;
9367           h->root.u.def.value = isa_bit;
9368           h->other = other;
9369           h->type = STT_FUNC;
9370         }
9371     }
9372
9373   /* Allocate space for global sym dynamic relocs.  */
9374   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, info);
9375
9376   mips_elf_estimate_stub_size (output_bfd, info);
9377
9378   if (!mips_elf_lay_out_got (output_bfd, info))
9379     return FALSE;
9380
9381   mips_elf_lay_out_lazy_stubs (info);
9382
9383   /* The check_relocs and adjust_dynamic_symbol entry points have
9384      determined the sizes of the various dynamic sections.  Allocate
9385      memory for them.  */
9386   reltext = FALSE;
9387   for (s = dynobj->sections; s != NULL; s = s->next)
9388     {
9389       const char *name;
9390
9391       /* It's OK to base decisions on the section name, because none
9392          of the dynobj section names depend upon the input files.  */
9393       name = bfd_get_section_name (dynobj, s);
9394
9395       if ((s->flags & SEC_LINKER_CREATED) == 0)
9396         continue;
9397
9398       if (CONST_STRNEQ (name, ".rel"))
9399         {
9400           if (s->size != 0)
9401             {
9402               const char *outname;
9403               asection *target;
9404
9405               /* If this relocation section applies to a read only
9406                  section, then we probably need a DT_TEXTREL entry.
9407                  If the relocation section is .rel(a).dyn, we always
9408                  assert a DT_TEXTREL entry rather than testing whether
9409                  there exists a relocation to a read only section or
9410                  not.  */
9411               outname = bfd_get_section_name (output_bfd,
9412                                               s->output_section);
9413               target = bfd_get_section_by_name (output_bfd, outname + 4);
9414               if ((target != NULL
9415                    && (target->flags & SEC_READONLY) != 0
9416                    && (target->flags & SEC_ALLOC) != 0)
9417                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
9418                 reltext = TRUE;
9419
9420               /* We use the reloc_count field as a counter if we need
9421                  to copy relocs into the output file.  */
9422               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
9423                 s->reloc_count = 0;
9424
9425               /* If combreloc is enabled, elf_link_sort_relocs() will
9426                  sort relocations, but in a different way than we do,
9427                  and before we're done creating relocations.  Also, it
9428                  will move them around between input sections'
9429                  relocation's contents, so our sorting would be
9430                  broken, so don't let it run.  */
9431               info->combreloc = 0;
9432             }
9433         }
9434       else if (! info->shared
9435                && ! mips_elf_hash_table (info)->use_rld_obj_head
9436                && CONST_STRNEQ (name, ".rld_map"))
9437         {
9438           /* We add a room for __rld_map.  It will be filled in by the
9439              rtld to contain a pointer to the _r_debug structure.  */
9440           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
9441         }
9442       else if (SGI_COMPAT (output_bfd)
9443                && CONST_STRNEQ (name, ".compact_rel"))
9444         s->size += mips_elf_hash_table (info)->compact_rel_size;
9445       else if (s == htab->splt)
9446         {
9447           /* If the last PLT entry has a branch delay slot, allocate
9448              room for an extra nop to fill the delay slot.  This is
9449              for CPUs without load interlocking.  */
9450           if (! LOAD_INTERLOCKS_P (output_bfd)
9451               && ! htab->is_vxworks && s->size > 0)
9452             s->size += 4;
9453         }
9454       else if (! CONST_STRNEQ (name, ".init")
9455                && s != htab->sgot
9456                && s != htab->sgotplt
9457                && s != htab->sstubs
9458                && s != htab->sdynbss)
9459         {
9460           /* It's not one of our sections, so don't allocate space.  */
9461           continue;
9462         }
9463
9464       if (s->size == 0)
9465         {
9466           s->flags |= SEC_EXCLUDE;
9467           continue;
9468         }
9469
9470       if ((s->flags & SEC_HAS_CONTENTS) == 0)
9471         continue;
9472
9473       /* Allocate memory for the section contents.  */
9474       s->contents = bfd_zalloc (dynobj, s->size);
9475       if (s->contents == NULL)
9476         {
9477           bfd_set_error (bfd_error_no_memory);
9478           return FALSE;
9479         }
9480     }
9481
9482   if (elf_hash_table (info)->dynamic_sections_created)
9483     {
9484       /* Add some entries to the .dynamic section.  We fill in the
9485          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
9486          must add the entries now so that we get the correct size for
9487          the .dynamic section.  */
9488
9489       /* SGI object has the equivalence of DT_DEBUG in the
9490          DT_MIPS_RLD_MAP entry.  This must come first because glibc
9491          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and some tools
9492          may only look at the first one they see.  */
9493       if (!info->shared
9494           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
9495         return FALSE;
9496
9497       /* The DT_DEBUG entry may be filled in by the dynamic linker and
9498          used by the debugger.  */
9499       if (info->executable
9500           && !SGI_COMPAT (output_bfd)
9501           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
9502         return FALSE;
9503
9504       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
9505         info->flags |= DF_TEXTREL;
9506
9507       if ((info->flags & DF_TEXTREL) != 0)
9508         {
9509           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
9510             return FALSE;
9511
9512           /* Clear the DF_TEXTREL flag.  It will be set again if we
9513              write out an actual text relocation; we may not, because
9514              at this point we do not know whether e.g. any .eh_frame
9515              absolute relocations have been converted to PC-relative.  */
9516           info->flags &= ~DF_TEXTREL;
9517         }
9518
9519       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
9520         return FALSE;
9521
9522       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
9523       if (htab->is_vxworks)
9524         {
9525           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
9526              use any of the DT_MIPS_* tags.  */
9527           if (sreldyn && sreldyn->size > 0)
9528             {
9529               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
9530                 return FALSE;
9531
9532               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
9533                 return FALSE;
9534
9535               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
9536                 return FALSE;
9537             }
9538         }
9539       else
9540         {
9541           if (sreldyn && sreldyn->size > 0)
9542             {
9543               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
9544                 return FALSE;
9545
9546               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
9547                 return FALSE;
9548
9549               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
9550                 return FALSE;
9551             }
9552
9553           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
9554             return FALSE;
9555
9556           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
9557             return FALSE;
9558
9559           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
9560             return FALSE;
9561
9562           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
9563             return FALSE;
9564
9565           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
9566             return FALSE;
9567
9568           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
9569             return FALSE;
9570
9571           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
9572             return FALSE;
9573
9574           if (IRIX_COMPAT (dynobj) == ict_irix5
9575               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
9576             return FALSE;
9577
9578           if (IRIX_COMPAT (dynobj) == ict_irix6
9579               && (bfd_get_section_by_name
9580                   (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
9581               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
9582             return FALSE;
9583         }
9584       if (htab->splt->size > 0)
9585         {
9586           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
9587             return FALSE;
9588
9589           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
9590             return FALSE;
9591
9592           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
9593             return FALSE;
9594
9595           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
9596             return FALSE;
9597         }
9598       if (htab->is_vxworks
9599           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
9600         return FALSE;
9601     }
9602
9603   return TRUE;
9604 }
9605 \f
9606 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
9607    Adjust its R_ADDEND field so that it is correct for the output file.
9608    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
9609    and sections respectively; both use symbol indexes.  */
9610
9611 static void
9612 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
9613                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
9614                         asection **local_sections, Elf_Internal_Rela *rel)
9615 {
9616   unsigned int r_type, r_symndx;
9617   Elf_Internal_Sym *sym;
9618   asection *sec;
9619
9620   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9621     {
9622       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9623       if (gprel16_reloc_p (r_type)
9624           || r_type == R_MIPS_GPREL32
9625           || literal_reloc_p (r_type))
9626         {
9627           rel->r_addend += _bfd_get_gp_value (input_bfd);
9628           rel->r_addend -= _bfd_get_gp_value (output_bfd);
9629         }
9630
9631       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
9632       sym = local_syms + r_symndx;
9633
9634       /* Adjust REL's addend to account for section merging.  */
9635       if (!info->relocatable)
9636         {
9637           sec = local_sections[r_symndx];
9638           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
9639         }
9640
9641       /* This would normally be done by the rela_normal code in elflink.c.  */
9642       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
9643         rel->r_addend += local_sections[r_symndx]->output_offset;
9644     }
9645 }
9646
9647 /* Handle relocations against symbols from removed linkonce sections,
9648    or sections discarded by a linker script.  We use this wrapper around
9649    RELOC_AGAINST_DISCARDED_SECTION to handle triplets of compound relocs
9650    on 64-bit ELF targets.  In this case for any relocation handled, which
9651    always be the first in a triplet, the remaining two have to be processed
9652    together with the first, even if they are R_MIPS_NONE.  It is the symbol
9653    index referred by the first reloc that applies to all the three and the
9654    remaining two never refer to an object symbol.  And it is the final
9655    relocation (the last non-null one) that determines the output field of
9656    the whole relocation so retrieve the corresponding howto structure for
9657    the relocatable field to be cleared by RELOC_AGAINST_DISCARDED_SECTION.
9658
9659    Note that RELOC_AGAINST_DISCARDED_SECTION is a macro that uses "continue"
9660    and therefore requires to be pasted in a loop.  It also defines a block
9661    and does not protect any of its arguments, hence the extra brackets.  */
9662
9663 static void
9664 mips_reloc_against_discarded_section (bfd *output_bfd,
9665                                       struct bfd_link_info *info,
9666                                       bfd *input_bfd, asection *input_section,
9667                                       Elf_Internal_Rela **rel,
9668                                       const Elf_Internal_Rela **relend,
9669                                       bfd_boolean rel_reloc,
9670                                       reloc_howto_type *howto,
9671                                       bfd_byte *contents)
9672 {
9673   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
9674   int count = bed->s->int_rels_per_ext_rel;
9675   unsigned int r_type;
9676   int i;
9677
9678   for (i = count - 1; i > 0; i--)
9679     {
9680       r_type = ELF_R_TYPE (output_bfd, (*rel)[i].r_info);
9681       if (r_type != R_MIPS_NONE)
9682         {
9683           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9684           break;
9685         }
9686     }
9687   do
9688     {
9689        RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
9690                                         (*rel), count, (*relend),
9691                                         howto, i, contents);
9692     }
9693   while (0);
9694 }
9695
9696 /* Relocate a MIPS ELF section.  */
9697
9698 bfd_boolean
9699 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
9700                                 bfd *input_bfd, asection *input_section,
9701                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
9702                                 Elf_Internal_Sym *local_syms,
9703                                 asection **local_sections)
9704 {
9705   Elf_Internal_Rela *rel;
9706   const Elf_Internal_Rela *relend;
9707   bfd_vma addend = 0;
9708   bfd_boolean use_saved_addend_p = FALSE;
9709   const struct elf_backend_data *bed;
9710
9711   bed = get_elf_backend_data (output_bfd);
9712   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
9713   for (rel = relocs; rel < relend; ++rel)
9714     {
9715       const char *name;
9716       bfd_vma value = 0;
9717       reloc_howto_type *howto;
9718       bfd_boolean cross_mode_jump_p = FALSE;
9719       /* TRUE if the relocation is a RELA relocation, rather than a
9720          REL relocation.  */
9721       bfd_boolean rela_relocation_p = TRUE;
9722       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9723       const char *msg;
9724       unsigned long r_symndx;
9725       asection *sec;
9726       Elf_Internal_Shdr *symtab_hdr;
9727       struct elf_link_hash_entry *h;
9728       bfd_boolean rel_reloc;
9729
9730       rel_reloc = (NEWABI_P (input_bfd)
9731                    && mips_elf_rel_relocation_p (input_bfd, input_section,
9732                                                  relocs, rel));
9733       /* Find the relocation howto for this relocation.  */
9734       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9735
9736       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
9737       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9738       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9739         {
9740           sec = local_sections[r_symndx];
9741           h = NULL;
9742         }
9743       else
9744         {
9745           unsigned long extsymoff;
9746
9747           extsymoff = 0;
9748           if (!elf_bad_symtab (input_bfd))
9749             extsymoff = symtab_hdr->sh_info;
9750           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
9751           while (h->root.type == bfd_link_hash_indirect
9752                  || h->root.type == bfd_link_hash_warning)
9753             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9754
9755           sec = NULL;
9756           if (h->root.type == bfd_link_hash_defined
9757               || h->root.type == bfd_link_hash_defweak)
9758             sec = h->root.u.def.section;
9759         }
9760
9761       if (sec != NULL && discarded_section (sec))
9762         {
9763           mips_reloc_against_discarded_section (output_bfd, info, input_bfd,
9764                                                 input_section, &rel, &relend,
9765                                                 rel_reloc, howto, contents);
9766           continue;
9767         }
9768
9769       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
9770         {
9771           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
9772              64-bit code, but make sure all their addresses are in the
9773              lowermost or uppermost 32-bit section of the 64-bit address
9774              space.  Thus, when they use an R_MIPS_64 they mean what is
9775              usually meant by R_MIPS_32, with the exception that the
9776              stored value is sign-extended to 64 bits.  */
9777           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
9778
9779           /* On big-endian systems, we need to lie about the position
9780              of the reloc.  */
9781           if (bfd_big_endian (input_bfd))
9782             rel->r_offset += 4;
9783         }
9784
9785       if (!use_saved_addend_p)
9786         {
9787           /* If these relocations were originally of the REL variety,
9788              we must pull the addend out of the field that will be
9789              relocated.  Otherwise, we simply use the contents of the
9790              RELA relocation.  */
9791           if (mips_elf_rel_relocation_p (input_bfd, input_section,
9792                                          relocs, rel))
9793             {
9794               rela_relocation_p = FALSE;
9795               addend = mips_elf_read_rel_addend (input_bfd, rel,
9796                                                  howto, contents);
9797               if (hi16_reloc_p (r_type)
9798                   || (got16_reloc_p (r_type)
9799                       && mips_elf_local_relocation_p (input_bfd, rel,
9800                                                       local_sections)))
9801                 {
9802                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
9803                                                      contents, &addend))
9804                     {
9805                       if (h)
9806                         name = h->root.root.string;
9807                       else
9808                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9809                                                  local_syms + r_symndx,
9810                                                  sec);
9811                       (*_bfd_error_handler)
9812                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
9813                          input_bfd, input_section, name, howto->name,
9814                          rel->r_offset);
9815                     }
9816                 }
9817               else
9818                 addend <<= howto->rightshift;
9819             }
9820           else
9821             addend = rel->r_addend;
9822           mips_elf_adjust_addend (output_bfd, info, input_bfd,
9823                                   local_syms, local_sections, rel);
9824         }
9825
9826       if (info->relocatable)
9827         {
9828           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
9829               && bfd_big_endian (input_bfd))
9830             rel->r_offset -= 4;
9831
9832           if (!rela_relocation_p && rel->r_addend)
9833             {
9834               addend += rel->r_addend;
9835               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
9836                 addend = mips_elf_high (addend);
9837               else if (r_type == R_MIPS_HIGHER)
9838                 addend = mips_elf_higher (addend);
9839               else if (r_type == R_MIPS_HIGHEST)
9840                 addend = mips_elf_highest (addend);
9841               else
9842                 addend >>= howto->rightshift;
9843
9844               /* We use the source mask, rather than the destination
9845                  mask because the place to which we are writing will be
9846                  source of the addend in the final link.  */
9847               addend &= howto->src_mask;
9848
9849               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9850                 /* See the comment above about using R_MIPS_64 in the 32-bit
9851                    ABI.  Here, we need to update the addend.  It would be
9852                    possible to get away with just using the R_MIPS_32 reloc
9853                    but for endianness.  */
9854                 {
9855                   bfd_vma sign_bits;
9856                   bfd_vma low_bits;
9857                   bfd_vma high_bits;
9858
9859                   if (addend & ((bfd_vma) 1 << 31))
9860 #ifdef BFD64
9861                     sign_bits = ((bfd_vma) 1 << 32) - 1;
9862 #else
9863                     sign_bits = -1;
9864 #endif
9865                   else
9866                     sign_bits = 0;
9867
9868                   /* If we don't know that we have a 64-bit type,
9869                      do two separate stores.  */
9870                   if (bfd_big_endian (input_bfd))
9871                     {
9872                       /* Store the sign-bits (which are most significant)
9873                          first.  */
9874                       low_bits = sign_bits;
9875                       high_bits = addend;
9876                     }
9877                   else
9878                     {
9879                       low_bits = addend;
9880                       high_bits = sign_bits;
9881                     }
9882                   bfd_put_32 (input_bfd, low_bits,
9883                               contents + rel->r_offset);
9884                   bfd_put_32 (input_bfd, high_bits,
9885                               contents + rel->r_offset + 4);
9886                   continue;
9887                 }
9888
9889               if (! mips_elf_perform_relocation (info, howto, rel, addend,
9890                                                  input_bfd, input_section,
9891                                                  contents, FALSE))
9892                 return FALSE;
9893             }
9894
9895           /* Go on to the next relocation.  */
9896           continue;
9897         }
9898
9899       /* In the N32 and 64-bit ABIs there may be multiple consecutive
9900          relocations for the same offset.  In that case we are
9901          supposed to treat the output of each relocation as the addend
9902          for the next.  */
9903       if (rel + 1 < relend
9904           && rel->r_offset == rel[1].r_offset
9905           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
9906         use_saved_addend_p = TRUE;
9907       else
9908         use_saved_addend_p = FALSE;
9909
9910       /* Figure out what value we are supposed to relocate.  */
9911       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
9912                                              input_section, info, rel,
9913                                              addend, howto, local_syms,
9914                                              local_sections, &value,
9915                                              &name, &cross_mode_jump_p,
9916                                              use_saved_addend_p))
9917         {
9918         case bfd_reloc_continue:
9919           /* There's nothing to do.  */
9920           continue;
9921
9922         case bfd_reloc_undefined:
9923           /* mips_elf_calculate_relocation already called the
9924              undefined_symbol callback.  There's no real point in
9925              trying to perform the relocation at this point, so we
9926              just skip ahead to the next relocation.  */
9927           continue;
9928
9929         case bfd_reloc_notsupported:
9930           msg = _("internal error: unsupported relocation error");
9931           info->callbacks->warning
9932             (info, msg, name, input_bfd, input_section, rel->r_offset);
9933           return FALSE;
9934
9935         case bfd_reloc_overflow:
9936           if (use_saved_addend_p)
9937             /* Ignore overflow until we reach the last relocation for
9938                a given location.  */
9939             ;
9940           else
9941             {
9942               struct mips_elf_link_hash_table *htab;
9943
9944               htab = mips_elf_hash_table (info);
9945               BFD_ASSERT (htab != NULL);
9946               BFD_ASSERT (name != NULL);
9947               if (!htab->small_data_overflow_reported
9948                   && (gprel16_reloc_p (howto->type)
9949                       || literal_reloc_p (howto->type)))
9950                 {
9951                   msg = _("small-data section exceeds 64KB;"
9952                           " lower small-data size limit (see option -G)");
9953
9954                   htab->small_data_overflow_reported = TRUE;
9955                   (*info->callbacks->einfo) ("%P: %s\n", msg);
9956                 }
9957               if (! ((*info->callbacks->reloc_overflow)
9958                      (info, NULL, name, howto->name, (bfd_vma) 0,
9959                       input_bfd, input_section, rel->r_offset)))
9960                 return FALSE;
9961             }
9962           break;
9963
9964         case bfd_reloc_ok:
9965           break;
9966
9967         case bfd_reloc_outofrange:
9968           if (jal_reloc_p (howto->type))
9969             {
9970               msg = _("JALX to a non-word-aligned address");
9971               info->callbacks->warning
9972                 (info, msg, name, input_bfd, input_section, rel->r_offset);
9973               return FALSE;
9974             }
9975           /* Fall through.  */
9976
9977         default:
9978           abort ();
9979           break;
9980         }
9981
9982       /* If we've got another relocation for the address, keep going
9983          until we reach the last one.  */
9984       if (use_saved_addend_p)
9985         {
9986           addend = value;
9987           continue;
9988         }
9989
9990       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9991         /* See the comment above about using R_MIPS_64 in the 32-bit
9992            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
9993            that calculated the right value.  Now, however, we
9994            sign-extend the 32-bit result to 64-bits, and store it as a
9995            64-bit value.  We are especially generous here in that we
9996            go to extreme lengths to support this usage on systems with
9997            only a 32-bit VMA.  */
9998         {
9999           bfd_vma sign_bits;
10000           bfd_vma low_bits;
10001           bfd_vma high_bits;
10002
10003           if (value & ((bfd_vma) 1 << 31))
10004 #ifdef BFD64
10005             sign_bits = ((bfd_vma) 1 << 32) - 1;
10006 #else
10007             sign_bits = -1;
10008 #endif
10009           else
10010             sign_bits = 0;
10011
10012           /* If we don't know that we have a 64-bit type,
10013              do two separate stores.  */
10014           if (bfd_big_endian (input_bfd))
10015             {
10016               /* Undo what we did above.  */
10017               rel->r_offset -= 4;
10018               /* Store the sign-bits (which are most significant)
10019                  first.  */
10020               low_bits = sign_bits;
10021               high_bits = value;
10022             }
10023           else
10024             {
10025               low_bits = value;
10026               high_bits = sign_bits;
10027             }
10028           bfd_put_32 (input_bfd, low_bits,
10029                       contents + rel->r_offset);
10030           bfd_put_32 (input_bfd, high_bits,
10031                       contents + rel->r_offset + 4);
10032           continue;
10033         }
10034
10035       /* Actually perform the relocation.  */
10036       if (! mips_elf_perform_relocation (info, howto, rel, value,
10037                                          input_bfd, input_section,
10038                                          contents, cross_mode_jump_p))
10039         return FALSE;
10040     }
10041
10042   return TRUE;
10043 }
10044 \f
10045 /* A function that iterates over each entry in la25_stubs and fills
10046    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
10047
10048 static int
10049 mips_elf_create_la25_stub (void **slot, void *data)
10050 {
10051   struct mips_htab_traverse_info *hti;
10052   struct mips_elf_link_hash_table *htab;
10053   struct mips_elf_la25_stub *stub;
10054   asection *s;
10055   bfd_byte *loc;
10056   bfd_vma offset, target, target_high, target_low;
10057
10058   stub = (struct mips_elf_la25_stub *) *slot;
10059   hti = (struct mips_htab_traverse_info *) data;
10060   htab = mips_elf_hash_table (hti->info);
10061   BFD_ASSERT (htab != NULL);
10062
10063   /* Create the section contents, if we haven't already.  */
10064   s = stub->stub_section;
10065   loc = s->contents;
10066   if (loc == NULL)
10067     {
10068       loc = bfd_malloc (s->size);
10069       if (loc == NULL)
10070         {
10071           hti->error = TRUE;
10072           return FALSE;
10073         }
10074       s->contents = loc;
10075     }
10076
10077   /* Work out where in the section this stub should go.  */
10078   offset = stub->offset;
10079
10080   /* Work out the target address.  */
10081   target = mips_elf_get_la25_target (stub, &s);
10082   target += s->output_section->vma + s->output_offset;
10083
10084   target_high = ((target + 0x8000) >> 16) & 0xffff;
10085   target_low = (target & 0xffff);
10086
10087   if (stub->stub_section != htab->strampoline)
10088     {
10089       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
10090          of the section and write the two instructions at the end.  */
10091       memset (loc, 0, offset);
10092       loc += offset;
10093       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
10094         {
10095           bfd_put_micromips_32 (hti->output_bfd,
10096                                 LA25_LUI_MICROMIPS (target_high),
10097                                 loc);
10098           bfd_put_micromips_32 (hti->output_bfd,
10099                                 LA25_ADDIU_MICROMIPS (target_low),
10100                                 loc + 4);
10101         }
10102       else
10103         {
10104           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
10105           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
10106         }
10107     }
10108   else
10109     {
10110       /* This is trampoline.  */
10111       loc += offset;
10112       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
10113         {
10114           bfd_put_micromips_32 (hti->output_bfd,
10115                                 LA25_LUI_MICROMIPS (target_high), loc);
10116           bfd_put_micromips_32 (hti->output_bfd,
10117                                 LA25_J_MICROMIPS (target), loc + 4);
10118           bfd_put_micromips_32 (hti->output_bfd,
10119                                 LA25_ADDIU_MICROMIPS (target_low), loc + 8);
10120           bfd_put_32 (hti->output_bfd, 0, loc + 12);
10121         }
10122       else
10123         {
10124           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
10125           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
10126           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
10127           bfd_put_32 (hti->output_bfd, 0, loc + 12);
10128         }
10129     }
10130   return TRUE;
10131 }
10132
10133 /* If NAME is one of the special IRIX6 symbols defined by the linker,
10134    adjust it appropriately now.  */
10135
10136 static void
10137 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
10138                                       const char *name, Elf_Internal_Sym *sym)
10139 {
10140   /* The linker script takes care of providing names and values for
10141      these, but we must place them into the right sections.  */
10142   static const char* const text_section_symbols[] = {
10143     "_ftext",
10144     "_etext",
10145     "__dso_displacement",
10146     "__elf_header",
10147     "__program_header_table",
10148     NULL
10149   };
10150
10151   static const char* const data_section_symbols[] = {
10152     "_fdata",
10153     "_edata",
10154     "_end",
10155     "_fbss",
10156     NULL
10157   };
10158
10159   const char* const *p;
10160   int i;
10161
10162   for (i = 0; i < 2; ++i)
10163     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
10164          *p;
10165          ++p)
10166       if (strcmp (*p, name) == 0)
10167         {
10168           /* All of these symbols are given type STT_SECTION by the
10169              IRIX6 linker.  */
10170           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10171           sym->st_other = STO_PROTECTED;
10172
10173           /* The IRIX linker puts these symbols in special sections.  */
10174           if (i == 0)
10175             sym->st_shndx = SHN_MIPS_TEXT;
10176           else
10177             sym->st_shndx = SHN_MIPS_DATA;
10178
10179           break;
10180         }
10181 }
10182
10183 /* Finish up dynamic symbol handling.  We set the contents of various
10184    dynamic sections here.  */
10185
10186 bfd_boolean
10187 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
10188                                      struct bfd_link_info *info,
10189                                      struct elf_link_hash_entry *h,
10190                                      Elf_Internal_Sym *sym)
10191 {
10192   bfd *dynobj;
10193   asection *sgot;
10194   struct mips_got_info *g, *gg;
10195   const char *name;
10196   int idx;
10197   struct mips_elf_link_hash_table *htab;
10198   struct mips_elf_link_hash_entry *hmips;
10199
10200   htab = mips_elf_hash_table (info);
10201   BFD_ASSERT (htab != NULL);
10202   dynobj = elf_hash_table (info)->dynobj;
10203   hmips = (struct mips_elf_link_hash_entry *) h;
10204
10205   BFD_ASSERT (!htab->is_vxworks);
10206
10207   if (h->plt.plist != NULL
10208       && (h->plt.plist->mips_offset != MINUS_ONE
10209           || h->plt.plist->comp_offset != MINUS_ONE))
10210     {
10211       /* We've decided to create a PLT entry for this symbol.  */
10212       bfd_byte *loc;
10213       bfd_vma header_address, got_address;
10214       bfd_vma got_address_high, got_address_low, load;
10215       bfd_vma got_index;
10216       bfd_vma isa_bit;
10217
10218       got_index = h->plt.plist->gotplt_index;
10219
10220       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10221       BFD_ASSERT (h->dynindx != -1);
10222       BFD_ASSERT (htab->splt != NULL);
10223       BFD_ASSERT (got_index != MINUS_ONE);
10224       BFD_ASSERT (!h->def_regular);
10225
10226       /* Calculate the address of the PLT header.  */
10227       isa_bit = htab->plt_header_is_comp;
10228       header_address = (htab->splt->output_section->vma
10229                         + htab->splt->output_offset + isa_bit);
10230
10231       /* Calculate the address of the .got.plt entry.  */
10232       got_address = (htab->sgotplt->output_section->vma
10233                      + htab->sgotplt->output_offset
10234                      + got_index * MIPS_ELF_GOT_SIZE (dynobj));
10235
10236       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10237       got_address_low = got_address & 0xffff;
10238
10239       /* Initially point the .got.plt entry at the PLT header.  */
10240       loc = (htab->sgotplt->contents + got_index * MIPS_ELF_GOT_SIZE (dynobj));
10241       if (ABI_64_P (output_bfd))
10242         bfd_put_64 (output_bfd, header_address, loc);
10243       else
10244         bfd_put_32 (output_bfd, header_address, loc);
10245
10246       /* Now handle the PLT itself.  First the standard entry (the order
10247          does not matter, we just have to pick one).  */
10248       if (h->plt.plist->mips_offset != MINUS_ONE)
10249         {
10250           const bfd_vma *plt_entry;
10251           bfd_vma plt_offset;
10252
10253           plt_offset = htab->plt_header_size + h->plt.plist->mips_offset;
10254
10255           BFD_ASSERT (plt_offset <= htab->splt->size);
10256
10257           /* Find out where the .plt entry should go.  */
10258           loc = htab->splt->contents + plt_offset;
10259
10260           /* Pick the load opcode.  */
10261           load = MIPS_ELF_LOAD_WORD (output_bfd);
10262
10263           /* Fill in the PLT entry itself.  */
10264           plt_entry = mips_exec_plt_entry;
10265           bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
10266           bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load,
10267                       loc + 4);
10268
10269           if (! LOAD_INTERLOCKS_P (output_bfd))
10270             {
10271               bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
10272               bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10273             }
10274           else
10275             {
10276               bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
10277               bfd_put_32 (output_bfd, plt_entry[2] | got_address_low,
10278                           loc + 12);
10279             }
10280         }
10281
10282       /* Now the compressed entry.  They come after any standard ones.  */
10283       if (h->plt.plist->comp_offset != MINUS_ONE)
10284         {
10285           bfd_vma plt_offset;
10286
10287           plt_offset = (htab->plt_header_size + htab->plt_mips_offset
10288                         + h->plt.plist->comp_offset);
10289
10290           BFD_ASSERT (plt_offset <= htab->splt->size);
10291
10292           /* Find out where the .plt entry should go.  */
10293           loc = htab->splt->contents + plt_offset;
10294
10295           /* Fill in the PLT entry itself.  */
10296           if (MICROMIPS_P (output_bfd))
10297             {
10298               const bfd_vma *plt_entry = micromips_o32_exec_plt_entry;
10299               bfd_signed_vma gotpc_offset;
10300               bfd_vma loc_address;
10301
10302               BFD_ASSERT (got_address % 4 == 0);
10303
10304               loc_address = (htab->splt->output_section->vma
10305                              + htab->splt->output_offset + plt_offset);
10306               gotpc_offset = got_address - ((loc_address | 3) ^ 3);
10307
10308               /* ADDIUPC has a span of +/-16MB, check we're in range.  */
10309               if (gotpc_offset + 0x1000000 >= 0x2000000)
10310                 {
10311                   (*_bfd_error_handler)
10312                     (_("%B: `%A' offset of %ld from `%A' "
10313                        "beyond the range of ADDIUPC"),
10314                      output_bfd,
10315                      htab->sgotplt->output_section,
10316                      htab->splt->output_section,
10317                      (long) gotpc_offset);
10318                   bfd_set_error (bfd_error_no_error);
10319                   return FALSE;
10320                 }
10321               bfd_put_16 (output_bfd,
10322                           plt_entry[0] | ((gotpc_offset >> 18) & 0x7f), loc);
10323               bfd_put_16 (output_bfd, (gotpc_offset >> 2) & 0xffff, loc + 2);
10324               bfd_put_16 (output_bfd, plt_entry[2], loc + 4);
10325               bfd_put_16 (output_bfd, plt_entry[3], loc + 6);
10326               bfd_put_16 (output_bfd, plt_entry[4], loc + 8);
10327               bfd_put_16 (output_bfd, plt_entry[5], loc + 10);
10328             }
10329           else
10330             {
10331               const bfd_vma *plt_entry = mips16_o32_exec_plt_entry;
10332
10333               bfd_put_16 (output_bfd, plt_entry[0], loc);
10334               bfd_put_16 (output_bfd, plt_entry[1], loc + 2);
10335               bfd_put_16 (output_bfd, plt_entry[2], loc + 4);
10336               bfd_put_16 (output_bfd, plt_entry[3], loc + 6);
10337               bfd_put_16 (output_bfd, plt_entry[4], loc + 8);
10338               bfd_put_16 (output_bfd, plt_entry[5], loc + 10);
10339               bfd_put_32 (output_bfd, got_address, loc + 12);
10340             }
10341         }
10342
10343       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10344       mips_elf_output_dynamic_relocation (output_bfd, htab->srelplt,
10345                                           got_index - 2, h->dynindx,
10346                                           R_MIPS_JUMP_SLOT, got_address);
10347
10348       /* We distinguish between PLT entries and lazy-binding stubs by
10349          giving the former an st_other value of STO_MIPS_PLT.  Set the
10350          flag and leave the value if there are any relocations in the
10351          binary where pointer equality matters.  */
10352       sym->st_shndx = SHN_UNDEF;
10353       if (h->pointer_equality_needed)
10354         sym->st_other = ELF_ST_SET_MIPS_PLT (sym->st_other);
10355       else
10356         {
10357           sym->st_value = 0;
10358           sym->st_other = 0;
10359         }
10360     }
10361
10362   if (h->plt.plist != NULL && h->plt.plist->stub_offset != MINUS_ONE)
10363     {
10364       /* We've decided to create a lazy-binding stub.  */
10365       bfd_boolean micromips_p = MICROMIPS_P (output_bfd);
10366       unsigned int other = micromips_p ? STO_MICROMIPS : 0;
10367       bfd_vma stub_size = htab->function_stub_size;
10368       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
10369       bfd_vma isa_bit = micromips_p;
10370       bfd_vma stub_big_size;
10371
10372       if (micromips_p)
10373         stub_big_size = MICROMIPS_FUNCTION_STUB_BIG_SIZE;
10374       else
10375         stub_big_size = MIPS_FUNCTION_STUB_BIG_SIZE;
10376
10377       /* This symbol has a stub.  Set it up.  */
10378
10379       BFD_ASSERT (h->dynindx != -1);
10380
10381       BFD_ASSERT (stub_size == stub_big_size || h->dynindx <= 0xffff);
10382
10383       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
10384          sign extension at runtime in the stub, resulting in a negative
10385          index value.  */
10386       if (h->dynindx & ~0x7fffffff)
10387         return FALSE;
10388
10389       /* Fill the stub.  */
10390       if (micromips_p)
10391         {
10392           idx = 0;
10393           bfd_put_micromips_32 (output_bfd, STUB_LW_MICROMIPS (output_bfd),
10394                                 stub + idx);
10395           idx += 4;
10396           bfd_put_16 (output_bfd, STUB_MOVE_MICROMIPS, stub + idx);
10397           idx += 2;
10398           if (stub_size == stub_big_size)
10399             {
10400               long dynindx_hi = (h->dynindx >> 16) & 0x7fff;
10401
10402               bfd_put_micromips_32 (output_bfd,
10403                                     STUB_LUI_MICROMIPS (dynindx_hi),
10404                                     stub + idx);
10405               idx += 4;
10406             }
10407           bfd_put_16 (output_bfd, STUB_JALR_MICROMIPS, stub + idx);
10408           idx += 2;
10409
10410           /* If a large stub is not required and sign extension is not a
10411              problem, then use legacy code in the stub.  */
10412           if (stub_size == stub_big_size)
10413             bfd_put_micromips_32 (output_bfd,
10414                                   STUB_ORI_MICROMIPS (h->dynindx & 0xffff),
10415                                   stub + idx);
10416           else if (h->dynindx & ~0x7fff)
10417             bfd_put_micromips_32 (output_bfd,
10418                                   STUB_LI16U_MICROMIPS (h->dynindx & 0xffff),
10419                                   stub + idx);
10420           else
10421             bfd_put_micromips_32 (output_bfd,
10422                                   STUB_LI16S_MICROMIPS (output_bfd,
10423                                                         h->dynindx),
10424                                   stub + idx);
10425         }
10426       else
10427         {
10428           idx = 0;
10429           bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
10430           idx += 4;
10431           bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + idx);
10432           idx += 4;
10433           if (stub_size == stub_big_size)
10434             {
10435               bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
10436                           stub + idx);
10437               idx += 4;
10438             }
10439           bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
10440           idx += 4;
10441
10442           /* If a large stub is not required and sign extension is not a
10443              problem, then use legacy code in the stub.  */
10444           if (stub_size == stub_big_size)
10445             bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff),
10446                         stub + idx);
10447           else if (h->dynindx & ~0x7fff)
10448             bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff),
10449                         stub + idx);
10450           else
10451             bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
10452                         stub + idx);
10453         }
10454
10455       BFD_ASSERT (h->plt.plist->stub_offset <= htab->sstubs->size);
10456       memcpy (htab->sstubs->contents + h->plt.plist->stub_offset,
10457               stub, stub_size);
10458
10459       /* Mark the symbol as undefined.  stub_offset != -1 occurs
10460          only for the referenced symbol.  */
10461       sym->st_shndx = SHN_UNDEF;
10462
10463       /* The run-time linker uses the st_value field of the symbol
10464          to reset the global offset table entry for this external
10465          to its stub address when unlinking a shared object.  */
10466       sym->st_value = (htab->sstubs->output_section->vma
10467                        + htab->sstubs->output_offset
10468                        + h->plt.plist->stub_offset
10469                        + isa_bit);
10470       sym->st_other = other;
10471     }
10472
10473   /* If we have a MIPS16 function with a stub, the dynamic symbol must
10474      refer to the stub, since only the stub uses the standard calling
10475      conventions.  */
10476   if (h->dynindx != -1 && hmips->fn_stub != NULL)
10477     {
10478       BFD_ASSERT (hmips->need_fn_stub);
10479       sym->st_value = (hmips->fn_stub->output_section->vma
10480                        + hmips->fn_stub->output_offset);
10481       sym->st_size = hmips->fn_stub->size;
10482       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
10483     }
10484
10485   BFD_ASSERT (h->dynindx != -1
10486               || h->forced_local);
10487
10488   sgot = htab->sgot;
10489   g = htab->got_info;
10490   BFD_ASSERT (g != NULL);
10491
10492   /* Run through the global symbol table, creating GOT entries for all
10493      the symbols that need them.  */
10494   if (hmips->global_got_area != GGA_NONE)
10495     {
10496       bfd_vma offset;
10497       bfd_vma value;
10498
10499       value = sym->st_value;
10500       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
10501       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
10502     }
10503
10504   if (hmips->global_got_area != GGA_NONE && g->next)
10505     {
10506       struct mips_got_entry e, *p;
10507       bfd_vma entry;
10508       bfd_vma offset;
10509
10510       gg = g;
10511
10512       e.abfd = output_bfd;
10513       e.symndx = -1;
10514       e.d.h = hmips;
10515       e.tls_type = GOT_TLS_NONE;
10516
10517       for (g = g->next; g->next != gg; g = g->next)
10518         {
10519           if (g->got_entries
10520               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
10521                                                            &e)))
10522             {
10523               offset = p->gotidx;
10524               BFD_ASSERT (offset > 0 && offset < htab->sgot->size);
10525               if (info->shared
10526                   || (elf_hash_table (info)->dynamic_sections_created
10527                       && p->d.h != NULL
10528                       && p->d.h->root.def_dynamic
10529                       && !p->d.h->root.def_regular))
10530                 {
10531                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
10532                      the various compatibility problems, it's easier to mock
10533                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
10534                      mips_elf_create_dynamic_relocation to calculate the
10535                      appropriate addend.  */
10536                   Elf_Internal_Rela rel[3];
10537
10538                   memset (rel, 0, sizeof (rel));
10539                   if (ABI_64_P (output_bfd))
10540                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
10541                   else
10542                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
10543                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
10544
10545                   entry = 0;
10546                   if (! (mips_elf_create_dynamic_relocation
10547                          (output_bfd, info, rel,
10548                           e.d.h, NULL, sym->st_value, &entry, sgot)))
10549                     return FALSE;
10550                 }
10551               else
10552                 entry = sym->st_value;
10553               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
10554             }
10555         }
10556     }
10557
10558   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
10559   name = h->root.root.string;
10560   if (h == elf_hash_table (info)->hdynamic
10561       || h == elf_hash_table (info)->hgot)
10562     sym->st_shndx = SHN_ABS;
10563   else if (strcmp (name, "_DYNAMIC_LINK") == 0
10564            || strcmp (name, "_DYNAMIC_LINKING") == 0)
10565     {
10566       sym->st_shndx = SHN_ABS;
10567       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10568       sym->st_value = 1;
10569     }
10570   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
10571     {
10572       sym->st_shndx = SHN_ABS;
10573       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10574       sym->st_value = elf_gp (output_bfd);
10575     }
10576   else if (SGI_COMPAT (output_bfd))
10577     {
10578       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
10579           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
10580         {
10581           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10582           sym->st_other = STO_PROTECTED;
10583           sym->st_value = 0;
10584           sym->st_shndx = SHN_MIPS_DATA;
10585         }
10586       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
10587         {
10588           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10589           sym->st_other = STO_PROTECTED;
10590           sym->st_value = mips_elf_hash_table (info)->procedure_count;
10591           sym->st_shndx = SHN_ABS;
10592         }
10593       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
10594         {
10595           if (h->type == STT_FUNC)
10596             sym->st_shndx = SHN_MIPS_TEXT;
10597           else if (h->type == STT_OBJECT)
10598             sym->st_shndx = SHN_MIPS_DATA;
10599         }
10600     }
10601
10602   /* Emit a copy reloc, if needed.  */
10603   if (h->needs_copy)
10604     {
10605       asection *s;
10606       bfd_vma symval;
10607
10608       BFD_ASSERT (h->dynindx != -1);
10609       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10610
10611       s = mips_elf_rel_dyn_section (info, FALSE);
10612       symval = (h->root.u.def.section->output_section->vma
10613                 + h->root.u.def.section->output_offset
10614                 + h->root.u.def.value);
10615       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
10616                                           h->dynindx, R_MIPS_COPY, symval);
10617     }
10618
10619   /* Handle the IRIX6-specific symbols.  */
10620   if (IRIX_COMPAT (output_bfd) == ict_irix6)
10621     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
10622
10623   /* Keep dynamic compressed symbols odd.  This allows the dynamic linker
10624      to treat compressed symbols like any other.  */
10625   if (ELF_ST_IS_MIPS16 (sym->st_other))
10626     {
10627       BFD_ASSERT (sym->st_value & 1);
10628       sym->st_other -= STO_MIPS16;
10629     }
10630   else if (ELF_ST_IS_MICROMIPS (sym->st_other))
10631     {
10632       BFD_ASSERT (sym->st_value & 1);
10633       sym->st_other -= STO_MICROMIPS;
10634     }
10635
10636   return TRUE;
10637 }
10638
10639 /* Likewise, for VxWorks.  */
10640
10641 bfd_boolean
10642 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
10643                                          struct bfd_link_info *info,
10644                                          struct elf_link_hash_entry *h,
10645                                          Elf_Internal_Sym *sym)
10646 {
10647   bfd *dynobj;
10648   asection *sgot;
10649   struct mips_got_info *g;
10650   struct mips_elf_link_hash_table *htab;
10651   struct mips_elf_link_hash_entry *hmips;
10652
10653   htab = mips_elf_hash_table (info);
10654   BFD_ASSERT (htab != NULL);
10655   dynobj = elf_hash_table (info)->dynobj;
10656   hmips = (struct mips_elf_link_hash_entry *) h;
10657
10658   if (h->plt.plist != NULL && h->plt.plist->mips_offset != MINUS_ONE)
10659     {
10660       bfd_byte *loc;
10661       bfd_vma plt_address, got_address, got_offset, branch_offset;
10662       Elf_Internal_Rela rel;
10663       static const bfd_vma *plt_entry;
10664       bfd_vma gotplt_index;
10665       bfd_vma plt_offset;
10666
10667       plt_offset = htab->plt_header_size + h->plt.plist->mips_offset;
10668       gotplt_index = h->plt.plist->gotplt_index;
10669
10670       BFD_ASSERT (h->dynindx != -1);
10671       BFD_ASSERT (htab->splt != NULL);
10672       BFD_ASSERT (gotplt_index != MINUS_ONE);
10673       BFD_ASSERT (plt_offset <= htab->splt->size);
10674
10675       /* Calculate the address of the .plt entry.  */
10676       plt_address = (htab->splt->output_section->vma
10677                      + htab->splt->output_offset
10678                      + plt_offset);
10679
10680       /* Calculate the address of the .got.plt entry.  */
10681       got_address = (htab->sgotplt->output_section->vma
10682                      + htab->sgotplt->output_offset
10683                      + gotplt_index * MIPS_ELF_GOT_SIZE (output_bfd));
10684
10685       /* Calculate the offset of the .got.plt entry from
10686          _GLOBAL_OFFSET_TABLE_.  */
10687       got_offset = mips_elf_gotplt_index (info, h);
10688
10689       /* Calculate the offset for the branch at the start of the PLT
10690          entry.  The branch jumps to the beginning of .plt.  */
10691       branch_offset = -(plt_offset / 4 + 1) & 0xffff;
10692
10693       /* Fill in the initial value of the .got.plt entry.  */
10694       bfd_put_32 (output_bfd, plt_address,
10695                   (htab->sgotplt->contents
10696                    + gotplt_index * MIPS_ELF_GOT_SIZE (output_bfd)));
10697
10698       /* Find out where the .plt entry should go.  */
10699       loc = htab->splt->contents + plt_offset;
10700
10701       if (info->shared)
10702         {
10703           plt_entry = mips_vxworks_shared_plt_entry;
10704           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10705           bfd_put_32 (output_bfd, plt_entry[1] | gotplt_index, loc + 4);
10706         }
10707       else
10708         {
10709           bfd_vma got_address_high, got_address_low;
10710
10711           plt_entry = mips_vxworks_exec_plt_entry;
10712           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10713           got_address_low = got_address & 0xffff;
10714
10715           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10716           bfd_put_32 (output_bfd, plt_entry[1] | gotplt_index, loc + 4);
10717           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
10718           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
10719           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10720           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10721           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10722           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10723
10724           loc = (htab->srelplt2->contents
10725                  + (gotplt_index * 3 + 2) * sizeof (Elf32_External_Rela));
10726
10727           /* Emit a relocation for the .got.plt entry.  */
10728           rel.r_offset = got_address;
10729           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10730           rel.r_addend = plt_offset;
10731           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10732
10733           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
10734           loc += sizeof (Elf32_External_Rela);
10735           rel.r_offset = plt_address + 8;
10736           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10737           rel.r_addend = got_offset;
10738           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10739
10740           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
10741           loc += sizeof (Elf32_External_Rela);
10742           rel.r_offset += 4;
10743           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10744           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10745         }
10746
10747       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10748       loc = (htab->srelplt->contents
10749              + gotplt_index * sizeof (Elf32_External_Rela));
10750       rel.r_offset = got_address;
10751       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
10752       rel.r_addend = 0;
10753       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10754
10755       if (!h->def_regular)
10756         sym->st_shndx = SHN_UNDEF;
10757     }
10758
10759   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
10760
10761   sgot = htab->sgot;
10762   g = htab->got_info;
10763   BFD_ASSERT (g != NULL);
10764
10765   /* See if this symbol has an entry in the GOT.  */
10766   if (hmips->global_got_area != GGA_NONE)
10767     {
10768       bfd_vma offset;
10769       Elf_Internal_Rela outrel;
10770       bfd_byte *loc;
10771       asection *s;
10772
10773       /* Install the symbol value in the GOT.   */
10774       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
10775       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
10776
10777       /* Add a dynamic relocation for it.  */
10778       s = mips_elf_rel_dyn_section (info, FALSE);
10779       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
10780       outrel.r_offset = (sgot->output_section->vma
10781                          + sgot->output_offset
10782                          + offset);
10783       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
10784       outrel.r_addend = 0;
10785       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
10786     }
10787
10788   /* Emit a copy reloc, if needed.  */
10789   if (h->needs_copy)
10790     {
10791       Elf_Internal_Rela rel;
10792
10793       BFD_ASSERT (h->dynindx != -1);
10794
10795       rel.r_offset = (h->root.u.def.section->output_section->vma
10796                       + h->root.u.def.section->output_offset
10797                       + h->root.u.def.value);
10798       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
10799       rel.r_addend = 0;
10800       bfd_elf32_swap_reloca_out (output_bfd, &rel,
10801                                  htab->srelbss->contents
10802                                  + (htab->srelbss->reloc_count
10803                                     * sizeof (Elf32_External_Rela)));
10804       ++htab->srelbss->reloc_count;
10805     }
10806
10807   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
10808   if (ELF_ST_IS_COMPRESSED (sym->st_other))
10809     sym->st_value &= ~1;
10810
10811   return TRUE;
10812 }
10813
10814 /* Write out a plt0 entry to the beginning of .plt.  */
10815
10816 static bfd_boolean
10817 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10818 {
10819   bfd_byte *loc;
10820   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
10821   static const bfd_vma *plt_entry;
10822   struct mips_elf_link_hash_table *htab;
10823
10824   htab = mips_elf_hash_table (info);
10825   BFD_ASSERT (htab != NULL);
10826
10827   if (ABI_64_P (output_bfd))
10828     plt_entry = mips_n64_exec_plt0_entry;
10829   else if (ABI_N32_P (output_bfd))
10830     plt_entry = mips_n32_exec_plt0_entry;
10831   else if (htab->plt_header_is_comp)
10832     plt_entry = micromips_o32_exec_plt0_entry;
10833   else
10834     plt_entry = mips_o32_exec_plt0_entry;
10835
10836   /* Calculate the value of .got.plt.  */
10837   gotplt_value = (htab->sgotplt->output_section->vma
10838                   + htab->sgotplt->output_offset);
10839   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
10840   gotplt_value_low = gotplt_value & 0xffff;
10841
10842   /* The PLT sequence is not safe for N64 if .got.plt's address can
10843      not be loaded in two instructions.  */
10844   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
10845               || ~(gotplt_value | 0x7fffffff) == 0);
10846
10847   /* Install the PLT header.  */
10848   loc = htab->splt->contents;
10849   if (plt_entry == micromips_o32_exec_plt0_entry)
10850     {
10851       bfd_vma gotpc_offset;
10852       bfd_vma loc_address;
10853       size_t i;
10854
10855       BFD_ASSERT (gotplt_value % 4 == 0);
10856
10857       loc_address = (htab->splt->output_section->vma
10858                      + htab->splt->output_offset);
10859       gotpc_offset = gotplt_value - ((loc_address | 3) ^ 3);
10860
10861       /* ADDIUPC has a span of +/-16MB, check we're in range.  */
10862       if (gotpc_offset + 0x1000000 >= 0x2000000)
10863         {
10864           (*_bfd_error_handler)
10865             (_("%B: `%A' offset of %ld from `%A' beyond the range of ADDIUPC"),
10866              output_bfd,
10867              htab->sgotplt->output_section,
10868              htab->splt->output_section,
10869              (long) gotpc_offset);
10870           bfd_set_error (bfd_error_no_error);
10871           return FALSE;
10872         }
10873       bfd_put_16 (output_bfd,
10874                   plt_entry[0] | ((gotpc_offset >> 18) & 0x7f), loc);
10875       bfd_put_16 (output_bfd, (gotpc_offset >> 2) & 0xffff, loc + 2);
10876       for (i = 2; i < ARRAY_SIZE (micromips_o32_exec_plt0_entry); i++)
10877         bfd_put_16 (output_bfd, plt_entry[i], loc + (i * 2));
10878     }
10879   else
10880     {
10881       bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
10882       bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
10883       bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
10884       bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10885       bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10886       bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10887       bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10888       bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10889     }
10890
10891   return TRUE;
10892 }
10893
10894 /* Install the PLT header for a VxWorks executable and finalize the
10895    contents of .rela.plt.unloaded.  */
10896
10897 static void
10898 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10899 {
10900   Elf_Internal_Rela rela;
10901   bfd_byte *loc;
10902   bfd_vma got_value, got_value_high, got_value_low, plt_address;
10903   static const bfd_vma *plt_entry;
10904   struct mips_elf_link_hash_table *htab;
10905
10906   htab = mips_elf_hash_table (info);
10907   BFD_ASSERT (htab != NULL);
10908
10909   plt_entry = mips_vxworks_exec_plt0_entry;
10910
10911   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
10912   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
10913                + htab->root.hgot->root.u.def.section->output_offset
10914                + htab->root.hgot->root.u.def.value);
10915
10916   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
10917   got_value_low = got_value & 0xffff;
10918
10919   /* Calculate the address of the PLT header.  */
10920   plt_address = htab->splt->output_section->vma + htab->splt->output_offset;
10921
10922   /* Install the PLT header.  */
10923   loc = htab->splt->contents;
10924   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
10925   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
10926   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
10927   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10928   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10929   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10930
10931   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
10932   loc = htab->srelplt2->contents;
10933   rela.r_offset = plt_address;
10934   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10935   rela.r_addend = 0;
10936   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10937   loc += sizeof (Elf32_External_Rela);
10938
10939   /* Output the relocation for the following addiu of
10940      %lo(_GLOBAL_OFFSET_TABLE_).  */
10941   rela.r_offset += 4;
10942   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10943   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10944   loc += sizeof (Elf32_External_Rela);
10945
10946   /* Fix up the remaining relocations.  They may have the wrong
10947      symbol index for _G_O_T_ or _P_L_T_ depending on the order
10948      in which symbols were output.  */
10949   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
10950     {
10951       Elf_Internal_Rela rel;
10952
10953       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10954       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10955       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10956       loc += sizeof (Elf32_External_Rela);
10957
10958       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10959       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10960       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10961       loc += sizeof (Elf32_External_Rela);
10962
10963       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10964       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10965       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10966       loc += sizeof (Elf32_External_Rela);
10967     }
10968 }
10969
10970 /* Install the PLT header for a VxWorks shared library.  */
10971
10972 static void
10973 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
10974 {
10975   unsigned int i;
10976   struct mips_elf_link_hash_table *htab;
10977
10978   htab = mips_elf_hash_table (info);
10979   BFD_ASSERT (htab != NULL);
10980
10981   /* We just need to copy the entry byte-by-byte.  */
10982   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
10983     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
10984                 htab->splt->contents + i * 4);
10985 }
10986
10987 /* Finish up the dynamic sections.  */
10988
10989 bfd_boolean
10990 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
10991                                        struct bfd_link_info *info)
10992 {
10993   bfd *dynobj;
10994   asection *sdyn;
10995   asection *sgot;
10996   struct mips_got_info *gg, *g;
10997   struct mips_elf_link_hash_table *htab;
10998
10999   htab = mips_elf_hash_table (info);
11000   BFD_ASSERT (htab != NULL);
11001
11002   dynobj = elf_hash_table (info)->dynobj;
11003
11004   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
11005
11006   sgot = htab->sgot;
11007   gg = htab->got_info;
11008
11009   if (elf_hash_table (info)->dynamic_sections_created)
11010     {
11011       bfd_byte *b;
11012       int dyn_to_skip = 0, dyn_skipped = 0;
11013
11014       BFD_ASSERT (sdyn != NULL);
11015       BFD_ASSERT (gg != NULL);
11016
11017       g = mips_elf_bfd_got (output_bfd, FALSE);
11018       BFD_ASSERT (g != NULL);
11019
11020       for (b = sdyn->contents;
11021            b < sdyn->contents + sdyn->size;
11022            b += MIPS_ELF_DYN_SIZE (dynobj))
11023         {
11024           Elf_Internal_Dyn dyn;
11025           const char *name;
11026           size_t elemsize;
11027           asection *s;
11028           bfd_boolean swap_out_p;
11029
11030           /* Read in the current dynamic entry.  */
11031           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
11032
11033           /* Assume that we're going to modify it and write it out.  */
11034           swap_out_p = TRUE;
11035
11036           switch (dyn.d_tag)
11037             {
11038             case DT_RELENT:
11039               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
11040               break;
11041
11042             case DT_RELAENT:
11043               BFD_ASSERT (htab->is_vxworks);
11044               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
11045               break;
11046
11047             case DT_STRSZ:
11048               /* Rewrite DT_STRSZ.  */
11049               dyn.d_un.d_val =
11050                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
11051               break;
11052
11053             case DT_PLTGOT:
11054               s = htab->sgot;
11055               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
11056               break;
11057
11058             case DT_MIPS_PLTGOT:
11059               s = htab->sgotplt;
11060               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
11061               break;
11062
11063             case DT_MIPS_RLD_VERSION:
11064               dyn.d_un.d_val = 1; /* XXX */
11065               break;
11066
11067             case DT_MIPS_FLAGS:
11068               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
11069               break;
11070
11071             case DT_MIPS_TIME_STAMP:
11072               {
11073                 time_t t;
11074                 time (&t);
11075                 dyn.d_un.d_val = t;
11076               }
11077               break;
11078
11079             case DT_MIPS_ICHECKSUM:
11080               /* XXX FIXME: */
11081               swap_out_p = FALSE;
11082               break;
11083
11084             case DT_MIPS_IVERSION:
11085               /* XXX FIXME: */
11086               swap_out_p = FALSE;
11087               break;
11088
11089             case DT_MIPS_BASE_ADDRESS:
11090               s = output_bfd->sections;
11091               BFD_ASSERT (s != NULL);
11092               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
11093               break;
11094
11095             case DT_MIPS_LOCAL_GOTNO:
11096               dyn.d_un.d_val = g->local_gotno;
11097               break;
11098
11099             case DT_MIPS_UNREFEXTNO:
11100               /* The index into the dynamic symbol table which is the
11101                  entry of the first external symbol that is not
11102                  referenced within the same object.  */
11103               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
11104               break;
11105
11106             case DT_MIPS_GOTSYM:
11107               if (htab->global_gotsym)
11108                 {
11109                   dyn.d_un.d_val = htab->global_gotsym->dynindx;
11110                   break;
11111                 }
11112               /* In case if we don't have global got symbols we default
11113                  to setting DT_MIPS_GOTSYM to the same value as
11114                  DT_MIPS_SYMTABNO, so we just fall through.  */
11115
11116             case DT_MIPS_SYMTABNO:
11117               name = ".dynsym";
11118               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
11119               s = bfd_get_section_by_name (output_bfd, name);
11120               BFD_ASSERT (s != NULL);
11121
11122               dyn.d_un.d_val = s->size / elemsize;
11123               break;
11124
11125             case DT_MIPS_HIPAGENO:
11126               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
11127               break;
11128
11129             case DT_MIPS_RLD_MAP:
11130               {
11131                 struct elf_link_hash_entry *h;
11132                 h = mips_elf_hash_table (info)->rld_symbol;
11133                 if (!h)
11134                   {
11135                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
11136                     swap_out_p = FALSE;
11137                     break;
11138                   }
11139                 s = h->root.u.def.section;
11140                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
11141                                   + h->root.u.def.value);
11142               }
11143               break;
11144
11145             case DT_MIPS_OPTIONS:
11146               s = (bfd_get_section_by_name
11147                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
11148               dyn.d_un.d_ptr = s->vma;
11149               break;
11150
11151             case DT_RELASZ:
11152               BFD_ASSERT (htab->is_vxworks);
11153               /* The count does not include the JUMP_SLOT relocations.  */
11154               if (htab->srelplt)
11155                 dyn.d_un.d_val -= htab->srelplt->size;
11156               break;
11157
11158             case DT_PLTREL:
11159               BFD_ASSERT (htab->use_plts_and_copy_relocs);
11160               if (htab->is_vxworks)
11161                 dyn.d_un.d_val = DT_RELA;
11162               else
11163                 dyn.d_un.d_val = DT_REL;
11164               break;
11165
11166             case DT_PLTRELSZ:
11167               BFD_ASSERT (htab->use_plts_and_copy_relocs);
11168               dyn.d_un.d_val = htab->srelplt->size;
11169               break;
11170
11171             case DT_JMPREL:
11172               BFD_ASSERT (htab->use_plts_and_copy_relocs);
11173               dyn.d_un.d_ptr = (htab->srelplt->output_section->vma
11174                                 + htab->srelplt->output_offset);
11175               break;
11176
11177             case DT_TEXTREL:
11178               /* If we didn't need any text relocations after all, delete
11179                  the dynamic tag.  */
11180               if (!(info->flags & DF_TEXTREL))
11181                 {
11182                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
11183                   swap_out_p = FALSE;
11184                 }
11185               break;
11186
11187             case DT_FLAGS:
11188               /* If we didn't need any text relocations after all, clear
11189                  DF_TEXTREL from DT_FLAGS.  */
11190               if (!(info->flags & DF_TEXTREL))
11191                 dyn.d_un.d_val &= ~DF_TEXTREL;
11192               else
11193                 swap_out_p = FALSE;
11194               break;
11195
11196             default:
11197               swap_out_p = FALSE;
11198               if (htab->is_vxworks
11199                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
11200                 swap_out_p = TRUE;
11201               break;
11202             }
11203
11204           if (swap_out_p || dyn_skipped)
11205             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
11206               (dynobj, &dyn, b - dyn_skipped);
11207
11208           if (dyn_to_skip)
11209             {
11210               dyn_skipped += dyn_to_skip;
11211               dyn_to_skip = 0;
11212             }
11213         }
11214
11215       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
11216       if (dyn_skipped > 0)
11217         memset (b - dyn_skipped, 0, dyn_skipped);
11218     }
11219
11220   if (sgot != NULL && sgot->size > 0
11221       && !bfd_is_abs_section (sgot->output_section))
11222     {
11223       if (htab->is_vxworks)
11224         {
11225           /* The first entry of the global offset table points to the
11226              ".dynamic" section.  The second is initialized by the
11227              loader and contains the shared library identifier.
11228              The third is also initialized by the loader and points
11229              to the lazy resolution stub.  */
11230           MIPS_ELF_PUT_WORD (output_bfd,
11231                              sdyn->output_offset + sdyn->output_section->vma,
11232                              sgot->contents);
11233           MIPS_ELF_PUT_WORD (output_bfd, 0,
11234                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
11235           MIPS_ELF_PUT_WORD (output_bfd, 0,
11236                              sgot->contents
11237                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
11238         }
11239       else
11240         {
11241           /* The first entry of the global offset table will be filled at
11242              runtime. The second entry will be used by some runtime loaders.
11243              This isn't the case of IRIX rld.  */
11244           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
11245           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
11246                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
11247         }
11248
11249       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
11250          = MIPS_ELF_GOT_SIZE (output_bfd);
11251     }
11252
11253   /* Generate dynamic relocations for the non-primary gots.  */
11254   if (gg != NULL && gg->next)
11255     {
11256       Elf_Internal_Rela rel[3];
11257       bfd_vma addend = 0;
11258
11259       memset (rel, 0, sizeof (rel));
11260       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
11261
11262       for (g = gg->next; g->next != gg; g = g->next)
11263         {
11264           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
11265             + g->next->tls_gotno;
11266
11267           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
11268                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
11269           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
11270                              sgot->contents
11271                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
11272
11273           if (! info->shared)
11274             continue;
11275
11276           while (got_index < g->assigned_gotno)
11277             {
11278               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
11279                 = got_index++ * MIPS_ELF_GOT_SIZE (output_bfd);
11280               if (!(mips_elf_create_dynamic_relocation
11281                     (output_bfd, info, rel, NULL,
11282                      bfd_abs_section_ptr,
11283                      0, &addend, sgot)))
11284                 return FALSE;
11285               BFD_ASSERT (addend == 0);
11286             }
11287         }
11288     }
11289
11290   /* The generation of dynamic relocations for the non-primary gots
11291      adds more dynamic relocations.  We cannot count them until
11292      here.  */
11293
11294   if (elf_hash_table (info)->dynamic_sections_created)
11295     {
11296       bfd_byte *b;
11297       bfd_boolean swap_out_p;
11298
11299       BFD_ASSERT (sdyn != NULL);
11300
11301       for (b = sdyn->contents;
11302            b < sdyn->contents + sdyn->size;
11303            b += MIPS_ELF_DYN_SIZE (dynobj))
11304         {
11305           Elf_Internal_Dyn dyn;
11306           asection *s;
11307
11308           /* Read in the current dynamic entry.  */
11309           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
11310
11311           /* Assume that we're going to modify it and write it out.  */
11312           swap_out_p = TRUE;
11313
11314           switch (dyn.d_tag)
11315             {
11316             case DT_RELSZ:
11317               /* Reduce DT_RELSZ to account for any relocations we
11318                  decided not to make.  This is for the n64 irix rld,
11319                  which doesn't seem to apply any relocations if there
11320                  are trailing null entries.  */
11321               s = mips_elf_rel_dyn_section (info, FALSE);
11322               dyn.d_un.d_val = (s->reloc_count
11323                                 * (ABI_64_P (output_bfd)
11324                                    ? sizeof (Elf64_Mips_External_Rel)
11325                                    : sizeof (Elf32_External_Rel)));
11326               /* Adjust the section size too.  Tools like the prelinker
11327                  can reasonably expect the values to the same.  */
11328               elf_section_data (s->output_section)->this_hdr.sh_size
11329                 = dyn.d_un.d_val;
11330               break;
11331
11332             default:
11333               swap_out_p = FALSE;
11334               break;
11335             }
11336
11337           if (swap_out_p)
11338             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
11339               (dynobj, &dyn, b);
11340         }
11341     }
11342
11343   {
11344     asection *s;
11345     Elf32_compact_rel cpt;
11346
11347     if (SGI_COMPAT (output_bfd))
11348       {
11349         /* Write .compact_rel section out.  */
11350         s = bfd_get_linker_section (dynobj, ".compact_rel");
11351         if (s != NULL)
11352           {
11353             cpt.id1 = 1;
11354             cpt.num = s->reloc_count;
11355             cpt.id2 = 2;
11356             cpt.offset = (s->output_section->filepos
11357                           + sizeof (Elf32_External_compact_rel));
11358             cpt.reserved0 = 0;
11359             cpt.reserved1 = 0;
11360             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
11361                                             ((Elf32_External_compact_rel *)
11362                                              s->contents));
11363
11364             /* Clean up a dummy stub function entry in .text.  */
11365             if (htab->sstubs != NULL)
11366               {
11367                 file_ptr dummy_offset;
11368
11369                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
11370                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
11371                 memset (htab->sstubs->contents + dummy_offset, 0,
11372                         htab->function_stub_size);
11373               }
11374           }
11375       }
11376
11377     /* The psABI says that the dynamic relocations must be sorted in
11378        increasing order of r_symndx.  The VxWorks EABI doesn't require
11379        this, and because the code below handles REL rather than RELA
11380        relocations, using it for VxWorks would be outright harmful.  */
11381     if (!htab->is_vxworks)
11382       {
11383         s = mips_elf_rel_dyn_section (info, FALSE);
11384         if (s != NULL
11385             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
11386           {
11387             reldyn_sorting_bfd = output_bfd;
11388
11389             if (ABI_64_P (output_bfd))
11390               qsort ((Elf64_External_Rel *) s->contents + 1,
11391                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
11392                      sort_dynamic_relocs_64);
11393             else
11394               qsort ((Elf32_External_Rel *) s->contents + 1,
11395                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
11396                      sort_dynamic_relocs);
11397           }
11398       }
11399   }
11400
11401   if (htab->splt && htab->splt->size > 0)
11402     {
11403       if (htab->is_vxworks)
11404         {
11405           if (info->shared)
11406             mips_vxworks_finish_shared_plt (output_bfd, info);
11407           else
11408             mips_vxworks_finish_exec_plt (output_bfd, info);
11409         }
11410       else
11411         {
11412           BFD_ASSERT (!info->shared);
11413           if (!mips_finish_exec_plt (output_bfd, info))
11414             return FALSE;
11415         }
11416     }
11417   return TRUE;
11418 }
11419
11420
11421 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
11422
11423 static void
11424 mips_set_isa_flags (bfd *abfd)
11425 {
11426   flagword val;
11427
11428   switch (bfd_get_mach (abfd))
11429     {
11430     default:
11431     case bfd_mach_mips3000:
11432       val = E_MIPS_ARCH_1;
11433       break;
11434
11435     case bfd_mach_mips3900:
11436       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
11437       break;
11438
11439     case bfd_mach_mips6000:
11440       val = E_MIPS_ARCH_2;
11441       break;
11442
11443     case bfd_mach_mips4000:
11444     case bfd_mach_mips4300:
11445     case bfd_mach_mips4400:
11446     case bfd_mach_mips4600:
11447       val = E_MIPS_ARCH_3;
11448       break;
11449
11450     case bfd_mach_mips4010:
11451       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
11452       break;
11453
11454     case bfd_mach_mips4100:
11455       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
11456       break;
11457
11458     case bfd_mach_mips4111:
11459       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
11460       break;
11461
11462     case bfd_mach_mips4120:
11463       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
11464       break;
11465
11466     case bfd_mach_mips4650:
11467       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
11468       break;
11469
11470     case bfd_mach_mips5400:
11471       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
11472       break;
11473
11474     case bfd_mach_mips5500:
11475       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
11476       break;
11477
11478     case bfd_mach_mips5900:
11479       val = E_MIPS_ARCH_3 | E_MIPS_MACH_5900;
11480       break;
11481
11482     case bfd_mach_mips9000:
11483       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
11484       break;
11485
11486     case bfd_mach_mips5000:
11487     case bfd_mach_mips7000:
11488     case bfd_mach_mips8000:
11489     case bfd_mach_mips10000:
11490     case bfd_mach_mips12000:
11491     case bfd_mach_mips14000:
11492     case bfd_mach_mips16000:
11493       val = E_MIPS_ARCH_4;
11494       break;
11495
11496     case bfd_mach_mips5:
11497       val = E_MIPS_ARCH_5;
11498       break;
11499
11500     case bfd_mach_mips_loongson_2e:
11501       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
11502       break;
11503
11504     case bfd_mach_mips_loongson_2f:
11505       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
11506       break;
11507
11508     case bfd_mach_mips_sb1:
11509       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
11510       break;
11511
11512     case bfd_mach_mips_loongson_3a:
11513       val = E_MIPS_ARCH_64 | E_MIPS_MACH_LS3A;
11514       break;
11515
11516     case bfd_mach_mips_octeon:
11517     case bfd_mach_mips_octeonp:
11518       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
11519       break;
11520
11521     case bfd_mach_mips_xlr:
11522       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
11523       break;
11524
11525     case bfd_mach_mips_octeon2:
11526       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
11527       break;
11528
11529     case bfd_mach_mipsisa32:
11530       val = E_MIPS_ARCH_32;
11531       break;
11532
11533     case bfd_mach_mipsisa64:
11534       val = E_MIPS_ARCH_64;
11535       break;
11536
11537     case bfd_mach_mipsisa32r2:
11538       val = E_MIPS_ARCH_32R2;
11539       break;
11540
11541     case bfd_mach_mipsisa64r2:
11542       val = E_MIPS_ARCH_64R2;
11543       break;
11544     }
11545   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
11546   elf_elfheader (abfd)->e_flags |= val;
11547
11548 }
11549
11550
11551 /* The final processing done just before writing out a MIPS ELF object
11552    file.  This gets the MIPS architecture right based on the machine
11553    number.  This is used by both the 32-bit and the 64-bit ABI.  */
11554
11555 void
11556 _bfd_mips_elf_final_write_processing (bfd *abfd,
11557                                       bfd_boolean linker ATTRIBUTE_UNUSED)
11558 {
11559   unsigned int i;
11560   Elf_Internal_Shdr **hdrpp;
11561   const char *name;
11562   asection *sec;
11563
11564   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
11565      is nonzero.  This is for compatibility with old objects, which used
11566      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
11567   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
11568     mips_set_isa_flags (abfd);
11569
11570   /* Set the sh_info field for .gptab sections and other appropriate
11571      info for each special section.  */
11572   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
11573        i < elf_numsections (abfd);
11574        i++, hdrpp++)
11575     {
11576       switch ((*hdrpp)->sh_type)
11577         {
11578         case SHT_MIPS_MSYM:
11579         case SHT_MIPS_LIBLIST:
11580           sec = bfd_get_section_by_name (abfd, ".dynstr");
11581           if (sec != NULL)
11582             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11583           break;
11584
11585         case SHT_MIPS_GPTAB:
11586           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11587           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11588           BFD_ASSERT (name != NULL
11589                       && CONST_STRNEQ (name, ".gptab."));
11590           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
11591           BFD_ASSERT (sec != NULL);
11592           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11593           break;
11594
11595         case SHT_MIPS_CONTENT:
11596           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11597           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11598           BFD_ASSERT (name != NULL
11599                       && CONST_STRNEQ (name, ".MIPS.content"));
11600           sec = bfd_get_section_by_name (abfd,
11601                                          name + sizeof ".MIPS.content" - 1);
11602           BFD_ASSERT (sec != NULL);
11603           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11604           break;
11605
11606         case SHT_MIPS_SYMBOL_LIB:
11607           sec = bfd_get_section_by_name (abfd, ".dynsym");
11608           if (sec != NULL)
11609             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11610           sec = bfd_get_section_by_name (abfd, ".liblist");
11611           if (sec != NULL)
11612             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11613           break;
11614
11615         case SHT_MIPS_EVENTS:
11616           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11617           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11618           BFD_ASSERT (name != NULL);
11619           if (CONST_STRNEQ (name, ".MIPS.events"))
11620             sec = bfd_get_section_by_name (abfd,
11621                                            name + sizeof ".MIPS.events" - 1);
11622           else
11623             {
11624               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
11625               sec = bfd_get_section_by_name (abfd,
11626                                              (name
11627                                               + sizeof ".MIPS.post_rel" - 1));
11628             }
11629           BFD_ASSERT (sec != NULL);
11630           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11631           break;
11632
11633         }
11634     }
11635 }
11636 \f
11637 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
11638    segments.  */
11639
11640 int
11641 _bfd_mips_elf_additional_program_headers (bfd *abfd,
11642                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
11643 {
11644   asection *s;
11645   int ret = 0;
11646
11647   /* See if we need a PT_MIPS_REGINFO segment.  */
11648   s = bfd_get_section_by_name (abfd, ".reginfo");
11649   if (s && (s->flags & SEC_LOAD))
11650     ++ret;
11651
11652   /* See if we need a PT_MIPS_OPTIONS segment.  */
11653   if (IRIX_COMPAT (abfd) == ict_irix6
11654       && bfd_get_section_by_name (abfd,
11655                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
11656     ++ret;
11657
11658   /* See if we need a PT_MIPS_RTPROC segment.  */
11659   if (IRIX_COMPAT (abfd) == ict_irix5
11660       && bfd_get_section_by_name (abfd, ".dynamic")
11661       && bfd_get_section_by_name (abfd, ".mdebug"))
11662     ++ret;
11663
11664   /* Allocate a PT_NULL header in dynamic objects.  See
11665      _bfd_mips_elf_modify_segment_map for details.  */
11666   if (!SGI_COMPAT (abfd)
11667       && bfd_get_section_by_name (abfd, ".dynamic"))
11668     ++ret;
11669
11670   return ret;
11671 }
11672
11673 /* Modify the segment map for an IRIX5 executable.  */
11674
11675 bfd_boolean
11676 _bfd_mips_elf_modify_segment_map (bfd *abfd,
11677                                   struct bfd_link_info *info)
11678 {
11679   asection *s;
11680   struct elf_segment_map *m, **pm;
11681   bfd_size_type amt;
11682
11683   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
11684      segment.  */
11685   s = bfd_get_section_by_name (abfd, ".reginfo");
11686   if (s != NULL && (s->flags & SEC_LOAD) != 0)
11687     {
11688       for (m = elf_seg_map (abfd); m != NULL; m = m->next)
11689         if (m->p_type == PT_MIPS_REGINFO)
11690           break;
11691       if (m == NULL)
11692         {
11693           amt = sizeof *m;
11694           m = bfd_zalloc (abfd, amt);
11695           if (m == NULL)
11696             return FALSE;
11697
11698           m->p_type = PT_MIPS_REGINFO;
11699           m->count = 1;
11700           m->sections[0] = s;
11701
11702           /* We want to put it after the PHDR and INTERP segments.  */
11703           pm = &elf_seg_map (abfd);
11704           while (*pm != NULL
11705                  && ((*pm)->p_type == PT_PHDR
11706                      || (*pm)->p_type == PT_INTERP))
11707             pm = &(*pm)->next;
11708
11709           m->next = *pm;
11710           *pm = m;
11711         }
11712     }
11713
11714   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
11715      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
11716      PT_MIPS_OPTIONS segment immediately following the program header
11717      table.  */
11718   if (NEWABI_P (abfd)
11719       /* On non-IRIX6 new abi, we'll have already created a segment
11720          for this section, so don't create another.  I'm not sure this
11721          is not also the case for IRIX 6, but I can't test it right
11722          now.  */
11723       && IRIX_COMPAT (abfd) == ict_irix6)
11724     {
11725       for (s = abfd->sections; s; s = s->next)
11726         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
11727           break;
11728
11729       if (s)
11730         {
11731           struct elf_segment_map *options_segment;
11732
11733           pm = &elf_seg_map (abfd);
11734           while (*pm != NULL
11735                  && ((*pm)->p_type == PT_PHDR
11736                      || (*pm)->p_type == PT_INTERP))
11737             pm = &(*pm)->next;
11738
11739           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
11740             {
11741               amt = sizeof (struct elf_segment_map);
11742               options_segment = bfd_zalloc (abfd, amt);
11743               options_segment->next = *pm;
11744               options_segment->p_type = PT_MIPS_OPTIONS;
11745               options_segment->p_flags = PF_R;
11746               options_segment->p_flags_valid = TRUE;
11747               options_segment->count = 1;
11748               options_segment->sections[0] = s;
11749               *pm = options_segment;
11750             }
11751         }
11752     }
11753   else
11754     {
11755       if (IRIX_COMPAT (abfd) == ict_irix5)
11756         {
11757           /* If there are .dynamic and .mdebug sections, we make a room
11758              for the RTPROC header.  FIXME: Rewrite without section names.  */
11759           if (bfd_get_section_by_name (abfd, ".interp") == NULL
11760               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
11761               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
11762             {
11763               for (m = elf_seg_map (abfd); m != NULL; m = m->next)
11764                 if (m->p_type == PT_MIPS_RTPROC)
11765                   break;
11766               if (m == NULL)
11767                 {
11768                   amt = sizeof *m;
11769                   m = bfd_zalloc (abfd, amt);
11770                   if (m == NULL)
11771                     return FALSE;
11772
11773                   m->p_type = PT_MIPS_RTPROC;
11774
11775                   s = bfd_get_section_by_name (abfd, ".rtproc");
11776                   if (s == NULL)
11777                     {
11778                       m->count = 0;
11779                       m->p_flags = 0;
11780                       m->p_flags_valid = 1;
11781                     }
11782                   else
11783                     {
11784                       m->count = 1;
11785                       m->sections[0] = s;
11786                     }
11787
11788                   /* We want to put it after the DYNAMIC segment.  */
11789                   pm = &elf_seg_map (abfd);
11790                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
11791                     pm = &(*pm)->next;
11792                   if (*pm != NULL)
11793                     pm = &(*pm)->next;
11794
11795                   m->next = *pm;
11796                   *pm = m;
11797                 }
11798             }
11799         }
11800       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
11801          .dynstr, .dynsym, and .hash sections, and everything in
11802          between.  */
11803       for (pm = &elf_seg_map (abfd); *pm != NULL;
11804            pm = &(*pm)->next)
11805         if ((*pm)->p_type == PT_DYNAMIC)
11806           break;
11807       m = *pm;
11808       if (m != NULL && IRIX_COMPAT (abfd) == ict_none)
11809         {
11810           /* For a normal mips executable the permissions for the PT_DYNAMIC
11811              segment are read, write and execute. We do that here since
11812              the code in elf.c sets only the read permission. This matters
11813              sometimes for the dynamic linker.  */
11814           if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
11815             {
11816               m->p_flags = PF_R | PF_W | PF_X;
11817               m->p_flags_valid = 1;
11818             }
11819         }
11820       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
11821          glibc's dynamic linker has traditionally derived the number of
11822          tags from the p_filesz field, and sometimes allocates stack
11823          arrays of that size.  An overly-big PT_DYNAMIC segment can
11824          be actively harmful in such cases.  Making PT_DYNAMIC contain
11825          other sections can also make life hard for the prelinker,
11826          which might move one of the other sections to a different
11827          PT_LOAD segment.  */
11828       if (SGI_COMPAT (abfd)
11829           && m != NULL
11830           && m->count == 1
11831           && strcmp (m->sections[0]->name, ".dynamic") == 0)
11832         {
11833           static const char *sec_names[] =
11834           {
11835             ".dynamic", ".dynstr", ".dynsym", ".hash"
11836           };
11837           bfd_vma low, high;
11838           unsigned int i, c;
11839           struct elf_segment_map *n;
11840
11841           low = ~(bfd_vma) 0;
11842           high = 0;
11843           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
11844             {
11845               s = bfd_get_section_by_name (abfd, sec_names[i]);
11846               if (s != NULL && (s->flags & SEC_LOAD) != 0)
11847                 {
11848                   bfd_size_type sz;
11849
11850                   if (low > s->vma)
11851                     low = s->vma;
11852                   sz = s->size;
11853                   if (high < s->vma + sz)
11854                     high = s->vma + sz;
11855                 }
11856             }
11857
11858           c = 0;
11859           for (s = abfd->sections; s != NULL; s = s->next)
11860             if ((s->flags & SEC_LOAD) != 0
11861                 && s->vma >= low
11862                 && s->vma + s->size <= high)
11863               ++c;
11864
11865           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
11866           n = bfd_zalloc (abfd, amt);
11867           if (n == NULL)
11868             return FALSE;
11869           *n = *m;
11870           n->count = c;
11871
11872           i = 0;
11873           for (s = abfd->sections; s != NULL; s = s->next)
11874             {
11875               if ((s->flags & SEC_LOAD) != 0
11876                   && s->vma >= low
11877                   && s->vma + s->size <= high)
11878                 {
11879                   n->sections[i] = s;
11880                   ++i;
11881                 }
11882             }
11883
11884           *pm = n;
11885         }
11886     }
11887
11888   /* Allocate a spare program header in dynamic objects so that tools
11889      like the prelinker can add an extra PT_LOAD entry.
11890
11891      If the prelinker needs to make room for a new PT_LOAD entry, its
11892      standard procedure is to move the first (read-only) sections into
11893      the new (writable) segment.  However, the MIPS ABI requires
11894      .dynamic to be in a read-only segment, and the section will often
11895      start within sizeof (ElfNN_Phdr) bytes of the last program header.
11896
11897      Although the prelinker could in principle move .dynamic to a
11898      writable segment, it seems better to allocate a spare program
11899      header instead, and avoid the need to move any sections.
11900      There is a long tradition of allocating spare dynamic tags,
11901      so allocating a spare program header seems like a natural
11902      extension.
11903
11904      If INFO is NULL, we may be copying an already prelinked binary
11905      with objcopy or strip, so do not add this header.  */
11906   if (info != NULL
11907       && !SGI_COMPAT (abfd)
11908       && bfd_get_section_by_name (abfd, ".dynamic"))
11909     {
11910       for (pm = &elf_seg_map (abfd); *pm != NULL; pm = &(*pm)->next)
11911         if ((*pm)->p_type == PT_NULL)
11912           break;
11913       if (*pm == NULL)
11914         {
11915           m = bfd_zalloc (abfd, sizeof (*m));
11916           if (m == NULL)
11917             return FALSE;
11918
11919           m->p_type = PT_NULL;
11920           *pm = m;
11921         }
11922     }
11923
11924   return TRUE;
11925 }
11926 \f
11927 /* Return the section that should be marked against GC for a given
11928    relocation.  */
11929
11930 asection *
11931 _bfd_mips_elf_gc_mark_hook (asection *sec,
11932                             struct bfd_link_info *info,
11933                             Elf_Internal_Rela *rel,
11934                             struct elf_link_hash_entry *h,
11935                             Elf_Internal_Sym *sym)
11936 {
11937   /* ??? Do mips16 stub sections need to be handled special?  */
11938
11939   if (h != NULL)
11940     switch (ELF_R_TYPE (sec->owner, rel->r_info))
11941       {
11942       case R_MIPS_GNU_VTINHERIT:
11943       case R_MIPS_GNU_VTENTRY:
11944         return NULL;
11945       }
11946
11947   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
11948 }
11949
11950 /* Update the got entry reference counts for the section being removed.  */
11951
11952 bfd_boolean
11953 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
11954                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
11955                              asection *sec ATTRIBUTE_UNUSED,
11956                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
11957 {
11958 #if 0
11959   Elf_Internal_Shdr *symtab_hdr;
11960   struct elf_link_hash_entry **sym_hashes;
11961   bfd_signed_vma *local_got_refcounts;
11962   const Elf_Internal_Rela *rel, *relend;
11963   unsigned long r_symndx;
11964   struct elf_link_hash_entry *h;
11965
11966   if (info->relocatable)
11967     return TRUE;
11968
11969   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11970   sym_hashes = elf_sym_hashes (abfd);
11971   local_got_refcounts = elf_local_got_refcounts (abfd);
11972
11973   relend = relocs + sec->reloc_count;
11974   for (rel = relocs; rel < relend; rel++)
11975     switch (ELF_R_TYPE (abfd, rel->r_info))
11976       {
11977       case R_MIPS16_GOT16:
11978       case R_MIPS16_CALL16:
11979       case R_MIPS_GOT16:
11980       case R_MIPS_CALL16:
11981       case R_MIPS_CALL_HI16:
11982       case R_MIPS_CALL_LO16:
11983       case R_MIPS_GOT_HI16:
11984       case R_MIPS_GOT_LO16:
11985       case R_MIPS_GOT_DISP:
11986       case R_MIPS_GOT_PAGE:
11987       case R_MIPS_GOT_OFST:
11988       case R_MICROMIPS_GOT16:
11989       case R_MICROMIPS_CALL16:
11990       case R_MICROMIPS_CALL_HI16:
11991       case R_MICROMIPS_CALL_LO16:
11992       case R_MICROMIPS_GOT_HI16:
11993       case R_MICROMIPS_GOT_LO16:
11994       case R_MICROMIPS_GOT_DISP:
11995       case R_MICROMIPS_GOT_PAGE:
11996       case R_MICROMIPS_GOT_OFST:
11997         /* ??? It would seem that the existing MIPS code does no sort
11998            of reference counting or whatnot on its GOT and PLT entries,
11999            so it is not possible to garbage collect them at this time.  */
12000         break;
12001
12002       default:
12003         break;
12004       }
12005 #endif
12006
12007   return TRUE;
12008 }
12009 \f
12010 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
12011    hiding the old indirect symbol.  Process additional relocation
12012    information.  Also called for weakdefs, in which case we just let
12013    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
12014
12015 void
12016 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
12017                                     struct elf_link_hash_entry *dir,
12018                                     struct elf_link_hash_entry *ind)
12019 {
12020   struct mips_elf_link_hash_entry *dirmips, *indmips;
12021
12022   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
12023
12024   dirmips = (struct mips_elf_link_hash_entry *) dir;
12025   indmips = (struct mips_elf_link_hash_entry *) ind;
12026   /* Any absolute non-dynamic relocations against an indirect or weak
12027      definition will be against the target symbol.  */
12028   if (indmips->has_static_relocs)
12029     dirmips->has_static_relocs = TRUE;
12030
12031   if (ind->root.type != bfd_link_hash_indirect)
12032     return;
12033
12034   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
12035   if (indmips->readonly_reloc)
12036     dirmips->readonly_reloc = TRUE;
12037   if (indmips->no_fn_stub)
12038     dirmips->no_fn_stub = TRUE;
12039   if (indmips->fn_stub)
12040     {
12041       dirmips->fn_stub = indmips->fn_stub;
12042       indmips->fn_stub = NULL;
12043     }
12044   if (indmips->need_fn_stub)
12045     {
12046       dirmips->need_fn_stub = TRUE;
12047       indmips->need_fn_stub = FALSE;
12048     }
12049   if (indmips->call_stub)
12050     {
12051       dirmips->call_stub = indmips->call_stub;
12052       indmips->call_stub = NULL;
12053     }
12054   if (indmips->call_fp_stub)
12055     {
12056       dirmips->call_fp_stub = indmips->call_fp_stub;
12057       indmips->call_fp_stub = NULL;
12058     }
12059   if (indmips->global_got_area < dirmips->global_got_area)
12060     dirmips->global_got_area = indmips->global_got_area;
12061   if (indmips->global_got_area < GGA_NONE)
12062     indmips->global_got_area = GGA_NONE;
12063   if (indmips->has_nonpic_branches)
12064     dirmips->has_nonpic_branches = TRUE;
12065 }
12066 \f
12067 #define PDR_SIZE 32
12068
12069 bfd_boolean
12070 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
12071                             struct bfd_link_info *info)
12072 {
12073   asection *o;
12074   bfd_boolean ret = FALSE;
12075   unsigned char *tdata;
12076   size_t i, skip;
12077
12078   o = bfd_get_section_by_name (abfd, ".pdr");
12079   if (! o)
12080     return FALSE;
12081   if (o->size == 0)
12082     return FALSE;
12083   if (o->size % PDR_SIZE != 0)
12084     return FALSE;
12085   if (o->output_section != NULL
12086       && bfd_is_abs_section (o->output_section))
12087     return FALSE;
12088
12089   tdata = bfd_zmalloc (o->size / PDR_SIZE);
12090   if (! tdata)
12091     return FALSE;
12092
12093   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
12094                                             info->keep_memory);
12095   if (!cookie->rels)
12096     {
12097       free (tdata);
12098       return FALSE;
12099     }
12100
12101   cookie->rel = cookie->rels;
12102   cookie->relend = cookie->rels + o->reloc_count;
12103
12104   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
12105     {
12106       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
12107         {
12108           tdata[i] = 1;
12109           skip ++;
12110         }
12111     }
12112
12113   if (skip != 0)
12114     {
12115       mips_elf_section_data (o)->u.tdata = tdata;
12116       o->size -= skip * PDR_SIZE;
12117       ret = TRUE;
12118     }
12119   else
12120     free (tdata);
12121
12122   if (! info->keep_memory)
12123     free (cookie->rels);
12124
12125   return ret;
12126 }
12127
12128 bfd_boolean
12129 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
12130 {
12131   if (strcmp (sec->name, ".pdr") == 0)
12132     return TRUE;
12133   return FALSE;
12134 }
12135
12136 bfd_boolean
12137 _bfd_mips_elf_write_section (bfd *output_bfd,
12138                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
12139                              asection *sec, bfd_byte *contents)
12140 {
12141   bfd_byte *to, *from, *end;
12142   int i;
12143
12144   if (strcmp (sec->name, ".pdr") != 0)
12145     return FALSE;
12146
12147   if (mips_elf_section_data (sec)->u.tdata == NULL)
12148     return FALSE;
12149
12150   to = contents;
12151   end = contents + sec->size;
12152   for (from = contents, i = 0;
12153        from < end;
12154        from += PDR_SIZE, i++)
12155     {
12156       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
12157         continue;
12158       if (to != from)
12159         memcpy (to, from, PDR_SIZE);
12160       to += PDR_SIZE;
12161     }
12162   bfd_set_section_contents (output_bfd, sec->output_section, contents,
12163                             sec->output_offset, sec->size);
12164   return TRUE;
12165 }
12166 \f
12167 /* microMIPS code retains local labels for linker relaxation.  Omit them
12168    from output by default for clarity.  */
12169
12170 bfd_boolean
12171 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
12172 {
12173   return _bfd_elf_is_local_label_name (abfd, sym->name);
12174 }
12175
12176 /* MIPS ELF uses a special find_nearest_line routine in order the
12177    handle the ECOFF debugging information.  */
12178
12179 struct mips_elf_find_line
12180 {
12181   struct ecoff_debug_info d;
12182   struct ecoff_find_line i;
12183 };
12184
12185 bfd_boolean
12186 _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section,
12187                                  asymbol **symbols, bfd_vma offset,
12188                                  const char **filename_ptr,
12189                                  const char **functionname_ptr,
12190                                  unsigned int *line_ptr)
12191 {
12192   asection *msec;
12193
12194   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
12195                                      filename_ptr, functionname_ptr,
12196                                      line_ptr))
12197     return TRUE;
12198
12199   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
12200                                      section, symbols, offset,
12201                                      filename_ptr, functionname_ptr,
12202                                      line_ptr, NULL, ABI_64_P (abfd) ? 8 : 0,
12203                                      &elf_tdata (abfd)->dwarf2_find_line_info))
12204     return TRUE;
12205
12206   msec = bfd_get_section_by_name (abfd, ".mdebug");
12207   if (msec != NULL)
12208     {
12209       flagword origflags;
12210       struct mips_elf_find_line *fi;
12211       const struct ecoff_debug_swap * const swap =
12212         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
12213
12214       /* If we are called during a link, mips_elf_final_link may have
12215          cleared the SEC_HAS_CONTENTS field.  We force it back on here
12216          if appropriate (which it normally will be).  */
12217       origflags = msec->flags;
12218       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
12219         msec->flags |= SEC_HAS_CONTENTS;
12220
12221       fi = mips_elf_tdata (abfd)->find_line_info;
12222       if (fi == NULL)
12223         {
12224           bfd_size_type external_fdr_size;
12225           char *fraw_src;
12226           char *fraw_end;
12227           struct fdr *fdr_ptr;
12228           bfd_size_type amt = sizeof (struct mips_elf_find_line);
12229
12230           fi = bfd_zalloc (abfd, amt);
12231           if (fi == NULL)
12232             {
12233               msec->flags = origflags;
12234               return FALSE;
12235             }
12236
12237           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
12238             {
12239               msec->flags = origflags;
12240               return FALSE;
12241             }
12242
12243           /* Swap in the FDR information.  */
12244           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
12245           fi->d.fdr = bfd_alloc (abfd, amt);
12246           if (fi->d.fdr == NULL)
12247             {
12248               msec->flags = origflags;
12249               return FALSE;
12250             }
12251           external_fdr_size = swap->external_fdr_size;
12252           fdr_ptr = fi->d.fdr;
12253           fraw_src = (char *) fi->d.external_fdr;
12254           fraw_end = (fraw_src
12255                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
12256           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
12257             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
12258
12259           mips_elf_tdata (abfd)->find_line_info = fi;
12260
12261           /* Note that we don't bother to ever free this information.
12262              find_nearest_line is either called all the time, as in
12263              objdump -l, so the information should be saved, or it is
12264              rarely called, as in ld error messages, so the memory
12265              wasted is unimportant.  Still, it would probably be a
12266              good idea for free_cached_info to throw it away.  */
12267         }
12268
12269       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
12270                                   &fi->i, filename_ptr, functionname_ptr,
12271                                   line_ptr))
12272         {
12273           msec->flags = origflags;
12274           return TRUE;
12275         }
12276
12277       msec->flags = origflags;
12278     }
12279
12280   /* Fall back on the generic ELF find_nearest_line routine.  */
12281
12282   return _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
12283                                      filename_ptr, functionname_ptr,
12284                                      line_ptr);
12285 }
12286
12287 bfd_boolean
12288 _bfd_mips_elf_find_inliner_info (bfd *abfd,
12289                                  const char **filename_ptr,
12290                                  const char **functionname_ptr,
12291                                  unsigned int *line_ptr)
12292 {
12293   bfd_boolean found;
12294   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
12295                                          functionname_ptr, line_ptr,
12296                                          & elf_tdata (abfd)->dwarf2_find_line_info);
12297   return found;
12298 }
12299
12300 \f
12301 /* When are writing out the .options or .MIPS.options section,
12302    remember the bytes we are writing out, so that we can install the
12303    GP value in the section_processing routine.  */
12304
12305 bfd_boolean
12306 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
12307                                     const void *location,
12308                                     file_ptr offset, bfd_size_type count)
12309 {
12310   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
12311     {
12312       bfd_byte *c;
12313
12314       if (elf_section_data (section) == NULL)
12315         {
12316           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
12317           section->used_by_bfd = bfd_zalloc (abfd, amt);
12318           if (elf_section_data (section) == NULL)
12319             return FALSE;
12320         }
12321       c = mips_elf_section_data (section)->u.tdata;
12322       if (c == NULL)
12323         {
12324           c = bfd_zalloc (abfd, section->size);
12325           if (c == NULL)
12326             return FALSE;
12327           mips_elf_section_data (section)->u.tdata = c;
12328         }
12329
12330       memcpy (c + offset, location, count);
12331     }
12332
12333   return _bfd_elf_set_section_contents (abfd, section, location, offset,
12334                                         count);
12335 }
12336
12337 /* This is almost identical to bfd_generic_get_... except that some
12338    MIPS relocations need to be handled specially.  Sigh.  */
12339
12340 bfd_byte *
12341 _bfd_elf_mips_get_relocated_section_contents
12342   (bfd *abfd,
12343    struct bfd_link_info *link_info,
12344    struct bfd_link_order *link_order,
12345    bfd_byte *data,
12346    bfd_boolean relocatable,
12347    asymbol **symbols)
12348 {
12349   /* Get enough memory to hold the stuff */
12350   bfd *input_bfd = link_order->u.indirect.section->owner;
12351   asection *input_section = link_order->u.indirect.section;
12352   bfd_size_type sz;
12353
12354   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
12355   arelent **reloc_vector = NULL;
12356   long reloc_count;
12357
12358   if (reloc_size < 0)
12359     goto error_return;
12360
12361   reloc_vector = bfd_malloc (reloc_size);
12362   if (reloc_vector == NULL && reloc_size != 0)
12363     goto error_return;
12364
12365   /* read in the section */
12366   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
12367   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
12368     goto error_return;
12369
12370   reloc_count = bfd_canonicalize_reloc (input_bfd,
12371                                         input_section,
12372                                         reloc_vector,
12373                                         symbols);
12374   if (reloc_count < 0)
12375     goto error_return;
12376
12377   if (reloc_count > 0)
12378     {
12379       arelent **parent;
12380       /* for mips */
12381       int gp_found;
12382       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
12383
12384       {
12385         struct bfd_hash_entry *h;
12386         struct bfd_link_hash_entry *lh;
12387         /* Skip all this stuff if we aren't mixing formats.  */
12388         if (abfd && input_bfd
12389             && abfd->xvec == input_bfd->xvec)
12390           lh = 0;
12391         else
12392           {
12393             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
12394             lh = (struct bfd_link_hash_entry *) h;
12395           }
12396       lookup:
12397         if (lh)
12398           {
12399             switch (lh->type)
12400               {
12401               case bfd_link_hash_undefined:
12402               case bfd_link_hash_undefweak:
12403               case bfd_link_hash_common:
12404                 gp_found = 0;
12405                 break;
12406               case bfd_link_hash_defined:
12407               case bfd_link_hash_defweak:
12408                 gp_found = 1;
12409                 gp = lh->u.def.value;
12410                 break;
12411               case bfd_link_hash_indirect:
12412               case bfd_link_hash_warning:
12413                 lh = lh->u.i.link;
12414                 /* @@FIXME  ignoring warning for now */
12415                 goto lookup;
12416               case bfd_link_hash_new:
12417               default:
12418                 abort ();
12419               }
12420           }
12421         else
12422           gp_found = 0;
12423       }
12424       /* end mips */
12425       for (parent = reloc_vector; *parent != NULL; parent++)
12426         {
12427           char *error_message = NULL;
12428           bfd_reloc_status_type r;
12429
12430           /* Specific to MIPS: Deal with relocation types that require
12431              knowing the gp of the output bfd.  */
12432           asymbol *sym = *(*parent)->sym_ptr_ptr;
12433
12434           /* If we've managed to find the gp and have a special
12435              function for the relocation then go ahead, else default
12436              to the generic handling.  */
12437           if (gp_found
12438               && (*parent)->howto->special_function
12439               == _bfd_mips_elf32_gprel16_reloc)
12440             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
12441                                                input_section, relocatable,
12442                                                data, gp);
12443           else
12444             r = bfd_perform_relocation (input_bfd, *parent, data,
12445                                         input_section,
12446                                         relocatable ? abfd : NULL,
12447                                         &error_message);
12448
12449           if (relocatable)
12450             {
12451               asection *os = input_section->output_section;
12452
12453               /* A partial link, so keep the relocs */
12454               os->orelocation[os->reloc_count] = *parent;
12455               os->reloc_count++;
12456             }
12457
12458           if (r != bfd_reloc_ok)
12459             {
12460               switch (r)
12461                 {
12462                 case bfd_reloc_undefined:
12463                   if (!((*link_info->callbacks->undefined_symbol)
12464                         (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
12465                          input_bfd, input_section, (*parent)->address, TRUE)))
12466                     goto error_return;
12467                   break;
12468                 case bfd_reloc_dangerous:
12469                   BFD_ASSERT (error_message != NULL);
12470                   if (!((*link_info->callbacks->reloc_dangerous)
12471                         (link_info, error_message, input_bfd, input_section,
12472                          (*parent)->address)))
12473                     goto error_return;
12474                   break;
12475                 case bfd_reloc_overflow:
12476                   if (!((*link_info->callbacks->reloc_overflow)
12477                         (link_info, NULL,
12478                          bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
12479                          (*parent)->howto->name, (*parent)->addend,
12480                          input_bfd, input_section, (*parent)->address)))
12481                     goto error_return;
12482                   break;
12483                 case bfd_reloc_outofrange:
12484                 default:
12485                   abort ();
12486                   break;
12487                 }
12488
12489             }
12490         }
12491     }
12492   if (reloc_vector != NULL)
12493     free (reloc_vector);
12494   return data;
12495
12496 error_return:
12497   if (reloc_vector != NULL)
12498     free (reloc_vector);
12499   return NULL;
12500 }
12501 \f
12502 static bfd_boolean
12503 mips_elf_relax_delete_bytes (bfd *abfd,
12504                              asection *sec, bfd_vma addr, int count)
12505 {
12506   Elf_Internal_Shdr *symtab_hdr;
12507   unsigned int sec_shndx;
12508   bfd_byte *contents;
12509   Elf_Internal_Rela *irel, *irelend;
12510   Elf_Internal_Sym *isym;
12511   Elf_Internal_Sym *isymend;
12512   struct elf_link_hash_entry **sym_hashes;
12513   struct elf_link_hash_entry **end_hashes;
12514   struct elf_link_hash_entry **start_hashes;
12515   unsigned int symcount;
12516
12517   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
12518   contents = elf_section_data (sec)->this_hdr.contents;
12519
12520   irel = elf_section_data (sec)->relocs;
12521   irelend = irel + sec->reloc_count;
12522
12523   /* Actually delete the bytes.  */
12524   memmove (contents + addr, contents + addr + count,
12525            (size_t) (sec->size - addr - count));
12526   sec->size -= count;
12527
12528   /* Adjust all the relocs.  */
12529   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
12530     {
12531       /* Get the new reloc address.  */
12532       if (irel->r_offset > addr)
12533         irel->r_offset -= count;
12534     }
12535
12536   BFD_ASSERT (addr % 2 == 0);
12537   BFD_ASSERT (count % 2 == 0);
12538
12539   /* Adjust the local symbols defined in this section.  */
12540   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12541   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
12542   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
12543     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
12544       isym->st_value -= count;
12545
12546   /* Now adjust the global symbols defined in this section.  */
12547   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
12548               - symtab_hdr->sh_info);
12549   sym_hashes = start_hashes = elf_sym_hashes (abfd);
12550   end_hashes = sym_hashes + symcount;
12551
12552   for (; sym_hashes < end_hashes; sym_hashes++)
12553     {
12554       struct elf_link_hash_entry *sym_hash = *sym_hashes;
12555
12556       if ((sym_hash->root.type == bfd_link_hash_defined
12557            || sym_hash->root.type == bfd_link_hash_defweak)
12558           && sym_hash->root.u.def.section == sec)
12559         {
12560           bfd_vma value = sym_hash->root.u.def.value;
12561
12562           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
12563             value &= MINUS_TWO;
12564           if (value > addr)
12565             sym_hash->root.u.def.value -= count;
12566         }
12567     }
12568
12569   return TRUE;
12570 }
12571
12572
12573 /* Opcodes needed for microMIPS relaxation as found in
12574    opcodes/micromips-opc.c.  */
12575
12576 struct opcode_descriptor {
12577   unsigned long match;
12578   unsigned long mask;
12579 };
12580
12581 /* The $ra register aka $31.  */
12582
12583 #define RA 31
12584
12585 /* 32-bit instruction format register fields.  */
12586
12587 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
12588 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
12589
12590 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
12591
12592 #define OP16_VALID_REG(r) \
12593   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
12594
12595
12596 /* 32-bit and 16-bit branches.  */
12597
12598 static const struct opcode_descriptor b_insns_32[] = {
12599   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
12600   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
12601   { 0, 0 }  /* End marker for find_match().  */
12602 };
12603
12604 static const struct opcode_descriptor bc_insn_32 =
12605   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
12606
12607 static const struct opcode_descriptor bz_insn_32 =
12608   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
12609
12610 static const struct opcode_descriptor bzal_insn_32 =
12611   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
12612
12613 static const struct opcode_descriptor beq_insn_32 =
12614   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
12615
12616 static const struct opcode_descriptor b_insn_16 =
12617   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
12618
12619 static const struct opcode_descriptor bz_insn_16 =
12620   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
12621
12622
12623 /* 32-bit and 16-bit branch EQ and NE zero.  */
12624
12625 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
12626    eq and second the ne.  This convention is used when replacing a
12627    32-bit BEQ/BNE with the 16-bit version.  */
12628
12629 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
12630
12631 static const struct opcode_descriptor bz_rs_insns_32[] = {
12632   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
12633   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
12634   { 0, 0 }  /* End marker for find_match().  */
12635 };
12636
12637 static const struct opcode_descriptor bz_rt_insns_32[] = {
12638   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
12639   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
12640   { 0, 0 }  /* End marker for find_match().  */
12641 };
12642
12643 static const struct opcode_descriptor bzc_insns_32[] = {
12644   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
12645   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
12646   { 0, 0 }  /* End marker for find_match().  */
12647 };
12648
12649 static const struct opcode_descriptor bz_insns_16[] = {
12650   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
12651   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
12652   { 0, 0 }  /* End marker for find_match().  */
12653 };
12654
12655 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
12656
12657 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0x17) + 2)
12658 #define BZ16_REG_FIELD(r) \
12659   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 7)
12660
12661
12662 /* 32-bit instructions with a delay slot.  */
12663
12664 static const struct opcode_descriptor jal_insn_32_bd16 =
12665   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
12666
12667 static const struct opcode_descriptor jal_insn_32_bd32 =
12668   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
12669
12670 static const struct opcode_descriptor jal_x_insn_32_bd32 =
12671   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
12672
12673 static const struct opcode_descriptor j_insn_32 =
12674   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
12675
12676 static const struct opcode_descriptor jalr_insn_32 =
12677   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
12678
12679 /* This table can be compacted, because no opcode replacement is made.  */
12680
12681 static const struct opcode_descriptor ds_insns_32_bd16[] = {
12682   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
12683
12684   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
12685   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
12686
12687   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
12688   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
12689   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
12690   { 0, 0 }  /* End marker for find_match().  */
12691 };
12692
12693 /* This table can be compacted, because no opcode replacement is made.  */
12694
12695 static const struct opcode_descriptor ds_insns_32_bd32[] = {
12696   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
12697
12698   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
12699   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
12700   { 0, 0 }  /* End marker for find_match().  */
12701 };
12702
12703
12704 /* 16-bit instructions with a delay slot.  */
12705
12706 static const struct opcode_descriptor jalr_insn_16_bd16 =
12707   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
12708
12709 static const struct opcode_descriptor jalr_insn_16_bd32 =
12710   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
12711
12712 static const struct opcode_descriptor jr_insn_16 =
12713   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
12714
12715 #define JR16_REG(opcode) ((opcode) & 0x1f)
12716
12717 /* This table can be compacted, because no opcode replacement is made.  */
12718
12719 static const struct opcode_descriptor ds_insns_16_bd16[] = {
12720   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
12721
12722   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
12723   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
12724   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
12725   { 0, 0 }  /* End marker for find_match().  */
12726 };
12727
12728
12729 /* LUI instruction.  */
12730
12731 static const struct opcode_descriptor lui_insn =
12732  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
12733
12734
12735 /* ADDIU instruction.  */
12736
12737 static const struct opcode_descriptor addiu_insn =
12738   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
12739
12740 static const struct opcode_descriptor addiupc_insn =
12741   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
12742
12743 #define ADDIUPC_REG_FIELD(r) \
12744   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
12745
12746
12747 /* Relaxable instructions in a JAL delay slot: MOVE.  */
12748
12749 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
12750    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
12751 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
12752 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
12753
12754 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
12755 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
12756
12757 static const struct opcode_descriptor move_insns_32[] = {
12758   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
12759   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
12760   { 0, 0 }  /* End marker for find_match().  */
12761 };
12762
12763 static const struct opcode_descriptor move_insn_16 =
12764   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
12765
12766
12767 /* NOP instructions.  */
12768
12769 static const struct opcode_descriptor nop_insn_32 =
12770   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
12771
12772 static const struct opcode_descriptor nop_insn_16 =
12773   { /* "nop",   "",             */ 0x0c00,     0xffff };
12774
12775
12776 /* Instruction match support.  */
12777
12778 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
12779
12780 static int
12781 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
12782 {
12783   unsigned long indx;
12784
12785   for (indx = 0; insn[indx].mask != 0; indx++)
12786     if (MATCH (opcode, insn[indx]))
12787       return indx;
12788
12789   return -1;
12790 }
12791
12792
12793 /* Branch and delay slot decoding support.  */
12794
12795 /* If PTR points to what *might* be a 16-bit branch or jump, then
12796    return the minimum length of its delay slot, otherwise return 0.
12797    Non-zero results are not definitive as we might be checking against
12798    the second half of another instruction.  */
12799
12800 static int
12801 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
12802 {
12803   unsigned long opcode;
12804   int bdsize;
12805
12806   opcode = bfd_get_16 (abfd, ptr);
12807   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
12808     /* 16-bit branch/jump with a 32-bit delay slot.  */
12809     bdsize = 4;
12810   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
12811            || find_match (opcode, ds_insns_16_bd16) >= 0)
12812     /* 16-bit branch/jump with a 16-bit delay slot.  */
12813     bdsize = 2;
12814   else
12815     /* No delay slot.  */
12816     bdsize = 0;
12817
12818   return bdsize;
12819 }
12820
12821 /* If PTR points to what *might* be a 32-bit branch or jump, then
12822    return the minimum length of its delay slot, otherwise return 0.
12823    Non-zero results are not definitive as we might be checking against
12824    the second half of another instruction.  */
12825
12826 static int
12827 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
12828 {
12829   unsigned long opcode;
12830   int bdsize;
12831
12832   opcode = bfd_get_micromips_32 (abfd, ptr);
12833   if (find_match (opcode, ds_insns_32_bd32) >= 0)
12834     /* 32-bit branch/jump with a 32-bit delay slot.  */
12835     bdsize = 4;
12836   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
12837     /* 32-bit branch/jump with a 16-bit delay slot.  */
12838     bdsize = 2;
12839   else
12840     /* No delay slot.  */
12841     bdsize = 0;
12842
12843   return bdsize;
12844 }
12845
12846 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
12847    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
12848
12849 static bfd_boolean
12850 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12851 {
12852   unsigned long opcode;
12853
12854   opcode = bfd_get_16 (abfd, ptr);
12855   if (MATCH (opcode, b_insn_16)
12856                                                 /* B16  */
12857       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
12858                                                 /* JR16  */
12859       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
12860                                                 /* BEQZ16, BNEZ16  */
12861       || (MATCH (opcode, jalr_insn_16_bd32)
12862                                                 /* JALR16  */
12863           && reg != JR16_REG (opcode) && reg != RA))
12864     return TRUE;
12865
12866   return FALSE;
12867 }
12868
12869 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
12870    then return TRUE, otherwise FALSE.  */
12871
12872 static bfd_boolean
12873 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12874 {
12875   unsigned long opcode;
12876
12877   opcode = bfd_get_micromips_32 (abfd, ptr);
12878   if (MATCH (opcode, j_insn_32)
12879                                                 /* J  */
12880       || MATCH (opcode, bc_insn_32)
12881                                                 /* BC1F, BC1T, BC2F, BC2T  */
12882       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
12883                                                 /* JAL, JALX  */
12884       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
12885                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
12886       || (MATCH (opcode, bzal_insn_32)
12887                                                 /* BGEZAL, BLTZAL  */
12888           && reg != OP32_SREG (opcode) && reg != RA)
12889       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
12890                                                 /* JALR, JALR.HB, BEQ, BNE  */
12891           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
12892     return TRUE;
12893
12894   return FALSE;
12895 }
12896
12897 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
12898    IRELEND) at OFFSET indicate that there must be a compact branch there,
12899    then return TRUE, otherwise FALSE.  */
12900
12901 static bfd_boolean
12902 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
12903                      const Elf_Internal_Rela *internal_relocs,
12904                      const Elf_Internal_Rela *irelend)
12905 {
12906   const Elf_Internal_Rela *irel;
12907   unsigned long opcode;
12908
12909   opcode = bfd_get_micromips_32 (abfd, ptr);
12910   if (find_match (opcode, bzc_insns_32) < 0)
12911     return FALSE;
12912
12913   for (irel = internal_relocs; irel < irelend; irel++)
12914     if (irel->r_offset == offset
12915         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
12916       return TRUE;
12917
12918   return FALSE;
12919 }
12920
12921 /* Bitsize checking.  */
12922 #define IS_BITSIZE(val, N)                                              \
12923   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
12924     - (1ULL << ((N) - 1))) == (val))
12925
12926 \f
12927 bfd_boolean
12928 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
12929                              struct bfd_link_info *link_info,
12930                              bfd_boolean *again)
12931 {
12932   Elf_Internal_Shdr *symtab_hdr;
12933   Elf_Internal_Rela *internal_relocs;
12934   Elf_Internal_Rela *irel, *irelend;
12935   bfd_byte *contents = NULL;
12936   Elf_Internal_Sym *isymbuf = NULL;
12937
12938   /* Assume nothing changes.  */
12939   *again = FALSE;
12940
12941   /* We don't have to do anything for a relocatable link, if
12942      this section does not have relocs, or if this is not a
12943      code section.  */
12944
12945   if (link_info->relocatable
12946       || (sec->flags & SEC_RELOC) == 0
12947       || sec->reloc_count == 0
12948       || (sec->flags & SEC_CODE) == 0)
12949     return TRUE;
12950
12951   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12952
12953   /* Get a copy of the native relocations.  */
12954   internal_relocs = (_bfd_elf_link_read_relocs
12955                      (abfd, sec, NULL, (Elf_Internal_Rela *) NULL,
12956                       link_info->keep_memory));
12957   if (internal_relocs == NULL)
12958     goto error_return;
12959
12960   /* Walk through them looking for relaxing opportunities.  */
12961   irelend = internal_relocs + sec->reloc_count;
12962   for (irel = internal_relocs; irel < irelend; irel++)
12963     {
12964       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
12965       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
12966       bfd_boolean target_is_micromips_code_p;
12967       unsigned long opcode;
12968       bfd_vma symval;
12969       bfd_vma pcrval;
12970       bfd_byte *ptr;
12971       int fndopc;
12972
12973       /* The number of bytes to delete for relaxation and from where
12974          to delete these bytes starting at irel->r_offset.  */
12975       int delcnt = 0;
12976       int deloff = 0;
12977
12978       /* If this isn't something that can be relaxed, then ignore
12979          this reloc.  */
12980       if (r_type != R_MICROMIPS_HI16
12981           && r_type != R_MICROMIPS_PC16_S1
12982           && r_type != R_MICROMIPS_26_S1)
12983         continue;
12984
12985       /* Get the section contents if we haven't done so already.  */
12986       if (contents == NULL)
12987         {
12988           /* Get cached copy if it exists.  */
12989           if (elf_section_data (sec)->this_hdr.contents != NULL)
12990             contents = elf_section_data (sec)->this_hdr.contents;
12991           /* Go get them off disk.  */
12992           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
12993             goto error_return;
12994         }
12995       ptr = contents + irel->r_offset;
12996
12997       /* Read this BFD's local symbols if we haven't done so already.  */
12998       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
12999         {
13000           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
13001           if (isymbuf == NULL)
13002             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
13003                                             symtab_hdr->sh_info, 0,
13004                                             NULL, NULL, NULL);
13005           if (isymbuf == NULL)
13006             goto error_return;
13007         }
13008
13009       /* Get the value of the symbol referred to by the reloc.  */
13010       if (r_symndx < symtab_hdr->sh_info)
13011         {
13012           /* A local symbol.  */
13013           Elf_Internal_Sym *isym;
13014           asection *sym_sec;
13015
13016           isym = isymbuf + r_symndx;
13017           if (isym->st_shndx == SHN_UNDEF)
13018             sym_sec = bfd_und_section_ptr;
13019           else if (isym->st_shndx == SHN_ABS)
13020             sym_sec = bfd_abs_section_ptr;
13021           else if (isym->st_shndx == SHN_COMMON)
13022             sym_sec = bfd_com_section_ptr;
13023           else
13024             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
13025           symval = (isym->st_value
13026                     + sym_sec->output_section->vma
13027                     + sym_sec->output_offset);
13028           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
13029         }
13030       else
13031         {
13032           unsigned long indx;
13033           struct elf_link_hash_entry *h;
13034
13035           /* An external symbol.  */
13036           indx = r_symndx - symtab_hdr->sh_info;
13037           h = elf_sym_hashes (abfd)[indx];
13038           BFD_ASSERT (h != NULL);
13039
13040           if (h->root.type != bfd_link_hash_defined
13041               && h->root.type != bfd_link_hash_defweak)
13042             /* This appears to be a reference to an undefined
13043                symbol.  Just ignore it -- it will be caught by the
13044                regular reloc processing.  */
13045             continue;
13046
13047           symval = (h->root.u.def.value
13048                     + h->root.u.def.section->output_section->vma
13049                     + h->root.u.def.section->output_offset);
13050           target_is_micromips_code_p = (!h->needs_plt
13051                                         && ELF_ST_IS_MICROMIPS (h->other));
13052         }
13053
13054
13055       /* For simplicity of coding, we are going to modify the
13056          section contents, the section relocs, and the BFD symbol
13057          table.  We must tell the rest of the code not to free up this
13058          information.  It would be possible to instead create a table
13059          of changes which have to be made, as is done in coff-mips.c;
13060          that would be more work, but would require less memory when
13061          the linker is run.  */
13062
13063       /* Only 32-bit instructions relaxed.  */
13064       if (irel->r_offset + 4 > sec->size)
13065         continue;
13066
13067       opcode = bfd_get_micromips_32 (abfd, ptr);
13068
13069       /* This is the pc-relative distance from the instruction the
13070          relocation is applied to, to the symbol referred.  */
13071       pcrval = (symval
13072                 - (sec->output_section->vma + sec->output_offset)
13073                 - irel->r_offset);
13074
13075       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
13076          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
13077          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
13078
13079            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
13080
13081          where pcrval has first to be adjusted to apply against the LO16
13082          location (we make the adjustment later on, when we have figured
13083          out the offset).  */
13084       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
13085         {
13086           bfd_boolean bzc = FALSE;
13087           unsigned long nextopc;
13088           unsigned long reg;
13089           bfd_vma offset;
13090
13091           /* Give up if the previous reloc was a HI16 against this symbol
13092              too.  */
13093           if (irel > internal_relocs
13094               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
13095               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
13096             continue;
13097
13098           /* Or if the next reloc is not a LO16 against this symbol.  */
13099           if (irel + 1 >= irelend
13100               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
13101               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
13102             continue;
13103
13104           /* Or if the second next reloc is a LO16 against this symbol too.  */
13105           if (irel + 2 >= irelend
13106               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
13107               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
13108             continue;
13109
13110           /* See if the LUI instruction *might* be in a branch delay slot.
13111              We check whether what looks like a 16-bit branch or jump is
13112              actually an immediate argument to a compact branch, and let
13113              it through if so.  */
13114           if (irel->r_offset >= 2
13115               && check_br16_dslot (abfd, ptr - 2)
13116               && !(irel->r_offset >= 4
13117                    && (bzc = check_relocated_bzc (abfd,
13118                                                   ptr - 4, irel->r_offset - 4,
13119                                                   internal_relocs, irelend))))
13120             continue;
13121           if (irel->r_offset >= 4
13122               && !bzc
13123               && check_br32_dslot (abfd, ptr - 4))
13124             continue;
13125
13126           reg = OP32_SREG (opcode);
13127
13128           /* We only relax adjacent instructions or ones separated with
13129              a branch or jump that has a delay slot.  The branch or jump
13130              must not fiddle with the register used to hold the address.
13131              Subtract 4 for the LUI itself.  */
13132           offset = irel[1].r_offset - irel[0].r_offset;
13133           switch (offset - 4)
13134             {
13135             case 0:
13136               break;
13137             case 2:
13138               if (check_br16 (abfd, ptr + 4, reg))
13139                 break;
13140               continue;
13141             case 4:
13142               if (check_br32 (abfd, ptr + 4, reg))
13143                 break;
13144               continue;
13145             default:
13146               continue;
13147             }
13148
13149           nextopc = bfd_get_micromips_32 (abfd, contents + irel[1].r_offset);
13150
13151           /* Give up unless the same register is used with both
13152              relocations.  */
13153           if (OP32_SREG (nextopc) != reg)
13154             continue;
13155
13156           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
13157              and rounding up to take masking of the two LSBs into account.  */
13158           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
13159
13160           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
13161           if (IS_BITSIZE (symval, 16))
13162             {
13163               /* Fix the relocation's type.  */
13164               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
13165
13166               /* Instructions using R_MICROMIPS_LO16 have the base or
13167                  source register in bits 20:16.  This register becomes $0
13168                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
13169               nextopc &= ~0x001f0000;
13170               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
13171                           contents + irel[1].r_offset);
13172             }
13173
13174           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
13175              We add 4 to take LUI deletion into account while checking
13176              the PC-relative distance.  */
13177           else if (symval % 4 == 0
13178                    && IS_BITSIZE (pcrval + 4, 25)
13179                    && MATCH (nextopc, addiu_insn)
13180                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
13181                    && OP16_VALID_REG (OP32_TREG (nextopc)))
13182             {
13183               /* Fix the relocation's type.  */
13184               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
13185
13186               /* Replace ADDIU with the ADDIUPC version.  */
13187               nextopc = (addiupc_insn.match
13188                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
13189
13190               bfd_put_micromips_32 (abfd, nextopc,
13191                                     contents + irel[1].r_offset);
13192             }
13193
13194           /* Can't do anything, give up, sigh...  */
13195           else
13196             continue;
13197
13198           /* Fix the relocation's type.  */
13199           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
13200
13201           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
13202           delcnt = 4;
13203           deloff = 0;
13204         }
13205
13206       /* Compact branch relaxation -- due to the multitude of macros
13207          employed by the compiler/assembler, compact branches are not
13208          always generated.  Obviously, this can/will be fixed elsewhere,
13209          but there is no drawback in double checking it here.  */
13210       else if (r_type == R_MICROMIPS_PC16_S1
13211                && irel->r_offset + 5 < sec->size
13212                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
13213                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
13214                && MATCH (bfd_get_16 (abfd, ptr + 4), nop_insn_16))
13215         {
13216           unsigned long reg;
13217
13218           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
13219
13220           /* Replace BEQZ/BNEZ with the compact version.  */
13221           opcode = (bzc_insns_32[fndopc].match
13222                     | BZC32_REG_FIELD (reg)
13223                     | (opcode & 0xffff));               /* Addend value.  */
13224
13225           bfd_put_micromips_32 (abfd, opcode, ptr);
13226
13227           /* Delete the 16-bit delay slot NOP: two bytes from
13228              irel->offset + 4.  */
13229           delcnt = 2;
13230           deloff = 4;
13231         }
13232
13233       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
13234          to check the distance from the next instruction, so subtract 2.  */
13235       else if (r_type == R_MICROMIPS_PC16_S1
13236                && IS_BITSIZE (pcrval - 2, 11)
13237                && find_match (opcode, b_insns_32) >= 0)
13238         {
13239           /* Fix the relocation's type.  */
13240           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
13241
13242           /* Replace the 32-bit opcode with a 16-bit opcode.  */
13243           bfd_put_16 (abfd,
13244                       (b_insn_16.match
13245                        | (opcode & 0x3ff)),             /* Addend value.  */
13246                       ptr);
13247
13248           /* Delete 2 bytes from irel->r_offset + 2.  */
13249           delcnt = 2;
13250           deloff = 2;
13251         }
13252
13253       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
13254          to check the distance from the next instruction, so subtract 2.  */
13255       else if (r_type == R_MICROMIPS_PC16_S1
13256                && IS_BITSIZE (pcrval - 2, 8)
13257                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
13258                     && OP16_VALID_REG (OP32_SREG (opcode)))
13259                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
13260                        && OP16_VALID_REG (OP32_TREG (opcode)))))
13261         {
13262           unsigned long reg;
13263
13264           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
13265
13266           /* Fix the relocation's type.  */
13267           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
13268
13269           /* Replace the 32-bit opcode with a 16-bit opcode.  */
13270           bfd_put_16 (abfd,
13271                       (bz_insns_16[fndopc].match
13272                        | BZ16_REG_FIELD (reg)
13273                        | (opcode & 0x7f)),              /* Addend value.  */
13274                       ptr);
13275
13276           /* Delete 2 bytes from irel->r_offset + 2.  */
13277           delcnt = 2;
13278           deloff = 2;
13279         }
13280
13281       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
13282       else if (r_type == R_MICROMIPS_26_S1
13283                && target_is_micromips_code_p
13284                && irel->r_offset + 7 < sec->size
13285                && MATCH (opcode, jal_insn_32_bd32))
13286         {
13287           unsigned long n32opc;
13288           bfd_boolean relaxed = FALSE;
13289
13290           n32opc = bfd_get_micromips_32 (abfd, ptr + 4);
13291
13292           if (MATCH (n32opc, nop_insn_32))
13293             {
13294               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
13295               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
13296
13297               relaxed = TRUE;
13298             }
13299           else if (find_match (n32opc, move_insns_32) >= 0)
13300             {
13301               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
13302               bfd_put_16 (abfd,
13303                           (move_insn_16.match
13304                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
13305                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
13306                           ptr + 4);
13307
13308               relaxed = TRUE;
13309             }
13310           /* Other 32-bit instructions relaxable to 16-bit
13311              instructions will be handled here later.  */
13312
13313           if (relaxed)
13314             {
13315               /* JAL with 32-bit delay slot that is changed to a JALS
13316                  with 16-bit delay slot.  */
13317               bfd_put_micromips_32 (abfd, jal_insn_32_bd16.match, ptr);
13318
13319               /* Delete 2 bytes from irel->r_offset + 6.  */
13320               delcnt = 2;
13321               deloff = 6;
13322             }
13323         }
13324
13325       if (delcnt != 0)
13326         {
13327           /* Note that we've changed the relocs, section contents, etc.  */
13328           elf_section_data (sec)->relocs = internal_relocs;
13329           elf_section_data (sec)->this_hdr.contents = contents;
13330           symtab_hdr->contents = (unsigned char *) isymbuf;
13331
13332           /* Delete bytes depending on the delcnt and deloff.  */
13333           if (!mips_elf_relax_delete_bytes (abfd, sec,
13334                                             irel->r_offset + deloff, delcnt))
13335             goto error_return;
13336
13337           /* That will change things, so we should relax again.
13338              Note that this is not required, and it may be slow.  */
13339           *again = TRUE;
13340         }
13341     }
13342
13343   if (isymbuf != NULL
13344       && symtab_hdr->contents != (unsigned char *) isymbuf)
13345     {
13346       if (! link_info->keep_memory)
13347         free (isymbuf);
13348       else
13349         {
13350           /* Cache the symbols for elf_link_input_bfd.  */
13351           symtab_hdr->contents = (unsigned char *) isymbuf;
13352         }
13353     }
13354
13355   if (contents != NULL
13356       && elf_section_data (sec)->this_hdr.contents != contents)
13357     {
13358       if (! link_info->keep_memory)
13359         free (contents);
13360       else
13361         {
13362           /* Cache the section contents for elf_link_input_bfd.  */
13363           elf_section_data (sec)->this_hdr.contents = contents;
13364         }
13365     }
13366
13367   if (internal_relocs != NULL
13368       && elf_section_data (sec)->relocs != internal_relocs)
13369     free (internal_relocs);
13370
13371   return TRUE;
13372
13373  error_return:
13374   if (isymbuf != NULL
13375       && symtab_hdr->contents != (unsigned char *) isymbuf)
13376     free (isymbuf);
13377   if (contents != NULL
13378       && elf_section_data (sec)->this_hdr.contents != contents)
13379     free (contents);
13380   if (internal_relocs != NULL
13381       && elf_section_data (sec)->relocs != internal_relocs)
13382     free (internal_relocs);
13383
13384   return FALSE;
13385 }
13386 \f
13387 /* Create a MIPS ELF linker hash table.  */
13388
13389 struct bfd_link_hash_table *
13390 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
13391 {
13392   struct mips_elf_link_hash_table *ret;
13393   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
13394
13395   ret = bfd_zmalloc (amt);
13396   if (ret == NULL)
13397     return NULL;
13398
13399   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
13400                                       mips_elf_link_hash_newfunc,
13401                                       sizeof (struct mips_elf_link_hash_entry),
13402                                       MIPS_ELF_DATA))
13403     {
13404       free (ret);
13405       return NULL;
13406     }
13407   ret->root.init_plt_refcount.plist = NULL;
13408   ret->root.init_plt_offset.plist = NULL;
13409
13410   return &ret->root.root;
13411 }
13412
13413 /* Likewise, but indicate that the target is VxWorks.  */
13414
13415 struct bfd_link_hash_table *
13416 _bfd_mips_vxworks_link_hash_table_create (bfd *abfd)
13417 {
13418   struct bfd_link_hash_table *ret;
13419
13420   ret = _bfd_mips_elf_link_hash_table_create (abfd);
13421   if (ret)
13422     {
13423       struct mips_elf_link_hash_table *htab;
13424
13425       htab = (struct mips_elf_link_hash_table *) ret;
13426       htab->use_plts_and_copy_relocs = TRUE;
13427       htab->is_vxworks = TRUE;
13428     }
13429   return ret;
13430 }
13431
13432 /* A function that the linker calls if we are allowed to use PLTs
13433    and copy relocs.  */
13434
13435 void
13436 _bfd_mips_elf_use_plts_and_copy_relocs (struct bfd_link_info *info)
13437 {
13438   mips_elf_hash_table (info)->use_plts_and_copy_relocs = TRUE;
13439 }
13440 \f
13441 /* We need to use a special link routine to handle the .reginfo and
13442    the .mdebug sections.  We need to merge all instances of these
13443    sections together, not write them all out sequentially.  */
13444
13445 bfd_boolean
13446 _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info)
13447 {
13448   asection *o;
13449   struct bfd_link_order *p;
13450   asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec;
13451   asection *rtproc_sec;
13452   Elf32_RegInfo reginfo;
13453   struct ecoff_debug_info debug;
13454   struct mips_htab_traverse_info hti;
13455   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13456   const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap;
13457   HDRR *symhdr = &debug.symbolic_header;
13458   void *mdebug_handle = NULL;
13459   asection *s;
13460   EXTR esym;
13461   unsigned int i;
13462   bfd_size_type amt;
13463   struct mips_elf_link_hash_table *htab;
13464
13465   static const char * const secname[] =
13466   {
13467     ".text", ".init", ".fini", ".data",
13468     ".rodata", ".sdata", ".sbss", ".bss"
13469   };
13470   static const int sc[] =
13471   {
13472     scText, scInit, scFini, scData,
13473     scRData, scSData, scSBss, scBss
13474   };
13475
13476   /* Sort the dynamic symbols so that those with GOT entries come after
13477      those without.  */
13478   htab = mips_elf_hash_table (info);
13479   BFD_ASSERT (htab != NULL);
13480
13481   if (!mips_elf_sort_hash_table (abfd, info))
13482     return FALSE;
13483
13484   /* Create any scheduled LA25 stubs.  */
13485   hti.info = info;
13486   hti.output_bfd = abfd;
13487   hti.error = FALSE;
13488   htab_traverse (htab->la25_stubs, mips_elf_create_la25_stub, &hti);
13489   if (hti.error)
13490     return FALSE;
13491
13492   /* Get a value for the GP register.  */
13493   if (elf_gp (abfd) == 0)
13494     {
13495       struct bfd_link_hash_entry *h;
13496
13497       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
13498       if (h != NULL && h->type == bfd_link_hash_defined)
13499         elf_gp (abfd) = (h->u.def.value
13500                          + h->u.def.section->output_section->vma
13501                          + h->u.def.section->output_offset);
13502       else if (htab->is_vxworks
13503                && (h = bfd_link_hash_lookup (info->hash,
13504                                              "_GLOBAL_OFFSET_TABLE_",
13505                                              FALSE, FALSE, TRUE))
13506                && h->type == bfd_link_hash_defined)
13507         elf_gp (abfd) = (h->u.def.section->output_section->vma
13508                          + h->u.def.section->output_offset
13509                          + h->u.def.value);
13510       else if (info->relocatable)
13511         {
13512           bfd_vma lo = MINUS_ONE;
13513
13514           /* Find the GP-relative section with the lowest offset.  */
13515           for (o = abfd->sections; o != NULL; o = o->next)
13516             if (o->vma < lo
13517                 && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL))
13518               lo = o->vma;
13519
13520           /* And calculate GP relative to that.  */
13521           elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (info);
13522         }
13523       else
13524         {
13525           /* If the relocate_section function needs to do a reloc
13526              involving the GP value, it should make a reloc_dangerous
13527              callback to warn that GP is not defined.  */
13528         }
13529     }
13530
13531   /* Go through the sections and collect the .reginfo and .mdebug
13532      information.  */
13533   reginfo_sec = NULL;
13534   mdebug_sec = NULL;
13535   gptab_data_sec = NULL;
13536   gptab_bss_sec = NULL;
13537   for (o = abfd->sections; o != NULL; o = o->next)
13538     {
13539       if (strcmp (o->name, ".reginfo") == 0)
13540         {
13541           memset (&reginfo, 0, sizeof reginfo);
13542
13543           /* We have found the .reginfo section in the output file.
13544              Look through all the link_orders comprising it and merge
13545              the information together.  */
13546           for (p = o->map_head.link_order; p != NULL; p = p->next)
13547             {
13548               asection *input_section;
13549               bfd *input_bfd;
13550               Elf32_External_RegInfo ext;
13551               Elf32_RegInfo sub;
13552
13553               if (p->type != bfd_indirect_link_order)
13554                 {
13555                   if (p->type == bfd_data_link_order)
13556                     continue;
13557                   abort ();
13558                 }
13559
13560               input_section = p->u.indirect.section;
13561               input_bfd = input_section->owner;
13562
13563               if (! bfd_get_section_contents (input_bfd, input_section,
13564                                               &ext, 0, sizeof ext))
13565                 return FALSE;
13566
13567               bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub);
13568
13569               reginfo.ri_gprmask |= sub.ri_gprmask;
13570               reginfo.ri_cprmask[0] |= sub.ri_cprmask[0];
13571               reginfo.ri_cprmask[1] |= sub.ri_cprmask[1];
13572               reginfo.ri_cprmask[2] |= sub.ri_cprmask[2];
13573               reginfo.ri_cprmask[3] |= sub.ri_cprmask[3];
13574
13575               /* ri_gp_value is set by the function
13576                  mips_elf32_section_processing when the section is
13577                  finally written out.  */
13578
13579               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13580                  elf_link_input_bfd ignores this section.  */
13581               input_section->flags &= ~SEC_HAS_CONTENTS;
13582             }
13583
13584           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
13585           BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo));
13586
13587           /* Skip this section later on (I don't think this currently
13588              matters, but someday it might).  */
13589           o->map_head.link_order = NULL;
13590
13591           reginfo_sec = o;
13592         }
13593
13594       if (strcmp (o->name, ".mdebug") == 0)
13595         {
13596           struct extsym_info einfo;
13597           bfd_vma last;
13598
13599           /* We have found the .mdebug section in the output file.
13600              Look through all the link_orders comprising it and merge
13601              the information together.  */
13602           symhdr->magic = swap->sym_magic;
13603           /* FIXME: What should the version stamp be?  */
13604           symhdr->vstamp = 0;
13605           symhdr->ilineMax = 0;
13606           symhdr->cbLine = 0;
13607           symhdr->idnMax = 0;
13608           symhdr->ipdMax = 0;
13609           symhdr->isymMax = 0;
13610           symhdr->ioptMax = 0;
13611           symhdr->iauxMax = 0;
13612           symhdr->issMax = 0;
13613           symhdr->issExtMax = 0;
13614           symhdr->ifdMax = 0;
13615           symhdr->crfd = 0;
13616           symhdr->iextMax = 0;
13617
13618           /* We accumulate the debugging information itself in the
13619              debug_info structure.  */
13620           debug.line = NULL;
13621           debug.external_dnr = NULL;
13622           debug.external_pdr = NULL;
13623           debug.external_sym = NULL;
13624           debug.external_opt = NULL;
13625           debug.external_aux = NULL;
13626           debug.ss = NULL;
13627           debug.ssext = debug.ssext_end = NULL;
13628           debug.external_fdr = NULL;
13629           debug.external_rfd = NULL;
13630           debug.external_ext = debug.external_ext_end = NULL;
13631
13632           mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info);
13633           if (mdebug_handle == NULL)
13634             return FALSE;
13635
13636           esym.jmptbl = 0;
13637           esym.cobol_main = 0;
13638           esym.weakext = 0;
13639           esym.reserved = 0;
13640           esym.ifd = ifdNil;
13641           esym.asym.iss = issNil;
13642           esym.asym.st = stLocal;
13643           esym.asym.reserved = 0;
13644           esym.asym.index = indexNil;
13645           last = 0;
13646           for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++)
13647             {
13648               esym.asym.sc = sc[i];
13649               s = bfd_get_section_by_name (abfd, secname[i]);
13650               if (s != NULL)
13651                 {
13652                   esym.asym.value = s->vma;
13653                   last = s->vma + s->size;
13654                 }
13655               else
13656                 esym.asym.value = last;
13657               if (!bfd_ecoff_debug_one_external (abfd, &debug, swap,
13658                                                  secname[i], &esym))
13659                 return FALSE;
13660             }
13661
13662           for (p = o->map_head.link_order; p != NULL; p = p->next)
13663             {
13664               asection *input_section;
13665               bfd *input_bfd;
13666               const struct ecoff_debug_swap *input_swap;
13667               struct ecoff_debug_info input_debug;
13668               char *eraw_src;
13669               char *eraw_end;
13670
13671               if (p->type != bfd_indirect_link_order)
13672                 {
13673                   if (p->type == bfd_data_link_order)
13674                     continue;
13675                   abort ();
13676                 }
13677
13678               input_section = p->u.indirect.section;
13679               input_bfd = input_section->owner;
13680
13681               if (!is_mips_elf (input_bfd))
13682                 {
13683                   /* I don't know what a non MIPS ELF bfd would be
13684                      doing with a .mdebug section, but I don't really
13685                      want to deal with it.  */
13686                   continue;
13687                 }
13688
13689               input_swap = (get_elf_backend_data (input_bfd)
13690                             ->elf_backend_ecoff_debug_swap);
13691
13692               BFD_ASSERT (p->size == input_section->size);
13693
13694               /* The ECOFF linking code expects that we have already
13695                  read in the debugging information and set up an
13696                  ecoff_debug_info structure, so we do that now.  */
13697               if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section,
13698                                                    &input_debug))
13699                 return FALSE;
13700
13701               if (! (bfd_ecoff_debug_accumulate
13702                      (mdebug_handle, abfd, &debug, swap, input_bfd,
13703                       &input_debug, input_swap, info)))
13704                 return FALSE;
13705
13706               /* Loop through the external symbols.  For each one with
13707                  interesting information, try to find the symbol in
13708                  the linker global hash table and save the information
13709                  for the output external symbols.  */
13710               eraw_src = input_debug.external_ext;
13711               eraw_end = (eraw_src
13712                           + (input_debug.symbolic_header.iextMax
13713                              * input_swap->external_ext_size));
13714               for (;
13715                    eraw_src < eraw_end;
13716                    eraw_src += input_swap->external_ext_size)
13717                 {
13718                   EXTR ext;
13719                   const char *name;
13720                   struct mips_elf_link_hash_entry *h;
13721
13722                   (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext);
13723                   if (ext.asym.sc == scNil
13724                       || ext.asym.sc == scUndefined
13725                       || ext.asym.sc == scSUndefined)
13726                     continue;
13727
13728                   name = input_debug.ssext + ext.asym.iss;
13729                   h = mips_elf_link_hash_lookup (mips_elf_hash_table (info),
13730                                                  name, FALSE, FALSE, TRUE);
13731                   if (h == NULL || h->esym.ifd != -2)
13732                     continue;
13733
13734                   if (ext.ifd != -1)
13735                     {
13736                       BFD_ASSERT (ext.ifd
13737                                   < input_debug.symbolic_header.ifdMax);
13738                       ext.ifd = input_debug.ifdmap[ext.ifd];
13739                     }
13740
13741                   h->esym = ext;
13742                 }
13743
13744               /* Free up the information we just read.  */
13745               free (input_debug.line);
13746               free (input_debug.external_dnr);
13747               free (input_debug.external_pdr);
13748               free (input_debug.external_sym);
13749               free (input_debug.external_opt);
13750               free (input_debug.external_aux);
13751               free (input_debug.ss);
13752               free (input_debug.ssext);
13753               free (input_debug.external_fdr);
13754               free (input_debug.external_rfd);
13755               free (input_debug.external_ext);
13756
13757               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13758                  elf_link_input_bfd ignores this section.  */
13759               input_section->flags &= ~SEC_HAS_CONTENTS;
13760             }
13761
13762           if (SGI_COMPAT (abfd) && info->shared)
13763             {
13764               /* Create .rtproc section.  */
13765               rtproc_sec = bfd_get_linker_section (abfd, ".rtproc");
13766               if (rtproc_sec == NULL)
13767                 {
13768                   flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
13769                                     | SEC_LINKER_CREATED | SEC_READONLY);
13770
13771                   rtproc_sec = bfd_make_section_anyway_with_flags (abfd,
13772                                                                    ".rtproc",
13773                                                                    flags);
13774                   if (rtproc_sec == NULL
13775                       || ! bfd_set_section_alignment (abfd, rtproc_sec, 4))
13776                     return FALSE;
13777                 }
13778
13779               if (! mips_elf_create_procedure_table (mdebug_handle, abfd,
13780                                                      info, rtproc_sec,
13781                                                      &debug))
13782                 return FALSE;
13783             }
13784
13785           /* Build the external symbol information.  */
13786           einfo.abfd = abfd;
13787           einfo.info = info;
13788           einfo.debug = &debug;
13789           einfo.swap = swap;
13790           einfo.failed = FALSE;
13791           mips_elf_link_hash_traverse (mips_elf_hash_table (info),
13792                                        mips_elf_output_extsym, &einfo);
13793           if (einfo.failed)
13794             return FALSE;
13795
13796           /* Set the size of the .mdebug section.  */
13797           o->size = bfd_ecoff_debug_size (abfd, &debug, swap);
13798
13799           /* Skip this section later on (I don't think this currently
13800              matters, but someday it might).  */
13801           o->map_head.link_order = NULL;
13802
13803           mdebug_sec = o;
13804         }
13805
13806       if (CONST_STRNEQ (o->name, ".gptab."))
13807         {
13808           const char *subname;
13809           unsigned int c;
13810           Elf32_gptab *tab;
13811           Elf32_External_gptab *ext_tab;
13812           unsigned int j;
13813
13814           /* The .gptab.sdata and .gptab.sbss sections hold
13815              information describing how the small data area would
13816              change depending upon the -G switch.  These sections
13817              not used in executables files.  */
13818           if (! info->relocatable)
13819             {
13820               for (p = o->map_head.link_order; p != NULL; p = p->next)
13821                 {
13822                   asection *input_section;
13823
13824                   if (p->type != bfd_indirect_link_order)
13825                     {
13826                       if (p->type == bfd_data_link_order)
13827                         continue;
13828                       abort ();
13829                     }
13830
13831                   input_section = p->u.indirect.section;
13832
13833                   /* Hack: reset the SEC_HAS_CONTENTS flag so that
13834                      elf_link_input_bfd ignores this section.  */
13835                   input_section->flags &= ~SEC_HAS_CONTENTS;
13836                 }
13837
13838               /* Skip this section later on (I don't think this
13839                  currently matters, but someday it might).  */
13840               o->map_head.link_order = NULL;
13841
13842               /* Really remove the section.  */
13843               bfd_section_list_remove (abfd, o);
13844               --abfd->section_count;
13845
13846               continue;
13847             }
13848
13849           /* There is one gptab for initialized data, and one for
13850              uninitialized data.  */
13851           if (strcmp (o->name, ".gptab.sdata") == 0)
13852             gptab_data_sec = o;
13853           else if (strcmp (o->name, ".gptab.sbss") == 0)
13854             gptab_bss_sec = o;
13855           else
13856             {
13857               (*_bfd_error_handler)
13858                 (_("%s: illegal section name `%s'"),
13859                  bfd_get_filename (abfd), o->name);
13860               bfd_set_error (bfd_error_nonrepresentable_section);
13861               return FALSE;
13862             }
13863
13864           /* The linker script always combines .gptab.data and
13865              .gptab.sdata into .gptab.sdata, and likewise for
13866              .gptab.bss and .gptab.sbss.  It is possible that there is
13867              no .sdata or .sbss section in the output file, in which
13868              case we must change the name of the output section.  */
13869           subname = o->name + sizeof ".gptab" - 1;
13870           if (bfd_get_section_by_name (abfd, subname) == NULL)
13871             {
13872               if (o == gptab_data_sec)
13873                 o->name = ".gptab.data";
13874               else
13875                 o->name = ".gptab.bss";
13876               subname = o->name + sizeof ".gptab" - 1;
13877               BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL);
13878             }
13879
13880           /* Set up the first entry.  */
13881           c = 1;
13882           amt = c * sizeof (Elf32_gptab);
13883           tab = bfd_malloc (amt);
13884           if (tab == NULL)
13885             return FALSE;
13886           tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd);
13887           tab[0].gt_header.gt_unused = 0;
13888
13889           /* Combine the input sections.  */
13890           for (p = o->map_head.link_order; p != NULL; p = p->next)
13891             {
13892               asection *input_section;
13893               bfd *input_bfd;
13894               bfd_size_type size;
13895               unsigned long last;
13896               bfd_size_type gpentry;
13897
13898               if (p->type != bfd_indirect_link_order)
13899                 {
13900                   if (p->type == bfd_data_link_order)
13901                     continue;
13902                   abort ();
13903                 }
13904
13905               input_section = p->u.indirect.section;
13906               input_bfd = input_section->owner;
13907
13908               /* Combine the gptab entries for this input section one
13909                  by one.  We know that the input gptab entries are
13910                  sorted by ascending -G value.  */
13911               size = input_section->size;
13912               last = 0;
13913               for (gpentry = sizeof (Elf32_External_gptab);
13914                    gpentry < size;
13915                    gpentry += sizeof (Elf32_External_gptab))
13916                 {
13917                   Elf32_External_gptab ext_gptab;
13918                   Elf32_gptab int_gptab;
13919                   unsigned long val;
13920                   unsigned long add;
13921                   bfd_boolean exact;
13922                   unsigned int look;
13923
13924                   if (! (bfd_get_section_contents
13925                          (input_bfd, input_section, &ext_gptab, gpentry,
13926                           sizeof (Elf32_External_gptab))))
13927                     {
13928                       free (tab);
13929                       return FALSE;
13930                     }
13931
13932                   bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab,
13933                                                 &int_gptab);
13934                   val = int_gptab.gt_entry.gt_g_value;
13935                   add = int_gptab.gt_entry.gt_bytes - last;
13936
13937                   exact = FALSE;
13938                   for (look = 1; look < c; look++)
13939                     {
13940                       if (tab[look].gt_entry.gt_g_value >= val)
13941                         tab[look].gt_entry.gt_bytes += add;
13942
13943                       if (tab[look].gt_entry.gt_g_value == val)
13944                         exact = TRUE;
13945                     }
13946
13947                   if (! exact)
13948                     {
13949                       Elf32_gptab *new_tab;
13950                       unsigned int max;
13951
13952                       /* We need a new table entry.  */
13953                       amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab);
13954                       new_tab = bfd_realloc (tab, amt);
13955                       if (new_tab == NULL)
13956                         {
13957                           free (tab);
13958                           return FALSE;
13959                         }
13960                       tab = new_tab;
13961                       tab[c].gt_entry.gt_g_value = val;
13962                       tab[c].gt_entry.gt_bytes = add;
13963
13964                       /* Merge in the size for the next smallest -G
13965                          value, since that will be implied by this new
13966                          value.  */
13967                       max = 0;
13968                       for (look = 1; look < c; look++)
13969                         {
13970                           if (tab[look].gt_entry.gt_g_value < val
13971                               && (max == 0
13972                                   || (tab[look].gt_entry.gt_g_value
13973                                       > tab[max].gt_entry.gt_g_value)))
13974                             max = look;
13975                         }
13976                       if (max != 0)
13977                         tab[c].gt_entry.gt_bytes +=
13978                           tab[max].gt_entry.gt_bytes;
13979
13980                       ++c;
13981                     }
13982
13983                   last = int_gptab.gt_entry.gt_bytes;
13984                 }
13985
13986               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13987                  elf_link_input_bfd ignores this section.  */
13988               input_section->flags &= ~SEC_HAS_CONTENTS;
13989             }
13990
13991           /* The table must be sorted by -G value.  */
13992           if (c > 2)
13993             qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare);
13994
13995           /* Swap out the table.  */
13996           amt = (bfd_size_type) c * sizeof (Elf32_External_gptab);
13997           ext_tab = bfd_alloc (abfd, amt);
13998           if (ext_tab == NULL)
13999             {
14000               free (tab);
14001               return FALSE;
14002             }
14003
14004           for (j = 0; j < c; j++)
14005             bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j);
14006           free (tab);
14007
14008           o->size = c * sizeof (Elf32_External_gptab);
14009           o->contents = (bfd_byte *) ext_tab;
14010
14011           /* Skip this section later on (I don't think this currently
14012              matters, but someday it might).  */
14013           o->map_head.link_order = NULL;
14014         }
14015     }
14016
14017   /* Invoke the regular ELF backend linker to do all the work.  */
14018   if (!bfd_elf_final_link (abfd, info))
14019     return FALSE;
14020
14021   /* Now write out the computed sections.  */
14022
14023   if (reginfo_sec != NULL)
14024     {
14025       Elf32_External_RegInfo ext;
14026
14027       bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext);
14028       if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext))
14029         return FALSE;
14030     }
14031
14032   if (mdebug_sec != NULL)
14033     {
14034       BFD_ASSERT (abfd->output_has_begun);
14035       if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug,
14036                                                swap, info,
14037                                                mdebug_sec->filepos))
14038         return FALSE;
14039
14040       bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info);
14041     }
14042
14043   if (gptab_data_sec != NULL)
14044     {
14045       if (! bfd_set_section_contents (abfd, gptab_data_sec,
14046                                       gptab_data_sec->contents,
14047                                       0, gptab_data_sec->size))
14048         return FALSE;
14049     }
14050
14051   if (gptab_bss_sec != NULL)
14052     {
14053       if (! bfd_set_section_contents (abfd, gptab_bss_sec,
14054                                       gptab_bss_sec->contents,
14055                                       0, gptab_bss_sec->size))
14056         return FALSE;
14057     }
14058
14059   if (SGI_COMPAT (abfd))
14060     {
14061       rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
14062       if (rtproc_sec != NULL)
14063         {
14064           if (! bfd_set_section_contents (abfd, rtproc_sec,
14065                                           rtproc_sec->contents,
14066                                           0, rtproc_sec->size))
14067             return FALSE;
14068         }
14069     }
14070
14071   return TRUE;
14072 }
14073 \f
14074 /* Structure for saying that BFD machine EXTENSION extends BASE.  */
14075
14076 struct mips_mach_extension
14077 {
14078   unsigned long extension, base;
14079 };
14080
14081
14082 /* An array describing how BFD machines relate to one another.  The entries
14083    are ordered topologically with MIPS I extensions listed last.  */
14084
14085 static const struct mips_mach_extension mips_mach_extensions[] =
14086 {
14087   /* MIPS64r2 extensions.  */
14088   { bfd_mach_mips_octeon2, bfd_mach_mips_octeonp },
14089   { bfd_mach_mips_octeonp, bfd_mach_mips_octeon },
14090   { bfd_mach_mips_octeon, bfd_mach_mipsisa64r2 },
14091
14092   /* MIPS64 extensions.  */
14093   { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 },
14094   { bfd_mach_mips_sb1, bfd_mach_mipsisa64 },
14095   { bfd_mach_mips_xlr, bfd_mach_mipsisa64 },
14096   { bfd_mach_mips_loongson_3a, bfd_mach_mipsisa64 },
14097
14098   /* MIPS V extensions.  */
14099   { bfd_mach_mipsisa64, bfd_mach_mips5 },
14100
14101   /* R10000 extensions.  */
14102   { bfd_mach_mips12000, bfd_mach_mips10000 },
14103   { bfd_mach_mips14000, bfd_mach_mips10000 },
14104   { bfd_mach_mips16000, bfd_mach_mips10000 },
14105
14106   /* R5000 extensions.  Note: the vr5500 ISA is an extension of the core
14107      vr5400 ISA, but doesn't include the multimedia stuff.  It seems
14108      better to allow vr5400 and vr5500 code to be merged anyway, since
14109      many libraries will just use the core ISA.  Perhaps we could add
14110      some sort of ASE flag if this ever proves a problem.  */
14111   { bfd_mach_mips5500, bfd_mach_mips5400 },
14112   { bfd_mach_mips5400, bfd_mach_mips5000 },
14113
14114   /* MIPS IV extensions.  */
14115   { bfd_mach_mips5, bfd_mach_mips8000 },
14116   { bfd_mach_mips10000, bfd_mach_mips8000 },
14117   { bfd_mach_mips5000, bfd_mach_mips8000 },
14118   { bfd_mach_mips7000, bfd_mach_mips8000 },
14119   { bfd_mach_mips9000, bfd_mach_mips8000 },
14120
14121   /* VR4100 extensions.  */
14122   { bfd_mach_mips4120, bfd_mach_mips4100 },
14123   { bfd_mach_mips4111, bfd_mach_mips4100 },
14124
14125   /* MIPS III extensions.  */
14126   { bfd_mach_mips_loongson_2e, bfd_mach_mips4000 },
14127   { bfd_mach_mips_loongson_2f, bfd_mach_mips4000 },
14128   { bfd_mach_mips8000, bfd_mach_mips4000 },
14129   { bfd_mach_mips4650, bfd_mach_mips4000 },
14130   { bfd_mach_mips4600, bfd_mach_mips4000 },
14131   { bfd_mach_mips4400, bfd_mach_mips4000 },
14132   { bfd_mach_mips4300, bfd_mach_mips4000 },
14133   { bfd_mach_mips4100, bfd_mach_mips4000 },
14134   { bfd_mach_mips4010, bfd_mach_mips4000 },
14135   { bfd_mach_mips5900, bfd_mach_mips4000 },
14136
14137   /* MIPS32 extensions.  */
14138   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
14139
14140   /* MIPS II extensions.  */
14141   { bfd_mach_mips4000, bfd_mach_mips6000 },
14142   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
14143
14144   /* MIPS I extensions.  */
14145   { bfd_mach_mips6000, bfd_mach_mips3000 },
14146   { bfd_mach_mips3900, bfd_mach_mips3000 }
14147 };
14148
14149
14150 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
14151
14152 static bfd_boolean
14153 mips_mach_extends_p (unsigned long base, unsigned long extension)
14154 {
14155   size_t i;
14156
14157   if (extension == base)
14158     return TRUE;
14159
14160   if (base == bfd_mach_mipsisa32
14161       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
14162     return TRUE;
14163
14164   if (base == bfd_mach_mipsisa32r2
14165       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
14166     return TRUE;
14167
14168   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
14169     if (extension == mips_mach_extensions[i].extension)
14170       {
14171         extension = mips_mach_extensions[i].base;
14172         if (extension == base)
14173           return TRUE;
14174       }
14175
14176   return FALSE;
14177 }
14178
14179
14180 /* Return true if the given ELF header flags describe a 32-bit binary.  */
14181
14182 static bfd_boolean
14183 mips_32bit_flags_p (flagword flags)
14184 {
14185   return ((flags & EF_MIPS_32BITMODE) != 0
14186           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
14187           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
14188           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
14189           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
14190           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
14191           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2);
14192 }
14193
14194
14195 /* Merge object attributes from IBFD into OBFD.  Raise an error if
14196    there are conflicting attributes.  */
14197 static bfd_boolean
14198 mips_elf_merge_obj_attributes (bfd *ibfd, bfd *obfd)
14199 {
14200   obj_attribute *in_attr;
14201   obj_attribute *out_attr;
14202   bfd *abi_fp_bfd;
14203
14204   abi_fp_bfd = mips_elf_tdata (obfd)->abi_fp_bfd;
14205   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
14206   if (!abi_fp_bfd && in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
14207     mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
14208
14209   if (!elf_known_obj_attributes_proc (obfd)[0].i)
14210     {
14211       /* This is the first object.  Copy the attributes.  */
14212       _bfd_elf_copy_obj_attributes (ibfd, obfd);
14213
14214       /* Use the Tag_null value to indicate the attributes have been
14215          initialized.  */
14216       elf_known_obj_attributes_proc (obfd)[0].i = 1;
14217
14218       return TRUE;
14219     }
14220
14221   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
14222      non-conflicting ones.  */
14223   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
14224   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
14225     {
14226       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
14227       if (out_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
14228         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
14229       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
14230         switch (out_attr[Tag_GNU_MIPS_ABI_FP].i)
14231           {
14232           case 1:
14233             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
14234               {
14235               case 2:
14236                 _bfd_error_handler
14237                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14238                    obfd, abi_fp_bfd, ibfd, "-mdouble-float", "-msingle-float");
14239                 break;
14240
14241               case 3:
14242                 _bfd_error_handler
14243                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14244                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
14245                 break;
14246
14247               case 4:
14248                 _bfd_error_handler
14249                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14250                    obfd, abi_fp_bfd, ibfd,
14251                    "-mdouble-float", "-mips32r2 -mfp64");
14252                 break;
14253
14254               default:
14255                 _bfd_error_handler
14256                   (_("Warning: %B uses %s (set by %B), "
14257                      "%B uses unknown floating point ABI %d"),
14258                    obfd, abi_fp_bfd, ibfd,
14259                    "-mdouble-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
14260                 break;
14261               }
14262             break;
14263
14264           case 2:
14265             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
14266               {
14267               case 1:
14268                 _bfd_error_handler
14269                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14270                    obfd, abi_fp_bfd, ibfd, "-msingle-float", "-mdouble-float");
14271                 break;
14272
14273               case 3:
14274                 _bfd_error_handler
14275                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14276                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
14277                 break;
14278
14279               case 4:
14280                 _bfd_error_handler
14281                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14282                    obfd, abi_fp_bfd, ibfd,
14283                    "-msingle-float", "-mips32r2 -mfp64");
14284                 break;
14285
14286               default:
14287                 _bfd_error_handler
14288                   (_("Warning: %B uses %s (set by %B), "
14289                      "%B uses unknown floating point ABI %d"),
14290                    obfd, abi_fp_bfd, ibfd,
14291                    "-msingle-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
14292                 break;
14293               }
14294             break;
14295
14296           case 3:
14297             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
14298               {
14299               case 1:
14300               case 2:
14301               case 4:
14302                 _bfd_error_handler
14303                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14304                    obfd, abi_fp_bfd, ibfd, "-msoft-float", "-mhard-float");
14305                 break;
14306
14307               default:
14308                 _bfd_error_handler
14309                   (_("Warning: %B uses %s (set by %B), "
14310                      "%B uses unknown floating point ABI %d"),
14311                    obfd, abi_fp_bfd, ibfd,
14312                    "-msoft-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
14313                 break;
14314               }
14315             break;
14316
14317           case 4:
14318             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
14319               {
14320               case 1:
14321                 _bfd_error_handler
14322                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14323                    obfd, abi_fp_bfd, ibfd,
14324                    "-mips32r2 -mfp64", "-mdouble-float");
14325                 break;
14326
14327               case 2:
14328                 _bfd_error_handler
14329                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14330                    obfd, abi_fp_bfd, ibfd,
14331                    "-mips32r2 -mfp64", "-msingle-float");
14332                 break;
14333
14334               case 3:
14335                 _bfd_error_handler
14336                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14337                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
14338                 break;
14339
14340               default:
14341                 _bfd_error_handler
14342                   (_("Warning: %B uses %s (set by %B), "
14343                      "%B uses unknown floating point ABI %d"),
14344                    obfd, abi_fp_bfd, ibfd,
14345                    "-mips32r2 -mfp64", in_attr[Tag_GNU_MIPS_ABI_FP].i);
14346                 break;
14347               }
14348             break;
14349
14350           default:
14351             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
14352               {
14353               case 1:
14354                 _bfd_error_handler
14355                   (_("Warning: %B uses unknown floating point ABI %d "
14356                      "(set by %B), %B uses %s"),
14357                    obfd, abi_fp_bfd, ibfd,
14358                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mdouble-float");
14359                 break;
14360
14361               case 2:
14362                 _bfd_error_handler
14363                   (_("Warning: %B uses unknown floating point ABI %d "
14364                      "(set by %B), %B uses %s"),
14365                    obfd, abi_fp_bfd, ibfd,
14366                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msingle-float");
14367                 break;
14368
14369               case 3:
14370                 _bfd_error_handler
14371                   (_("Warning: %B uses unknown floating point ABI %d "
14372                      "(set by %B), %B uses %s"),
14373                    obfd, abi_fp_bfd, ibfd,
14374                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msoft-float");
14375                 break;
14376
14377               case 4:
14378                 _bfd_error_handler
14379                   (_("Warning: %B uses unknown floating point ABI %d "
14380                      "(set by %B), %B uses %s"),
14381                    obfd, abi_fp_bfd, ibfd,
14382                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mips32r2 -mfp64");
14383                 break;
14384
14385               default:
14386                 _bfd_error_handler
14387                   (_("Warning: %B uses unknown floating point ABI %d "
14388                      "(set by %B), %B uses unknown floating point ABI %d"),
14389                    obfd, abi_fp_bfd, ibfd,
14390                    out_attr[Tag_GNU_MIPS_ABI_FP].i,
14391                    in_attr[Tag_GNU_MIPS_ABI_FP].i);
14392                 break;
14393               }
14394             break;
14395           }
14396     }
14397
14398   /* Merge Tag_compatibility attributes and any common GNU ones.  */
14399   _bfd_elf_merge_object_attributes (ibfd, obfd);
14400
14401   return TRUE;
14402 }
14403
14404 /* Merge backend specific data from an object file to the output
14405    object file when linking.  */
14406
14407 bfd_boolean
14408 _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
14409 {
14410   flagword old_flags;
14411   flagword new_flags;
14412   bfd_boolean ok;
14413   bfd_boolean null_input_bfd = TRUE;
14414   asection *sec;
14415
14416   /* Check if we have the same endianness.  */
14417   if (! _bfd_generic_verify_endian_match (ibfd, obfd))
14418     {
14419       (*_bfd_error_handler)
14420         (_("%B: endianness incompatible with that of the selected emulation"),
14421          ibfd);
14422       return FALSE;
14423     }
14424
14425   if (!is_mips_elf (ibfd) || !is_mips_elf (obfd))
14426     return TRUE;
14427
14428   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
14429     {
14430       (*_bfd_error_handler)
14431         (_("%B: ABI is incompatible with that of the selected emulation"),
14432          ibfd);
14433       return FALSE;
14434     }
14435
14436   if (!mips_elf_merge_obj_attributes (ibfd, obfd))
14437     return FALSE;
14438
14439   new_flags = elf_elfheader (ibfd)->e_flags;
14440   elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER;
14441   old_flags = elf_elfheader (obfd)->e_flags;
14442
14443   if (! elf_flags_init (obfd))
14444     {
14445       elf_flags_init (obfd) = TRUE;
14446       elf_elfheader (obfd)->e_flags = new_flags;
14447       elf_elfheader (obfd)->e_ident[EI_CLASS]
14448         = elf_elfheader (ibfd)->e_ident[EI_CLASS];
14449
14450       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
14451           && (bfd_get_arch_info (obfd)->the_default
14452               || mips_mach_extends_p (bfd_get_mach (obfd),
14453                                       bfd_get_mach (ibfd))))
14454         {
14455           if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
14456                                    bfd_get_mach (ibfd)))
14457             return FALSE;
14458         }
14459
14460       return TRUE;
14461     }
14462
14463   /* Check flag compatibility.  */
14464
14465   new_flags &= ~EF_MIPS_NOREORDER;
14466   old_flags &= ~EF_MIPS_NOREORDER;
14467
14468   /* Some IRIX 6 BSD-compatibility objects have this bit set.  It
14469      doesn't seem to matter.  */
14470   new_flags &= ~EF_MIPS_XGOT;
14471   old_flags &= ~EF_MIPS_XGOT;
14472
14473   /* MIPSpro generates ucode info in n64 objects.  Again, we should
14474      just be able to ignore this.  */
14475   new_flags &= ~EF_MIPS_UCODE;
14476   old_flags &= ~EF_MIPS_UCODE;
14477
14478   /* DSOs should only be linked with CPIC code.  */
14479   if ((ibfd->flags & DYNAMIC) != 0)
14480     new_flags |= EF_MIPS_PIC | EF_MIPS_CPIC;
14481
14482   if (new_flags == old_flags)
14483     return TRUE;
14484
14485   /* Check to see if the input BFD actually contains any sections.
14486      If not, its flags may not have been initialised either, but it cannot
14487      actually cause any incompatibility.  */
14488   for (sec = ibfd->sections; sec != NULL; sec = sec->next)
14489     {
14490       /* Ignore synthetic sections and empty .text, .data and .bss sections
14491          which are automatically generated by gas.  Also ignore fake
14492          (s)common sections, since merely defining a common symbol does
14493          not affect compatibility.  */
14494       if ((sec->flags & SEC_IS_COMMON) == 0
14495           && strcmp (sec->name, ".reginfo")
14496           && strcmp (sec->name, ".mdebug")
14497           && (sec->size != 0
14498               || (strcmp (sec->name, ".text")
14499                   && strcmp (sec->name, ".data")
14500                   && strcmp (sec->name, ".bss"))))
14501         {
14502           null_input_bfd = FALSE;
14503           break;
14504         }
14505     }
14506   if (null_input_bfd)
14507     return TRUE;
14508
14509   ok = TRUE;
14510
14511   if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)
14512       != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0))
14513     {
14514       (*_bfd_error_handler)
14515         (_("%B: warning: linking abicalls files with non-abicalls files"),
14516          ibfd);
14517       ok = TRUE;
14518     }
14519
14520   if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC))
14521     elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC;
14522   if (! (new_flags & EF_MIPS_PIC))
14523     elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC;
14524
14525   new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
14526   old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
14527
14528   /* Compare the ISAs.  */
14529   if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags))
14530     {
14531       (*_bfd_error_handler)
14532         (_("%B: linking 32-bit code with 64-bit code"),
14533          ibfd);
14534       ok = FALSE;
14535     }
14536   else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd)))
14537     {
14538       /* OBFD's ISA isn't the same as, or an extension of, IBFD's.  */
14539       if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd)))
14540         {
14541           /* Copy the architecture info from IBFD to OBFD.  Also copy
14542              the 32-bit flag (if set) so that we continue to recognise
14543              OBFD as a 32-bit binary.  */
14544           bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd));
14545           elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
14546           elf_elfheader (obfd)->e_flags
14547             |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14548
14549           /* Copy across the ABI flags if OBFD doesn't use them
14550              and if that was what caused us to treat IBFD as 32-bit.  */
14551           if ((old_flags & EF_MIPS_ABI) == 0
14552               && mips_32bit_flags_p (new_flags)
14553               && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI))
14554             elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI;
14555         }
14556       else
14557         {
14558           /* The ISAs aren't compatible.  */
14559           (*_bfd_error_handler)
14560             (_("%B: linking %s module with previous %s modules"),
14561              ibfd,
14562              bfd_printable_name (ibfd),
14563              bfd_printable_name (obfd));
14564           ok = FALSE;
14565         }
14566     }
14567
14568   new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14569   old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14570
14571   /* Compare ABIs.  The 64-bit ABI does not use EF_MIPS_ABI.  But, it
14572      does set EI_CLASS differently from any 32-bit ABI.  */
14573   if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI)
14574       || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14575           != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14576     {
14577       /* Only error if both are set (to different values).  */
14578       if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI))
14579           || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14580               != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14581         {
14582           (*_bfd_error_handler)
14583             (_("%B: ABI mismatch: linking %s module with previous %s modules"),
14584              ibfd,
14585              elf_mips_abi_name (ibfd),
14586              elf_mips_abi_name (obfd));
14587           ok = FALSE;
14588         }
14589       new_flags &= ~EF_MIPS_ABI;
14590       old_flags &= ~EF_MIPS_ABI;
14591     }
14592
14593   /* Compare ASEs.  Forbid linking MIPS16 and microMIPS ASE modules together
14594      and allow arbitrary mixing of the remaining ASEs (retain the union).  */
14595   if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE))
14596     {
14597       int old_micro = old_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14598       int new_micro = new_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14599       int old_m16 = old_flags & EF_MIPS_ARCH_ASE_M16;
14600       int new_m16 = new_flags & EF_MIPS_ARCH_ASE_M16;
14601       int micro_mis = old_m16 && new_micro;
14602       int m16_mis = old_micro && new_m16;
14603
14604       if (m16_mis || micro_mis)
14605         {
14606           (*_bfd_error_handler)
14607             (_("%B: ASE mismatch: linking %s module with previous %s modules"),
14608              ibfd,
14609              m16_mis ? "MIPS16" : "microMIPS",
14610              m16_mis ? "microMIPS" : "MIPS16");
14611           ok = FALSE;
14612         }
14613
14614       elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE;
14615
14616       new_flags &= ~ EF_MIPS_ARCH_ASE;
14617       old_flags &= ~ EF_MIPS_ARCH_ASE;
14618     }
14619
14620   /* Warn about any other mismatches */
14621   if (new_flags != old_flags)
14622     {
14623       (*_bfd_error_handler)
14624         (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"),
14625          ibfd, (unsigned long) new_flags,
14626          (unsigned long) old_flags);
14627       ok = FALSE;
14628     }
14629
14630   if (! ok)
14631     {
14632       bfd_set_error (bfd_error_bad_value);
14633       return FALSE;
14634     }
14635
14636   return TRUE;
14637 }
14638
14639 /* Function to keep MIPS specific file flags like as EF_MIPS_PIC.  */
14640
14641 bfd_boolean
14642 _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags)
14643 {
14644   BFD_ASSERT (!elf_flags_init (abfd)
14645               || elf_elfheader (abfd)->e_flags == flags);
14646
14647   elf_elfheader (abfd)->e_flags = flags;
14648   elf_flags_init (abfd) = TRUE;
14649   return TRUE;
14650 }
14651
14652 char *
14653 _bfd_mips_elf_get_target_dtag (bfd_vma dtag)
14654 {
14655   switch (dtag)
14656     {
14657     default: return "";
14658     case DT_MIPS_RLD_VERSION:
14659       return "MIPS_RLD_VERSION";
14660     case DT_MIPS_TIME_STAMP:
14661       return "MIPS_TIME_STAMP";
14662     case DT_MIPS_ICHECKSUM:
14663       return "MIPS_ICHECKSUM";
14664     case DT_MIPS_IVERSION:
14665       return "MIPS_IVERSION";
14666     case DT_MIPS_FLAGS:
14667       return "MIPS_FLAGS";
14668     case DT_MIPS_BASE_ADDRESS:
14669       return "MIPS_BASE_ADDRESS";
14670     case DT_MIPS_MSYM:
14671       return "MIPS_MSYM";
14672     case DT_MIPS_CONFLICT:
14673       return "MIPS_CONFLICT";
14674     case DT_MIPS_LIBLIST:
14675       return "MIPS_LIBLIST";
14676     case DT_MIPS_LOCAL_GOTNO:
14677       return "MIPS_LOCAL_GOTNO";
14678     case DT_MIPS_CONFLICTNO:
14679       return "MIPS_CONFLICTNO";
14680     case DT_MIPS_LIBLISTNO:
14681       return "MIPS_LIBLISTNO";
14682     case DT_MIPS_SYMTABNO:
14683       return "MIPS_SYMTABNO";
14684     case DT_MIPS_UNREFEXTNO:
14685       return "MIPS_UNREFEXTNO";
14686     case DT_MIPS_GOTSYM:
14687       return "MIPS_GOTSYM";
14688     case DT_MIPS_HIPAGENO:
14689       return "MIPS_HIPAGENO";
14690     case DT_MIPS_RLD_MAP:
14691       return "MIPS_RLD_MAP";
14692     case DT_MIPS_DELTA_CLASS:
14693       return "MIPS_DELTA_CLASS";
14694     case DT_MIPS_DELTA_CLASS_NO:
14695       return "MIPS_DELTA_CLASS_NO";
14696     case DT_MIPS_DELTA_INSTANCE:
14697       return "MIPS_DELTA_INSTANCE";
14698     case DT_MIPS_DELTA_INSTANCE_NO:
14699       return "MIPS_DELTA_INSTANCE_NO";
14700     case DT_MIPS_DELTA_RELOC:
14701       return "MIPS_DELTA_RELOC";
14702     case DT_MIPS_DELTA_RELOC_NO:
14703       return "MIPS_DELTA_RELOC_NO";
14704     case DT_MIPS_DELTA_SYM:
14705       return "MIPS_DELTA_SYM";
14706     case DT_MIPS_DELTA_SYM_NO:
14707       return "MIPS_DELTA_SYM_NO";
14708     case DT_MIPS_DELTA_CLASSSYM:
14709       return "MIPS_DELTA_CLASSSYM";
14710     case DT_MIPS_DELTA_CLASSSYM_NO:
14711       return "MIPS_DELTA_CLASSSYM_NO";
14712     case DT_MIPS_CXX_FLAGS:
14713       return "MIPS_CXX_FLAGS";
14714     case DT_MIPS_PIXIE_INIT:
14715       return "MIPS_PIXIE_INIT";
14716     case DT_MIPS_SYMBOL_LIB:
14717       return "MIPS_SYMBOL_LIB";
14718     case DT_MIPS_LOCALPAGE_GOTIDX:
14719       return "MIPS_LOCALPAGE_GOTIDX";
14720     case DT_MIPS_LOCAL_GOTIDX:
14721       return "MIPS_LOCAL_GOTIDX";
14722     case DT_MIPS_HIDDEN_GOTIDX:
14723       return "MIPS_HIDDEN_GOTIDX";
14724     case DT_MIPS_PROTECTED_GOTIDX:
14725       return "MIPS_PROTECTED_GOT_IDX";
14726     case DT_MIPS_OPTIONS:
14727       return "MIPS_OPTIONS";
14728     case DT_MIPS_INTERFACE:
14729       return "MIPS_INTERFACE";
14730     case DT_MIPS_DYNSTR_ALIGN:
14731       return "DT_MIPS_DYNSTR_ALIGN";
14732     case DT_MIPS_INTERFACE_SIZE:
14733       return "DT_MIPS_INTERFACE_SIZE";
14734     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
14735       return "DT_MIPS_RLD_TEXT_RESOLVE_ADDR";
14736     case DT_MIPS_PERF_SUFFIX:
14737       return "DT_MIPS_PERF_SUFFIX";
14738     case DT_MIPS_COMPACT_SIZE:
14739       return "DT_MIPS_COMPACT_SIZE";
14740     case DT_MIPS_GP_VALUE:
14741       return "DT_MIPS_GP_VALUE";
14742     case DT_MIPS_AUX_DYNAMIC:
14743       return "DT_MIPS_AUX_DYNAMIC";
14744     case DT_MIPS_PLTGOT:
14745       return "DT_MIPS_PLTGOT";
14746     case DT_MIPS_RWPLT:
14747       return "DT_MIPS_RWPLT";
14748     }
14749 }
14750
14751 bfd_boolean
14752 _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr)
14753 {
14754   FILE *file = ptr;
14755
14756   BFD_ASSERT (abfd != NULL && ptr != NULL);
14757
14758   /* Print normal ELF private data.  */
14759   _bfd_elf_print_private_bfd_data (abfd, ptr);
14760
14761   /* xgettext:c-format */
14762   fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
14763
14764   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
14765     fprintf (file, _(" [abi=O32]"));
14766   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64)
14767     fprintf (file, _(" [abi=O64]"));
14768   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32)
14769     fprintf (file, _(" [abi=EABI32]"));
14770   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
14771     fprintf (file, _(" [abi=EABI64]"));
14772   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI))
14773     fprintf (file, _(" [abi unknown]"));
14774   else if (ABI_N32_P (abfd))
14775     fprintf (file, _(" [abi=N32]"));
14776   else if (ABI_64_P (abfd))
14777     fprintf (file, _(" [abi=64]"));
14778   else
14779     fprintf (file, _(" [no abi set]"));
14780
14781   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1)
14782     fprintf (file, " [mips1]");
14783   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2)
14784     fprintf (file, " [mips2]");
14785   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3)
14786     fprintf (file, " [mips3]");
14787   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4)
14788     fprintf (file, " [mips4]");
14789   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5)
14790     fprintf (file, " [mips5]");
14791   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32)
14792     fprintf (file, " [mips32]");
14793   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64)
14794     fprintf (file, " [mips64]");
14795   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2)
14796     fprintf (file, " [mips32r2]");
14797   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2)
14798     fprintf (file, " [mips64r2]");
14799   else
14800     fprintf (file, _(" [unknown ISA]"));
14801
14802   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
14803     fprintf (file, " [mdmx]");
14804
14805   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
14806     fprintf (file, " [mips16]");
14807
14808   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
14809     fprintf (file, " [micromips]");
14810
14811   if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE)
14812     fprintf (file, " [32bitmode]");
14813   else
14814     fprintf (file, _(" [not 32bitmode]"));
14815
14816   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NOREORDER)
14817     fprintf (file, " [noreorder]");
14818
14819   if (elf_elfheader (abfd)->e_flags & EF_MIPS_PIC)
14820     fprintf (file, " [PIC]");
14821
14822   if (elf_elfheader (abfd)->e_flags & EF_MIPS_CPIC)
14823     fprintf (file, " [CPIC]");
14824
14825   if (elf_elfheader (abfd)->e_flags & EF_MIPS_XGOT)
14826     fprintf (file, " [XGOT]");
14827
14828   if (elf_elfheader (abfd)->e_flags & EF_MIPS_UCODE)
14829     fprintf (file, " [UCODE]");
14830
14831   fputc ('\n', file);
14832
14833   return TRUE;
14834 }
14835
14836 const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] =
14837 {
14838   { STRING_COMMA_LEN (".lit4"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14839   { STRING_COMMA_LEN (".lit8"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14840   { STRING_COMMA_LEN (".mdebug"), 0, SHT_MIPS_DEBUG, 0 },
14841   { STRING_COMMA_LEN (".sbss"),  -2, SHT_NOBITS,     SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14842   { STRING_COMMA_LEN (".sdata"), -2, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14843   { STRING_COMMA_LEN (".ucode"),  0, SHT_MIPS_UCODE, 0 },
14844   { NULL,                     0,  0, 0,              0 }
14845 };
14846
14847 /* Merge non visibility st_other attributes.  Ensure that the
14848    STO_OPTIONAL flag is copied into h->other, even if this is not a
14849    definiton of the symbol.  */
14850 void
14851 _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
14852                                       const Elf_Internal_Sym *isym,
14853                                       bfd_boolean definition,
14854                                       bfd_boolean dynamic ATTRIBUTE_UNUSED)
14855 {
14856   if ((isym->st_other & ~ELF_ST_VISIBILITY (-1)) != 0)
14857     {
14858       unsigned char other;
14859
14860       other = (definition ? isym->st_other : h->other);
14861       other &= ~ELF_ST_VISIBILITY (-1);
14862       h->other = other | ELF_ST_VISIBILITY (h->other);
14863     }
14864
14865   if (!definition
14866       && ELF_MIPS_IS_OPTIONAL (isym->st_other))
14867     h->other |= STO_OPTIONAL;
14868 }
14869
14870 /* Decide whether an undefined symbol is special and can be ignored.
14871    This is the case for OPTIONAL symbols on IRIX.  */
14872 bfd_boolean
14873 _bfd_mips_elf_ignore_undef_symbol (struct elf_link_hash_entry *h)
14874 {
14875   return ELF_MIPS_IS_OPTIONAL (h->other) ? TRUE : FALSE;
14876 }
14877
14878 bfd_boolean
14879 _bfd_mips_elf_common_definition (Elf_Internal_Sym *sym)
14880 {
14881   return (sym->st_shndx == SHN_COMMON
14882           || sym->st_shndx == SHN_MIPS_ACOMMON
14883           || sym->st_shndx == SHN_MIPS_SCOMMON);
14884 }
14885
14886 /* Return address for Ith PLT stub in section PLT, for relocation REL
14887    or (bfd_vma) -1 if it should not be included.  */
14888
14889 bfd_vma
14890 _bfd_mips_elf_plt_sym_val (bfd_vma i, const asection *plt,
14891                            const arelent *rel ATTRIBUTE_UNUSED)
14892 {
14893   return (plt->vma
14894           + 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry)
14895           + i * 4 * ARRAY_SIZE (mips_exec_plt_entry));
14896 }
14897
14898 /* Build a table of synthetic symbols to represent the PLT.  As with MIPS16
14899    and microMIPS PLT slots we may have a many-to-one mapping between .plt
14900    and .got.plt and also the slots may be of a different size each we walk
14901    the PLT manually fetching instructions and matching them against known
14902    patterns.  To make things easier standard MIPS slots, if any, always come
14903    first.  As we don't create proper ELF symbols we use the UDATA.I member
14904    of ASYMBOL to carry ISA annotation.  The encoding used is the same as
14905    with the ST_OTHER member of the ELF symbol.  */
14906
14907 long
14908 _bfd_mips_elf_get_synthetic_symtab (bfd *abfd,
14909                                     long symcount ATTRIBUTE_UNUSED,
14910                                     asymbol **syms ATTRIBUTE_UNUSED,
14911                                     long dynsymcount, asymbol **dynsyms,
14912                                     asymbol **ret)
14913 {
14914   static const char pltname[] = "_PROCEDURE_LINKAGE_TABLE_";
14915   static const char microsuffix[] = "@micromipsplt";
14916   static const char m16suffix[] = "@mips16plt";
14917   static const char mipssuffix[] = "@plt";
14918
14919   bfd_boolean (*slurp_relocs) (bfd *, asection *, asymbol **, bfd_boolean);
14920   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14921   bfd_boolean micromips_p = MICROMIPS_P (abfd);
14922   Elf_Internal_Shdr *hdr;
14923   bfd_byte *plt_data;
14924   bfd_vma plt_offset;
14925   unsigned int other;
14926   bfd_vma entry_size;
14927   bfd_vma plt0_size;
14928   asection *relplt;
14929   bfd_vma opcode;
14930   asection *plt;
14931   asymbol *send;
14932   size_t size;
14933   char *names;
14934   long counti;
14935   arelent *p;
14936   asymbol *s;
14937   char *nend;
14938   long count;
14939   long pi;
14940   long i;
14941   long n;
14942
14943   *ret = NULL;
14944
14945   if ((abfd->flags & (DYNAMIC | EXEC_P)) == 0 || dynsymcount <= 0)
14946     return 0;
14947
14948   relplt = bfd_get_section_by_name (abfd, ".rel.plt");
14949   if (relplt == NULL)
14950     return 0;
14951
14952   hdr = &elf_section_data (relplt)->this_hdr;
14953   if (hdr->sh_link != elf_dynsymtab (abfd) || hdr->sh_type != SHT_REL)
14954     return 0;
14955
14956   plt = bfd_get_section_by_name (abfd, ".plt");
14957   if (plt == NULL)
14958     return 0;
14959
14960   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
14961   if (!(*slurp_relocs) (abfd, relplt, dynsyms, TRUE))
14962     return -1;
14963   p = relplt->relocation;
14964
14965   /* Calculating the exact amount of space required for symbols would
14966      require two passes over the PLT, so just pessimise assuming two
14967      PLT slots per relocation.  */
14968   count = relplt->size / hdr->sh_entsize;
14969   counti = count * bed->s->int_rels_per_ext_rel;
14970   size = 2 * count * sizeof (asymbol);
14971   size += count * (sizeof (mipssuffix) +
14972                    (micromips_p ? sizeof (microsuffix) : sizeof (m16suffix)));
14973   for (pi = 0; pi < counti; pi += bed->s->int_rels_per_ext_rel)
14974     size += 2 * strlen ((*p[pi].sym_ptr_ptr)->name);
14975
14976   /* Add the size of "_PROCEDURE_LINKAGE_TABLE_" too.  */
14977   size += sizeof (asymbol) + sizeof (pltname);
14978
14979   if (!bfd_malloc_and_get_section (abfd, plt, &plt_data))
14980     return -1;
14981
14982   if (plt->size < 16)
14983     return -1;
14984
14985   s = *ret = bfd_malloc (size);
14986   if (s == NULL)
14987     return -1;
14988   send = s + 2 * count + 1;
14989
14990   names = (char *) send;
14991   nend = (char *) s + size;
14992   n = 0;
14993
14994   opcode = bfd_get_micromips_32 (abfd, plt_data + 12);
14995   if (opcode == 0x3302fffe)
14996     {
14997       if (!micromips_p)
14998         return -1;
14999       plt0_size = 2 * ARRAY_SIZE (micromips_o32_exec_plt0_entry);
15000       other = STO_MICROMIPS;
15001     }
15002   else
15003     {
15004       plt0_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
15005       other = 0;
15006     }
15007
15008   s->the_bfd = abfd;
15009   s->flags = BSF_SYNTHETIC | BSF_FUNCTION | BSF_LOCAL;
15010   s->section = plt;
15011   s->value = 0;
15012   s->name = names;
15013   s->udata.i = other;
15014   memcpy (names, pltname, sizeof (pltname));
15015   names += sizeof (pltname);
15016   ++s, ++n;
15017
15018   pi = 0;
15019   for (plt_offset = plt0_size;
15020        plt_offset + 8 <= plt->size && s < send;
15021        plt_offset += entry_size)
15022     {
15023       bfd_vma gotplt_addr;
15024       const char *suffix;
15025       bfd_vma gotplt_hi;
15026       bfd_vma gotplt_lo;
15027       size_t suffixlen;
15028
15029       opcode = bfd_get_micromips_32 (abfd, plt_data + plt_offset + 4);
15030
15031       /* Check if the second word matches the expected MIPS16 instruction.  */
15032       if (opcode == 0x651aeb00)
15033         {
15034           if (micromips_p)
15035             return -1;
15036           /* Truncated table???  */
15037           if (plt_offset + 16 > plt->size)
15038             break;
15039           gotplt_addr = bfd_get_32 (abfd, plt_data + plt_offset + 12);
15040           entry_size = 2 * ARRAY_SIZE (mips16_o32_exec_plt_entry);
15041           suffixlen = sizeof (m16suffix);
15042           suffix = m16suffix;
15043           other = STO_MIPS16;
15044         }
15045       /* Likewise the expected microMIPS instruction.  */
15046       else if (opcode == 0xff220000)
15047         {
15048           if (!micromips_p)
15049             return -1;
15050           gotplt_hi = bfd_get_16 (abfd, plt_data + plt_offset) & 0x7f;
15051           gotplt_lo = bfd_get_16 (abfd, plt_data + plt_offset + 2) & 0xffff;
15052           gotplt_hi = ((gotplt_hi ^ 0x40) - 0x40) << 18;
15053           gotplt_lo <<= 2;
15054           gotplt_addr = gotplt_hi + gotplt_lo;
15055           gotplt_addr += ((plt->vma + plt_offset) | 3) ^ 3;
15056           entry_size = 2 * ARRAY_SIZE (micromips_o32_exec_plt_entry);
15057           suffixlen = sizeof (microsuffix);
15058           suffix = microsuffix;
15059           other = STO_MICROMIPS;
15060         }
15061       /* Otherwise assume standard MIPS code.  */
15062       else
15063         {
15064           gotplt_hi = bfd_get_32 (abfd, plt_data + plt_offset) & 0xffff;
15065           gotplt_lo = bfd_get_32 (abfd, plt_data + plt_offset + 4) & 0xffff;
15066           gotplt_hi = ((gotplt_hi ^ 0x8000) - 0x8000) << 16;
15067           gotplt_lo = (gotplt_lo ^ 0x8000) - 0x8000;
15068           gotplt_addr = gotplt_hi + gotplt_lo;
15069           entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
15070           suffixlen = sizeof (mipssuffix);
15071           suffix = mipssuffix;
15072           other = 0;
15073         }
15074       /* Truncated table???  */
15075       if (plt_offset + entry_size > plt->size)
15076         break;
15077
15078       for (i = 0;
15079            i < count && p[pi].address != gotplt_addr;
15080            i++, pi = (pi + bed->s->int_rels_per_ext_rel) % counti);
15081
15082       if (i < count)
15083         {
15084           size_t namelen;
15085           size_t len;
15086
15087           *s = **p[pi].sym_ptr_ptr;
15088           /* Undefined syms won't have BSF_LOCAL or BSF_GLOBAL set.  Since
15089              we are defining a symbol, ensure one of them is set.  */
15090           if ((s->flags & BSF_LOCAL) == 0)
15091             s->flags |= BSF_GLOBAL;
15092           s->flags |= BSF_SYNTHETIC;
15093           s->section = plt;
15094           s->value = plt_offset;
15095           s->name = names;
15096           s->udata.i = other;
15097
15098           len = strlen ((*p[pi].sym_ptr_ptr)->name);
15099           namelen = len + suffixlen;
15100           if (names + namelen > nend)
15101             break;
15102
15103           memcpy (names, (*p[pi].sym_ptr_ptr)->name, len);
15104           names += len;
15105           memcpy (names, suffix, suffixlen);
15106           names += suffixlen;
15107
15108           ++s, ++n;
15109           pi = (pi + bed->s->int_rels_per_ext_rel) % counti;
15110         }
15111     }
15112
15113   free (plt_data);
15114
15115   return n;
15116 }
15117
15118 void
15119 _bfd_mips_post_process_headers (bfd *abfd, struct bfd_link_info *link_info)
15120 {
15121   struct mips_elf_link_hash_table *htab;
15122   Elf_Internal_Ehdr *i_ehdrp;
15123
15124   i_ehdrp = elf_elfheader (abfd);
15125   if (link_info)
15126     {
15127       htab = mips_elf_hash_table (link_info);
15128       BFD_ASSERT (htab != NULL);
15129
15130       if (htab->use_plts_and_copy_relocs && !htab->is_vxworks)
15131         i_ehdrp->e_ident[EI_ABIVERSION] = 1;
15132     }
15133 }