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 can only use 32-bit microMIPS instructions.  */
441   bfd_boolean insn32;
442
443   /* True if we're generating code for VxWorks.  */
444   bfd_boolean is_vxworks;
445
446   /* True if we already reported the small-data section overflow.  */
447   bfd_boolean small_data_overflow_reported;
448
449   /* Shortcuts to some dynamic sections, or NULL if they are not
450      being used.  */
451   asection *srelbss;
452   asection *sdynbss;
453   asection *srelplt;
454   asection *srelplt2;
455   asection *sgotplt;
456   asection *splt;
457   asection *sstubs;
458   asection *sgot;
459
460   /* The master GOT information.  */
461   struct mips_got_info *got_info;
462
463   /* The global symbol in the GOT with the lowest index in the dynamic
464      symbol table.  */
465   struct elf_link_hash_entry *global_gotsym;
466
467   /* The size of the PLT header in bytes.  */
468   bfd_vma plt_header_size;
469
470   /* The size of a standard PLT entry in bytes.  */
471   bfd_vma plt_mips_entry_size;
472
473   /* The size of a compressed PLT entry in bytes.  */
474   bfd_vma plt_comp_entry_size;
475
476   /* The offset of the next standard PLT entry to create.  */
477   bfd_vma plt_mips_offset;
478
479   /* The offset of the next compressed PLT entry to create.  */
480   bfd_vma plt_comp_offset;
481
482   /* The index of the next .got.plt entry to create.  */
483   bfd_vma plt_got_index;
484
485   /* The number of functions that need a lazy-binding stub.  */
486   bfd_vma lazy_stub_count;
487
488   /* The size of a function stub entry in bytes.  */
489   bfd_vma function_stub_size;
490
491   /* The number of reserved entries at the beginning of the GOT.  */
492   unsigned int reserved_gotno;
493
494   /* The section used for mips_elf_la25_stub trampolines.
495      See the comment above that structure for details.  */
496   asection *strampoline;
497
498   /* A table of mips_elf_la25_stubs, indexed by (input_section, offset)
499      pairs.  */
500   htab_t la25_stubs;
501
502   /* A function FN (NAME, IS, OS) that creates a new input section
503      called NAME and links it to output section OS.  If IS is nonnull,
504      the new section should go immediately before it, otherwise it
505      should go at the (current) beginning of OS.
506
507      The function returns the new section on success, otherwise it
508      returns null.  */
509   asection *(*add_stub_section) (const char *, asection *, asection *);
510
511   /* Small local sym cache.  */
512   struct sym_cache sym_cache;
513
514   /* Is the PLT header compressed?  */
515   unsigned int plt_header_is_comp : 1;
516 };
517
518 /* Get the MIPS ELF linker hash table from a link_info structure.  */
519
520 #define mips_elf_hash_table(p) \
521   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
522   == MIPS_ELF_DATA ? ((struct mips_elf_link_hash_table *) ((p)->hash)) : NULL)
523
524 /* A structure used to communicate with htab_traverse callbacks.  */
525 struct mips_htab_traverse_info
526 {
527   /* The usual link-wide information.  */
528   struct bfd_link_info *info;
529   bfd *output_bfd;
530
531   /* Starts off FALSE and is set to TRUE if the link should be aborted.  */
532   bfd_boolean error;
533 };
534
535 /* MIPS ELF private object data.  */
536
537 struct mips_elf_obj_tdata
538 {
539   /* Generic ELF private object data.  */
540   struct elf_obj_tdata root;
541
542   /* Input BFD providing Tag_GNU_MIPS_ABI_FP attribute for output.  */
543   bfd *abi_fp_bfd;
544
545   /* The GOT requirements of input bfds.  */
546   struct mips_got_info *got;
547
548   /* Used by _bfd_mips_elf_find_nearest_line.  The structure could be
549      included directly in this one, but there's no point to wasting
550      the memory just for the infrequently called find_nearest_line.  */
551   struct mips_elf_find_line *find_line_info;
552
553   /* An array of stub sections indexed by symbol number.  */
554   asection **local_stubs;
555   asection **local_call_stubs;
556
557   /* The Irix 5 support uses two virtual sections, which represent
558      text/data symbols defined in dynamic objects.  */
559   asymbol *elf_data_symbol;
560   asymbol *elf_text_symbol;
561   asection *elf_data_section;
562   asection *elf_text_section;
563 };
564
565 /* Get MIPS ELF private object data from BFD's tdata.  */
566
567 #define mips_elf_tdata(bfd) \
568   ((struct mips_elf_obj_tdata *) (bfd)->tdata.any)
569
570 #define TLS_RELOC_P(r_type) \
571   (r_type == R_MIPS_TLS_DTPMOD32                \
572    || r_type == R_MIPS_TLS_DTPMOD64             \
573    || r_type == R_MIPS_TLS_DTPREL32             \
574    || r_type == R_MIPS_TLS_DTPREL64             \
575    || r_type == R_MIPS_TLS_GD                   \
576    || r_type == R_MIPS_TLS_LDM                  \
577    || r_type == R_MIPS_TLS_DTPREL_HI16          \
578    || r_type == R_MIPS_TLS_DTPREL_LO16          \
579    || r_type == R_MIPS_TLS_GOTTPREL             \
580    || r_type == R_MIPS_TLS_TPREL32              \
581    || r_type == R_MIPS_TLS_TPREL64              \
582    || r_type == R_MIPS_TLS_TPREL_HI16           \
583    || r_type == R_MIPS_TLS_TPREL_LO16           \
584    || r_type == R_MIPS16_TLS_GD                 \
585    || r_type == R_MIPS16_TLS_LDM                \
586    || r_type == R_MIPS16_TLS_DTPREL_HI16        \
587    || r_type == R_MIPS16_TLS_DTPREL_LO16        \
588    || r_type == R_MIPS16_TLS_GOTTPREL           \
589    || r_type == R_MIPS16_TLS_TPREL_HI16         \
590    || r_type == R_MIPS16_TLS_TPREL_LO16         \
591    || r_type == R_MICROMIPS_TLS_GD              \
592    || r_type == R_MICROMIPS_TLS_LDM             \
593    || r_type == R_MICROMIPS_TLS_DTPREL_HI16     \
594    || r_type == R_MICROMIPS_TLS_DTPREL_LO16     \
595    || r_type == R_MICROMIPS_TLS_GOTTPREL        \
596    || r_type == R_MICROMIPS_TLS_TPREL_HI16      \
597    || r_type == R_MICROMIPS_TLS_TPREL_LO16)
598
599 /* Structure used to pass information to mips_elf_output_extsym.  */
600
601 struct extsym_info
602 {
603   bfd *abfd;
604   struct bfd_link_info *info;
605   struct ecoff_debug_info *debug;
606   const struct ecoff_debug_swap *swap;
607   bfd_boolean failed;
608 };
609
610 /* The names of the runtime procedure table symbols used on IRIX5.  */
611
612 static const char * const mips_elf_dynsym_rtproc_names[] =
613 {
614   "_procedure_table",
615   "_procedure_string_table",
616   "_procedure_table_size",
617   NULL
618 };
619
620 /* These structures are used to generate the .compact_rel section on
621    IRIX5.  */
622
623 typedef struct
624 {
625   unsigned long id1;            /* Always one?  */
626   unsigned long num;            /* Number of compact relocation entries.  */
627   unsigned long id2;            /* Always two?  */
628   unsigned long offset;         /* The file offset of the first relocation.  */
629   unsigned long reserved0;      /* Zero?  */
630   unsigned long reserved1;      /* Zero?  */
631 } Elf32_compact_rel;
632
633 typedef struct
634 {
635   bfd_byte id1[4];
636   bfd_byte num[4];
637   bfd_byte id2[4];
638   bfd_byte offset[4];
639   bfd_byte reserved0[4];
640   bfd_byte reserved1[4];
641 } Elf32_External_compact_rel;
642
643 typedef struct
644 {
645   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
646   unsigned int rtype : 4;       /* Relocation types. See below.  */
647   unsigned int dist2to : 8;
648   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
649   unsigned long konst;          /* KONST field. See below.  */
650   unsigned long vaddr;          /* VADDR to be relocated.  */
651 } Elf32_crinfo;
652
653 typedef struct
654 {
655   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
656   unsigned int rtype : 4;       /* Relocation types. See below.  */
657   unsigned int dist2to : 8;
658   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
659   unsigned long konst;          /* KONST field. See below.  */
660 } Elf32_crinfo2;
661
662 typedef struct
663 {
664   bfd_byte info[4];
665   bfd_byte konst[4];
666   bfd_byte vaddr[4];
667 } Elf32_External_crinfo;
668
669 typedef struct
670 {
671   bfd_byte info[4];
672   bfd_byte konst[4];
673 } Elf32_External_crinfo2;
674
675 /* These are the constants used to swap the bitfields in a crinfo.  */
676
677 #define CRINFO_CTYPE (0x1)
678 #define CRINFO_CTYPE_SH (31)
679 #define CRINFO_RTYPE (0xf)
680 #define CRINFO_RTYPE_SH (27)
681 #define CRINFO_DIST2TO (0xff)
682 #define CRINFO_DIST2TO_SH (19)
683 #define CRINFO_RELVADDR (0x7ffff)
684 #define CRINFO_RELVADDR_SH (0)
685
686 /* A compact relocation info has long (3 words) or short (2 words)
687    formats.  A short format doesn't have VADDR field and relvaddr
688    fields contains ((VADDR - vaddr of the previous entry) >> 2).  */
689 #define CRF_MIPS_LONG                   1
690 #define CRF_MIPS_SHORT                  0
691
692 /* There are 4 types of compact relocation at least. The value KONST
693    has different meaning for each type:
694
695    (type)               (konst)
696    CT_MIPS_REL32        Address in data
697    CT_MIPS_WORD         Address in word (XXX)
698    CT_MIPS_GPHI_LO      GP - vaddr
699    CT_MIPS_JMPAD        Address to jump
700    */
701
702 #define CRT_MIPS_REL32                  0xa
703 #define CRT_MIPS_WORD                   0xb
704 #define CRT_MIPS_GPHI_LO                0xc
705 #define CRT_MIPS_JMPAD                  0xd
706
707 #define mips_elf_set_cr_format(x,format)        ((x).ctype = (format))
708 #define mips_elf_set_cr_type(x,type)            ((x).rtype = (type))
709 #define mips_elf_set_cr_dist2to(x,v)            ((x).dist2to = (v))
710 #define mips_elf_set_cr_relvaddr(x,d)           ((x).relvaddr = (d)<<2)
711 \f
712 /* The structure of the runtime procedure descriptor created by the
713    loader for use by the static exception system.  */
714
715 typedef struct runtime_pdr {
716         bfd_vma adr;            /* Memory address of start of procedure.  */
717         long    regmask;        /* Save register mask.  */
718         long    regoffset;      /* Save register offset.  */
719         long    fregmask;       /* Save floating point register mask.  */
720         long    fregoffset;     /* Save floating point register offset.  */
721         long    frameoffset;    /* Frame size.  */
722         short   framereg;       /* Frame pointer register.  */
723         short   pcreg;          /* Offset or reg of return pc.  */
724         long    irpss;          /* Index into the runtime string table.  */
725         long    reserved;
726         struct exception_info *exception_info;/* Pointer to exception array.  */
727 } RPDR, *pRPDR;
728 #define cbRPDR sizeof (RPDR)
729 #define rpdNil ((pRPDR) 0)
730 \f
731 static struct mips_got_entry *mips_elf_create_local_got_entry
732   (bfd *, struct bfd_link_info *, bfd *, bfd_vma, unsigned long,
733    struct mips_elf_link_hash_entry *, int);
734 static bfd_boolean mips_elf_sort_hash_table_f
735   (struct mips_elf_link_hash_entry *, void *);
736 static bfd_vma mips_elf_high
737   (bfd_vma);
738 static bfd_boolean mips_elf_create_dynamic_relocation
739   (bfd *, struct bfd_link_info *, const Elf_Internal_Rela *,
740    struct mips_elf_link_hash_entry *, asection *, bfd_vma,
741    bfd_vma *, asection *);
742 static bfd_vma mips_elf_adjust_gp
743   (bfd *, struct mips_got_info *, bfd *);
744
745 /* This will be used when we sort the dynamic relocation records.  */
746 static bfd *reldyn_sorting_bfd;
747
748 /* True if ABFD is for CPUs with load interlocking that include
749    non-MIPS1 CPUs and R3900.  */
750 #define LOAD_INTERLOCKS_P(abfd) \
751   (   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) != E_MIPS_ARCH_1) \
752    || ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_3900))
753
754 /* True if ABFD is for CPUs that are faster if JAL is converted to BAL.
755    This should be safe for all architectures.  We enable this predicate
756    for RM9000 for now.  */
757 #define JAL_TO_BAL_P(abfd) \
758   ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_9000)
759
760 /* True if ABFD is for CPUs that are faster if JALR is converted to BAL.
761    This should be safe for all architectures.  We enable this predicate for
762    all CPUs.  */
763 #define JALR_TO_BAL_P(abfd) 1
764
765 /* True if ABFD is for CPUs that are faster if JR is converted to B.
766    This should be safe for all architectures.  We enable this predicate for
767    all CPUs.  */
768 #define JR_TO_B_P(abfd) 1
769
770 /* True if ABFD is a PIC object.  */
771 #define PIC_OBJECT_P(abfd) \
772   ((elf_elfheader (abfd)->e_flags & EF_MIPS_PIC) != 0)
773
774 /* Nonzero if ABFD is using the N32 ABI.  */
775 #define ABI_N32_P(abfd) \
776   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI2) != 0)
777
778 /* Nonzero if ABFD is using the N64 ABI.  */
779 #define ABI_64_P(abfd) \
780   (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS64)
781
782 /* Nonzero if ABFD is using NewABI conventions.  */
783 #define NEWABI_P(abfd) (ABI_N32_P (abfd) || ABI_64_P (abfd))
784
785 /* Nonzero if ABFD has microMIPS code.  */
786 #define MICROMIPS_P(abfd) \
787   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS) != 0)
788
789 /* The IRIX compatibility level we are striving for.  */
790 #define IRIX_COMPAT(abfd) \
791   (get_elf_backend_data (abfd)->elf_backend_mips_irix_compat (abfd))
792
793 /* Whether we are trying to be compatible with IRIX at all.  */
794 #define SGI_COMPAT(abfd) \
795   (IRIX_COMPAT (abfd) != ict_none)
796
797 /* The name of the options section.  */
798 #define MIPS_ELF_OPTIONS_SECTION_NAME(abfd) \
799   (NEWABI_P (abfd) ? ".MIPS.options" : ".options")
800
801 /* True if NAME is the recognized name of any SHT_MIPS_OPTIONS section.
802    Some IRIX system files do not use MIPS_ELF_OPTIONS_SECTION_NAME.  */
803 #define MIPS_ELF_OPTIONS_SECTION_NAME_P(NAME) \
804   (strcmp (NAME, ".MIPS.options") == 0 || strcmp (NAME, ".options") == 0)
805
806 /* Whether the section is readonly.  */
807 #define MIPS_ELF_READONLY_SECTION(sec) \
808   ((sec->flags & (SEC_ALLOC | SEC_LOAD | SEC_READONLY))         \
809    == (SEC_ALLOC | SEC_LOAD | SEC_READONLY))
810
811 /* The name of the stub section.  */
812 #define MIPS_ELF_STUB_SECTION_NAME(abfd) ".MIPS.stubs"
813
814 /* The size of an external REL relocation.  */
815 #define MIPS_ELF_REL_SIZE(abfd) \
816   (get_elf_backend_data (abfd)->s->sizeof_rel)
817
818 /* The size of an external RELA relocation.  */
819 #define MIPS_ELF_RELA_SIZE(abfd) \
820   (get_elf_backend_data (abfd)->s->sizeof_rela)
821
822 /* The size of an external dynamic table entry.  */
823 #define MIPS_ELF_DYN_SIZE(abfd) \
824   (get_elf_backend_data (abfd)->s->sizeof_dyn)
825
826 /* The size of a GOT entry.  */
827 #define MIPS_ELF_GOT_SIZE(abfd) \
828   (get_elf_backend_data (abfd)->s->arch_size / 8)
829
830 /* The size of the .rld_map section. */
831 #define MIPS_ELF_RLD_MAP_SIZE(abfd) \
832   (get_elf_backend_data (abfd)->s->arch_size / 8)
833
834 /* The size of a symbol-table entry.  */
835 #define MIPS_ELF_SYM_SIZE(abfd) \
836   (get_elf_backend_data (abfd)->s->sizeof_sym)
837
838 /* The default alignment for sections, as a power of two.  */
839 #define MIPS_ELF_LOG_FILE_ALIGN(abfd)                           \
840   (get_elf_backend_data (abfd)->s->log_file_align)
841
842 /* Get word-sized data.  */
843 #define MIPS_ELF_GET_WORD(abfd, ptr) \
844   (ABI_64_P (abfd) ? bfd_get_64 (abfd, ptr) : bfd_get_32 (abfd, ptr))
845
846 /* Put out word-sized data.  */
847 #define MIPS_ELF_PUT_WORD(abfd, val, ptr)       \
848   (ABI_64_P (abfd)                              \
849    ? bfd_put_64 (abfd, val, ptr)                \
850    : bfd_put_32 (abfd, val, ptr))
851
852 /* The opcode for word-sized loads (LW or LD).  */
853 #define MIPS_ELF_LOAD_WORD(abfd) \
854   (ABI_64_P (abfd) ? 0xdc000000 : 0x8c000000)
855
856 /* Add a dynamic symbol table-entry.  */
857 #define MIPS_ELF_ADD_DYNAMIC_ENTRY(info, tag, val)      \
858   _bfd_elf_add_dynamic_entry (info, tag, val)
859
860 #define MIPS_ELF_RTYPE_TO_HOWTO(abfd, rtype, rela)                      \
861   (get_elf_backend_data (abfd)->elf_backend_mips_rtype_to_howto (rtype, rela))
862
863 /* The name of the dynamic relocation section.  */
864 #define MIPS_ELF_REL_DYN_NAME(INFO) \
865   (mips_elf_hash_table (INFO)->is_vxworks ? ".rela.dyn" : ".rel.dyn")
866
867 /* In case we're on a 32-bit machine, construct a 64-bit "-1" value
868    from smaller values.  Start with zero, widen, *then* decrement.  */
869 #define MINUS_ONE       (((bfd_vma)0) - 1)
870 #define MINUS_TWO       (((bfd_vma)0) - 2)
871
872 /* The value to write into got[1] for SVR4 targets, to identify it is
873    a GNU object.  The dynamic linker can then use got[1] to store the
874    module pointer.  */
875 #define MIPS_ELF_GNU_GOT1_MASK(abfd) \
876   ((bfd_vma) 1 << (ABI_64_P (abfd) ? 63 : 31))
877
878 /* The offset of $gp from the beginning of the .got section.  */
879 #define ELF_MIPS_GP_OFFSET(INFO) \
880   (mips_elf_hash_table (INFO)->is_vxworks ? 0x0 : 0x7ff0)
881
882 /* The maximum size of the GOT for it to be addressable using 16-bit
883    offsets from $gp.  */
884 #define MIPS_ELF_GOT_MAX_SIZE(INFO) (ELF_MIPS_GP_OFFSET (INFO) + 0x7fff)
885
886 /* Instructions which appear in a stub.  */
887 #define STUB_LW(abfd)                                                   \
888   ((ABI_64_P (abfd)                                                     \
889     ? 0xdf998010                                /* ld t9,0x8010(gp) */  \
890     : 0x8f998010))                              /* lw t9,0x8010(gp) */
891 #define STUB_MOVE(abfd)                                                 \
892    ((ABI_64_P (abfd)                                                    \
893      ? 0x03e0782d                               /* daddu t7,ra */       \
894      : 0x03e07821))                             /* addu t7,ra */
895 #define STUB_LUI(VAL) (0x3c180000 + (VAL))      /* lui t8,VAL */
896 #define STUB_JALR 0x0320f809                    /* jalr t9,ra */
897 #define STUB_ORI(VAL) (0x37180000 + (VAL))      /* ori t8,t8,VAL */
898 #define STUB_LI16U(VAL) (0x34180000 + (VAL))    /* ori t8,zero,VAL unsigned */
899 #define STUB_LI16S(abfd, VAL)                                           \
900    ((ABI_64_P (abfd)                                                    \
901     ? (0x64180000 + (VAL))      /* daddiu t8,zero,VAL sign extended */  \
902     : (0x24180000 + (VAL))))    /* addiu t8,zero,VAL sign extended */
903
904 /* Likewise for the microMIPS ASE.  */
905 #define STUB_LW_MICROMIPS(abfd)                                         \
906   (ABI_64_P (abfd)                                                      \
907    ? 0xdf3c8010                                 /* ld t9,0x8010(gp) */  \
908    : 0xff3c8010)                                /* lw t9,0x8010(gp) */
909 #define STUB_MOVE_MICROMIPS 0x0dff              /* move t7,ra */
910 #define STUB_MOVE32_MICROMIPS(abfd)                                     \
911    (ABI_64_P (abfd)                                                     \
912     ? 0x581f7950                                /* daddu t7,ra,zero */  \
913     : 0x001f7950)                               /* addu t7,ra,zero */
914 #define STUB_LUI_MICROMIPS(VAL)                                         \
915    (0x41b80000 + (VAL))                         /* lui t8,VAL */
916 #define STUB_JALR_MICROMIPS 0x45d9              /* jalr t9 */
917 #define STUB_JALR32_MICROMIPS 0x03f90f3c        /* jalr ra,t9 */
918 #define STUB_ORI_MICROMIPS(VAL)                                         \
919   (0x53180000 + (VAL))                          /* ori t8,t8,VAL */
920 #define STUB_LI16U_MICROMIPS(VAL)                                       \
921   (0x53000000 + (VAL))                          /* ori t8,zero,VAL unsigned */
922 #define STUB_LI16S_MICROMIPS(abfd, VAL)                                 \
923    (ABI_64_P (abfd)                                                     \
924     ? 0x5f000000 + (VAL)        /* daddiu t8,zero,VAL sign extended */  \
925     : 0x33000000 + (VAL))       /* addiu t8,zero,VAL sign extended */
926
927 #define MIPS_FUNCTION_STUB_NORMAL_SIZE 16
928 #define MIPS_FUNCTION_STUB_BIG_SIZE 20
929 #define MICROMIPS_FUNCTION_STUB_NORMAL_SIZE 12
930 #define MICROMIPS_FUNCTION_STUB_BIG_SIZE 16
931 #define MICROMIPS_INSN32_FUNCTION_STUB_NORMAL_SIZE 16
932 #define MICROMIPS_INSN32_FUNCTION_STUB_BIG_SIZE 20
933
934 /* The name of the dynamic interpreter.  This is put in the .interp
935    section.  */
936
937 #define ELF_DYNAMIC_INTERPRETER(abfd)           \
938    (ABI_N32_P (abfd) ? "/usr/lib32/libc.so.1"   \
939     : ABI_64_P (abfd) ? "/usr/lib64/libc.so.1"  \
940     : "/usr/lib/libc.so.1")
941
942 #ifdef BFD64
943 #define MNAME(bfd,pre,pos) \
944   (ABI_64_P (bfd) ? CONCAT4 (pre,64,_,pos) : CONCAT4 (pre,32,_,pos))
945 #define ELF_R_SYM(bfd, i)                                       \
946   (ABI_64_P (bfd) ? ELF64_R_SYM (i) : ELF32_R_SYM (i))
947 #define ELF_R_TYPE(bfd, i)                                      \
948   (ABI_64_P (bfd) ? ELF64_MIPS_R_TYPE (i) : ELF32_R_TYPE (i))
949 #define ELF_R_INFO(bfd, s, t)                                   \
950   (ABI_64_P (bfd) ? ELF64_R_INFO (s, t) : ELF32_R_INFO (s, t))
951 #else
952 #define MNAME(bfd,pre,pos) CONCAT4 (pre,32,_,pos)
953 #define ELF_R_SYM(bfd, i)                                       \
954   (ELF32_R_SYM (i))
955 #define ELF_R_TYPE(bfd, i)                                      \
956   (ELF32_R_TYPE (i))
957 #define ELF_R_INFO(bfd, s, t)                                   \
958   (ELF32_R_INFO (s, t))
959 #endif
960 \f
961   /* The mips16 compiler uses a couple of special sections to handle
962      floating point arguments.
963
964      Section names that look like .mips16.fn.FNNAME contain stubs that
965      copy floating point arguments from the fp regs to the gp regs and
966      then jump to FNNAME.  If any 32 bit function calls FNNAME, the
967      call should be redirected to the stub instead.  If no 32 bit
968      function calls FNNAME, the stub should be discarded.  We need to
969      consider any reference to the function, not just a call, because
970      if the address of the function is taken we will need the stub,
971      since the address might be passed to a 32 bit function.
972
973      Section names that look like .mips16.call.FNNAME contain stubs
974      that copy floating point arguments from the gp regs to the fp
975      regs and then jump to FNNAME.  If FNNAME is a 32 bit function,
976      then any 16 bit function that calls FNNAME should be redirected
977      to the stub instead.  If FNNAME is not a 32 bit function, the
978      stub should be discarded.
979
980      .mips16.call.fp.FNNAME sections are similar, but contain stubs
981      which call FNNAME and then copy the return value from the fp regs
982      to the gp regs.  These stubs store the return value in $18 while
983      calling FNNAME; any function which might call one of these stubs
984      must arrange to save $18 around the call.  (This case is not
985      needed for 32 bit functions that call 16 bit functions, because
986      16 bit functions always return floating point values in both
987      $f0/$f1 and $2/$3.)
988
989      Note that in all cases FNNAME might be defined statically.
990      Therefore, FNNAME is not used literally.  Instead, the relocation
991      information will indicate which symbol the section is for.
992
993      We record any stubs that we find in the symbol table.  */
994
995 #define FN_STUB ".mips16.fn."
996 #define CALL_STUB ".mips16.call."
997 #define CALL_FP_STUB ".mips16.call.fp."
998
999 #define FN_STUB_P(name) CONST_STRNEQ (name, FN_STUB)
1000 #define CALL_STUB_P(name) CONST_STRNEQ (name, CALL_STUB)
1001 #define CALL_FP_STUB_P(name) CONST_STRNEQ (name, CALL_FP_STUB)
1002 \f
1003 /* The format of the first PLT entry in an O32 executable.  */
1004 static const bfd_vma mips_o32_exec_plt0_entry[] =
1005 {
1006   0x3c1c0000,   /* lui $28, %hi(&GOTPLT[0])                             */
1007   0x8f990000,   /* lw $25, %lo(&GOTPLT[0])($28)                         */
1008   0x279c0000,   /* addiu $28, $28, %lo(&GOTPLT[0])                      */
1009   0x031cc023,   /* subu $24, $24, $28                                   */
1010   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
1011   0x0018c082,   /* srl $24, $24, 2                                      */
1012   0x0320f809,   /* jalr $25                                             */
1013   0x2718fffe    /* subu $24, $24, 2                                     */
1014 };
1015
1016 /* The format of the first PLT entry in an N32 executable.  Different
1017    because gp ($28) is not available; we use t2 ($14) instead.  */
1018 static const bfd_vma mips_n32_exec_plt0_entry[] =
1019 {
1020   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
1021   0x8dd90000,   /* lw $25, %lo(&GOTPLT[0])($14)                         */
1022   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
1023   0x030ec023,   /* subu $24, $24, $14                                   */
1024   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
1025   0x0018c082,   /* srl $24, $24, 2                                      */
1026   0x0320f809,   /* jalr $25                                             */
1027   0x2718fffe    /* subu $24, $24, 2                                     */
1028 };
1029
1030 /* The format of the first PLT entry in an N64 executable.  Different
1031    from N32 because of the increased size of GOT entries.  */
1032 static const bfd_vma mips_n64_exec_plt0_entry[] =
1033 {
1034   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
1035   0xddd90000,   /* ld $25, %lo(&GOTPLT[0])($14)                         */
1036   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
1037   0x030ec023,   /* subu $24, $24, $14                                   */
1038   0x03e0782d,   /* move $15, $31        # 64-bit move (daddu)           */
1039   0x0018c0c2,   /* srl $24, $24, 3                                      */
1040   0x0320f809,   /* jalr $25                                             */
1041   0x2718fffe    /* subu $24, $24, 2                                     */
1042 };
1043
1044 /* The format of the microMIPS first PLT entry in an O32 executable.
1045    We rely on v0 ($2) rather than t8 ($24) to contain the address
1046    of the GOTPLT entry handled, so this stub may only be used when
1047    all the subsequent PLT entries are microMIPS code too.
1048
1049    The trailing NOP is for alignment and correct disassembly only.  */
1050 static const bfd_vma micromips_o32_exec_plt0_entry[] =
1051 {
1052   0x7980, 0x0000,       /* addiupc $3, (&GOTPLT[0]) - .                 */
1053   0xff23, 0x0000,       /* lw $25, 0($3)                                */
1054   0x0535,               /* subu $2, $2, $3                              */
1055   0x2525,               /* srl $2, $2, 2                                */
1056   0x3302, 0xfffe,       /* subu $24, $2, 2                              */
1057   0x0dff,               /* move $15, $31                                */
1058   0x45f9,               /* jalrs $25                                    */
1059   0x0f83,               /* move $28, $3                                 */
1060   0x0c00                /* nop                                          */
1061 };
1062
1063 /* The format of the microMIPS first PLT entry in an O32 executable
1064    in the insn32 mode.  */
1065 static const bfd_vma micromips_insn32_o32_exec_plt0_entry[] =
1066 {
1067   0x41bc, 0x0000,       /* lui $28, %hi(&GOTPLT[0])                     */
1068   0xff3c, 0x0000,       /* lw $25, %lo(&GOTPLT[0])($28)                 */
1069   0x339c, 0x0000,       /* addiu $28, $28, %lo(&GOTPLT[0])              */
1070   0x0398, 0xc1d0,       /* subu $24, $24, $28                           */
1071   0x001f, 0x7950,       /* move $15, $31                                */
1072   0x0318, 0x1040,       /* srl $24, $24, 2                              */
1073   0x03f9, 0x0f3c,       /* jalr $25                                     */
1074   0x3318, 0xfffe        /* subu $24, $24, 2                             */
1075 };
1076
1077 /* The format of subsequent standard PLT entries.  */
1078 static const bfd_vma mips_exec_plt_entry[] =
1079 {
1080   0x3c0f0000,   /* lui $15, %hi(.got.plt entry)                 */
1081   0x01f90000,   /* l[wd] $25, %lo(.got.plt entry)($15)          */
1082   0x25f80000,   /* addiu $24, $15, %lo(.got.plt entry)          */
1083   0x03200008    /* jr $25                                       */
1084 };
1085
1086 /* The format of subsequent MIPS16 o32 PLT entries.  We use v0 ($2)
1087    and v1 ($3) as temporaries because t8 ($24) and t9 ($25) are not
1088    directly addressable.  */
1089 static const bfd_vma mips16_o32_exec_plt_entry[] =
1090 {
1091   0xb203,               /* lw $2, 12($pc)                       */
1092   0x9a60,               /* lw $3, 0($2)                         */
1093   0x651a,               /* move $24, $2                         */
1094   0xeb00,               /* jr $3                                */
1095   0x653b,               /* move $25, $3                         */
1096   0x6500,               /* nop                                  */
1097   0x0000, 0x0000        /* .word (.got.plt entry)               */
1098 };
1099
1100 /* The format of subsequent microMIPS o32 PLT entries.  We use v0 ($2)
1101    as a temporary because t8 ($24) is not addressable with ADDIUPC.  */
1102 static const bfd_vma micromips_o32_exec_plt_entry[] =
1103 {
1104   0x7900, 0x0000,       /* addiupc $2, (.got.plt entry) - .     */
1105   0xff22, 0x0000,       /* lw $25, 0($2)                        */
1106   0x4599,               /* jr $25                               */
1107   0x0f02                /* move $24, $2                         */
1108 };
1109
1110 /* The format of subsequent microMIPS o32 PLT entries in the insn32 mode.  */
1111 static const bfd_vma micromips_insn32_o32_exec_plt_entry[] =
1112 {
1113   0x41af, 0x0000,       /* lui $15, %hi(.got.plt entry)         */
1114   0xff2f, 0x0000,       /* lw $25, %lo(.got.plt entry)($15)     */
1115   0x0019, 0x0f3c,       /* jr $25                               */
1116   0x330f, 0x0000        /* addiu $24, $15, %lo(.got.plt entry)  */
1117 };
1118
1119 /* The format of the first PLT entry in a VxWorks executable.  */
1120 static const bfd_vma mips_vxworks_exec_plt0_entry[] =
1121 {
1122   0x3c190000,   /* lui t9, %hi(_GLOBAL_OFFSET_TABLE_)           */
1123   0x27390000,   /* addiu t9, t9, %lo(_GLOBAL_OFFSET_TABLE_)     */
1124   0x8f390008,   /* lw t9, 8(t9)                                 */
1125   0x00000000,   /* nop                                          */
1126   0x03200008,   /* jr t9                                        */
1127   0x00000000    /* nop                                          */
1128 };
1129
1130 /* The format of subsequent PLT entries.  */
1131 static const bfd_vma mips_vxworks_exec_plt_entry[] =
1132 {
1133   0x10000000,   /* b .PLT_resolver                      */
1134   0x24180000,   /* li t8, <pltindex>                    */
1135   0x3c190000,   /* lui t9, %hi(<.got.plt slot>)         */
1136   0x27390000,   /* addiu t9, t9, %lo(<.got.plt slot>)   */
1137   0x8f390000,   /* lw t9, 0(t9)                         */
1138   0x00000000,   /* nop                                  */
1139   0x03200008,   /* jr t9                                */
1140   0x00000000    /* nop                                  */
1141 };
1142
1143 /* The format of the first PLT entry in a VxWorks shared object.  */
1144 static const bfd_vma mips_vxworks_shared_plt0_entry[] =
1145 {
1146   0x8f990008,   /* lw t9, 8(gp)         */
1147   0x00000000,   /* nop                  */
1148   0x03200008,   /* jr t9                */
1149   0x00000000,   /* nop                  */
1150   0x00000000,   /* nop                  */
1151   0x00000000    /* nop                  */
1152 };
1153
1154 /* The format of subsequent PLT entries.  */
1155 static const bfd_vma mips_vxworks_shared_plt_entry[] =
1156 {
1157   0x10000000,   /* b .PLT_resolver      */
1158   0x24180000    /* li t8, <pltindex>    */
1159 };
1160 \f
1161 /* microMIPS 32-bit opcode helper installer.  */
1162
1163 static void
1164 bfd_put_micromips_32 (const bfd *abfd, bfd_vma opcode, bfd_byte *ptr)
1165 {
1166   bfd_put_16 (abfd, (opcode >> 16) & 0xffff, ptr);
1167   bfd_put_16 (abfd,  opcode        & 0xffff, ptr + 2);
1168 }
1169
1170 /* microMIPS 32-bit opcode helper retriever.  */
1171
1172 static bfd_vma
1173 bfd_get_micromips_32 (const bfd *abfd, const bfd_byte *ptr)
1174 {
1175   return (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
1176 }
1177 \f
1178 /* Look up an entry in a MIPS ELF linker hash table.  */
1179
1180 #define mips_elf_link_hash_lookup(table, string, create, copy, follow)  \
1181   ((struct mips_elf_link_hash_entry *)                                  \
1182    elf_link_hash_lookup (&(table)->root, (string), (create),            \
1183                          (copy), (follow)))
1184
1185 /* Traverse a MIPS ELF linker hash table.  */
1186
1187 #define mips_elf_link_hash_traverse(table, func, info)                  \
1188   (elf_link_hash_traverse                                               \
1189    (&(table)->root,                                                     \
1190     (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func),    \
1191     (info)))
1192
1193 /* Find the base offsets for thread-local storage in this object,
1194    for GD/LD and IE/LE respectively.  */
1195
1196 #define TP_OFFSET 0x7000
1197 #define DTP_OFFSET 0x8000
1198
1199 static bfd_vma
1200 dtprel_base (struct bfd_link_info *info)
1201 {
1202   /* If tls_sec is NULL, we should have signalled an error already.  */
1203   if (elf_hash_table (info)->tls_sec == NULL)
1204     return 0;
1205   return elf_hash_table (info)->tls_sec->vma + DTP_OFFSET;
1206 }
1207
1208 static bfd_vma
1209 tprel_base (struct bfd_link_info *info)
1210 {
1211   /* If tls_sec is NULL, we should have signalled an error already.  */
1212   if (elf_hash_table (info)->tls_sec == NULL)
1213     return 0;
1214   return elf_hash_table (info)->tls_sec->vma + TP_OFFSET;
1215 }
1216
1217 /* Create an entry in a MIPS ELF linker hash table.  */
1218
1219 static struct bfd_hash_entry *
1220 mips_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
1221                             struct bfd_hash_table *table, const char *string)
1222 {
1223   struct mips_elf_link_hash_entry *ret =
1224     (struct mips_elf_link_hash_entry *) entry;
1225
1226   /* Allocate the structure if it has not already been allocated by a
1227      subclass.  */
1228   if (ret == NULL)
1229     ret = bfd_hash_allocate (table, sizeof (struct mips_elf_link_hash_entry));
1230   if (ret == NULL)
1231     return (struct bfd_hash_entry *) ret;
1232
1233   /* Call the allocation method of the superclass.  */
1234   ret = ((struct mips_elf_link_hash_entry *)
1235          _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret,
1236                                      table, string));
1237   if (ret != NULL)
1238     {
1239       /* Set local fields.  */
1240       memset (&ret->esym, 0, sizeof (EXTR));
1241       /* We use -2 as a marker to indicate that the information has
1242          not been set.  -1 means there is no associated ifd.  */
1243       ret->esym.ifd = -2;
1244       ret->la25_stub = 0;
1245       ret->possibly_dynamic_relocs = 0;
1246       ret->fn_stub = NULL;
1247       ret->call_stub = NULL;
1248       ret->call_fp_stub = NULL;
1249       ret->global_got_area = GGA_NONE;
1250       ret->got_only_for_calls = TRUE;
1251       ret->readonly_reloc = FALSE;
1252       ret->has_static_relocs = FALSE;
1253       ret->no_fn_stub = FALSE;
1254       ret->need_fn_stub = FALSE;
1255       ret->has_nonpic_branches = FALSE;
1256       ret->needs_lazy_stub = FALSE;
1257       ret->use_plt_entry = FALSE;
1258     }
1259
1260   return (struct bfd_hash_entry *) ret;
1261 }
1262
1263 /* Allocate MIPS ELF private object data.  */
1264
1265 bfd_boolean
1266 _bfd_mips_elf_mkobject (bfd *abfd)
1267 {
1268   return bfd_elf_allocate_object (abfd, sizeof (struct mips_elf_obj_tdata),
1269                                   MIPS_ELF_DATA);
1270 }
1271
1272 bfd_boolean
1273 _bfd_mips_elf_new_section_hook (bfd *abfd, asection *sec)
1274 {
1275   if (!sec->used_by_bfd)
1276     {
1277       struct _mips_elf_section_data *sdata;
1278       bfd_size_type amt = sizeof (*sdata);
1279
1280       sdata = bfd_zalloc (abfd, amt);
1281       if (sdata == NULL)
1282         return FALSE;
1283       sec->used_by_bfd = sdata;
1284     }
1285
1286   return _bfd_elf_new_section_hook (abfd, sec);
1287 }
1288 \f
1289 /* Read ECOFF debugging information from a .mdebug section into a
1290    ecoff_debug_info structure.  */
1291
1292 bfd_boolean
1293 _bfd_mips_elf_read_ecoff_info (bfd *abfd, asection *section,
1294                                struct ecoff_debug_info *debug)
1295 {
1296   HDRR *symhdr;
1297   const struct ecoff_debug_swap *swap;
1298   char *ext_hdr;
1299
1300   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1301   memset (debug, 0, sizeof (*debug));
1302
1303   ext_hdr = bfd_malloc (swap->external_hdr_size);
1304   if (ext_hdr == NULL && swap->external_hdr_size != 0)
1305     goto error_return;
1306
1307   if (! bfd_get_section_contents (abfd, section, ext_hdr, 0,
1308                                   swap->external_hdr_size))
1309     goto error_return;
1310
1311   symhdr = &debug->symbolic_header;
1312   (*swap->swap_hdr_in) (abfd, ext_hdr, symhdr);
1313
1314   /* The symbolic header contains absolute file offsets and sizes to
1315      read.  */
1316 #define READ(ptr, offset, count, size, type)                            \
1317   if (symhdr->count == 0)                                               \
1318     debug->ptr = NULL;                                                  \
1319   else                                                                  \
1320     {                                                                   \
1321       bfd_size_type amt = (bfd_size_type) size * symhdr->count;         \
1322       debug->ptr = bfd_malloc (amt);                                    \
1323       if (debug->ptr == NULL)                                           \
1324         goto error_return;                                              \
1325       if (bfd_seek (abfd, symhdr->offset, SEEK_SET) != 0                \
1326           || bfd_bread (debug->ptr, amt, abfd) != amt)                  \
1327         goto error_return;                                              \
1328     }
1329
1330   READ (line, cbLineOffset, cbLine, sizeof (unsigned char), unsigned char *);
1331   READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *);
1332   READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *);
1333   READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *);
1334   READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *);
1335   READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext),
1336         union aux_ext *);
1337   READ (ss, cbSsOffset, issMax, sizeof (char), char *);
1338   READ (ssext, cbSsExtOffset, issExtMax, sizeof (char), char *);
1339   READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *);
1340   READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *);
1341   READ (external_ext, cbExtOffset, iextMax, swap->external_ext_size, void *);
1342 #undef READ
1343
1344   debug->fdr = NULL;
1345
1346   return TRUE;
1347
1348  error_return:
1349   if (ext_hdr != NULL)
1350     free (ext_hdr);
1351   if (debug->line != NULL)
1352     free (debug->line);
1353   if (debug->external_dnr != NULL)
1354     free (debug->external_dnr);
1355   if (debug->external_pdr != NULL)
1356     free (debug->external_pdr);
1357   if (debug->external_sym != NULL)
1358     free (debug->external_sym);
1359   if (debug->external_opt != NULL)
1360     free (debug->external_opt);
1361   if (debug->external_aux != NULL)
1362     free (debug->external_aux);
1363   if (debug->ss != NULL)
1364     free (debug->ss);
1365   if (debug->ssext != NULL)
1366     free (debug->ssext);
1367   if (debug->external_fdr != NULL)
1368     free (debug->external_fdr);
1369   if (debug->external_rfd != NULL)
1370     free (debug->external_rfd);
1371   if (debug->external_ext != NULL)
1372     free (debug->external_ext);
1373   return FALSE;
1374 }
1375 \f
1376 /* Swap RPDR (runtime procedure table entry) for output.  */
1377
1378 static void
1379 ecoff_swap_rpdr_out (bfd *abfd, const RPDR *in, struct rpdr_ext *ex)
1380 {
1381   H_PUT_S32 (abfd, in->adr, ex->p_adr);
1382   H_PUT_32 (abfd, in->regmask, ex->p_regmask);
1383   H_PUT_32 (abfd, in->regoffset, ex->p_regoffset);
1384   H_PUT_32 (abfd, in->fregmask, ex->p_fregmask);
1385   H_PUT_32 (abfd, in->fregoffset, ex->p_fregoffset);
1386   H_PUT_32 (abfd, in->frameoffset, ex->p_frameoffset);
1387
1388   H_PUT_16 (abfd, in->framereg, ex->p_framereg);
1389   H_PUT_16 (abfd, in->pcreg, ex->p_pcreg);
1390
1391   H_PUT_32 (abfd, in->irpss, ex->p_irpss);
1392 }
1393
1394 /* Create a runtime procedure table from the .mdebug section.  */
1395
1396 static bfd_boolean
1397 mips_elf_create_procedure_table (void *handle, bfd *abfd,
1398                                  struct bfd_link_info *info, asection *s,
1399                                  struct ecoff_debug_info *debug)
1400 {
1401   const struct ecoff_debug_swap *swap;
1402   HDRR *hdr = &debug->symbolic_header;
1403   RPDR *rpdr, *rp;
1404   struct rpdr_ext *erp;
1405   void *rtproc;
1406   struct pdr_ext *epdr;
1407   struct sym_ext *esym;
1408   char *ss, **sv;
1409   char *str;
1410   bfd_size_type size;
1411   bfd_size_type count;
1412   unsigned long sindex;
1413   unsigned long i;
1414   PDR pdr;
1415   SYMR sym;
1416   const char *no_name_func = _("static procedure (no name)");
1417
1418   epdr = NULL;
1419   rpdr = NULL;
1420   esym = NULL;
1421   ss = NULL;
1422   sv = NULL;
1423
1424   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1425
1426   sindex = strlen (no_name_func) + 1;
1427   count = hdr->ipdMax;
1428   if (count > 0)
1429     {
1430       size = swap->external_pdr_size;
1431
1432       epdr = bfd_malloc (size * count);
1433       if (epdr == NULL)
1434         goto error_return;
1435
1436       if (! _bfd_ecoff_get_accumulated_pdr (handle, (bfd_byte *) epdr))
1437         goto error_return;
1438
1439       size = sizeof (RPDR);
1440       rp = rpdr = bfd_malloc (size * count);
1441       if (rpdr == NULL)
1442         goto error_return;
1443
1444       size = sizeof (char *);
1445       sv = bfd_malloc (size * count);
1446       if (sv == NULL)
1447         goto error_return;
1448
1449       count = hdr->isymMax;
1450       size = swap->external_sym_size;
1451       esym = bfd_malloc (size * count);
1452       if (esym == NULL)
1453         goto error_return;
1454
1455       if (! _bfd_ecoff_get_accumulated_sym (handle, (bfd_byte *) esym))
1456         goto error_return;
1457
1458       count = hdr->issMax;
1459       ss = bfd_malloc (count);
1460       if (ss == NULL)
1461         goto error_return;
1462       if (! _bfd_ecoff_get_accumulated_ss (handle, (bfd_byte *) ss))
1463         goto error_return;
1464
1465       count = hdr->ipdMax;
1466       for (i = 0; i < (unsigned long) count; i++, rp++)
1467         {
1468           (*swap->swap_pdr_in) (abfd, epdr + i, &pdr);
1469           (*swap->swap_sym_in) (abfd, &esym[pdr.isym], &sym);
1470           rp->adr = sym.value;
1471           rp->regmask = pdr.regmask;
1472           rp->regoffset = pdr.regoffset;
1473           rp->fregmask = pdr.fregmask;
1474           rp->fregoffset = pdr.fregoffset;
1475           rp->frameoffset = pdr.frameoffset;
1476           rp->framereg = pdr.framereg;
1477           rp->pcreg = pdr.pcreg;
1478           rp->irpss = sindex;
1479           sv[i] = ss + sym.iss;
1480           sindex += strlen (sv[i]) + 1;
1481         }
1482     }
1483
1484   size = sizeof (struct rpdr_ext) * (count + 2) + sindex;
1485   size = BFD_ALIGN (size, 16);
1486   rtproc = bfd_alloc (abfd, size);
1487   if (rtproc == NULL)
1488     {
1489       mips_elf_hash_table (info)->procedure_count = 0;
1490       goto error_return;
1491     }
1492
1493   mips_elf_hash_table (info)->procedure_count = count + 2;
1494
1495   erp = rtproc;
1496   memset (erp, 0, sizeof (struct rpdr_ext));
1497   erp++;
1498   str = (char *) rtproc + sizeof (struct rpdr_ext) * (count + 2);
1499   strcpy (str, no_name_func);
1500   str += strlen (no_name_func) + 1;
1501   for (i = 0; i < count; i++)
1502     {
1503       ecoff_swap_rpdr_out (abfd, rpdr + i, erp + i);
1504       strcpy (str, sv[i]);
1505       str += strlen (sv[i]) + 1;
1506     }
1507   H_PUT_S32 (abfd, -1, (erp + count)->p_adr);
1508
1509   /* Set the size and contents of .rtproc section.  */
1510   s->size = size;
1511   s->contents = rtproc;
1512
1513   /* Skip this section later on (I don't think this currently
1514      matters, but someday it might).  */
1515   s->map_head.link_order = NULL;
1516
1517   if (epdr != NULL)
1518     free (epdr);
1519   if (rpdr != NULL)
1520     free (rpdr);
1521   if (esym != NULL)
1522     free (esym);
1523   if (ss != NULL)
1524     free (ss);
1525   if (sv != NULL)
1526     free (sv);
1527
1528   return TRUE;
1529
1530  error_return:
1531   if (epdr != NULL)
1532     free (epdr);
1533   if (rpdr != NULL)
1534     free (rpdr);
1535   if (esym != NULL)
1536     free (esym);
1537   if (ss != NULL)
1538     free (ss);
1539   if (sv != NULL)
1540     free (sv);
1541   return FALSE;
1542 }
1543 \f
1544 /* We're going to create a stub for H.  Create a symbol for the stub's
1545    value and size, to help make the disassembly easier to read.  */
1546
1547 static bfd_boolean
1548 mips_elf_create_stub_symbol (struct bfd_link_info *info,
1549                              struct mips_elf_link_hash_entry *h,
1550                              const char *prefix, asection *s, bfd_vma value,
1551                              bfd_vma size)
1552 {
1553   struct bfd_link_hash_entry *bh;
1554   struct elf_link_hash_entry *elfh;
1555   const char *name;
1556
1557   if (ELF_ST_IS_MICROMIPS (h->root.other))
1558     value |= 1;
1559
1560   /* Create a new symbol.  */
1561   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1562   bh = NULL;
1563   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1564                                          BSF_LOCAL, s, value, NULL,
1565                                          TRUE, FALSE, &bh))
1566     return FALSE;
1567
1568   /* Make it a local function.  */
1569   elfh = (struct elf_link_hash_entry *) bh;
1570   elfh->type = ELF_ST_INFO (STB_LOCAL, STT_FUNC);
1571   elfh->size = size;
1572   elfh->forced_local = 1;
1573   return TRUE;
1574 }
1575
1576 /* We're about to redefine H.  Create a symbol to represent H's
1577    current value and size, to help make the disassembly easier
1578    to read.  */
1579
1580 static bfd_boolean
1581 mips_elf_create_shadow_symbol (struct bfd_link_info *info,
1582                                struct mips_elf_link_hash_entry *h,
1583                                const char *prefix)
1584 {
1585   struct bfd_link_hash_entry *bh;
1586   struct elf_link_hash_entry *elfh;
1587   const char *name;
1588   asection *s;
1589   bfd_vma value;
1590
1591   /* Read the symbol's value.  */
1592   BFD_ASSERT (h->root.root.type == bfd_link_hash_defined
1593               || h->root.root.type == bfd_link_hash_defweak);
1594   s = h->root.root.u.def.section;
1595   value = h->root.root.u.def.value;
1596
1597   /* Create a new symbol.  */
1598   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1599   bh = NULL;
1600   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1601                                          BSF_LOCAL, s, value, NULL,
1602                                          TRUE, FALSE, &bh))
1603     return FALSE;
1604
1605   /* Make it local and copy the other attributes from H.  */
1606   elfh = (struct elf_link_hash_entry *) bh;
1607   elfh->type = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (h->root.type));
1608   elfh->other = h->root.other;
1609   elfh->size = h->root.size;
1610   elfh->forced_local = 1;
1611   return TRUE;
1612 }
1613
1614 /* Return TRUE if relocations in SECTION can refer directly to a MIPS16
1615    function rather than to a hard-float stub.  */
1616
1617 static bfd_boolean
1618 section_allows_mips16_refs_p (asection *section)
1619 {
1620   const char *name;
1621
1622   name = bfd_get_section_name (section->owner, section);
1623   return (FN_STUB_P (name)
1624           || CALL_STUB_P (name)
1625           || CALL_FP_STUB_P (name)
1626           || strcmp (name, ".pdr") == 0);
1627 }
1628
1629 /* [RELOCS, RELEND) are the relocations against SEC, which is a MIPS16
1630    stub section of some kind.  Return the R_SYMNDX of the target
1631    function, or 0 if we can't decide which function that is.  */
1632
1633 static unsigned long
1634 mips16_stub_symndx (const struct elf_backend_data *bed,
1635                     asection *sec ATTRIBUTE_UNUSED,
1636                     const Elf_Internal_Rela *relocs,
1637                     const Elf_Internal_Rela *relend)
1638 {
1639   int int_rels_per_ext_rel = bed->s->int_rels_per_ext_rel;
1640   const Elf_Internal_Rela *rel;
1641
1642   /* Trust the first R_MIPS_NONE relocation, if any, but not a subsequent
1643      one in a compound relocation.  */
1644   for (rel = relocs; rel < relend; rel += int_rels_per_ext_rel)
1645     if (ELF_R_TYPE (sec->owner, rel->r_info) == R_MIPS_NONE)
1646       return ELF_R_SYM (sec->owner, rel->r_info);
1647
1648   /* Otherwise trust the first relocation, whatever its kind.  This is
1649      the traditional behavior.  */
1650   if (relocs < relend)
1651     return ELF_R_SYM (sec->owner, relocs->r_info);
1652
1653   return 0;
1654 }
1655
1656 /* Check the mips16 stubs for a particular symbol, and see if we can
1657    discard them.  */
1658
1659 static void
1660 mips_elf_check_mips16_stubs (struct bfd_link_info *info,
1661                              struct mips_elf_link_hash_entry *h)
1662 {
1663   /* Dynamic symbols must use the standard call interface, in case other
1664      objects try to call them.  */
1665   if (h->fn_stub != NULL
1666       && h->root.dynindx != -1)
1667     {
1668       mips_elf_create_shadow_symbol (info, h, ".mips16.");
1669       h->need_fn_stub = TRUE;
1670     }
1671
1672   if (h->fn_stub != NULL
1673       && ! h->need_fn_stub)
1674     {
1675       /* We don't need the fn_stub; the only references to this symbol
1676          are 16 bit calls.  Clobber the size to 0 to prevent it from
1677          being included in the link.  */
1678       h->fn_stub->size = 0;
1679       h->fn_stub->flags &= ~SEC_RELOC;
1680       h->fn_stub->reloc_count = 0;
1681       h->fn_stub->flags |= SEC_EXCLUDE;
1682     }
1683
1684   if (h->call_stub != NULL
1685       && ELF_ST_IS_MIPS16 (h->root.other))
1686     {
1687       /* We don't need the call_stub; this is a 16 bit function, so
1688          calls from other 16 bit functions are OK.  Clobber the size
1689          to 0 to prevent it from being included in the link.  */
1690       h->call_stub->size = 0;
1691       h->call_stub->flags &= ~SEC_RELOC;
1692       h->call_stub->reloc_count = 0;
1693       h->call_stub->flags |= SEC_EXCLUDE;
1694     }
1695
1696   if (h->call_fp_stub != NULL
1697       && ELF_ST_IS_MIPS16 (h->root.other))
1698     {
1699       /* We don't need the call_stub; this is a 16 bit function, so
1700          calls from other 16 bit functions are OK.  Clobber the size
1701          to 0 to prevent it from being included in the link.  */
1702       h->call_fp_stub->size = 0;
1703       h->call_fp_stub->flags &= ~SEC_RELOC;
1704       h->call_fp_stub->reloc_count = 0;
1705       h->call_fp_stub->flags |= SEC_EXCLUDE;
1706     }
1707 }
1708
1709 /* Hashtable callbacks for mips_elf_la25_stubs.  */
1710
1711 static hashval_t
1712 mips_elf_la25_stub_hash (const void *entry_)
1713 {
1714   const struct mips_elf_la25_stub *entry;
1715
1716   entry = (struct mips_elf_la25_stub *) entry_;
1717   return entry->h->root.root.u.def.section->id
1718     + entry->h->root.root.u.def.value;
1719 }
1720
1721 static int
1722 mips_elf_la25_stub_eq (const void *entry1_, const void *entry2_)
1723 {
1724   const struct mips_elf_la25_stub *entry1, *entry2;
1725
1726   entry1 = (struct mips_elf_la25_stub *) entry1_;
1727   entry2 = (struct mips_elf_la25_stub *) entry2_;
1728   return ((entry1->h->root.root.u.def.section
1729            == entry2->h->root.root.u.def.section)
1730           && (entry1->h->root.root.u.def.value
1731               == entry2->h->root.root.u.def.value));
1732 }
1733
1734 /* Called by the linker to set up the la25 stub-creation code.  FN is
1735    the linker's implementation of add_stub_function.  Return true on
1736    success.  */
1737
1738 bfd_boolean
1739 _bfd_mips_elf_init_stubs (struct bfd_link_info *info,
1740                           asection *(*fn) (const char *, asection *,
1741                                            asection *))
1742 {
1743   struct mips_elf_link_hash_table *htab;
1744
1745   htab = mips_elf_hash_table (info);
1746   if (htab == NULL)
1747     return FALSE;
1748
1749   htab->add_stub_section = fn;
1750   htab->la25_stubs = htab_try_create (1, mips_elf_la25_stub_hash,
1751                                       mips_elf_la25_stub_eq, NULL);
1752   if (htab->la25_stubs == NULL)
1753     return FALSE;
1754
1755   return TRUE;
1756 }
1757
1758 /* Return true if H is a locally-defined PIC function, in the sense
1759    that it or its fn_stub might need $25 to be valid on entry.
1760    Note that MIPS16 functions set up $gp using PC-relative instructions,
1761    so they themselves never need $25 to be valid.  Only non-MIPS16
1762    entry points are of interest here.  */
1763
1764 static bfd_boolean
1765 mips_elf_local_pic_function_p (struct mips_elf_link_hash_entry *h)
1766 {
1767   return ((h->root.root.type == bfd_link_hash_defined
1768            || h->root.root.type == bfd_link_hash_defweak)
1769           && h->root.def_regular
1770           && !bfd_is_abs_section (h->root.root.u.def.section)
1771           && (!ELF_ST_IS_MIPS16 (h->root.other)
1772               || (h->fn_stub && h->need_fn_stub))
1773           && (PIC_OBJECT_P (h->root.root.u.def.section->owner)
1774               || ELF_ST_IS_MIPS_PIC (h->root.other)));
1775 }
1776
1777 /* Set *SEC to the input section that contains the target of STUB.
1778    Return the offset of the target from the start of that section.  */
1779
1780 static bfd_vma
1781 mips_elf_get_la25_target (struct mips_elf_la25_stub *stub,
1782                           asection **sec)
1783 {
1784   if (ELF_ST_IS_MIPS16 (stub->h->root.other))
1785     {
1786       BFD_ASSERT (stub->h->need_fn_stub);
1787       *sec = stub->h->fn_stub;
1788       return 0;
1789     }
1790   else
1791     {
1792       *sec = stub->h->root.root.u.def.section;
1793       return stub->h->root.root.u.def.value;
1794     }
1795 }
1796
1797 /* STUB describes an la25 stub that we have decided to implement
1798    by inserting an LUI/ADDIU pair before the target function.
1799    Create the section and redirect the function symbol to it.  */
1800
1801 static bfd_boolean
1802 mips_elf_add_la25_intro (struct mips_elf_la25_stub *stub,
1803                          struct bfd_link_info *info)
1804 {
1805   struct mips_elf_link_hash_table *htab;
1806   char *name;
1807   asection *s, *input_section;
1808   unsigned int align;
1809
1810   htab = mips_elf_hash_table (info);
1811   if (htab == NULL)
1812     return FALSE;
1813
1814   /* Create a unique name for the new section.  */
1815   name = bfd_malloc (11 + sizeof (".text.stub."));
1816   if (name == NULL)
1817     return FALSE;
1818   sprintf (name, ".text.stub.%d", (int) htab_elements (htab->la25_stubs));
1819
1820   /* Create the section.  */
1821   mips_elf_get_la25_target (stub, &input_section);
1822   s = htab->add_stub_section (name, input_section,
1823                               input_section->output_section);
1824   if (s == NULL)
1825     return FALSE;
1826
1827   /* Make sure that any padding goes before the stub.  */
1828   align = input_section->alignment_power;
1829   if (!bfd_set_section_alignment (s->owner, s, align))
1830     return FALSE;
1831   if (align > 3)
1832     s->size = (1 << align) - 8;
1833
1834   /* Create a symbol for the stub.  */
1835   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 8);
1836   stub->stub_section = s;
1837   stub->offset = s->size;
1838
1839   /* Allocate room for it.  */
1840   s->size += 8;
1841   return TRUE;
1842 }
1843
1844 /* STUB describes an la25 stub that we have decided to implement
1845    with a separate trampoline.  Allocate room for it and redirect
1846    the function symbol to it.  */
1847
1848 static bfd_boolean
1849 mips_elf_add_la25_trampoline (struct mips_elf_la25_stub *stub,
1850                               struct bfd_link_info *info)
1851 {
1852   struct mips_elf_link_hash_table *htab;
1853   asection *s;
1854
1855   htab = mips_elf_hash_table (info);
1856   if (htab == NULL)
1857     return FALSE;
1858
1859   /* Create a trampoline section, if we haven't already.  */
1860   s = htab->strampoline;
1861   if (s == NULL)
1862     {
1863       asection *input_section = stub->h->root.root.u.def.section;
1864       s = htab->add_stub_section (".text", NULL,
1865                                   input_section->output_section);
1866       if (s == NULL || !bfd_set_section_alignment (s->owner, s, 4))
1867         return FALSE;
1868       htab->strampoline = s;
1869     }
1870
1871   /* Create a symbol for the stub.  */
1872   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 16);
1873   stub->stub_section = s;
1874   stub->offset = s->size;
1875
1876   /* Allocate room for it.  */
1877   s->size += 16;
1878   return TRUE;
1879 }
1880
1881 /* H describes a symbol that needs an la25 stub.  Make sure that an
1882    appropriate stub exists and point H at it.  */
1883
1884 static bfd_boolean
1885 mips_elf_add_la25_stub (struct bfd_link_info *info,
1886                         struct mips_elf_link_hash_entry *h)
1887 {
1888   struct mips_elf_link_hash_table *htab;
1889   struct mips_elf_la25_stub search, *stub;
1890   bfd_boolean use_trampoline_p;
1891   asection *s;
1892   bfd_vma value;
1893   void **slot;
1894
1895   /* Describe the stub we want.  */
1896   search.stub_section = NULL;
1897   search.offset = 0;
1898   search.h = h;
1899
1900   /* See if we've already created an equivalent stub.  */
1901   htab = mips_elf_hash_table (info);
1902   if (htab == NULL)
1903     return FALSE;
1904
1905   slot = htab_find_slot (htab->la25_stubs, &search, INSERT);
1906   if (slot == NULL)
1907     return FALSE;
1908
1909   stub = (struct mips_elf_la25_stub *) *slot;
1910   if (stub != NULL)
1911     {
1912       /* We can reuse the existing stub.  */
1913       h->la25_stub = stub;
1914       return TRUE;
1915     }
1916
1917   /* Create a permanent copy of ENTRY and add it to the hash table.  */
1918   stub = bfd_malloc (sizeof (search));
1919   if (stub == NULL)
1920     return FALSE;
1921   *stub = search;
1922   *slot = stub;
1923
1924   /* Prefer to use LUI/ADDIU stubs if the function is at the beginning
1925      of the section and if we would need no more than 2 nops.  */
1926   value = mips_elf_get_la25_target (stub, &s);
1927   use_trampoline_p = (value != 0 || s->alignment_power > 4);
1928
1929   h->la25_stub = stub;
1930   return (use_trampoline_p
1931           ? mips_elf_add_la25_trampoline (stub, info)
1932           : mips_elf_add_la25_intro (stub, info));
1933 }
1934
1935 /* A mips_elf_link_hash_traverse callback that is called before sizing
1936    sections.  DATA points to a mips_htab_traverse_info structure.  */
1937
1938 static bfd_boolean
1939 mips_elf_check_symbols (struct mips_elf_link_hash_entry *h, void *data)
1940 {
1941   struct mips_htab_traverse_info *hti;
1942
1943   hti = (struct mips_htab_traverse_info *) data;
1944   if (!hti->info->relocatable)
1945     mips_elf_check_mips16_stubs (hti->info, h);
1946
1947   if (mips_elf_local_pic_function_p (h))
1948     {
1949       /* PR 12845: If H is in a section that has been garbage
1950          collected it will have its output section set to *ABS*.  */
1951       if (bfd_is_abs_section (h->root.root.u.def.section->output_section))
1952         return TRUE;
1953
1954       /* H is a function that might need $25 to be valid on entry.
1955          If we're creating a non-PIC relocatable object, mark H as
1956          being PIC.  If we're creating a non-relocatable object with
1957          non-PIC branches and jumps to H, make sure that H has an la25
1958          stub.  */
1959       if (hti->info->relocatable)
1960         {
1961           if (!PIC_OBJECT_P (hti->output_bfd))
1962             h->root.other = ELF_ST_SET_MIPS_PIC (h->root.other);
1963         }
1964       else if (h->has_nonpic_branches && !mips_elf_add_la25_stub (hti->info, h))
1965         {
1966           hti->error = TRUE;
1967           return FALSE;
1968         }
1969     }
1970   return TRUE;
1971 }
1972 \f
1973 /* R_MIPS16_26 is used for the mips16 jal and jalx instructions.
1974    Most mips16 instructions are 16 bits, but these instructions
1975    are 32 bits.
1976
1977    The format of these instructions is:
1978
1979    +--------------+--------------------------------+
1980    |     JALX     | X|   Imm 20:16  |   Imm 25:21  |
1981    +--------------+--------------------------------+
1982    |                Immediate  15:0                |
1983    +-----------------------------------------------+
1984
1985    JALX is the 5-bit value 00011.  X is 0 for jal, 1 for jalx.
1986    Note that the immediate value in the first word is swapped.
1987
1988    When producing a relocatable object file, R_MIPS16_26 is
1989    handled mostly like R_MIPS_26.  In particular, the addend is
1990    stored as a straight 26-bit value in a 32-bit instruction.
1991    (gas makes life simpler for itself by never adjusting a
1992    R_MIPS16_26 reloc to be against a section, so the addend is
1993    always zero).  However, the 32 bit instruction is stored as 2
1994    16-bit values, rather than a single 32-bit value.  In a
1995    big-endian file, the result is the same; in a little-endian
1996    file, the two 16-bit halves of the 32 bit value are swapped.
1997    This is so that a disassembler can recognize the jal
1998    instruction.
1999
2000    When doing a final link, R_MIPS16_26 is treated as a 32 bit
2001    instruction stored as two 16-bit values.  The addend A is the
2002    contents of the targ26 field.  The calculation is the same as
2003    R_MIPS_26.  When storing the calculated value, reorder the
2004    immediate value as shown above, and don't forget to store the
2005    value as two 16-bit values.
2006
2007    To put it in MIPS ABI terms, the relocation field is T-targ26-16,
2008    defined as
2009
2010    big-endian:
2011    +--------+----------------------+
2012    |        |                      |
2013    |        |    targ26-16         |
2014    |31    26|25                   0|
2015    +--------+----------------------+
2016
2017    little-endian:
2018    +----------+------+-------------+
2019    |          |      |             |
2020    |  sub1    |      |     sub2    |
2021    |0        9|10  15|16         31|
2022    +----------+--------------------+
2023    where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is
2024    ((sub1 << 16) | sub2)).
2025
2026    When producing a relocatable object file, the calculation is
2027    (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
2028    When producing a fully linked file, the calculation is
2029    let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
2030    ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff)
2031
2032    The table below lists the other MIPS16 instruction relocations.
2033    Each one is calculated in the same way as the non-MIPS16 relocation
2034    given on the right, but using the extended MIPS16 layout of 16-bit
2035    immediate fields:
2036
2037         R_MIPS16_GPREL          R_MIPS_GPREL16
2038         R_MIPS16_GOT16          R_MIPS_GOT16
2039         R_MIPS16_CALL16         R_MIPS_CALL16
2040         R_MIPS16_HI16           R_MIPS_HI16
2041         R_MIPS16_LO16           R_MIPS_LO16
2042
2043    A typical instruction will have a format like this:
2044
2045    +--------------+--------------------------------+
2046    |    EXTEND    |     Imm 10:5    |   Imm 15:11  |
2047    +--------------+--------------------------------+
2048    |    Major     |   rx   |   ry   |   Imm  4:0   |
2049    +--------------+--------------------------------+
2050
2051    EXTEND is the five bit value 11110.  Major is the instruction
2052    opcode.
2053
2054    All we need to do here is shuffle the bits appropriately.
2055    As above, the two 16-bit halves must be swapped on a
2056    little-endian system.  */
2057
2058 static inline bfd_boolean
2059 mips16_reloc_p (int r_type)
2060 {
2061   switch (r_type)
2062     {
2063     case R_MIPS16_26:
2064     case R_MIPS16_GPREL:
2065     case R_MIPS16_GOT16:
2066     case R_MIPS16_CALL16:
2067     case R_MIPS16_HI16:
2068     case R_MIPS16_LO16:
2069     case R_MIPS16_TLS_GD:
2070     case R_MIPS16_TLS_LDM:
2071     case R_MIPS16_TLS_DTPREL_HI16:
2072     case R_MIPS16_TLS_DTPREL_LO16:
2073     case R_MIPS16_TLS_GOTTPREL:
2074     case R_MIPS16_TLS_TPREL_HI16:
2075     case R_MIPS16_TLS_TPREL_LO16:
2076       return TRUE;
2077
2078     default:
2079       return FALSE;
2080     }
2081 }
2082
2083 /* Check if a microMIPS reloc.  */
2084
2085 static inline bfd_boolean
2086 micromips_reloc_p (unsigned int r_type)
2087 {
2088   return r_type >= R_MICROMIPS_min && r_type < R_MICROMIPS_max;
2089 }
2090
2091 /* Similar to MIPS16, the two 16-bit halves in microMIPS must be swapped
2092    on a little-endian system.  This does not apply to R_MICROMIPS_PC7_S1
2093    and R_MICROMIPS_PC10_S1 relocs that apply to 16-bit instructions.  */
2094
2095 static inline bfd_boolean
2096 micromips_reloc_shuffle_p (unsigned int r_type)
2097 {
2098   return (micromips_reloc_p (r_type)
2099           && r_type != R_MICROMIPS_PC7_S1
2100           && r_type != R_MICROMIPS_PC10_S1);
2101 }
2102
2103 static inline bfd_boolean
2104 got16_reloc_p (int r_type)
2105 {
2106   return (r_type == R_MIPS_GOT16
2107           || r_type == R_MIPS16_GOT16
2108           || r_type == R_MICROMIPS_GOT16);
2109 }
2110
2111 static inline bfd_boolean
2112 call16_reloc_p (int r_type)
2113 {
2114   return (r_type == R_MIPS_CALL16
2115           || r_type == R_MIPS16_CALL16
2116           || r_type == R_MICROMIPS_CALL16);
2117 }
2118
2119 static inline bfd_boolean
2120 got_disp_reloc_p (unsigned int r_type)
2121 {
2122   return r_type == R_MIPS_GOT_DISP || r_type == R_MICROMIPS_GOT_DISP;
2123 }
2124
2125 static inline bfd_boolean
2126 got_page_reloc_p (unsigned int r_type)
2127 {
2128   return r_type == R_MIPS_GOT_PAGE || r_type == R_MICROMIPS_GOT_PAGE;
2129 }
2130
2131 static inline bfd_boolean
2132 got_ofst_reloc_p (unsigned int r_type)
2133 {
2134   return r_type == R_MIPS_GOT_OFST || r_type == R_MICROMIPS_GOT_OFST;
2135 }
2136
2137 static inline bfd_boolean
2138 got_hi16_reloc_p (unsigned int r_type)
2139 {
2140   return r_type == R_MIPS_GOT_HI16 || r_type == R_MICROMIPS_GOT_HI16;
2141 }
2142
2143 static inline bfd_boolean
2144 got_lo16_reloc_p (unsigned int r_type)
2145 {
2146   return r_type == R_MIPS_GOT_LO16 || r_type == R_MICROMIPS_GOT_LO16;
2147 }
2148
2149 static inline bfd_boolean
2150 call_hi16_reloc_p (unsigned int r_type)
2151 {
2152   return r_type == R_MIPS_CALL_HI16 || r_type == R_MICROMIPS_CALL_HI16;
2153 }
2154
2155 static inline bfd_boolean
2156 call_lo16_reloc_p (unsigned int r_type)
2157 {
2158   return r_type == R_MIPS_CALL_LO16 || r_type == R_MICROMIPS_CALL_LO16;
2159 }
2160
2161 static inline bfd_boolean
2162 hi16_reloc_p (int r_type)
2163 {
2164   return (r_type == R_MIPS_HI16
2165           || r_type == R_MIPS16_HI16
2166           || r_type == R_MICROMIPS_HI16);
2167 }
2168
2169 static inline bfd_boolean
2170 lo16_reloc_p (int r_type)
2171 {
2172   return (r_type == R_MIPS_LO16
2173           || r_type == R_MIPS16_LO16
2174           || r_type == R_MICROMIPS_LO16);
2175 }
2176
2177 static inline bfd_boolean
2178 mips16_call_reloc_p (int r_type)
2179 {
2180   return r_type == R_MIPS16_26 || r_type == R_MIPS16_CALL16;
2181 }
2182
2183 static inline bfd_boolean
2184 jal_reloc_p (int r_type)
2185 {
2186   return (r_type == R_MIPS_26
2187           || r_type == R_MIPS16_26
2188           || r_type == R_MICROMIPS_26_S1);
2189 }
2190
2191 static inline bfd_boolean
2192 micromips_branch_reloc_p (int r_type)
2193 {
2194   return (r_type == R_MICROMIPS_26_S1
2195           || r_type == R_MICROMIPS_PC16_S1
2196           || r_type == R_MICROMIPS_PC10_S1
2197           || r_type == R_MICROMIPS_PC7_S1);
2198 }
2199
2200 static inline bfd_boolean
2201 tls_gd_reloc_p (unsigned int r_type)
2202 {
2203   return (r_type == R_MIPS_TLS_GD
2204           || r_type == R_MIPS16_TLS_GD
2205           || r_type == R_MICROMIPS_TLS_GD);
2206 }
2207
2208 static inline bfd_boolean
2209 tls_ldm_reloc_p (unsigned int r_type)
2210 {
2211   return (r_type == R_MIPS_TLS_LDM
2212           || r_type == R_MIPS16_TLS_LDM
2213           || r_type == R_MICROMIPS_TLS_LDM);
2214 }
2215
2216 static inline bfd_boolean
2217 tls_gottprel_reloc_p (unsigned int r_type)
2218 {
2219   return (r_type == R_MIPS_TLS_GOTTPREL
2220           || r_type == R_MIPS16_TLS_GOTTPREL
2221           || r_type == R_MICROMIPS_TLS_GOTTPREL);
2222 }
2223
2224 void
2225 _bfd_mips_elf_reloc_unshuffle (bfd *abfd, int r_type,
2226                                bfd_boolean jal_shuffle, bfd_byte *data)
2227 {
2228   bfd_vma first, second, val;
2229
2230   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2231     return;
2232
2233   /* Pick up the first and second halfwords of the instruction.  */
2234   first = bfd_get_16 (abfd, data);
2235   second = bfd_get_16 (abfd, data + 2);
2236   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2237     val = first << 16 | second;
2238   else if (r_type != R_MIPS16_26)
2239     val = (((first & 0xf800) << 16) | ((second & 0xffe0) << 11)
2240            | ((first & 0x1f) << 11) | (first & 0x7e0) | (second & 0x1f));
2241   else
2242     val = (((first & 0xfc00) << 16) | ((first & 0x3e0) << 11)
2243            | ((first & 0x1f) << 21) | second);
2244   bfd_put_32 (abfd, val, data);
2245 }
2246
2247 void
2248 _bfd_mips_elf_reloc_shuffle (bfd *abfd, int r_type,
2249                              bfd_boolean jal_shuffle, bfd_byte *data)
2250 {
2251   bfd_vma first, second, val;
2252
2253   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2254     return;
2255
2256   val = bfd_get_32 (abfd, data);
2257   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2258     {
2259       second = val & 0xffff;
2260       first = val >> 16;
2261     }
2262   else if (r_type != R_MIPS16_26)
2263     {
2264       second = ((val >> 11) & 0xffe0) | (val & 0x1f);
2265       first = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0);
2266     }
2267   else
2268     {
2269       second = val & 0xffff;
2270       first = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0)
2271                | ((val >> 21) & 0x1f);
2272     }
2273   bfd_put_16 (abfd, second, data + 2);
2274   bfd_put_16 (abfd, first, data);
2275 }
2276
2277 bfd_reloc_status_type
2278 _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol,
2279                                arelent *reloc_entry, asection *input_section,
2280                                bfd_boolean relocatable, void *data, bfd_vma gp)
2281 {
2282   bfd_vma relocation;
2283   bfd_signed_vma val;
2284   bfd_reloc_status_type status;
2285
2286   if (bfd_is_com_section (symbol->section))
2287     relocation = 0;
2288   else
2289     relocation = symbol->value;
2290
2291   relocation += symbol->section->output_section->vma;
2292   relocation += symbol->section->output_offset;
2293
2294   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2295     return bfd_reloc_outofrange;
2296
2297   /* Set val to the offset into the section or symbol.  */
2298   val = reloc_entry->addend;
2299
2300   _bfd_mips_elf_sign_extend (val, 16);
2301
2302   /* Adjust val for the final section location and GP value.  If we
2303      are producing relocatable output, we don't want to do this for
2304      an external symbol.  */
2305   if (! relocatable
2306       || (symbol->flags & BSF_SECTION_SYM) != 0)
2307     val += relocation - gp;
2308
2309   if (reloc_entry->howto->partial_inplace)
2310     {
2311       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2312                                        (bfd_byte *) data
2313                                        + reloc_entry->address);
2314       if (status != bfd_reloc_ok)
2315         return status;
2316     }
2317   else
2318     reloc_entry->addend = val;
2319
2320   if (relocatable)
2321     reloc_entry->address += input_section->output_offset;
2322
2323   return bfd_reloc_ok;
2324 }
2325
2326 /* Used to store a REL high-part relocation such as R_MIPS_HI16 or
2327    R_MIPS_GOT16.  REL is the relocation, INPUT_SECTION is the section
2328    that contains the relocation field and DATA points to the start of
2329    INPUT_SECTION.  */
2330
2331 struct mips_hi16
2332 {
2333   struct mips_hi16 *next;
2334   bfd_byte *data;
2335   asection *input_section;
2336   arelent rel;
2337 };
2338
2339 /* FIXME: This should not be a static variable.  */
2340
2341 static struct mips_hi16 *mips_hi16_list;
2342
2343 /* A howto special_function for REL *HI16 relocations.  We can only
2344    calculate the correct value once we've seen the partnering
2345    *LO16 relocation, so just save the information for later.
2346
2347    The ABI requires that the *LO16 immediately follow the *HI16.
2348    However, as a GNU extension, we permit an arbitrary number of
2349    *HI16s to be associated with a single *LO16.  This significantly
2350    simplies the relocation handling in gcc.  */
2351
2352 bfd_reloc_status_type
2353 _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2354                           asymbol *symbol ATTRIBUTE_UNUSED, void *data,
2355                           asection *input_section, bfd *output_bfd,
2356                           char **error_message ATTRIBUTE_UNUSED)
2357 {
2358   struct mips_hi16 *n;
2359
2360   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2361     return bfd_reloc_outofrange;
2362
2363   n = bfd_malloc (sizeof *n);
2364   if (n == NULL)
2365     return bfd_reloc_outofrange;
2366
2367   n->next = mips_hi16_list;
2368   n->data = data;
2369   n->input_section = input_section;
2370   n->rel = *reloc_entry;
2371   mips_hi16_list = n;
2372
2373   if (output_bfd != NULL)
2374     reloc_entry->address += input_section->output_offset;
2375
2376   return bfd_reloc_ok;
2377 }
2378
2379 /* A howto special_function for REL R_MIPS*_GOT16 relocations.  This is just
2380    like any other 16-bit relocation when applied to global symbols, but is
2381    treated in the same as R_MIPS_HI16 when applied to local symbols.  */
2382
2383 bfd_reloc_status_type
2384 _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2385                            void *data, asection *input_section,
2386                            bfd *output_bfd, char **error_message)
2387 {
2388   if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2389       || bfd_is_und_section (bfd_get_section (symbol))
2390       || bfd_is_com_section (bfd_get_section (symbol)))
2391     /* The relocation is against a global symbol.  */
2392     return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2393                                         input_section, output_bfd,
2394                                         error_message);
2395
2396   return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
2397                                    input_section, output_bfd, error_message);
2398 }
2399
2400 /* A howto special_function for REL *LO16 relocations.  The *LO16 itself
2401    is a straightforward 16 bit inplace relocation, but we must deal with
2402    any partnering high-part relocations as well.  */
2403
2404 bfd_reloc_status_type
2405 _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2406                           void *data, asection *input_section,
2407                           bfd *output_bfd, char **error_message)
2408 {
2409   bfd_vma vallo;
2410   bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2411
2412   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2413     return bfd_reloc_outofrange;
2414
2415   _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2416                                  location);
2417   vallo = bfd_get_32 (abfd, location);
2418   _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2419                                location);
2420
2421   while (mips_hi16_list != NULL)
2422     {
2423       bfd_reloc_status_type ret;
2424       struct mips_hi16 *hi;
2425
2426       hi = mips_hi16_list;
2427
2428       /* R_MIPS*_GOT16 relocations are something of a special case.  We
2429          want to install the addend in the same way as for a R_MIPS*_HI16
2430          relocation (with a rightshift of 16).  However, since GOT16
2431          relocations can also be used with global symbols, their howto
2432          has a rightshift of 0.  */
2433       if (hi->rel.howto->type == R_MIPS_GOT16)
2434         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE);
2435       else if (hi->rel.howto->type == R_MIPS16_GOT16)
2436         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS16_HI16, FALSE);
2437       else if (hi->rel.howto->type == R_MICROMIPS_GOT16)
2438         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MICROMIPS_HI16, FALSE);
2439
2440       /* VALLO is a signed 16-bit number.  Bias it by 0x8000 so that any
2441          carry or borrow will induce a change of +1 or -1 in the high part.  */
2442       hi->rel.addend += (vallo + 0x8000) & 0xffff;
2443
2444       ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data,
2445                                          hi->input_section, output_bfd,
2446                                          error_message);
2447       if (ret != bfd_reloc_ok)
2448         return ret;
2449
2450       mips_hi16_list = hi->next;
2451       free (hi);
2452     }
2453
2454   return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2455                                       input_section, output_bfd,
2456                                       error_message);
2457 }
2458
2459 /* A generic howto special_function.  This calculates and installs the
2460    relocation itself, thus avoiding the oft-discussed problems in
2461    bfd_perform_relocation and bfd_install_relocation.  */
2462
2463 bfd_reloc_status_type
2464 _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2465                              asymbol *symbol, void *data ATTRIBUTE_UNUSED,
2466                              asection *input_section, bfd *output_bfd,
2467                              char **error_message ATTRIBUTE_UNUSED)
2468 {
2469   bfd_signed_vma val;
2470   bfd_reloc_status_type status;
2471   bfd_boolean relocatable;
2472
2473   relocatable = (output_bfd != NULL);
2474
2475   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2476     return bfd_reloc_outofrange;
2477
2478   /* Build up the field adjustment in VAL.  */
2479   val = 0;
2480   if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)
2481     {
2482       /* Either we're calculating the final field value or we have a
2483          relocation against a section symbol.  Add in the section's
2484          offset or address.  */
2485       val += symbol->section->output_section->vma;
2486       val += symbol->section->output_offset;
2487     }
2488
2489   if (!relocatable)
2490     {
2491       /* We're calculating the final field value.  Add in the symbol's value
2492          and, if pc-relative, subtract the address of the field itself.  */
2493       val += symbol->value;
2494       if (reloc_entry->howto->pc_relative)
2495         {
2496           val -= input_section->output_section->vma;
2497           val -= input_section->output_offset;
2498           val -= reloc_entry->address;
2499         }
2500     }
2501
2502   /* VAL is now the final adjustment.  If we're keeping this relocation
2503      in the output file, and if the relocation uses a separate addend,
2504      we just need to add VAL to that addend.  Otherwise we need to add
2505      VAL to the relocation field itself.  */
2506   if (relocatable && !reloc_entry->howto->partial_inplace)
2507     reloc_entry->addend += val;
2508   else
2509     {
2510       bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2511
2512       /* Add in the separate addend, if any.  */
2513       val += reloc_entry->addend;
2514
2515       /* Add VAL to the relocation field.  */
2516       _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2517                                      location);
2518       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2519                                        location);
2520       _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2521                                    location);
2522
2523       if (status != bfd_reloc_ok)
2524         return status;
2525     }
2526
2527   if (relocatable)
2528     reloc_entry->address += input_section->output_offset;
2529
2530   return bfd_reloc_ok;
2531 }
2532 \f
2533 /* Swap an entry in a .gptab section.  Note that these routines rely
2534    on the equivalence of the two elements of the union.  */
2535
2536 static void
2537 bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex,
2538                               Elf32_gptab *in)
2539 {
2540   in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value);
2541   in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes);
2542 }
2543
2544 static void
2545 bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in,
2546                                Elf32_External_gptab *ex)
2547 {
2548   H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value);
2549   H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes);
2550 }
2551
2552 static void
2553 bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in,
2554                                 Elf32_External_compact_rel *ex)
2555 {
2556   H_PUT_32 (abfd, in->id1, ex->id1);
2557   H_PUT_32 (abfd, in->num, ex->num);
2558   H_PUT_32 (abfd, in->id2, ex->id2);
2559   H_PUT_32 (abfd, in->offset, ex->offset);
2560   H_PUT_32 (abfd, in->reserved0, ex->reserved0);
2561   H_PUT_32 (abfd, in->reserved1, ex->reserved1);
2562 }
2563
2564 static void
2565 bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in,
2566                            Elf32_External_crinfo *ex)
2567 {
2568   unsigned long l;
2569
2570   l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH)
2571        | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH)
2572        | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH)
2573        | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH));
2574   H_PUT_32 (abfd, l, ex->info);
2575   H_PUT_32 (abfd, in->konst, ex->konst);
2576   H_PUT_32 (abfd, in->vaddr, ex->vaddr);
2577 }
2578 \f
2579 /* A .reginfo section holds a single Elf32_RegInfo structure.  These
2580    routines swap this structure in and out.  They are used outside of
2581    BFD, so they are globally visible.  */
2582
2583 void
2584 bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex,
2585                                 Elf32_RegInfo *in)
2586 {
2587   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2588   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2589   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2590   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2591   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2592   in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value);
2593 }
2594
2595 void
2596 bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in,
2597                                  Elf32_External_RegInfo *ex)
2598 {
2599   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2600   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2601   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2602   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2603   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2604   H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value);
2605 }
2606
2607 /* In the 64 bit ABI, the .MIPS.options section holds register
2608    information in an Elf64_Reginfo structure.  These routines swap
2609    them in and out.  They are globally visible because they are used
2610    outside of BFD.  These routines are here so that gas can call them
2611    without worrying about whether the 64 bit ABI has been included.  */
2612
2613 void
2614 bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex,
2615                                 Elf64_Internal_RegInfo *in)
2616 {
2617   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2618   in->ri_pad = H_GET_32 (abfd, ex->ri_pad);
2619   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2620   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2621   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2622   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2623   in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value);
2624 }
2625
2626 void
2627 bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in,
2628                                  Elf64_External_RegInfo *ex)
2629 {
2630   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2631   H_PUT_32 (abfd, in->ri_pad, ex->ri_pad);
2632   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2633   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2634   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2635   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2636   H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value);
2637 }
2638
2639 /* Swap in an options header.  */
2640
2641 void
2642 bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex,
2643                               Elf_Internal_Options *in)
2644 {
2645   in->kind = H_GET_8 (abfd, ex->kind);
2646   in->size = H_GET_8 (abfd, ex->size);
2647   in->section = H_GET_16 (abfd, ex->section);
2648   in->info = H_GET_32 (abfd, ex->info);
2649 }
2650
2651 /* Swap out an options header.  */
2652
2653 void
2654 bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in,
2655                                Elf_External_Options *ex)
2656 {
2657   H_PUT_8 (abfd, in->kind, ex->kind);
2658   H_PUT_8 (abfd, in->size, ex->size);
2659   H_PUT_16 (abfd, in->section, ex->section);
2660   H_PUT_32 (abfd, in->info, ex->info);
2661 }
2662 \f
2663 /* This function is called via qsort() to sort the dynamic relocation
2664    entries by increasing r_symndx value.  */
2665
2666 static int
2667 sort_dynamic_relocs (const void *arg1, const void *arg2)
2668 {
2669   Elf_Internal_Rela int_reloc1;
2670   Elf_Internal_Rela int_reloc2;
2671   int diff;
2672
2673   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
2674   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
2675
2676   diff = ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info);
2677   if (diff != 0)
2678     return diff;
2679
2680   if (int_reloc1.r_offset < int_reloc2.r_offset)
2681     return -1;
2682   if (int_reloc1.r_offset > int_reloc2.r_offset)
2683     return 1;
2684   return 0;
2685 }
2686
2687 /* Like sort_dynamic_relocs, but used for elf64 relocations.  */
2688
2689 static int
2690 sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED,
2691                         const void *arg2 ATTRIBUTE_UNUSED)
2692 {
2693 #ifdef BFD64
2694   Elf_Internal_Rela int_reloc1[3];
2695   Elf_Internal_Rela int_reloc2[3];
2696
2697   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2698     (reldyn_sorting_bfd, arg1, int_reloc1);
2699   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2700     (reldyn_sorting_bfd, arg2, int_reloc2);
2701
2702   if (ELF64_R_SYM (int_reloc1[0].r_info) < ELF64_R_SYM (int_reloc2[0].r_info))
2703     return -1;
2704   if (ELF64_R_SYM (int_reloc1[0].r_info) > ELF64_R_SYM (int_reloc2[0].r_info))
2705     return 1;
2706
2707   if (int_reloc1[0].r_offset < int_reloc2[0].r_offset)
2708     return -1;
2709   if (int_reloc1[0].r_offset > int_reloc2[0].r_offset)
2710     return 1;
2711   return 0;
2712 #else
2713   abort ();
2714 #endif
2715 }
2716
2717
2718 /* This routine is used to write out ECOFF debugging external symbol
2719    information.  It is called via mips_elf_link_hash_traverse.  The
2720    ECOFF external symbol information must match the ELF external
2721    symbol information.  Unfortunately, at this point we don't know
2722    whether a symbol is required by reloc information, so the two
2723    tables may wind up being different.  We must sort out the external
2724    symbol information before we can set the final size of the .mdebug
2725    section, and we must set the size of the .mdebug section before we
2726    can relocate any sections, and we can't know which symbols are
2727    required by relocation until we relocate the sections.
2728    Fortunately, it is relatively unlikely that any symbol will be
2729    stripped but required by a reloc.  In particular, it can not happen
2730    when generating a final executable.  */
2731
2732 static bfd_boolean
2733 mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data)
2734 {
2735   struct extsym_info *einfo = data;
2736   bfd_boolean strip;
2737   asection *sec, *output_section;
2738
2739   if (h->root.indx == -2)
2740     strip = FALSE;
2741   else if ((h->root.def_dynamic
2742             || h->root.ref_dynamic
2743             || h->root.type == bfd_link_hash_new)
2744            && !h->root.def_regular
2745            && !h->root.ref_regular)
2746     strip = TRUE;
2747   else if (einfo->info->strip == strip_all
2748            || (einfo->info->strip == strip_some
2749                && bfd_hash_lookup (einfo->info->keep_hash,
2750                                    h->root.root.root.string,
2751                                    FALSE, FALSE) == NULL))
2752     strip = TRUE;
2753   else
2754     strip = FALSE;
2755
2756   if (strip)
2757     return TRUE;
2758
2759   if (h->esym.ifd == -2)
2760     {
2761       h->esym.jmptbl = 0;
2762       h->esym.cobol_main = 0;
2763       h->esym.weakext = 0;
2764       h->esym.reserved = 0;
2765       h->esym.ifd = ifdNil;
2766       h->esym.asym.value = 0;
2767       h->esym.asym.st = stGlobal;
2768
2769       if (h->root.root.type == bfd_link_hash_undefined
2770           || h->root.root.type == bfd_link_hash_undefweak)
2771         {
2772           const char *name;
2773
2774           /* Use undefined class.  Also, set class and type for some
2775              special symbols.  */
2776           name = h->root.root.root.string;
2777           if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
2778               || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
2779             {
2780               h->esym.asym.sc = scData;
2781               h->esym.asym.st = stLabel;
2782               h->esym.asym.value = 0;
2783             }
2784           else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
2785             {
2786               h->esym.asym.sc = scAbs;
2787               h->esym.asym.st = stLabel;
2788               h->esym.asym.value =
2789                 mips_elf_hash_table (einfo->info)->procedure_count;
2790             }
2791           else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd))
2792             {
2793               h->esym.asym.sc = scAbs;
2794               h->esym.asym.st = stLabel;
2795               h->esym.asym.value = elf_gp (einfo->abfd);
2796             }
2797           else
2798             h->esym.asym.sc = scUndefined;
2799         }
2800       else if (h->root.root.type != bfd_link_hash_defined
2801           && h->root.root.type != bfd_link_hash_defweak)
2802         h->esym.asym.sc = scAbs;
2803       else
2804         {
2805           const char *name;
2806
2807           sec = h->root.root.u.def.section;
2808           output_section = sec->output_section;
2809
2810           /* When making a shared library and symbol h is the one from
2811              the another shared library, OUTPUT_SECTION may be null.  */
2812           if (output_section == NULL)
2813             h->esym.asym.sc = scUndefined;
2814           else
2815             {
2816               name = bfd_section_name (output_section->owner, output_section);
2817
2818               if (strcmp (name, ".text") == 0)
2819                 h->esym.asym.sc = scText;
2820               else if (strcmp (name, ".data") == 0)
2821                 h->esym.asym.sc = scData;
2822               else if (strcmp (name, ".sdata") == 0)
2823                 h->esym.asym.sc = scSData;
2824               else if (strcmp (name, ".rodata") == 0
2825                        || strcmp (name, ".rdata") == 0)
2826                 h->esym.asym.sc = scRData;
2827               else if (strcmp (name, ".bss") == 0)
2828                 h->esym.asym.sc = scBss;
2829               else if (strcmp (name, ".sbss") == 0)
2830                 h->esym.asym.sc = scSBss;
2831               else if (strcmp (name, ".init") == 0)
2832                 h->esym.asym.sc = scInit;
2833               else if (strcmp (name, ".fini") == 0)
2834                 h->esym.asym.sc = scFini;
2835               else
2836                 h->esym.asym.sc = scAbs;
2837             }
2838         }
2839
2840       h->esym.asym.reserved = 0;
2841       h->esym.asym.index = indexNil;
2842     }
2843
2844   if (h->root.root.type == bfd_link_hash_common)
2845     h->esym.asym.value = h->root.root.u.c.size;
2846   else if (h->root.root.type == bfd_link_hash_defined
2847            || h->root.root.type == bfd_link_hash_defweak)
2848     {
2849       if (h->esym.asym.sc == scCommon)
2850         h->esym.asym.sc = scBss;
2851       else if (h->esym.asym.sc == scSCommon)
2852         h->esym.asym.sc = scSBss;
2853
2854       sec = h->root.root.u.def.section;
2855       output_section = sec->output_section;
2856       if (output_section != NULL)
2857         h->esym.asym.value = (h->root.root.u.def.value
2858                               + sec->output_offset
2859                               + output_section->vma);
2860       else
2861         h->esym.asym.value = 0;
2862     }
2863   else
2864     {
2865       struct mips_elf_link_hash_entry *hd = h;
2866
2867       while (hd->root.root.type == bfd_link_hash_indirect)
2868         hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link;
2869
2870       if (hd->needs_lazy_stub)
2871         {
2872           BFD_ASSERT (hd->root.plt.plist != NULL);
2873           BFD_ASSERT (hd->root.plt.plist->stub_offset != MINUS_ONE);
2874           /* Set type and value for a symbol with a function stub.  */
2875           h->esym.asym.st = stProc;
2876           sec = hd->root.root.u.def.section;
2877           if (sec == NULL)
2878             h->esym.asym.value = 0;
2879           else
2880             {
2881               output_section = sec->output_section;
2882               if (output_section != NULL)
2883                 h->esym.asym.value = (hd->root.plt.plist->stub_offset
2884                                       + sec->output_offset
2885                                       + output_section->vma);
2886               else
2887                 h->esym.asym.value = 0;
2888             }
2889         }
2890     }
2891
2892   if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap,
2893                                       h->root.root.root.string,
2894                                       &h->esym))
2895     {
2896       einfo->failed = TRUE;
2897       return FALSE;
2898     }
2899
2900   return TRUE;
2901 }
2902
2903 /* A comparison routine used to sort .gptab entries.  */
2904
2905 static int
2906 gptab_compare (const void *p1, const void *p2)
2907 {
2908   const Elf32_gptab *a1 = p1;
2909   const Elf32_gptab *a2 = p2;
2910
2911   return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value;
2912 }
2913 \f
2914 /* Functions to manage the got entry hash table.  */
2915
2916 /* Use all 64 bits of a bfd_vma for the computation of a 32-bit
2917    hash number.  */
2918
2919 static INLINE hashval_t
2920 mips_elf_hash_bfd_vma (bfd_vma addr)
2921 {
2922 #ifdef BFD64
2923   return addr + (addr >> 32);
2924 #else
2925   return addr;
2926 #endif
2927 }
2928
2929 static hashval_t
2930 mips_elf_got_entry_hash (const void *entry_)
2931 {
2932   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2933
2934   return (entry->symndx
2935           + ((entry->tls_type == GOT_TLS_LDM) << 18)
2936           + (entry->tls_type == GOT_TLS_LDM ? 0
2937              : !entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address)
2938              : entry->symndx >= 0 ? (entry->abfd->id
2939                                      + mips_elf_hash_bfd_vma (entry->d.addend))
2940              : entry->d.h->root.root.root.hash));
2941 }
2942
2943 static int
2944 mips_elf_got_entry_eq (const void *entry1, const void *entry2)
2945 {
2946   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2947   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2948
2949   return (e1->symndx == e2->symndx
2950           && e1->tls_type == e2->tls_type
2951           && (e1->tls_type == GOT_TLS_LDM ? TRUE
2952               : !e1->abfd ? !e2->abfd && e1->d.address == e2->d.address
2953               : e1->symndx >= 0 ? (e1->abfd == e2->abfd
2954                                    && e1->d.addend == e2->d.addend)
2955               : e2->abfd && e1->d.h == e2->d.h));
2956 }
2957
2958 static hashval_t
2959 mips_got_page_ref_hash (const void *ref_)
2960 {
2961   const struct mips_got_page_ref *ref;
2962
2963   ref = (const struct mips_got_page_ref *) ref_;
2964   return ((ref->symndx >= 0
2965            ? (hashval_t) (ref->u.abfd->id + ref->symndx)
2966            : ref->u.h->root.root.root.hash)
2967           + mips_elf_hash_bfd_vma (ref->addend));
2968 }
2969
2970 static int
2971 mips_got_page_ref_eq (const void *ref1_, const void *ref2_)
2972 {
2973   const struct mips_got_page_ref *ref1, *ref2;
2974
2975   ref1 = (const struct mips_got_page_ref *) ref1_;
2976   ref2 = (const struct mips_got_page_ref *) ref2_;
2977   return (ref1->symndx == ref2->symndx
2978           && (ref1->symndx < 0
2979               ? ref1->u.h == ref2->u.h
2980               : ref1->u.abfd == ref2->u.abfd)
2981           && ref1->addend == ref2->addend);
2982 }
2983
2984 static hashval_t
2985 mips_got_page_entry_hash (const void *entry_)
2986 {
2987   const struct mips_got_page_entry *entry;
2988
2989   entry = (const struct mips_got_page_entry *) entry_;
2990   return entry->sec->id;
2991 }
2992
2993 static int
2994 mips_got_page_entry_eq (const void *entry1_, const void *entry2_)
2995 {
2996   const struct mips_got_page_entry *entry1, *entry2;
2997
2998   entry1 = (const struct mips_got_page_entry *) entry1_;
2999   entry2 = (const struct mips_got_page_entry *) entry2_;
3000   return entry1->sec == entry2->sec;
3001 }
3002 \f
3003 /* Create and return a new mips_got_info structure.  */
3004
3005 static struct mips_got_info *
3006 mips_elf_create_got_info (bfd *abfd)
3007 {
3008   struct mips_got_info *g;
3009
3010   g = bfd_zalloc (abfd, sizeof (struct mips_got_info));
3011   if (g == NULL)
3012     return NULL;
3013
3014   g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
3015                                     mips_elf_got_entry_eq, NULL);
3016   if (g->got_entries == NULL)
3017     return NULL;
3018
3019   g->got_page_refs = htab_try_create (1, mips_got_page_ref_hash,
3020                                       mips_got_page_ref_eq, NULL);
3021   if (g->got_page_refs == NULL)
3022     return NULL;
3023
3024   return g;
3025 }
3026
3027 /* Return the GOT info for input bfd ABFD, trying to create a new one if
3028    CREATE_P and if ABFD doesn't already have a GOT.  */
3029
3030 static struct mips_got_info *
3031 mips_elf_bfd_got (bfd *abfd, bfd_boolean create_p)
3032 {
3033   struct mips_elf_obj_tdata *tdata;
3034
3035   if (!is_mips_elf (abfd))
3036     return NULL;
3037
3038   tdata = mips_elf_tdata (abfd);
3039   if (!tdata->got && create_p)
3040     tdata->got = mips_elf_create_got_info (abfd);
3041   return tdata->got;
3042 }
3043
3044 /* Record that ABFD should use output GOT G.  */
3045
3046 static void
3047 mips_elf_replace_bfd_got (bfd *abfd, struct mips_got_info *g)
3048 {
3049   struct mips_elf_obj_tdata *tdata;
3050
3051   BFD_ASSERT (is_mips_elf (abfd));
3052   tdata = mips_elf_tdata (abfd);
3053   if (tdata->got)
3054     {
3055       /* The GOT structure itself and the hash table entries are
3056          allocated to a bfd, but the hash tables aren't.  */
3057       htab_delete (tdata->got->got_entries);
3058       htab_delete (tdata->got->got_page_refs);
3059       if (tdata->got->got_page_entries)
3060         htab_delete (tdata->got->got_page_entries);
3061     }
3062   tdata->got = g;
3063 }
3064
3065 /* Return the dynamic relocation section.  If it doesn't exist, try to
3066    create a new it if CREATE_P, otherwise return NULL.  Also return NULL
3067    if creation fails.  */
3068
3069 static asection *
3070 mips_elf_rel_dyn_section (struct bfd_link_info *info, bfd_boolean create_p)
3071 {
3072   const char *dname;
3073   asection *sreloc;
3074   bfd *dynobj;
3075
3076   dname = MIPS_ELF_REL_DYN_NAME (info);
3077   dynobj = elf_hash_table (info)->dynobj;
3078   sreloc = bfd_get_linker_section (dynobj, dname);
3079   if (sreloc == NULL && create_p)
3080     {
3081       sreloc = bfd_make_section_anyway_with_flags (dynobj, dname,
3082                                                    (SEC_ALLOC
3083                                                     | SEC_LOAD
3084                                                     | SEC_HAS_CONTENTS
3085                                                     | SEC_IN_MEMORY
3086                                                     | SEC_LINKER_CREATED
3087                                                     | SEC_READONLY));
3088       if (sreloc == NULL
3089           || ! bfd_set_section_alignment (dynobj, sreloc,
3090                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
3091         return NULL;
3092     }
3093   return sreloc;
3094 }
3095
3096 /* Return the GOT_TLS_* type required by relocation type R_TYPE.  */
3097
3098 static int
3099 mips_elf_reloc_tls_type (unsigned int r_type)
3100 {
3101   if (tls_gd_reloc_p (r_type))
3102     return GOT_TLS_GD;
3103
3104   if (tls_ldm_reloc_p (r_type))
3105     return GOT_TLS_LDM;
3106
3107   if (tls_gottprel_reloc_p (r_type))
3108     return GOT_TLS_IE;
3109
3110   return GOT_TLS_NONE;
3111 }
3112
3113 /* Return the number of GOT slots needed for GOT TLS type TYPE.  */
3114
3115 static int
3116 mips_tls_got_entries (unsigned int type)
3117 {
3118   switch (type)
3119     {
3120     case GOT_TLS_GD:
3121     case GOT_TLS_LDM:
3122       return 2;
3123
3124     case GOT_TLS_IE:
3125       return 1;
3126
3127     case GOT_TLS_NONE:
3128       return 0;
3129     }
3130   abort ();
3131 }
3132
3133 /* Count the number of relocations needed for a TLS GOT entry, with
3134    access types from TLS_TYPE, and symbol H (or a local symbol if H
3135    is NULL).  */
3136
3137 static int
3138 mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type,
3139                      struct elf_link_hash_entry *h)
3140 {
3141   int indx = 0;
3142   bfd_boolean need_relocs = FALSE;
3143   bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3144
3145   if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, h)
3146       && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, h)))
3147     indx = h->dynindx;
3148
3149   if ((info->shared || indx != 0)
3150       && (h == NULL
3151           || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
3152           || h->root.type != bfd_link_hash_undefweak))
3153     need_relocs = TRUE;
3154
3155   if (!need_relocs)
3156     return 0;
3157
3158   switch (tls_type)
3159     {
3160     case GOT_TLS_GD:
3161       return indx != 0 ? 2 : 1;
3162
3163     case GOT_TLS_IE:
3164       return 1;
3165
3166     case GOT_TLS_LDM:
3167       return info->shared ? 1 : 0;
3168
3169     default:
3170       return 0;
3171     }
3172 }
3173
3174 /* Add the number of GOT entries and TLS relocations required by ENTRY
3175    to G.  */
3176
3177 static void
3178 mips_elf_count_got_entry (struct bfd_link_info *info,
3179                           struct mips_got_info *g,
3180                           struct mips_got_entry *entry)
3181 {
3182   if (entry->tls_type)
3183     {
3184       g->tls_gotno += mips_tls_got_entries (entry->tls_type);
3185       g->relocs += mips_tls_got_relocs (info, entry->tls_type,
3186                                         entry->symndx < 0
3187                                         ? &entry->d.h->root : NULL);
3188     }
3189   else if (entry->symndx >= 0 || entry->d.h->global_got_area == GGA_NONE)
3190     g->local_gotno += 1;
3191   else
3192     g->global_gotno += 1;
3193 }
3194
3195 /* Output a simple dynamic relocation into SRELOC.  */
3196
3197 static void
3198 mips_elf_output_dynamic_relocation (bfd *output_bfd,
3199                                     asection *sreloc,
3200                                     unsigned long reloc_index,
3201                                     unsigned long indx,
3202                                     int r_type,
3203                                     bfd_vma offset)
3204 {
3205   Elf_Internal_Rela rel[3];
3206
3207   memset (rel, 0, sizeof (rel));
3208
3209   rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type);
3210   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
3211
3212   if (ABI_64_P (output_bfd))
3213     {
3214       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
3215         (output_bfd, &rel[0],
3216          (sreloc->contents
3217           + reloc_index * sizeof (Elf64_Mips_External_Rel)));
3218     }
3219   else
3220     bfd_elf32_swap_reloc_out
3221       (output_bfd, &rel[0],
3222        (sreloc->contents
3223         + reloc_index * sizeof (Elf32_External_Rel)));
3224 }
3225
3226 /* Initialize a set of TLS GOT entries for one symbol.  */
3227
3228 static void
3229 mips_elf_initialize_tls_slots (bfd *abfd, struct bfd_link_info *info,
3230                                struct mips_got_entry *entry,
3231                                struct mips_elf_link_hash_entry *h,
3232                                bfd_vma value)
3233 {
3234   struct mips_elf_link_hash_table *htab;
3235   int indx;
3236   asection *sreloc, *sgot;
3237   bfd_vma got_offset, got_offset2;
3238   bfd_boolean need_relocs = FALSE;
3239
3240   htab = mips_elf_hash_table (info);
3241   if (htab == NULL)
3242     return;
3243
3244   sgot = htab->sgot;
3245
3246   indx = 0;
3247   if (h != NULL)
3248     {
3249       bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3250
3251       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, &h->root)
3252           && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3253         indx = h->root.dynindx;
3254     }
3255
3256   if (entry->tls_initialized)
3257     return;
3258
3259   if ((info->shared || indx != 0)
3260       && (h == NULL
3261           || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT
3262           || h->root.type != bfd_link_hash_undefweak))
3263     need_relocs = TRUE;
3264
3265   /* MINUS_ONE means the symbol is not defined in this object.  It may not
3266      be defined at all; assume that the value doesn't matter in that
3267      case.  Otherwise complain if we would use the value.  */
3268   BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs)
3269               || h->root.root.type == bfd_link_hash_undefweak);
3270
3271   /* Emit necessary relocations.  */
3272   sreloc = mips_elf_rel_dyn_section (info, FALSE);
3273   got_offset = entry->gotidx;
3274
3275   switch (entry->tls_type)
3276     {
3277     case GOT_TLS_GD:
3278       /* General Dynamic.  */
3279       got_offset2 = got_offset + MIPS_ELF_GOT_SIZE (abfd);
3280
3281       if (need_relocs)
3282         {
3283           mips_elf_output_dynamic_relocation
3284             (abfd, sreloc, sreloc->reloc_count++, indx,
3285              ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3286              sgot->output_offset + sgot->output_section->vma + got_offset);
3287
3288           if (indx)
3289             mips_elf_output_dynamic_relocation
3290               (abfd, sreloc, sreloc->reloc_count++, indx,
3291                ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32,
3292                sgot->output_offset + sgot->output_section->vma + got_offset2);
3293           else
3294             MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3295                                sgot->contents + got_offset2);
3296         }
3297       else
3298         {
3299           MIPS_ELF_PUT_WORD (abfd, 1,
3300                              sgot->contents + got_offset);
3301           MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3302                              sgot->contents + got_offset2);
3303         }
3304       break;
3305
3306     case GOT_TLS_IE:
3307       /* Initial Exec model.  */
3308       if (need_relocs)
3309         {
3310           if (indx == 0)
3311             MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma,
3312                                sgot->contents + got_offset);
3313           else
3314             MIPS_ELF_PUT_WORD (abfd, 0,
3315                                sgot->contents + got_offset);
3316
3317           mips_elf_output_dynamic_relocation
3318             (abfd, sreloc, sreloc->reloc_count++, indx,
3319              ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32,
3320              sgot->output_offset + sgot->output_section->vma + got_offset);
3321         }
3322       else
3323         MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info),
3324                            sgot->contents + got_offset);
3325       break;
3326
3327     case GOT_TLS_LDM:
3328       /* The initial offset is zero, and the LD offsets will include the
3329          bias by DTP_OFFSET.  */
3330       MIPS_ELF_PUT_WORD (abfd, 0,
3331                          sgot->contents + got_offset
3332                          + MIPS_ELF_GOT_SIZE (abfd));
3333
3334       if (!info->shared)
3335         MIPS_ELF_PUT_WORD (abfd, 1,
3336                            sgot->contents + got_offset);
3337       else
3338         mips_elf_output_dynamic_relocation
3339           (abfd, sreloc, sreloc->reloc_count++, indx,
3340            ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3341            sgot->output_offset + sgot->output_section->vma + got_offset);
3342       break;
3343
3344     default:
3345       abort ();
3346     }
3347
3348   entry->tls_initialized = TRUE;
3349 }
3350
3351 /* Return the offset from _GLOBAL_OFFSET_TABLE_ of the .got.plt entry
3352    for global symbol H.  .got.plt comes before the GOT, so the offset
3353    will be negative.  */
3354
3355 static bfd_vma
3356 mips_elf_gotplt_index (struct bfd_link_info *info,
3357                        struct elf_link_hash_entry *h)
3358 {
3359   bfd_vma got_address, got_value;
3360   struct mips_elf_link_hash_table *htab;
3361
3362   htab = mips_elf_hash_table (info);
3363   BFD_ASSERT (htab != NULL);
3364
3365   BFD_ASSERT (h->plt.plist != NULL);
3366   BFD_ASSERT (h->plt.plist->gotplt_index != MINUS_ONE);
3367
3368   /* Calculate the address of the associated .got.plt entry.  */
3369   got_address = (htab->sgotplt->output_section->vma
3370                  + htab->sgotplt->output_offset
3371                  + (h->plt.plist->gotplt_index
3372                     * MIPS_ELF_GOT_SIZE (info->output_bfd)));
3373
3374   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
3375   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
3376                + htab->root.hgot->root.u.def.section->output_offset
3377                + htab->root.hgot->root.u.def.value);
3378
3379   return got_address - got_value;
3380 }
3381
3382 /* Return the GOT offset for address VALUE.   If there is not yet a GOT
3383    entry for this value, create one.  If R_SYMNDX refers to a TLS symbol,
3384    create a TLS GOT entry instead.  Return -1 if no satisfactory GOT
3385    offset can be found.  */
3386
3387 static bfd_vma
3388 mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3389                           bfd_vma value, unsigned long r_symndx,
3390                           struct mips_elf_link_hash_entry *h, int r_type)
3391 {
3392   struct mips_elf_link_hash_table *htab;
3393   struct mips_got_entry *entry;
3394
3395   htab = mips_elf_hash_table (info);
3396   BFD_ASSERT (htab != NULL);
3397
3398   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value,
3399                                            r_symndx, h, r_type);
3400   if (!entry)
3401     return MINUS_ONE;
3402
3403   if (entry->tls_type)
3404     mips_elf_initialize_tls_slots (abfd, info, entry, h, value);
3405   return entry->gotidx;
3406 }
3407
3408 /* Return the GOT index of global symbol H in the primary GOT.  */
3409
3410 static bfd_vma
3411 mips_elf_primary_global_got_index (bfd *obfd, struct bfd_link_info *info,
3412                                    struct elf_link_hash_entry *h)
3413 {
3414   struct mips_elf_link_hash_table *htab;
3415   long global_got_dynindx;
3416   struct mips_got_info *g;
3417   bfd_vma got_index;
3418
3419   htab = mips_elf_hash_table (info);
3420   BFD_ASSERT (htab != NULL);
3421
3422   global_got_dynindx = 0;
3423   if (htab->global_gotsym != NULL)
3424     global_got_dynindx = htab->global_gotsym->dynindx;
3425
3426   /* Once we determine the global GOT entry with the lowest dynamic
3427      symbol table index, we must put all dynamic symbols with greater
3428      indices into the primary GOT.  That makes it easy to calculate the
3429      GOT offset.  */
3430   BFD_ASSERT (h->dynindx >= global_got_dynindx);
3431   g = mips_elf_bfd_got (obfd, FALSE);
3432   got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3433                * MIPS_ELF_GOT_SIZE (obfd));
3434   BFD_ASSERT (got_index < htab->sgot->size);
3435
3436   return got_index;
3437 }
3438
3439 /* Return the GOT index for the global symbol indicated by H, which is
3440    referenced by a relocation of type R_TYPE in IBFD.  */
3441
3442 static bfd_vma
3443 mips_elf_global_got_index (bfd *obfd, struct bfd_link_info *info, bfd *ibfd,
3444                            struct elf_link_hash_entry *h, int r_type)
3445 {
3446   struct mips_elf_link_hash_table *htab;
3447   struct mips_got_info *g;
3448   struct mips_got_entry lookup, *entry;
3449   bfd_vma gotidx;
3450
3451   htab = mips_elf_hash_table (info);
3452   BFD_ASSERT (htab != NULL);
3453
3454   g = mips_elf_bfd_got (ibfd, FALSE);
3455   BFD_ASSERT (g);
3456
3457   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3458   if (!lookup.tls_type && g == mips_elf_bfd_got (obfd, FALSE))
3459     return mips_elf_primary_global_got_index (obfd, info, h);
3460
3461   lookup.abfd = ibfd;
3462   lookup.symndx = -1;
3463   lookup.d.h = (struct mips_elf_link_hash_entry *) h;
3464   entry = htab_find (g->got_entries, &lookup);
3465   BFD_ASSERT (entry);
3466
3467   gotidx = entry->gotidx;
3468   BFD_ASSERT (gotidx > 0 && gotidx < htab->sgot->size);
3469
3470   if (lookup.tls_type)
3471     {
3472       bfd_vma value = MINUS_ONE;
3473
3474       if ((h->root.type == bfd_link_hash_defined
3475            || h->root.type == bfd_link_hash_defweak)
3476           && h->root.u.def.section->output_section)
3477         value = (h->root.u.def.value
3478                  + h->root.u.def.section->output_offset
3479                  + h->root.u.def.section->output_section->vma);
3480
3481       mips_elf_initialize_tls_slots (obfd, info, entry, lookup.d.h, value);
3482     }
3483   return gotidx;
3484 }
3485
3486 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3487    entries are supposed to be placed at small offsets in the GOT, i.e.,
3488    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3489    entry could be created.  If OFFSETP is nonnull, use it to return the
3490    offset of the GOT entry from VALUE.  */
3491
3492 static bfd_vma
3493 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3494                    bfd_vma value, bfd_vma *offsetp)
3495 {
3496   bfd_vma page, got_index;
3497   struct mips_got_entry *entry;
3498
3499   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3500   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3501                                            NULL, R_MIPS_GOT_PAGE);
3502
3503   if (!entry)
3504     return MINUS_ONE;
3505
3506   got_index = entry->gotidx;
3507
3508   if (offsetp)
3509     *offsetp = value - entry->d.address;
3510
3511   return got_index;
3512 }
3513
3514 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3515    EXTERNAL is true if the relocation was originally against a global
3516    symbol that binds locally.  */
3517
3518 static bfd_vma
3519 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3520                       bfd_vma value, bfd_boolean external)
3521 {
3522   struct mips_got_entry *entry;
3523
3524   /* GOT16 relocations against local symbols are followed by a LO16
3525      relocation; those against global symbols are not.  Thus if the
3526      symbol was originally local, the GOT16 relocation should load the
3527      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3528   if (! external)
3529     value = mips_elf_high (value) << 16;
3530
3531   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3532      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3533      same in all cases.  */
3534   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3535                                            NULL, R_MIPS_GOT16);
3536   if (entry)
3537     return entry->gotidx;
3538   else
3539     return MINUS_ONE;
3540 }
3541
3542 /* Returns the offset for the entry at the INDEXth position
3543    in the GOT.  */
3544
3545 static bfd_vma
3546 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3547                                 bfd *input_bfd, bfd_vma got_index)
3548 {
3549   struct mips_elf_link_hash_table *htab;
3550   asection *sgot;
3551   bfd_vma gp;
3552
3553   htab = mips_elf_hash_table (info);
3554   BFD_ASSERT (htab != NULL);
3555
3556   sgot = htab->sgot;
3557   gp = _bfd_get_gp_value (output_bfd)
3558     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3559
3560   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3561 }
3562
3563 /* Create and return a local GOT entry for VALUE, which was calculated
3564    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3565    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3566    instead.  */
3567
3568 static struct mips_got_entry *
3569 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3570                                  bfd *ibfd, bfd_vma value,
3571                                  unsigned long r_symndx,
3572                                  struct mips_elf_link_hash_entry *h,
3573                                  int r_type)
3574 {
3575   struct mips_got_entry lookup, *entry;
3576   void **loc;
3577   struct mips_got_info *g;
3578   struct mips_elf_link_hash_table *htab;
3579   bfd_vma gotidx;
3580
3581   htab = mips_elf_hash_table (info);
3582   BFD_ASSERT (htab != NULL);
3583
3584   g = mips_elf_bfd_got (ibfd, FALSE);
3585   if (g == NULL)
3586     {
3587       g = mips_elf_bfd_got (abfd, FALSE);
3588       BFD_ASSERT (g != NULL);
3589     }
3590
3591   /* This function shouldn't be called for symbols that live in the global
3592      area of the GOT.  */
3593   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3594
3595   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3596   if (lookup.tls_type)
3597     {
3598       lookup.abfd = ibfd;
3599       if (tls_ldm_reloc_p (r_type))
3600         {
3601           lookup.symndx = 0;
3602           lookup.d.addend = 0;
3603         }
3604       else if (h == NULL)
3605         {
3606           lookup.symndx = r_symndx;
3607           lookup.d.addend = 0;
3608         }
3609       else
3610         {
3611           lookup.symndx = -1;
3612           lookup.d.h = h;
3613         }
3614
3615       entry = (struct mips_got_entry *) htab_find (g->got_entries, &lookup);
3616       BFD_ASSERT (entry);
3617
3618       gotidx = entry->gotidx;
3619       BFD_ASSERT (gotidx > 0 && gotidx < htab->sgot->size);
3620
3621       return entry;
3622     }
3623
3624   lookup.abfd = NULL;
3625   lookup.symndx = -1;
3626   lookup.d.address = value;
3627   loc = htab_find_slot (g->got_entries, &lookup, INSERT);
3628   if (!loc)
3629     return NULL;
3630
3631   entry = (struct mips_got_entry *) *loc;
3632   if (entry)
3633     return entry;
3634
3635   if (g->assigned_gotno >= g->local_gotno)
3636     {
3637       /* We didn't allocate enough space in the GOT.  */
3638       (*_bfd_error_handler)
3639         (_("not enough GOT space for local GOT entries"));
3640       bfd_set_error (bfd_error_bad_value);
3641       return NULL;
3642     }
3643
3644   entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3645   if (!entry)
3646     return NULL;
3647
3648   lookup.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_gotno++;
3649   *entry = lookup;
3650   *loc = entry;
3651
3652   MIPS_ELF_PUT_WORD (abfd, value, htab->sgot->contents + entry->gotidx);
3653
3654   /* These GOT entries need a dynamic relocation on VxWorks.  */
3655   if (htab->is_vxworks)
3656     {
3657       Elf_Internal_Rela outrel;
3658       asection *s;
3659       bfd_byte *rloc;
3660       bfd_vma got_address;
3661
3662       s = mips_elf_rel_dyn_section (info, FALSE);
3663       got_address = (htab->sgot->output_section->vma
3664                      + htab->sgot->output_offset
3665                      + entry->gotidx);
3666
3667       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3668       outrel.r_offset = got_address;
3669       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3670       outrel.r_addend = value;
3671       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3672     }
3673
3674   return entry;
3675 }
3676
3677 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3678    The number might be exact or a worst-case estimate, depending on how
3679    much information is available to elf_backend_omit_section_dynsym at
3680    the current linking stage.  */
3681
3682 static bfd_size_type
3683 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3684 {
3685   bfd_size_type count;
3686
3687   count = 0;
3688   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
3689     {
3690       asection *p;
3691       const struct elf_backend_data *bed;
3692
3693       bed = get_elf_backend_data (output_bfd);
3694       for (p = output_bfd->sections; p ; p = p->next)
3695         if ((p->flags & SEC_EXCLUDE) == 0
3696             && (p->flags & SEC_ALLOC) != 0
3697             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3698           ++count;
3699     }
3700   return count;
3701 }
3702
3703 /* Sort the dynamic symbol table so that symbols that need GOT entries
3704    appear towards the end.  */
3705
3706 static bfd_boolean
3707 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3708 {
3709   struct mips_elf_link_hash_table *htab;
3710   struct mips_elf_hash_sort_data hsd;
3711   struct mips_got_info *g;
3712
3713   if (elf_hash_table (info)->dynsymcount == 0)
3714     return TRUE;
3715
3716   htab = mips_elf_hash_table (info);
3717   BFD_ASSERT (htab != NULL);
3718
3719   g = htab->got_info;
3720   if (g == NULL)
3721     return TRUE;
3722
3723   hsd.low = NULL;
3724   hsd.max_unref_got_dynindx
3725     = hsd.min_got_dynindx
3726     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3727   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3728   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3729                                 elf_hash_table (info)),
3730                                mips_elf_sort_hash_table_f,
3731                                &hsd);
3732
3733   /* There should have been enough room in the symbol table to
3734      accommodate both the GOT and non-GOT symbols.  */
3735   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3736   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3737               == elf_hash_table (info)->dynsymcount);
3738   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3739               == g->global_gotno);
3740
3741   /* Now we know which dynamic symbol has the lowest dynamic symbol
3742      table index in the GOT.  */
3743   htab->global_gotsym = hsd.low;
3744
3745   return TRUE;
3746 }
3747
3748 /* If H needs a GOT entry, assign it the highest available dynamic
3749    index.  Otherwise, assign it the lowest available dynamic
3750    index.  */
3751
3752 static bfd_boolean
3753 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3754 {
3755   struct mips_elf_hash_sort_data *hsd = data;
3756
3757   /* Symbols without dynamic symbol table entries aren't interesting
3758      at all.  */
3759   if (h->root.dynindx == -1)
3760     return TRUE;
3761
3762   switch (h->global_got_area)
3763     {
3764     case GGA_NONE:
3765       h->root.dynindx = hsd->max_non_got_dynindx++;
3766       break;
3767
3768     case GGA_NORMAL:
3769       h->root.dynindx = --hsd->min_got_dynindx;
3770       hsd->low = (struct elf_link_hash_entry *) h;
3771       break;
3772
3773     case GGA_RELOC_ONLY:
3774       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3775         hsd->low = (struct elf_link_hash_entry *) h;
3776       h->root.dynindx = hsd->max_unref_got_dynindx++;
3777       break;
3778     }
3779
3780   return TRUE;
3781 }
3782
3783 /* Record that input bfd ABFD requires a GOT entry like *LOOKUP
3784    (which is owned by the caller and shouldn't be added to the
3785    hash table directly).  */
3786
3787 static bfd_boolean
3788 mips_elf_record_got_entry (struct bfd_link_info *info, bfd *abfd,
3789                            struct mips_got_entry *lookup)
3790 {
3791   struct mips_elf_link_hash_table *htab;
3792   struct mips_got_entry *entry;
3793   struct mips_got_info *g;
3794   void **loc, **bfd_loc;
3795
3796   /* Make sure there's a slot for this entry in the master GOT.  */
3797   htab = mips_elf_hash_table (info);
3798   g = htab->got_info;
3799   loc = htab_find_slot (g->got_entries, lookup, INSERT);
3800   if (!loc)
3801     return FALSE;
3802
3803   /* Populate the entry if it isn't already.  */
3804   entry = (struct mips_got_entry *) *loc;
3805   if (!entry)
3806     {
3807       entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3808       if (!entry)
3809         return FALSE;
3810
3811       lookup->tls_initialized = FALSE;
3812       lookup->gotidx = -1;
3813       *entry = *lookup;
3814       *loc = entry;
3815     }
3816
3817   /* Reuse the same GOT entry for the BFD's GOT.  */
3818   g = mips_elf_bfd_got (abfd, TRUE);
3819   if (!g)
3820     return FALSE;
3821
3822   bfd_loc = htab_find_slot (g->got_entries, lookup, INSERT);
3823   if (!bfd_loc)
3824     return FALSE;
3825
3826   if (!*bfd_loc)
3827     *bfd_loc = entry;
3828   return TRUE;
3829 }
3830
3831 /* ABFD has a GOT relocation of type R_TYPE against H.  Reserve a GOT
3832    entry for it.  FOR_CALL is true if the caller is only interested in
3833    using the GOT entry for calls.  */
3834
3835 static bfd_boolean
3836 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3837                                    bfd *abfd, struct bfd_link_info *info,
3838                                    bfd_boolean for_call, int r_type)
3839 {
3840   struct mips_elf_link_hash_table *htab;
3841   struct mips_elf_link_hash_entry *hmips;
3842   struct mips_got_entry entry;
3843   unsigned char tls_type;
3844
3845   htab = mips_elf_hash_table (info);
3846   BFD_ASSERT (htab != NULL);
3847
3848   hmips = (struct mips_elf_link_hash_entry *) h;
3849   if (!for_call)
3850     hmips->got_only_for_calls = FALSE;
3851
3852   /* A global symbol in the GOT must also be in the dynamic symbol
3853      table.  */
3854   if (h->dynindx == -1)
3855     {
3856       switch (ELF_ST_VISIBILITY (h->other))
3857         {
3858         case STV_INTERNAL:
3859         case STV_HIDDEN:
3860           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3861           break;
3862         }
3863       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3864         return FALSE;
3865     }
3866
3867   tls_type = mips_elf_reloc_tls_type (r_type);
3868   if (tls_type == GOT_TLS_NONE && hmips->global_got_area > GGA_NORMAL)
3869     hmips->global_got_area = GGA_NORMAL;
3870
3871   entry.abfd = abfd;
3872   entry.symndx = -1;
3873   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3874   entry.tls_type = tls_type;
3875   return mips_elf_record_got_entry (info, abfd, &entry);
3876 }
3877
3878 /* ABFD has a GOT relocation of type R_TYPE against symbol SYMNDX + ADDEND,
3879    where SYMNDX is a local symbol.  Reserve a GOT entry for it.  */
3880
3881 static bfd_boolean
3882 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
3883                                   struct bfd_link_info *info, int r_type)
3884 {
3885   struct mips_elf_link_hash_table *htab;
3886   struct mips_got_info *g;
3887   struct mips_got_entry entry;
3888
3889   htab = mips_elf_hash_table (info);
3890   BFD_ASSERT (htab != NULL);
3891
3892   g = htab->got_info;
3893   BFD_ASSERT (g != NULL);
3894
3895   entry.abfd = abfd;
3896   entry.symndx = symndx;
3897   entry.d.addend = addend;
3898   entry.tls_type = mips_elf_reloc_tls_type (r_type);
3899   return mips_elf_record_got_entry (info, abfd, &entry);
3900 }
3901
3902 /* Record that ABFD has a page relocation against SYMNDX + ADDEND.
3903    H is the symbol's hash table entry, or null if SYMNDX is local
3904    to ABFD.  */
3905
3906 static bfd_boolean
3907 mips_elf_record_got_page_ref (struct bfd_link_info *info, bfd *abfd,
3908                               long symndx, struct elf_link_hash_entry *h,
3909                               bfd_signed_vma addend)
3910 {
3911   struct mips_elf_link_hash_table *htab;
3912   struct mips_got_info *g1, *g2;
3913   struct mips_got_page_ref lookup, *entry;
3914   void **loc, **bfd_loc;
3915
3916   htab = mips_elf_hash_table (info);
3917   BFD_ASSERT (htab != NULL);
3918
3919   g1 = htab->got_info;
3920   BFD_ASSERT (g1 != NULL);
3921
3922   if (h)
3923     {
3924       lookup.symndx = -1;
3925       lookup.u.h = (struct mips_elf_link_hash_entry *) h;
3926     }
3927   else
3928     {
3929       lookup.symndx = symndx;
3930       lookup.u.abfd = abfd;
3931     }
3932   lookup.addend = addend;
3933   loc = htab_find_slot (g1->got_page_refs, &lookup, INSERT);
3934   if (loc == NULL)
3935     return FALSE;
3936
3937   entry = (struct mips_got_page_ref *) *loc;
3938   if (!entry)
3939     {
3940       entry = bfd_alloc (abfd, sizeof (*entry));
3941       if (!entry)
3942         return FALSE;
3943
3944       *entry = lookup;
3945       *loc = entry;
3946     }
3947
3948   /* Add the same entry to the BFD's GOT.  */
3949   g2 = mips_elf_bfd_got (abfd, TRUE);
3950   if (!g2)
3951     return FALSE;
3952
3953   bfd_loc = htab_find_slot (g2->got_page_refs, &lookup, INSERT);
3954   if (!bfd_loc)
3955     return FALSE;
3956
3957   if (!*bfd_loc)
3958     *bfd_loc = entry;
3959
3960   return TRUE;
3961 }
3962
3963 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
3964
3965 static void
3966 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
3967                                        unsigned int n)
3968 {
3969   asection *s;
3970   struct mips_elf_link_hash_table *htab;
3971
3972   htab = mips_elf_hash_table (info);
3973   BFD_ASSERT (htab != NULL);
3974
3975   s = mips_elf_rel_dyn_section (info, FALSE);
3976   BFD_ASSERT (s != NULL);
3977
3978   if (htab->is_vxworks)
3979     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
3980   else
3981     {
3982       if (s->size == 0)
3983         {
3984           /* Make room for a null element.  */
3985           s->size += MIPS_ELF_REL_SIZE (abfd);
3986           ++s->reloc_count;
3987         }
3988       s->size += n * MIPS_ELF_REL_SIZE (abfd);
3989     }
3990 }
3991 \f
3992 /* A htab_traverse callback for GOT entries, with DATA pointing to a
3993    mips_elf_traverse_got_arg structure.  Count the number of GOT
3994    entries and TLS relocs.  Set DATA->value to true if we need
3995    to resolve indirect or warning symbols and then recreate the GOT.  */
3996
3997 static int
3998 mips_elf_check_recreate_got (void **entryp, void *data)
3999 {
4000   struct mips_got_entry *entry;
4001   struct mips_elf_traverse_got_arg *arg;
4002
4003   entry = (struct mips_got_entry *) *entryp;
4004   arg = (struct mips_elf_traverse_got_arg *) data;
4005   if (entry->abfd != NULL && entry->symndx == -1)
4006     {
4007       struct mips_elf_link_hash_entry *h;
4008
4009       h = entry->d.h;
4010       if (h->root.root.type == bfd_link_hash_indirect
4011           || h->root.root.type == bfd_link_hash_warning)
4012         {
4013           arg->value = TRUE;
4014           return 0;
4015         }
4016     }
4017   mips_elf_count_got_entry (arg->info, arg->g, entry);
4018   return 1;
4019 }
4020
4021 /* A htab_traverse callback for GOT entries, with DATA pointing to a
4022    mips_elf_traverse_got_arg structure.  Add all entries to DATA->g,
4023    converting entries for indirect and warning symbols into entries
4024    for the target symbol.  Set DATA->g to null on error.  */
4025
4026 static int
4027 mips_elf_recreate_got (void **entryp, void *data)
4028 {
4029   struct mips_got_entry new_entry, *entry;
4030   struct mips_elf_traverse_got_arg *arg;
4031   void **slot;
4032
4033   entry = (struct mips_got_entry *) *entryp;
4034   arg = (struct mips_elf_traverse_got_arg *) data;
4035   if (entry->abfd != NULL
4036       && entry->symndx == -1
4037       && (entry->d.h->root.root.type == bfd_link_hash_indirect
4038           || entry->d.h->root.root.type == bfd_link_hash_warning))
4039     {
4040       struct mips_elf_link_hash_entry *h;
4041
4042       new_entry = *entry;
4043       entry = &new_entry;
4044       h = entry->d.h;
4045       do
4046         {
4047           BFD_ASSERT (h->global_got_area == GGA_NONE);
4048           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
4049         }
4050       while (h->root.root.type == bfd_link_hash_indirect
4051              || h->root.root.type == bfd_link_hash_warning);
4052       entry->d.h = h;
4053     }
4054   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
4055   if (slot == NULL)
4056     {
4057       arg->g = NULL;
4058       return 0;
4059     }
4060   if (*slot == NULL)
4061     {
4062       if (entry == &new_entry)
4063         {
4064           entry = bfd_alloc (entry->abfd, sizeof (*entry));
4065           if (!entry)
4066             {
4067               arg->g = NULL;
4068               return 0;
4069             }
4070           *entry = new_entry;
4071         }
4072       *slot = entry;
4073       mips_elf_count_got_entry (arg->info, arg->g, entry);
4074     }
4075   return 1;
4076 }
4077
4078 /* Return the maximum number of GOT page entries required for RANGE.  */
4079
4080 static bfd_vma
4081 mips_elf_pages_for_range (const struct mips_got_page_range *range)
4082 {
4083   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
4084 }
4085
4086 /* Record that G requires a page entry that can reach SEC + ADDEND.  */
4087
4088 static bfd_boolean
4089 mips_elf_record_got_page_entry (struct mips_got_info *g,
4090                                 asection *sec, bfd_signed_vma addend)
4091 {
4092   struct mips_got_page_entry lookup, *entry;
4093   struct mips_got_page_range **range_ptr, *range;
4094   bfd_vma old_pages, new_pages;
4095   void **loc;
4096
4097   /* Find the mips_got_page_entry hash table entry for this section.  */
4098   lookup.sec = sec;
4099   loc = htab_find_slot (g->got_page_entries, &lookup, INSERT);
4100   if (loc == NULL)
4101     return FALSE;
4102
4103   /* Create a mips_got_page_entry if this is the first time we've
4104      seen the section.  */
4105   entry = (struct mips_got_page_entry *) *loc;
4106   if (!entry)
4107     {
4108       entry = bfd_zalloc (sec->owner, sizeof (*entry));
4109       if (!entry)
4110         return FALSE;
4111
4112       entry->sec = sec;
4113       *loc = entry;
4114     }
4115
4116   /* Skip over ranges whose maximum extent cannot share a page entry
4117      with ADDEND.  */
4118   range_ptr = &entry->ranges;
4119   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
4120     range_ptr = &(*range_ptr)->next;
4121
4122   /* If we scanned to the end of the list, or found a range whose
4123      minimum extent cannot share a page entry with ADDEND, create
4124      a new singleton range.  */
4125   range = *range_ptr;
4126   if (!range || addend < range->min_addend - 0xffff)
4127     {
4128       range = bfd_zalloc (sec->owner, sizeof (*range));
4129       if (!range)
4130         return FALSE;
4131
4132       range->next = *range_ptr;
4133       range->min_addend = addend;
4134       range->max_addend = addend;
4135
4136       *range_ptr = range;
4137       entry->num_pages++;
4138       g->page_gotno++;
4139       return TRUE;
4140     }
4141
4142   /* Remember how many pages the old range contributed.  */
4143   old_pages = mips_elf_pages_for_range (range);
4144
4145   /* Update the ranges.  */
4146   if (addend < range->min_addend)
4147     range->min_addend = addend;
4148   else if (addend > range->max_addend)
4149     {
4150       if (range->next && addend >= range->next->min_addend - 0xffff)
4151         {
4152           old_pages += mips_elf_pages_for_range (range->next);
4153           range->max_addend = range->next->max_addend;
4154           range->next = range->next->next;
4155         }
4156       else
4157         range->max_addend = addend;
4158     }
4159
4160   /* Record any change in the total estimate.  */
4161   new_pages = mips_elf_pages_for_range (range);
4162   if (old_pages != new_pages)
4163     {
4164       entry->num_pages += new_pages - old_pages;
4165       g->page_gotno += new_pages - old_pages;
4166     }
4167
4168   return TRUE;
4169 }
4170
4171 /* A htab_traverse callback for which *REFP points to a mips_got_page_ref
4172    and for which DATA points to a mips_elf_traverse_got_arg.  Work out
4173    whether the page reference described by *REFP needs a GOT page entry,
4174    and record that entry in DATA->g if so.  Set DATA->g to null on failure.  */
4175
4176 static bfd_boolean
4177 mips_elf_resolve_got_page_ref (void **refp, void *data)
4178 {
4179   struct mips_got_page_ref *ref;
4180   struct mips_elf_traverse_got_arg *arg;
4181   struct mips_elf_link_hash_table *htab;
4182   asection *sec;
4183   bfd_vma addend;
4184
4185   ref = (struct mips_got_page_ref *) *refp;
4186   arg = (struct mips_elf_traverse_got_arg *) data;
4187   htab = mips_elf_hash_table (arg->info);
4188
4189   if (ref->symndx < 0)
4190     {
4191       struct mips_elf_link_hash_entry *h;
4192
4193       /* Global GOT_PAGEs decay to GOT_DISP and so don't need page entries.  */
4194       h = ref->u.h;
4195       if (!SYMBOL_REFERENCES_LOCAL (arg->info, &h->root))
4196         return 1;
4197
4198       /* Ignore undefined symbols; we'll issue an error later if
4199          appropriate.  */
4200       if (!((h->root.root.type == bfd_link_hash_defined
4201              || h->root.root.type == bfd_link_hash_defweak)
4202             && h->root.root.u.def.section))
4203         return 1;
4204
4205       sec = h->root.root.u.def.section;
4206       addend = h->root.root.u.def.value + ref->addend;
4207     }
4208   else
4209     {
4210       Elf_Internal_Sym *isym;
4211
4212       /* Read in the symbol.  */
4213       isym = bfd_sym_from_r_symndx (&htab->sym_cache, ref->u.abfd,
4214                                     ref->symndx);
4215       if (isym == NULL)
4216         {
4217           arg->g = NULL;
4218           return 0;
4219         }
4220
4221       /* Get the associated input section.  */
4222       sec = bfd_section_from_elf_index (ref->u.abfd, isym->st_shndx);
4223       if (sec == NULL)
4224         {
4225           arg->g = NULL;
4226           return 0;
4227         }
4228
4229       /* If this is a mergable section, work out the section and offset
4230          of the merged data.  For section symbols, the addend specifies
4231          of the offset _of_ the first byte in the data, otherwise it
4232          specifies the offset _from_ the first byte.  */
4233       if (sec->flags & SEC_MERGE)
4234         {
4235           void *secinfo;
4236
4237           secinfo = elf_section_data (sec)->sec_info;
4238           if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
4239             addend = _bfd_merged_section_offset (ref->u.abfd, &sec, secinfo,
4240                                                  isym->st_value + ref->addend);
4241           else
4242             addend = _bfd_merged_section_offset (ref->u.abfd, &sec, secinfo,
4243                                                  isym->st_value) + ref->addend;
4244         }
4245       else
4246         addend = isym->st_value + ref->addend;
4247     }
4248   if (!mips_elf_record_got_page_entry (arg->g, sec, addend))
4249     {
4250       arg->g = NULL;
4251       return 0;
4252     }
4253   return 1;
4254 }
4255
4256 /* If any entries in G->got_entries are for indirect or warning symbols,
4257    replace them with entries for the target symbol.  Convert g->got_page_refs
4258    into got_page_entry structures and estimate the number of page entries
4259    that they require.  */
4260
4261 static bfd_boolean
4262 mips_elf_resolve_final_got_entries (struct bfd_link_info *info,
4263                                     struct mips_got_info *g)
4264 {
4265   struct mips_elf_traverse_got_arg tga;
4266   struct mips_got_info oldg;
4267
4268   oldg = *g;
4269
4270   tga.info = info;
4271   tga.g = g;
4272   tga.value = FALSE;
4273   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &tga);
4274   if (tga.value)
4275     {
4276       *g = oldg;
4277       g->got_entries = htab_create (htab_size (oldg.got_entries),
4278                                     mips_elf_got_entry_hash,
4279                                     mips_elf_got_entry_eq, NULL);
4280       if (!g->got_entries)
4281         return FALSE;
4282
4283       htab_traverse (oldg.got_entries, mips_elf_recreate_got, &tga);
4284       if (!tga.g)
4285         return FALSE;
4286
4287       htab_delete (oldg.got_entries);
4288     }
4289
4290   g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4291                                          mips_got_page_entry_eq, NULL);
4292   if (g->got_page_entries == NULL)
4293     return FALSE;
4294
4295   tga.info = info;
4296   tga.g = g;
4297   htab_traverse (g->got_page_refs, mips_elf_resolve_got_page_ref, &tga);
4298
4299   return TRUE;
4300 }
4301
4302 /* A mips_elf_link_hash_traverse callback for which DATA points to the
4303    link_info structure.  Decide whether the hash entry needs an entry in
4304    the global part of the primary GOT, setting global_got_area accordingly.
4305    Count the number of global symbols that are in the primary GOT only
4306    because they have relocations against them (reloc_only_gotno).  */
4307
4308 static int
4309 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
4310 {
4311   struct bfd_link_info *info;
4312   struct mips_elf_link_hash_table *htab;
4313   struct mips_got_info *g;
4314
4315   info = (struct bfd_link_info *) data;
4316   htab = mips_elf_hash_table (info);
4317   g = htab->got_info;
4318   if (h->global_got_area != GGA_NONE)
4319     {
4320       /* Make a final decision about whether the symbol belongs in the
4321          local or global GOT.  Symbols that bind locally can (and in the
4322          case of forced-local symbols, must) live in the local GOT.
4323          Those that are aren't in the dynamic symbol table must also
4324          live in the local GOT.
4325
4326          Note that the former condition does not always imply the
4327          latter: symbols do not bind locally if they are completely
4328          undefined.  We'll report undefined symbols later if appropriate.  */
4329       if (h->root.dynindx == -1
4330           || (h->got_only_for_calls
4331               ? SYMBOL_CALLS_LOCAL (info, &h->root)
4332               : SYMBOL_REFERENCES_LOCAL (info, &h->root)))
4333         /* The symbol belongs in the local GOT.  We no longer need this
4334            entry if it was only used for relocations; those relocations
4335            will be against the null or section symbol instead of H.  */
4336         h->global_got_area = GGA_NONE;
4337       else if (htab->is_vxworks
4338                && h->got_only_for_calls
4339                && h->root.plt.plist->mips_offset != MINUS_ONE)
4340         /* On VxWorks, calls can refer directly to the .got.plt entry;
4341            they don't need entries in the regular GOT.  .got.plt entries
4342            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4343         h->global_got_area = GGA_NONE;
4344       else if (h->global_got_area == GGA_RELOC_ONLY)
4345         {
4346           g->reloc_only_gotno++;
4347           g->global_gotno++;
4348         }
4349     }
4350   return 1;
4351 }
4352 \f
4353 /* A htab_traverse callback for GOT entries.  Add each one to the GOT
4354    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4355
4356 static int
4357 mips_elf_add_got_entry (void **entryp, void *data)
4358 {
4359   struct mips_got_entry *entry;
4360   struct mips_elf_traverse_got_arg *arg;
4361   void **slot;
4362
4363   entry = (struct mips_got_entry *) *entryp;
4364   arg = (struct mips_elf_traverse_got_arg *) data;
4365   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
4366   if (!slot)
4367     {
4368       arg->g = NULL;
4369       return 0;
4370     }
4371   if (!*slot)
4372     {
4373       *slot = entry;
4374       mips_elf_count_got_entry (arg->info, arg->g, entry);
4375     }
4376   return 1;
4377 }
4378
4379 /* A htab_traverse callback for GOT page entries.  Add each one to the GOT
4380    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4381
4382 static int
4383 mips_elf_add_got_page_entry (void **entryp, void *data)
4384 {
4385   struct mips_got_page_entry *entry;
4386   struct mips_elf_traverse_got_arg *arg;
4387   void **slot;
4388
4389   entry = (struct mips_got_page_entry *) *entryp;
4390   arg = (struct mips_elf_traverse_got_arg *) data;
4391   slot = htab_find_slot (arg->g->got_page_entries, entry, INSERT);
4392   if (!slot)
4393     {
4394       arg->g = NULL;
4395       return 0;
4396     }
4397   if (!*slot)
4398     {
4399       *slot = entry;
4400       arg->g->page_gotno += entry->num_pages;
4401     }
4402   return 1;
4403 }
4404
4405 /* Consider merging FROM, which is ABFD's GOT, into TO.  Return -1 if
4406    this would lead to overflow, 1 if they were merged successfully,
4407    and 0 if a merge failed due to lack of memory.  (These values are chosen
4408    so that nonnegative return values can be returned by a htab_traverse
4409    callback.)  */
4410
4411 static int
4412 mips_elf_merge_got_with (bfd *abfd, struct mips_got_info *from,
4413                          struct mips_got_info *to,
4414                          struct mips_elf_got_per_bfd_arg *arg)
4415 {
4416   struct mips_elf_traverse_got_arg tga;
4417   unsigned int estimate;
4418
4419   /* Work out how many page entries we would need for the combined GOT.  */
4420   estimate = arg->max_pages;
4421   if (estimate >= from->page_gotno + to->page_gotno)
4422     estimate = from->page_gotno + to->page_gotno;
4423
4424   /* And conservatively estimate how many local and TLS entries
4425      would be needed.  */
4426   estimate += from->local_gotno + to->local_gotno;
4427   estimate += from->tls_gotno + to->tls_gotno;
4428
4429   /* If we're merging with the primary got, any TLS relocations will
4430      come after the full set of global entries.  Otherwise estimate those
4431      conservatively as well.  */
4432   if (to == arg->primary && from->tls_gotno + to->tls_gotno)
4433     estimate += arg->global_count;
4434   else
4435     estimate += from->global_gotno + to->global_gotno;
4436
4437   /* Bail out if the combined GOT might be too big.  */
4438   if (estimate > arg->max_count)
4439     return -1;
4440
4441   /* Transfer the bfd's got information from FROM to TO.  */
4442   tga.info = arg->info;
4443   tga.g = to;
4444   htab_traverse (from->got_entries, mips_elf_add_got_entry, &tga);
4445   if (!tga.g)
4446     return 0;
4447
4448   htab_traverse (from->got_page_entries, mips_elf_add_got_page_entry, &tga);
4449   if (!tga.g)
4450     return 0;
4451
4452   mips_elf_replace_bfd_got (abfd, to);
4453   return 1;
4454 }
4455
4456 /* Attempt to merge GOT G, which belongs to ABFD.  Try to use as much
4457    as possible of the primary got, since it doesn't require explicit
4458    dynamic relocations, but don't use bfds that would reference global
4459    symbols out of the addressable range.  Failing the primary got,
4460    attempt to merge with the current got, or finish the current got
4461    and then make make the new got current.  */
4462
4463 static bfd_boolean
4464 mips_elf_merge_got (bfd *abfd, struct mips_got_info *g,
4465                     struct mips_elf_got_per_bfd_arg *arg)
4466 {
4467   unsigned int estimate;
4468   int result;
4469
4470   if (!mips_elf_resolve_final_got_entries (arg->info, g))
4471     return FALSE;
4472
4473   /* Work out the number of page, local and TLS entries.  */
4474   estimate = arg->max_pages;
4475   if (estimate > g->page_gotno)
4476     estimate = g->page_gotno;
4477   estimate += g->local_gotno + g->tls_gotno;
4478
4479   /* We place TLS GOT entries after both locals and globals.  The globals
4480      for the primary GOT may overflow the normal GOT size limit, so be
4481      sure not to merge a GOT which requires TLS with the primary GOT in that
4482      case.  This doesn't affect non-primary GOTs.  */
4483   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4484
4485   if (estimate <= arg->max_count)
4486     {
4487       /* If we don't have a primary GOT, use it as
4488          a starting point for the primary GOT.  */
4489       if (!arg->primary)
4490         {
4491           arg->primary = g;
4492           return TRUE;
4493         }
4494
4495       /* Try merging with the primary GOT.  */
4496       result = mips_elf_merge_got_with (abfd, g, arg->primary, arg);
4497       if (result >= 0)
4498         return result;
4499     }
4500
4501   /* If we can merge with the last-created got, do it.  */
4502   if (arg->current)
4503     {
4504       result = mips_elf_merge_got_with (abfd, g, arg->current, arg);
4505       if (result >= 0)
4506         return result;
4507     }
4508
4509   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4510      fits; if it turns out that it doesn't, we'll get relocation
4511      overflows anyway.  */
4512   g->next = arg->current;
4513   arg->current = g;
4514
4515   return TRUE;
4516 }
4517
4518 /* ENTRYP is a hash table entry for a mips_got_entry.  Set its gotidx
4519    to GOTIDX, duplicating the entry if it has already been assigned
4520    an index in a different GOT.  */
4521
4522 static bfd_boolean
4523 mips_elf_set_gotidx (void **entryp, long gotidx)
4524 {
4525   struct mips_got_entry *entry;
4526
4527   entry = (struct mips_got_entry *) *entryp;
4528   if (entry->gotidx > 0)
4529     {
4530       struct mips_got_entry *new_entry;
4531
4532       new_entry = bfd_alloc (entry->abfd, sizeof (*entry));
4533       if (!new_entry)
4534         return FALSE;
4535
4536       *new_entry = *entry;
4537       *entryp = new_entry;
4538       entry = new_entry;
4539     }
4540   entry->gotidx = gotidx;
4541   return TRUE;
4542 }
4543
4544 /* Set the TLS GOT index for the GOT entry in ENTRYP.  DATA points to a
4545    mips_elf_traverse_got_arg in which DATA->value is the size of one
4546    GOT entry.  Set DATA->g to null on failure.  */
4547
4548 static int
4549 mips_elf_initialize_tls_index (void **entryp, void *data)
4550 {
4551   struct mips_got_entry *entry;
4552   struct mips_elf_traverse_got_arg *arg;
4553
4554   /* We're only interested in TLS symbols.  */
4555   entry = (struct mips_got_entry *) *entryp;
4556   if (entry->tls_type == GOT_TLS_NONE)
4557     return 1;
4558
4559   arg = (struct mips_elf_traverse_got_arg *) data;
4560   if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->tls_assigned_gotno))
4561     {
4562       arg->g = NULL;
4563       return 0;
4564     }
4565
4566   /* Account for the entries we've just allocated.  */
4567   arg->g->tls_assigned_gotno += mips_tls_got_entries (entry->tls_type);
4568   return 1;
4569 }
4570
4571 /* A htab_traverse callback for GOT entries, where DATA points to a
4572    mips_elf_traverse_got_arg.  Set the global_got_area of each global
4573    symbol to DATA->value.  */
4574
4575 static int
4576 mips_elf_set_global_got_area (void **entryp, void *data)
4577 {
4578   struct mips_got_entry *entry;
4579   struct mips_elf_traverse_got_arg *arg;
4580
4581   entry = (struct mips_got_entry *) *entryp;
4582   arg = (struct mips_elf_traverse_got_arg *) data;
4583   if (entry->abfd != NULL
4584       && entry->symndx == -1
4585       && entry->d.h->global_got_area != GGA_NONE)
4586     entry->d.h->global_got_area = arg->value;
4587   return 1;
4588 }
4589
4590 /* A htab_traverse callback for secondary GOT entries, where DATA points
4591    to a mips_elf_traverse_got_arg.  Assign GOT indices to global entries
4592    and record the number of relocations they require.  DATA->value is
4593    the size of one GOT entry.  Set DATA->g to null on failure.  */
4594
4595 static int
4596 mips_elf_set_global_gotidx (void **entryp, void *data)
4597 {
4598   struct mips_got_entry *entry;
4599   struct mips_elf_traverse_got_arg *arg;
4600
4601   entry = (struct mips_got_entry *) *entryp;
4602   arg = (struct mips_elf_traverse_got_arg *) data;
4603   if (entry->abfd != NULL
4604       && entry->symndx == -1
4605       && entry->d.h->global_got_area != GGA_NONE)
4606     {
4607       if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->assigned_gotno))
4608         {
4609           arg->g = NULL;
4610           return 0;
4611         }
4612       arg->g->assigned_gotno += 1;
4613
4614       if (arg->info->shared
4615           || (elf_hash_table (arg->info)->dynamic_sections_created
4616               && entry->d.h->root.def_dynamic
4617               && !entry->d.h->root.def_regular))
4618         arg->g->relocs += 1;
4619     }
4620
4621   return 1;
4622 }
4623
4624 /* A htab_traverse callback for GOT entries for which DATA is the
4625    bfd_link_info.  Forbid any global symbols from having traditional
4626    lazy-binding stubs.  */
4627
4628 static int
4629 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4630 {
4631   struct bfd_link_info *info;
4632   struct mips_elf_link_hash_table *htab;
4633   struct mips_got_entry *entry;
4634
4635   entry = (struct mips_got_entry *) *entryp;
4636   info = (struct bfd_link_info *) data;
4637   htab = mips_elf_hash_table (info);
4638   BFD_ASSERT (htab != NULL);
4639
4640   if (entry->abfd != NULL
4641       && entry->symndx == -1
4642       && entry->d.h->needs_lazy_stub)
4643     {
4644       entry->d.h->needs_lazy_stub = FALSE;
4645       htab->lazy_stub_count--;
4646     }
4647
4648   return 1;
4649 }
4650
4651 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4652    the primary GOT.  */
4653 static bfd_vma
4654 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4655 {
4656   if (!g->next)
4657     return 0;
4658
4659   g = mips_elf_bfd_got (ibfd, FALSE);
4660   if (! g)
4661     return 0;
4662
4663   BFD_ASSERT (g->next);
4664
4665   g = g->next;
4666
4667   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4668     * MIPS_ELF_GOT_SIZE (abfd);
4669 }
4670
4671 /* Turn a single GOT that is too big for 16-bit addressing into
4672    a sequence of GOTs, each one 16-bit addressable.  */
4673
4674 static bfd_boolean
4675 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4676                     asection *got, bfd_size_type pages)
4677 {
4678   struct mips_elf_link_hash_table *htab;
4679   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4680   struct mips_elf_traverse_got_arg tga;
4681   struct mips_got_info *g, *gg;
4682   unsigned int assign, needed_relocs;
4683   bfd *dynobj, *ibfd;
4684
4685   dynobj = elf_hash_table (info)->dynobj;
4686   htab = mips_elf_hash_table (info);
4687   BFD_ASSERT (htab != NULL);
4688
4689   g = htab->got_info;
4690
4691   got_per_bfd_arg.obfd = abfd;
4692   got_per_bfd_arg.info = info;
4693   got_per_bfd_arg.current = NULL;
4694   got_per_bfd_arg.primary = NULL;
4695   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4696                                 / MIPS_ELF_GOT_SIZE (abfd))
4697                                - htab->reserved_gotno);
4698   got_per_bfd_arg.max_pages = pages;
4699   /* The number of globals that will be included in the primary GOT.
4700      See the calls to mips_elf_set_global_got_area below for more
4701      information.  */
4702   got_per_bfd_arg.global_count = g->global_gotno;
4703
4704   /* Try to merge the GOTs of input bfds together, as long as they
4705      don't seem to exceed the maximum GOT size, choosing one of them
4706      to be the primary GOT.  */
4707   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
4708     {
4709       gg = mips_elf_bfd_got (ibfd, FALSE);
4710       if (gg && !mips_elf_merge_got (ibfd, gg, &got_per_bfd_arg))
4711         return FALSE;
4712     }
4713
4714   /* If we do not find any suitable primary GOT, create an empty one.  */
4715   if (got_per_bfd_arg.primary == NULL)
4716     g->next = mips_elf_create_got_info (abfd);
4717   else
4718     g->next = got_per_bfd_arg.primary;
4719   g->next->next = got_per_bfd_arg.current;
4720
4721   /* GG is now the master GOT, and G is the primary GOT.  */
4722   gg = g;
4723   g = g->next;
4724
4725   /* Map the output bfd to the primary got.  That's what we're going
4726      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4727      didn't mark in check_relocs, and we want a quick way to find it.
4728      We can't just use gg->next because we're going to reverse the
4729      list.  */
4730   mips_elf_replace_bfd_got (abfd, g);
4731
4732   /* Every symbol that is referenced in a dynamic relocation must be
4733      present in the primary GOT, so arrange for them to appear after
4734      those that are actually referenced.  */
4735   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4736   g->global_gotno = gg->global_gotno;
4737
4738   tga.info = info;
4739   tga.value = GGA_RELOC_ONLY;
4740   htab_traverse (gg->got_entries, mips_elf_set_global_got_area, &tga);
4741   tga.value = GGA_NORMAL;
4742   htab_traverse (g->got_entries, mips_elf_set_global_got_area, &tga);
4743
4744   /* Now go through the GOTs assigning them offset ranges.
4745      [assigned_gotno, local_gotno[ will be set to the range of local
4746      entries in each GOT.  We can then compute the end of a GOT by
4747      adding local_gotno to global_gotno.  We reverse the list and make
4748      it circular since then we'll be able to quickly compute the
4749      beginning of a GOT, by computing the end of its predecessor.  To
4750      avoid special cases for the primary GOT, while still preserving
4751      assertions that are valid for both single- and multi-got links,
4752      we arrange for the main got struct to have the right number of
4753      global entries, but set its local_gotno such that the initial
4754      offset of the primary GOT is zero.  Remember that the primary GOT
4755      will become the last item in the circular linked list, so it
4756      points back to the master GOT.  */
4757   gg->local_gotno = -g->global_gotno;
4758   gg->global_gotno = g->global_gotno;
4759   gg->tls_gotno = 0;
4760   assign = 0;
4761   gg->next = gg;
4762
4763   do
4764     {
4765       struct mips_got_info *gn;
4766
4767       assign += htab->reserved_gotno;
4768       g->assigned_gotno = assign;
4769       g->local_gotno += assign;
4770       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4771       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4772
4773       /* Take g out of the direct list, and push it onto the reversed
4774          list that gg points to.  g->next is guaranteed to be nonnull after
4775          this operation, as required by mips_elf_initialize_tls_index. */
4776       gn = g->next;
4777       g->next = gg->next;
4778       gg->next = g;
4779
4780       /* Set up any TLS entries.  We always place the TLS entries after
4781          all non-TLS entries.  */
4782       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4783       tga.g = g;
4784       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4785       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
4786       if (!tga.g)
4787         return FALSE;
4788       BFD_ASSERT (g->tls_assigned_gotno == assign);
4789
4790       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4791       g = gn;
4792
4793       /* Forbid global symbols in every non-primary GOT from having
4794          lazy-binding stubs.  */
4795       if (g)
4796         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4797     }
4798   while (g);
4799
4800   got->size = assign * MIPS_ELF_GOT_SIZE (abfd);
4801
4802   needed_relocs = 0;
4803   for (g = gg->next; g && g->next != gg; g = g->next)
4804     {
4805       unsigned int save_assign;
4806
4807       /* Assign offsets to global GOT entries and count how many
4808          relocations they need.  */
4809       save_assign = g->assigned_gotno;
4810       g->assigned_gotno = g->local_gotno;
4811       tga.info = info;
4812       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4813       tga.g = g;
4814       htab_traverse (g->got_entries, mips_elf_set_global_gotidx, &tga);
4815       if (!tga.g)
4816         return FALSE;
4817       BFD_ASSERT (g->assigned_gotno == g->local_gotno + g->global_gotno);
4818       g->assigned_gotno = save_assign;
4819
4820       if (info->shared)
4821         {
4822           g->relocs += g->local_gotno - g->assigned_gotno;
4823           BFD_ASSERT (g->assigned_gotno == g->next->local_gotno
4824                       + g->next->global_gotno
4825                       + g->next->tls_gotno
4826                       + htab->reserved_gotno);
4827         }
4828       needed_relocs += g->relocs;
4829     }
4830   needed_relocs += g->relocs;
4831
4832   if (needed_relocs)
4833     mips_elf_allocate_dynamic_relocations (dynobj, info,
4834                                            needed_relocs);
4835
4836   return TRUE;
4837 }
4838
4839 \f
4840 /* Returns the first relocation of type r_type found, beginning with
4841    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4842
4843 static const Elf_Internal_Rela *
4844 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4845                           const Elf_Internal_Rela *relocation,
4846                           const Elf_Internal_Rela *relend)
4847 {
4848   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4849
4850   while (relocation < relend)
4851     {
4852       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4853           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4854         return relocation;
4855
4856       ++relocation;
4857     }
4858
4859   /* We didn't find it.  */
4860   return NULL;
4861 }
4862
4863 /* Return whether an input relocation is against a local symbol.  */
4864
4865 static bfd_boolean
4866 mips_elf_local_relocation_p (bfd *input_bfd,
4867                              const Elf_Internal_Rela *relocation,
4868                              asection **local_sections)
4869 {
4870   unsigned long r_symndx;
4871   Elf_Internal_Shdr *symtab_hdr;
4872   size_t extsymoff;
4873
4874   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4875   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4876   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
4877
4878   if (r_symndx < extsymoff)
4879     return TRUE;
4880   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
4881     return TRUE;
4882
4883   return FALSE;
4884 }
4885 \f
4886 /* Sign-extend VALUE, which has the indicated number of BITS.  */
4887
4888 bfd_vma
4889 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
4890 {
4891   if (value & ((bfd_vma) 1 << (bits - 1)))
4892     /* VALUE is negative.  */
4893     value |= ((bfd_vma) - 1) << bits;
4894
4895   return value;
4896 }
4897
4898 /* Return non-zero if the indicated VALUE has overflowed the maximum
4899    range expressible by a signed number with the indicated number of
4900    BITS.  */
4901
4902 static bfd_boolean
4903 mips_elf_overflow_p (bfd_vma value, int bits)
4904 {
4905   bfd_signed_vma svalue = (bfd_signed_vma) value;
4906
4907   if (svalue > (1 << (bits - 1)) - 1)
4908     /* The value is too big.  */
4909     return TRUE;
4910   else if (svalue < -(1 << (bits - 1)))
4911     /* The value is too small.  */
4912     return TRUE;
4913
4914   /* All is well.  */
4915   return FALSE;
4916 }
4917
4918 /* Calculate the %high function.  */
4919
4920 static bfd_vma
4921 mips_elf_high (bfd_vma value)
4922 {
4923   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
4924 }
4925
4926 /* Calculate the %higher function.  */
4927
4928 static bfd_vma
4929 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
4930 {
4931 #ifdef BFD64
4932   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
4933 #else
4934   abort ();
4935   return MINUS_ONE;
4936 #endif
4937 }
4938
4939 /* Calculate the %highest function.  */
4940
4941 static bfd_vma
4942 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
4943 {
4944 #ifdef BFD64
4945   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
4946 #else
4947   abort ();
4948   return MINUS_ONE;
4949 #endif
4950 }
4951 \f
4952 /* Create the .compact_rel section.  */
4953
4954 static bfd_boolean
4955 mips_elf_create_compact_rel_section
4956   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
4957 {
4958   flagword flags;
4959   register asection *s;
4960
4961   if (bfd_get_linker_section (abfd, ".compact_rel") == NULL)
4962     {
4963       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
4964                | SEC_READONLY);
4965
4966       s = bfd_make_section_anyway_with_flags (abfd, ".compact_rel", flags);
4967       if (s == NULL
4968           || ! bfd_set_section_alignment (abfd, s,
4969                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
4970         return FALSE;
4971
4972       s->size = sizeof (Elf32_External_compact_rel);
4973     }
4974
4975   return TRUE;
4976 }
4977
4978 /* Create the .got section to hold the global offset table.  */
4979
4980 static bfd_boolean
4981 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
4982 {
4983   flagword flags;
4984   register asection *s;
4985   struct elf_link_hash_entry *h;
4986   struct bfd_link_hash_entry *bh;
4987   struct mips_elf_link_hash_table *htab;
4988
4989   htab = mips_elf_hash_table (info);
4990   BFD_ASSERT (htab != NULL);
4991
4992   /* This function may be called more than once.  */
4993   if (htab->sgot)
4994     return TRUE;
4995
4996   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
4997            | SEC_LINKER_CREATED);
4998
4999   /* We have to use an alignment of 2**4 here because this is hardcoded
5000      in the function stub generation and in the linker script.  */
5001   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
5002   if (s == NULL
5003       || ! bfd_set_section_alignment (abfd, s, 4))
5004     return FALSE;
5005   htab->sgot = s;
5006
5007   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
5008      linker script because we don't want to define the symbol if we
5009      are not creating a global offset table.  */
5010   bh = NULL;
5011   if (! (_bfd_generic_link_add_one_symbol
5012          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
5013           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
5014     return FALSE;
5015
5016   h = (struct elf_link_hash_entry *) bh;
5017   h->non_elf = 0;
5018   h->def_regular = 1;
5019   h->type = STT_OBJECT;
5020   elf_hash_table (info)->hgot = h;
5021
5022   if (info->shared
5023       && ! bfd_elf_link_record_dynamic_symbol (info, h))
5024     return FALSE;
5025
5026   htab->got_info = mips_elf_create_got_info (abfd);
5027   mips_elf_section_data (s)->elf.this_hdr.sh_flags
5028     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
5029
5030   /* We also need a .got.plt section when generating PLTs.  */
5031   s = bfd_make_section_anyway_with_flags (abfd, ".got.plt",
5032                                           SEC_ALLOC | SEC_LOAD
5033                                           | SEC_HAS_CONTENTS
5034                                           | SEC_IN_MEMORY
5035                                           | SEC_LINKER_CREATED);
5036   if (s == NULL)
5037     return FALSE;
5038   htab->sgotplt = s;
5039
5040   return TRUE;
5041 }
5042 \f
5043 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
5044    __GOTT_INDEX__ symbols.  These symbols are only special for
5045    shared objects; they are not used in executables.  */
5046
5047 static bfd_boolean
5048 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
5049 {
5050   return (mips_elf_hash_table (info)->is_vxworks
5051           && info->shared
5052           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
5053               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
5054 }
5055
5056 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
5057    require an la25 stub.  See also mips_elf_local_pic_function_p,
5058    which determines whether the destination function ever requires a
5059    stub.  */
5060
5061 static bfd_boolean
5062 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type,
5063                                      bfd_boolean target_is_16_bit_code_p)
5064 {
5065   /* We specifically ignore branches and jumps from EF_PIC objects,
5066      where the onus is on the compiler or programmer to perform any
5067      necessary initialization of $25.  Sometimes such initialization
5068      is unnecessary; for example, -mno-shared functions do not use
5069      the incoming value of $25, and may therefore be called directly.  */
5070   if (PIC_OBJECT_P (input_bfd))
5071     return FALSE;
5072
5073   switch (r_type)
5074     {
5075     case R_MIPS_26:
5076     case R_MIPS_PC16:
5077     case R_MICROMIPS_26_S1:
5078     case R_MICROMIPS_PC7_S1:
5079     case R_MICROMIPS_PC10_S1:
5080     case R_MICROMIPS_PC16_S1:
5081     case R_MICROMIPS_PC23_S2:
5082       return TRUE;
5083
5084     case R_MIPS16_26:
5085       return !target_is_16_bit_code_p;
5086
5087     default:
5088       return FALSE;
5089     }
5090 }
5091 \f
5092 /* Calculate the value produced by the RELOCATION (which comes from
5093    the INPUT_BFD).  The ADDEND is the addend to use for this
5094    RELOCATION; RELOCATION->R_ADDEND is ignored.
5095
5096    The result of the relocation calculation is stored in VALUEP.
5097    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
5098    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5099
5100    This function returns bfd_reloc_continue if the caller need take no
5101    further action regarding this relocation, bfd_reloc_notsupported if
5102    something goes dramatically wrong, bfd_reloc_overflow if an
5103    overflow occurs, and bfd_reloc_ok to indicate success.  */
5104
5105 static bfd_reloc_status_type
5106 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
5107                                asection *input_section,
5108                                struct bfd_link_info *info,
5109                                const Elf_Internal_Rela *relocation,
5110                                bfd_vma addend, reloc_howto_type *howto,
5111                                Elf_Internal_Sym *local_syms,
5112                                asection **local_sections, bfd_vma *valuep,
5113                                const char **namep,
5114                                bfd_boolean *cross_mode_jump_p,
5115                                bfd_boolean save_addend)
5116 {
5117   /* The eventual value we will return.  */
5118   bfd_vma value;
5119   /* The address of the symbol against which the relocation is
5120      occurring.  */
5121   bfd_vma symbol = 0;
5122   /* The final GP value to be used for the relocatable, executable, or
5123      shared object file being produced.  */
5124   bfd_vma gp;
5125   /* The place (section offset or address) of the storage unit being
5126      relocated.  */
5127   bfd_vma p;
5128   /* The value of GP used to create the relocatable object.  */
5129   bfd_vma gp0;
5130   /* The offset into the global offset table at which the address of
5131      the relocation entry symbol, adjusted by the addend, resides
5132      during execution.  */
5133   bfd_vma g = MINUS_ONE;
5134   /* The section in which the symbol referenced by the relocation is
5135      located.  */
5136   asection *sec = NULL;
5137   struct mips_elf_link_hash_entry *h = NULL;
5138   /* TRUE if the symbol referred to by this relocation is a local
5139      symbol.  */
5140   bfd_boolean local_p, was_local_p;
5141   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
5142   bfd_boolean gp_disp_p = FALSE;
5143   /* TRUE if the symbol referred to by this relocation is
5144      "__gnu_local_gp".  */
5145   bfd_boolean gnu_local_gp_p = FALSE;
5146   Elf_Internal_Shdr *symtab_hdr;
5147   size_t extsymoff;
5148   unsigned long r_symndx;
5149   int r_type;
5150   /* TRUE if overflow occurred during the calculation of the
5151      relocation value.  */
5152   bfd_boolean overflowed_p;
5153   /* TRUE if this relocation refers to a MIPS16 function.  */
5154   bfd_boolean target_is_16_bit_code_p = FALSE;
5155   bfd_boolean target_is_micromips_code_p = FALSE;
5156   struct mips_elf_link_hash_table *htab;
5157   bfd *dynobj;
5158
5159   dynobj = elf_hash_table (info)->dynobj;
5160   htab = mips_elf_hash_table (info);
5161   BFD_ASSERT (htab != NULL);
5162
5163   /* Parse the relocation.  */
5164   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
5165   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5166   p = (input_section->output_section->vma
5167        + input_section->output_offset
5168        + relocation->r_offset);
5169
5170   /* Assume that there will be no overflow.  */
5171   overflowed_p = FALSE;
5172
5173   /* Figure out whether or not the symbol is local, and get the offset
5174      used in the array of hash table entries.  */
5175   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
5176   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
5177                                          local_sections);
5178   was_local_p = local_p;
5179   if (! elf_bad_symtab (input_bfd))
5180     extsymoff = symtab_hdr->sh_info;
5181   else
5182     {
5183       /* The symbol table does not follow the rule that local symbols
5184          must come before globals.  */
5185       extsymoff = 0;
5186     }
5187
5188   /* Figure out the value of the symbol.  */
5189   if (local_p)
5190     {
5191       Elf_Internal_Sym *sym;
5192
5193       sym = local_syms + r_symndx;
5194       sec = local_sections[r_symndx];
5195
5196       symbol = sec->output_section->vma + sec->output_offset;
5197       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION
5198           || (sec->flags & SEC_MERGE))
5199         symbol += sym->st_value;
5200       if ((sec->flags & SEC_MERGE)
5201           && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
5202         {
5203           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
5204           addend -= symbol;
5205           addend += sec->output_section->vma + sec->output_offset;
5206         }
5207
5208       /* MIPS16/microMIPS text labels should be treated as odd.  */
5209       if (ELF_ST_IS_COMPRESSED (sym->st_other))
5210         ++symbol;
5211
5212       /* Record the name of this symbol, for our caller.  */
5213       *namep = bfd_elf_string_from_elf_section (input_bfd,
5214                                                 symtab_hdr->sh_link,
5215                                                 sym->st_name);
5216       if (*namep == '\0')
5217         *namep = bfd_section_name (input_bfd, sec);
5218
5219       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
5220       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
5221     }
5222   else
5223     {
5224       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
5225
5226       /* For global symbols we look up the symbol in the hash-table.  */
5227       h = ((struct mips_elf_link_hash_entry *)
5228            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
5229       /* Find the real hash-table entry for this symbol.  */
5230       while (h->root.root.type == bfd_link_hash_indirect
5231              || h->root.root.type == bfd_link_hash_warning)
5232         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
5233
5234       /* Record the name of this symbol, for our caller.  */
5235       *namep = h->root.root.root.string;
5236
5237       /* See if this is the special _gp_disp symbol.  Note that such a
5238          symbol must always be a global symbol.  */
5239       if (strcmp (*namep, "_gp_disp") == 0
5240           && ! NEWABI_P (input_bfd))
5241         {
5242           /* Relocations against _gp_disp are permitted only with
5243              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
5244           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
5245             return bfd_reloc_notsupported;
5246
5247           gp_disp_p = TRUE;
5248         }
5249       /* See if this is the special _gp symbol.  Note that such a
5250          symbol must always be a global symbol.  */
5251       else if (strcmp (*namep, "__gnu_local_gp") == 0)
5252         gnu_local_gp_p = TRUE;
5253
5254
5255       /* If this symbol is defined, calculate its address.  Note that
5256          _gp_disp is a magic symbol, always implicitly defined by the
5257          linker, so it's inappropriate to check to see whether or not
5258          its defined.  */
5259       else if ((h->root.root.type == bfd_link_hash_defined
5260                 || h->root.root.type == bfd_link_hash_defweak)
5261                && h->root.root.u.def.section)
5262         {
5263           sec = h->root.root.u.def.section;
5264           if (sec->output_section)
5265             symbol = (h->root.root.u.def.value
5266                       + sec->output_section->vma
5267                       + sec->output_offset);
5268           else
5269             symbol = h->root.root.u.def.value;
5270         }
5271       else if (h->root.root.type == bfd_link_hash_undefweak)
5272         /* We allow relocations against undefined weak symbols, giving
5273            it the value zero, so that you can undefined weak functions
5274            and check to see if they exist by looking at their
5275            addresses.  */
5276         symbol = 0;
5277       else if (info->unresolved_syms_in_objects == RM_IGNORE
5278                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5279         symbol = 0;
5280       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
5281                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
5282         {
5283           /* If this is a dynamic link, we should have created a
5284              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
5285              in in _bfd_mips_elf_create_dynamic_sections.
5286              Otherwise, we should define the symbol with a value of 0.
5287              FIXME: It should probably get into the symbol table
5288              somehow as well.  */
5289           BFD_ASSERT (! info->shared);
5290           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
5291           symbol = 0;
5292         }
5293       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
5294         {
5295           /* This is an optional symbol - an Irix specific extension to the
5296              ELF spec.  Ignore it for now.
5297              XXX - FIXME - there is more to the spec for OPTIONAL symbols
5298              than simply ignoring them, but we do not handle this for now.
5299              For information see the "64-bit ELF Object File Specification"
5300              which is available from here:
5301              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
5302           symbol = 0;
5303         }
5304       else if ((*info->callbacks->undefined_symbol)
5305                (info, h->root.root.root.string, input_bfd,
5306                 input_section, relocation->r_offset,
5307                 (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
5308                  || ELF_ST_VISIBILITY (h->root.other)))
5309         {
5310           return bfd_reloc_undefined;
5311         }
5312       else
5313         {
5314           return bfd_reloc_notsupported;
5315         }
5316
5317       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
5318       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (h->root.other);
5319     }
5320
5321   /* If this is a reference to a 16-bit function with a stub, we need
5322      to redirect the relocation to the stub unless:
5323
5324      (a) the relocation is for a MIPS16 JAL;
5325
5326      (b) the relocation is for a MIPS16 PIC call, and there are no
5327          non-MIPS16 uses of the GOT slot; or
5328
5329      (c) the section allows direct references to MIPS16 functions.  */
5330   if (r_type != R_MIPS16_26
5331       && !info->relocatable
5332       && ((h != NULL
5333            && h->fn_stub != NULL
5334            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5335           || (local_p
5336               && mips_elf_tdata (input_bfd)->local_stubs != NULL
5337               && mips_elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5338       && !section_allows_mips16_refs_p (input_section))
5339     {
5340       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5341          have already noticed that we were going to need the
5342          stub.  */
5343       if (local_p)
5344         {
5345           sec = mips_elf_tdata (input_bfd)->local_stubs[r_symndx];
5346           value = 0;
5347         }
5348       else
5349         {
5350           BFD_ASSERT (h->need_fn_stub);
5351           if (h->la25_stub)
5352             {
5353               /* If a LA25 header for the stub itself exists, point to the
5354                  prepended LUI/ADDIU sequence.  */
5355               sec = h->la25_stub->stub_section;
5356               value = h->la25_stub->offset;
5357             }
5358           else
5359             {
5360               sec = h->fn_stub;
5361               value = 0;
5362             }
5363         }
5364
5365       symbol = sec->output_section->vma + sec->output_offset + value;
5366       /* The target is 16-bit, but the stub isn't.  */
5367       target_is_16_bit_code_p = FALSE;
5368     }
5369   /* If this is a MIPS16 call with a stub, that is made through the PLT or
5370      to a standard MIPS function, we need to redirect the call to the stub.
5371      Note that we specifically exclude R_MIPS16_CALL16 from this behavior;
5372      indirect calls should use an indirect stub instead.  */
5373   else if (r_type == R_MIPS16_26 && !info->relocatable
5374            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5375                || (local_p
5376                    && mips_elf_tdata (input_bfd)->local_call_stubs != NULL
5377                    && mips_elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5378            && ((h != NULL && h->use_plt_entry) || !target_is_16_bit_code_p))
5379     {
5380       if (local_p)
5381         sec = mips_elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5382       else
5383         {
5384           /* If both call_stub and call_fp_stub are defined, we can figure
5385              out which one to use by checking which one appears in the input
5386              file.  */
5387           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5388             {
5389               asection *o;
5390
5391               sec = NULL;
5392               for (o = input_bfd->sections; o != NULL; o = o->next)
5393                 {
5394                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5395                     {
5396                       sec = h->call_fp_stub;
5397                       break;
5398                     }
5399                 }
5400               if (sec == NULL)
5401                 sec = h->call_stub;
5402             }
5403           else if (h->call_stub != NULL)
5404             sec = h->call_stub;
5405           else
5406             sec = h->call_fp_stub;
5407         }
5408
5409       BFD_ASSERT (sec->size > 0);
5410       symbol = sec->output_section->vma + sec->output_offset;
5411     }
5412   /* If this is a direct call to a PIC function, redirect to the
5413      non-PIC stub.  */
5414   else if (h != NULL && h->la25_stub
5415            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type,
5416                                                    target_is_16_bit_code_p))
5417     symbol = (h->la25_stub->stub_section->output_section->vma
5418               + h->la25_stub->stub_section->output_offset
5419               + h->la25_stub->offset);
5420   /* For direct MIPS16 and microMIPS calls make sure the compressed PLT
5421      entry is used if a standard PLT entry has also been made.  In this
5422      case the symbol will have been set by mips_elf_set_plt_sym_value
5423      to point to the standard PLT entry, so redirect to the compressed
5424      one.  */
5425   else if ((r_type == R_MIPS16_26 || r_type == R_MICROMIPS_26_S1)
5426            && !info->relocatable
5427            && h != NULL
5428            && h->use_plt_entry
5429            && h->root.plt.plist->comp_offset != MINUS_ONE
5430            && h->root.plt.plist->mips_offset != MINUS_ONE)
5431     {
5432       bfd_boolean micromips_p = MICROMIPS_P (abfd);
5433
5434       sec = htab->splt;
5435       symbol = (sec->output_section->vma
5436                 + sec->output_offset
5437                 + htab->plt_header_size
5438                 + htab->plt_mips_offset
5439                 + h->root.plt.plist->comp_offset
5440                 + 1);
5441
5442       target_is_16_bit_code_p = !micromips_p;
5443       target_is_micromips_code_p = micromips_p;
5444     }
5445
5446   /* Make sure MIPS16 and microMIPS are not used together.  */
5447   if ((r_type == R_MIPS16_26 && target_is_micromips_code_p)
5448       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5449    {
5450       (*_bfd_error_handler)
5451         (_("MIPS16 and microMIPS functions cannot call each other"));
5452       return bfd_reloc_notsupported;
5453    }
5454
5455   /* Calls from 16-bit code to 32-bit code and vice versa require the
5456      mode change.  However, we can ignore calls to undefined weak symbols,
5457      which should never be executed at runtime.  This exception is important
5458      because the assembly writer may have "known" that any definition of the
5459      symbol would be 16-bit code, and that direct jumps were therefore
5460      acceptable.  */
5461   *cross_mode_jump_p = (!info->relocatable
5462                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5463                         && ((r_type == R_MIPS16_26 && !target_is_16_bit_code_p)
5464                             || (r_type == R_MICROMIPS_26_S1
5465                                 && !target_is_micromips_code_p)
5466                             || ((r_type == R_MIPS_26 || r_type == R_MIPS_JALR)
5467                                 && (target_is_16_bit_code_p
5468                                     || target_is_micromips_code_p))));
5469
5470   local_p = (h == NULL
5471              || (h->got_only_for_calls
5472                  ? SYMBOL_CALLS_LOCAL (info, &h->root)
5473                  : SYMBOL_REFERENCES_LOCAL (info, &h->root)));
5474
5475   gp0 = _bfd_get_gp_value (input_bfd);
5476   gp = _bfd_get_gp_value (abfd);
5477   if (htab->got_info)
5478     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5479
5480   if (gnu_local_gp_p)
5481     symbol = gp;
5482
5483   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5484      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5485      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5486   if (got_page_reloc_p (r_type) && !local_p)
5487     {
5488       r_type = (micromips_reloc_p (r_type)
5489                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5490       addend = 0;
5491     }
5492
5493   /* If we haven't already determined the GOT offset, and we're going
5494      to need it, get it now.  */
5495   switch (r_type)
5496     {
5497     case R_MIPS16_CALL16:
5498     case R_MIPS16_GOT16:
5499     case R_MIPS_CALL16:
5500     case R_MIPS_GOT16:
5501     case R_MIPS_GOT_DISP:
5502     case R_MIPS_GOT_HI16:
5503     case R_MIPS_CALL_HI16:
5504     case R_MIPS_GOT_LO16:
5505     case R_MIPS_CALL_LO16:
5506     case R_MICROMIPS_CALL16:
5507     case R_MICROMIPS_GOT16:
5508     case R_MICROMIPS_GOT_DISP:
5509     case R_MICROMIPS_GOT_HI16:
5510     case R_MICROMIPS_CALL_HI16:
5511     case R_MICROMIPS_GOT_LO16:
5512     case R_MICROMIPS_CALL_LO16:
5513     case R_MIPS_TLS_GD:
5514     case R_MIPS_TLS_GOTTPREL:
5515     case R_MIPS_TLS_LDM:
5516     case R_MIPS16_TLS_GD:
5517     case R_MIPS16_TLS_GOTTPREL:
5518     case R_MIPS16_TLS_LDM:
5519     case R_MICROMIPS_TLS_GD:
5520     case R_MICROMIPS_TLS_GOTTPREL:
5521     case R_MICROMIPS_TLS_LDM:
5522       /* Find the index into the GOT where this value is located.  */
5523       if (tls_ldm_reloc_p (r_type))
5524         {
5525           g = mips_elf_local_got_index (abfd, input_bfd, info,
5526                                         0, 0, NULL, r_type);
5527           if (g == MINUS_ONE)
5528             return bfd_reloc_outofrange;
5529         }
5530       else if (!local_p)
5531         {
5532           /* On VxWorks, CALL relocations should refer to the .got.plt
5533              entry, which is initialized to point at the PLT stub.  */
5534           if (htab->is_vxworks
5535               && (call_hi16_reloc_p (r_type)
5536                   || call_lo16_reloc_p (r_type)
5537                   || call16_reloc_p (r_type)))
5538             {
5539               BFD_ASSERT (addend == 0);
5540               BFD_ASSERT (h->root.needs_plt);
5541               g = mips_elf_gotplt_index (info, &h->root);
5542             }
5543           else
5544             {
5545               BFD_ASSERT (addend == 0);
5546               g = mips_elf_global_got_index (abfd, info, input_bfd,
5547                                              &h->root, r_type);
5548               if (!TLS_RELOC_P (r_type)
5549                   && !elf_hash_table (info)->dynamic_sections_created)
5550                 /* This is a static link.  We must initialize the GOT entry.  */
5551                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->sgot->contents + g);
5552             }
5553         }
5554       else if (!htab->is_vxworks
5555                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5556         /* The calculation below does not involve "g".  */
5557         break;
5558       else
5559         {
5560           g = mips_elf_local_got_index (abfd, input_bfd, info,
5561                                         symbol + addend, r_symndx, h, r_type);
5562           if (g == MINUS_ONE)
5563             return bfd_reloc_outofrange;
5564         }
5565
5566       /* Convert GOT indices to actual offsets.  */
5567       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5568       break;
5569     }
5570
5571   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5572      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5573   if (h != NULL && is_gott_symbol (info, &h->root))
5574     {
5575       Elf_Internal_Rela outrel;
5576       bfd_byte *loc;
5577       asection *s;
5578
5579       s = mips_elf_rel_dyn_section (info, FALSE);
5580       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5581
5582       outrel.r_offset = (input_section->output_section->vma
5583                          + input_section->output_offset
5584                          + relocation->r_offset);
5585       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5586       outrel.r_addend = addend;
5587       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5588
5589       /* If we've written this relocation for a readonly section,
5590          we need to set DF_TEXTREL again, so that we do not delete the
5591          DT_TEXTREL tag.  */
5592       if (MIPS_ELF_READONLY_SECTION (input_section))
5593         info->flags |= DF_TEXTREL;
5594
5595       *valuep = 0;
5596       return bfd_reloc_ok;
5597     }
5598
5599   /* Figure out what kind of relocation is being performed.  */
5600   switch (r_type)
5601     {
5602     case R_MIPS_NONE:
5603       return bfd_reloc_continue;
5604
5605     case R_MIPS_16:
5606       value = symbol + _bfd_mips_elf_sign_extend (addend, 16);
5607       overflowed_p = mips_elf_overflow_p (value, 16);
5608       break;
5609
5610     case R_MIPS_32:
5611     case R_MIPS_REL32:
5612     case R_MIPS_64:
5613       if ((info->shared
5614            || (htab->root.dynamic_sections_created
5615                && h != NULL
5616                && h->root.def_dynamic
5617                && !h->root.def_regular
5618                && !h->has_static_relocs))
5619           && r_symndx != STN_UNDEF
5620           && (h == NULL
5621               || h->root.root.type != bfd_link_hash_undefweak
5622               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5623           && (input_section->flags & SEC_ALLOC) != 0)
5624         {
5625           /* If we're creating a shared library, then we can't know
5626              where the symbol will end up.  So, we create a relocation
5627              record in the output, and leave the job up to the dynamic
5628              linker.  We must do the same for executable references to
5629              shared library symbols, unless we've decided to use copy
5630              relocs or PLTs instead.  */
5631           value = addend;
5632           if (!mips_elf_create_dynamic_relocation (abfd,
5633                                                    info,
5634                                                    relocation,
5635                                                    h,
5636                                                    sec,
5637                                                    symbol,
5638                                                    &value,
5639                                                    input_section))
5640             return bfd_reloc_undefined;
5641         }
5642       else
5643         {
5644           if (r_type != R_MIPS_REL32)
5645             value = symbol + addend;
5646           else
5647             value = addend;
5648         }
5649       value &= howto->dst_mask;
5650       break;
5651
5652     case R_MIPS_PC32:
5653       value = symbol + addend - p;
5654       value &= howto->dst_mask;
5655       break;
5656
5657     case R_MIPS16_26:
5658       /* The calculation for R_MIPS16_26 is just the same as for an
5659          R_MIPS_26.  It's only the storage of the relocated field into
5660          the output file that's different.  That's handled in
5661          mips_elf_perform_relocation.  So, we just fall through to the
5662          R_MIPS_26 case here.  */
5663     case R_MIPS_26:
5664     case R_MICROMIPS_26_S1:
5665       {
5666         unsigned int shift;
5667
5668         /* Make sure the target of JALX is word-aligned.  Bit 0 must be
5669            the correct ISA mode selector and bit 1 must be 0.  */
5670         if (*cross_mode_jump_p && (symbol & 3) != (r_type == R_MIPS_26))
5671           return bfd_reloc_outofrange;
5672
5673         /* Shift is 2, unusually, for microMIPS JALX.  */
5674         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5675
5676         if (was_local_p)
5677           value = addend | ((p + 4) & (0xfc000000 << shift));
5678         else
5679           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5680         value = (value + symbol) >> shift;
5681         if (!was_local_p && h->root.root.type != bfd_link_hash_undefweak)
5682           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5683         value &= howto->dst_mask;
5684       }
5685       break;
5686
5687     case R_MIPS_TLS_DTPREL_HI16:
5688     case R_MIPS16_TLS_DTPREL_HI16:
5689     case R_MICROMIPS_TLS_DTPREL_HI16:
5690       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5691                & howto->dst_mask);
5692       break;
5693
5694     case R_MIPS_TLS_DTPREL_LO16:
5695     case R_MIPS_TLS_DTPREL32:
5696     case R_MIPS_TLS_DTPREL64:
5697     case R_MIPS16_TLS_DTPREL_LO16:
5698     case R_MICROMIPS_TLS_DTPREL_LO16:
5699       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5700       break;
5701
5702     case R_MIPS_TLS_TPREL_HI16:
5703     case R_MIPS16_TLS_TPREL_HI16:
5704     case R_MICROMIPS_TLS_TPREL_HI16:
5705       value = (mips_elf_high (addend + symbol - tprel_base (info))
5706                & howto->dst_mask);
5707       break;
5708
5709     case R_MIPS_TLS_TPREL_LO16:
5710     case R_MIPS_TLS_TPREL32:
5711     case R_MIPS_TLS_TPREL64:
5712     case R_MIPS16_TLS_TPREL_LO16:
5713     case R_MICROMIPS_TLS_TPREL_LO16:
5714       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5715       break;
5716
5717     case R_MIPS_HI16:
5718     case R_MIPS16_HI16:
5719     case R_MICROMIPS_HI16:
5720       if (!gp_disp_p)
5721         {
5722           value = mips_elf_high (addend + symbol);
5723           value &= howto->dst_mask;
5724         }
5725       else
5726         {
5727           /* For MIPS16 ABI code we generate this sequence
5728                 0: li      $v0,%hi(_gp_disp)
5729                 4: addiupc $v1,%lo(_gp_disp)
5730                 8: sll     $v0,16
5731                12: addu    $v0,$v1
5732                14: move    $gp,$v0
5733              So the offsets of hi and lo relocs are the same, but the
5734              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5735              ADDIUPC clears the low two bits of the instruction address,
5736              so the base is ($t9 + 4) & ~3.  */
5737           if (r_type == R_MIPS16_HI16)
5738             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5739           /* The microMIPS .cpload sequence uses the same assembly
5740              instructions as the traditional psABI version, but the
5741              incoming $t9 has the low bit set.  */
5742           else if (r_type == R_MICROMIPS_HI16)
5743             value = mips_elf_high (addend + gp - p - 1);
5744           else
5745             value = mips_elf_high (addend + gp - p);
5746           overflowed_p = mips_elf_overflow_p (value, 16);
5747         }
5748       break;
5749
5750     case R_MIPS_LO16:
5751     case R_MIPS16_LO16:
5752     case R_MICROMIPS_LO16:
5753     case R_MICROMIPS_HI0_LO16:
5754       if (!gp_disp_p)
5755         value = (symbol + addend) & howto->dst_mask;
5756       else
5757         {
5758           /* See the comment for R_MIPS16_HI16 above for the reason
5759              for this conditional.  */
5760           if (r_type == R_MIPS16_LO16)
5761             value = addend + gp - (p & ~(bfd_vma) 0x3);
5762           else if (r_type == R_MICROMIPS_LO16
5763                    || r_type == R_MICROMIPS_HI0_LO16)
5764             value = addend + gp - p + 3;
5765           else
5766             value = addend + gp - p + 4;
5767           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5768              for overflow.  But, on, say, IRIX5, relocations against
5769              _gp_disp are normally generated from the .cpload
5770              pseudo-op.  It generates code that normally looks like
5771              this:
5772
5773                lui    $gp,%hi(_gp_disp)
5774                addiu  $gp,$gp,%lo(_gp_disp)
5775                addu   $gp,$gp,$t9
5776
5777              Here $t9 holds the address of the function being called,
5778              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5779              relocation can easily overflow in this situation, but the
5780              R_MIPS_HI16 relocation will handle the overflow.
5781              Therefore, we consider this a bug in the MIPS ABI, and do
5782              not check for overflow here.  */
5783         }
5784       break;
5785
5786     case R_MIPS_LITERAL:
5787     case R_MICROMIPS_LITERAL:
5788       /* Because we don't merge literal sections, we can handle this
5789          just like R_MIPS_GPREL16.  In the long run, we should merge
5790          shared literals, and then we will need to additional work
5791          here.  */
5792
5793       /* Fall through.  */
5794
5795     case R_MIPS16_GPREL:
5796       /* The R_MIPS16_GPREL performs the same calculation as
5797          R_MIPS_GPREL16, but stores the relocated bits in a different
5798          order.  We don't need to do anything special here; the
5799          differences are handled in mips_elf_perform_relocation.  */
5800     case R_MIPS_GPREL16:
5801     case R_MICROMIPS_GPREL7_S2:
5802     case R_MICROMIPS_GPREL16:
5803       /* Only sign-extend the addend if it was extracted from the
5804          instruction.  If the addend was separate, leave it alone,
5805          otherwise we may lose significant bits.  */
5806       if (howto->partial_inplace)
5807         addend = _bfd_mips_elf_sign_extend (addend, 16);
5808       value = symbol + addend - gp;
5809       /* If the symbol was local, any earlier relocatable links will
5810          have adjusted its addend with the gp offset, so compensate
5811          for that now.  Don't do it for symbols forced local in this
5812          link, though, since they won't have had the gp offset applied
5813          to them before.  */
5814       if (was_local_p)
5815         value += gp0;
5816       overflowed_p = mips_elf_overflow_p (value, 16);
5817       break;
5818
5819     case R_MIPS16_GOT16:
5820     case R_MIPS16_CALL16:
5821     case R_MIPS_GOT16:
5822     case R_MIPS_CALL16:
5823     case R_MICROMIPS_GOT16:
5824     case R_MICROMIPS_CALL16:
5825       /* VxWorks does not have separate local and global semantics for
5826          R_MIPS*_GOT16; every relocation evaluates to "G".  */
5827       if (!htab->is_vxworks && local_p)
5828         {
5829           value = mips_elf_got16_entry (abfd, input_bfd, info,
5830                                         symbol + addend, !was_local_p);
5831           if (value == MINUS_ONE)
5832             return bfd_reloc_outofrange;
5833           value
5834             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5835           overflowed_p = mips_elf_overflow_p (value, 16);
5836           break;
5837         }
5838
5839       /* Fall through.  */
5840
5841     case R_MIPS_TLS_GD:
5842     case R_MIPS_TLS_GOTTPREL:
5843     case R_MIPS_TLS_LDM:
5844     case R_MIPS_GOT_DISP:
5845     case R_MIPS16_TLS_GD:
5846     case R_MIPS16_TLS_GOTTPREL:
5847     case R_MIPS16_TLS_LDM:
5848     case R_MICROMIPS_TLS_GD:
5849     case R_MICROMIPS_TLS_GOTTPREL:
5850     case R_MICROMIPS_TLS_LDM:
5851     case R_MICROMIPS_GOT_DISP:
5852       value = g;
5853       overflowed_p = mips_elf_overflow_p (value, 16);
5854       break;
5855
5856     case R_MIPS_GPREL32:
5857       value = (addend + symbol + gp0 - gp);
5858       if (!save_addend)
5859         value &= howto->dst_mask;
5860       break;
5861
5862     case R_MIPS_PC16:
5863     case R_MIPS_GNU_REL16_S2:
5864       value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p;
5865       overflowed_p = mips_elf_overflow_p (value, 18);
5866       value >>= howto->rightshift;
5867       value &= howto->dst_mask;
5868       break;
5869
5870     case R_MICROMIPS_PC7_S1:
5871       value = symbol + _bfd_mips_elf_sign_extend (addend, 8) - p;
5872       overflowed_p = mips_elf_overflow_p (value, 8);
5873       value >>= howto->rightshift;
5874       value &= howto->dst_mask;
5875       break;
5876
5877     case R_MICROMIPS_PC10_S1:
5878       value = symbol + _bfd_mips_elf_sign_extend (addend, 11) - p;
5879       overflowed_p = mips_elf_overflow_p (value, 11);
5880       value >>= howto->rightshift;
5881       value &= howto->dst_mask;
5882       break;
5883
5884     case R_MICROMIPS_PC16_S1:
5885       value = symbol + _bfd_mips_elf_sign_extend (addend, 17) - p;
5886       overflowed_p = mips_elf_overflow_p (value, 17);
5887       value >>= howto->rightshift;
5888       value &= howto->dst_mask;
5889       break;
5890
5891     case R_MICROMIPS_PC23_S2:
5892       value = symbol + _bfd_mips_elf_sign_extend (addend, 25) - ((p | 3) ^ 3);
5893       overflowed_p = mips_elf_overflow_p (value, 25);
5894       value >>= howto->rightshift;
5895       value &= howto->dst_mask;
5896       break;
5897
5898     case R_MIPS_GOT_HI16:
5899     case R_MIPS_CALL_HI16:
5900     case R_MICROMIPS_GOT_HI16:
5901     case R_MICROMIPS_CALL_HI16:
5902       /* We're allowed to handle these two relocations identically.
5903          The dynamic linker is allowed to handle the CALL relocations
5904          differently by creating a lazy evaluation stub.  */
5905       value = g;
5906       value = mips_elf_high (value);
5907       value &= howto->dst_mask;
5908       break;
5909
5910     case R_MIPS_GOT_LO16:
5911     case R_MIPS_CALL_LO16:
5912     case R_MICROMIPS_GOT_LO16:
5913     case R_MICROMIPS_CALL_LO16:
5914       value = g & howto->dst_mask;
5915       break;
5916
5917     case R_MIPS_GOT_PAGE:
5918     case R_MICROMIPS_GOT_PAGE:
5919       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
5920       if (value == MINUS_ONE)
5921         return bfd_reloc_outofrange;
5922       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5923       overflowed_p = mips_elf_overflow_p (value, 16);
5924       break;
5925
5926     case R_MIPS_GOT_OFST:
5927     case R_MICROMIPS_GOT_OFST:
5928       if (local_p)
5929         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
5930       else
5931         value = addend;
5932       overflowed_p = mips_elf_overflow_p (value, 16);
5933       break;
5934
5935     case R_MIPS_SUB:
5936     case R_MICROMIPS_SUB:
5937       value = symbol - addend;
5938       value &= howto->dst_mask;
5939       break;
5940
5941     case R_MIPS_HIGHER:
5942     case R_MICROMIPS_HIGHER:
5943       value = mips_elf_higher (addend + symbol);
5944       value &= howto->dst_mask;
5945       break;
5946
5947     case R_MIPS_HIGHEST:
5948     case R_MICROMIPS_HIGHEST:
5949       value = mips_elf_highest (addend + symbol);
5950       value &= howto->dst_mask;
5951       break;
5952
5953     case R_MIPS_SCN_DISP:
5954     case R_MICROMIPS_SCN_DISP:
5955       value = symbol + addend - sec->output_offset;
5956       value &= howto->dst_mask;
5957       break;
5958
5959     case R_MIPS_JALR:
5960     case R_MICROMIPS_JALR:
5961       /* This relocation is only a hint.  In some cases, we optimize
5962          it into a bal instruction.  But we don't try to optimize
5963          when the symbol does not resolve locally.  */
5964       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
5965         return bfd_reloc_continue;
5966       value = symbol + addend;
5967       break;
5968
5969     case R_MIPS_PJUMP:
5970     case R_MIPS_GNU_VTINHERIT:
5971     case R_MIPS_GNU_VTENTRY:
5972       /* We don't do anything with these at present.  */
5973       return bfd_reloc_continue;
5974
5975     default:
5976       /* An unrecognized relocation type.  */
5977       return bfd_reloc_notsupported;
5978     }
5979
5980   /* Store the VALUE for our caller.  */
5981   *valuep = value;
5982   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
5983 }
5984
5985 /* Obtain the field relocated by RELOCATION.  */
5986
5987 static bfd_vma
5988 mips_elf_obtain_contents (reloc_howto_type *howto,
5989                           const Elf_Internal_Rela *relocation,
5990                           bfd *input_bfd, bfd_byte *contents)
5991 {
5992   bfd_vma x;
5993   bfd_byte *location = contents + relocation->r_offset;
5994
5995   /* Obtain the bytes.  */
5996   x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location);
5997
5998   return x;
5999 }
6000
6001 /* It has been determined that the result of the RELOCATION is the
6002    VALUE.  Use HOWTO to place VALUE into the output file at the
6003    appropriate position.  The SECTION is the section to which the
6004    relocation applies.
6005    CROSS_MODE_JUMP_P is true if the relocation field
6006    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
6007
6008    Returns FALSE if anything goes wrong.  */
6009
6010 static bfd_boolean
6011 mips_elf_perform_relocation (struct bfd_link_info *info,
6012                              reloc_howto_type *howto,
6013                              const Elf_Internal_Rela *relocation,
6014                              bfd_vma value, bfd *input_bfd,
6015                              asection *input_section, bfd_byte *contents,
6016                              bfd_boolean cross_mode_jump_p)
6017 {
6018   bfd_vma x;
6019   bfd_byte *location;
6020   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
6021
6022   /* Figure out where the relocation is occurring.  */
6023   location = contents + relocation->r_offset;
6024
6025   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
6026
6027   /* Obtain the current value.  */
6028   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
6029
6030   /* Clear the field we are setting.  */
6031   x &= ~howto->dst_mask;
6032
6033   /* Set the field.  */
6034   x |= (value & howto->dst_mask);
6035
6036   /* If required, turn JAL into JALX.  */
6037   if (cross_mode_jump_p && jal_reloc_p (r_type))
6038     {
6039       bfd_boolean ok;
6040       bfd_vma opcode = x >> 26;
6041       bfd_vma jalx_opcode;
6042
6043       /* Check to see if the opcode is already JAL or JALX.  */
6044       if (r_type == R_MIPS16_26)
6045         {
6046           ok = ((opcode == 0x6) || (opcode == 0x7));
6047           jalx_opcode = 0x7;
6048         }
6049       else if (r_type == R_MICROMIPS_26_S1)
6050         {
6051           ok = ((opcode == 0x3d) || (opcode == 0x3c));
6052           jalx_opcode = 0x3c;
6053         }
6054       else
6055         {
6056           ok = ((opcode == 0x3) || (opcode == 0x1d));
6057           jalx_opcode = 0x1d;
6058         }
6059
6060       /* If the opcode is not JAL or JALX, there's a problem.  We cannot
6061          convert J or JALS to JALX.  */
6062       if (!ok)
6063         {
6064           (*_bfd_error_handler)
6065             (_("%B: %A+0x%lx: Unsupported jump between ISA modes; consider recompiling with interlinking enabled."),
6066              input_bfd,
6067              input_section,
6068              (unsigned long) relocation->r_offset);
6069           bfd_set_error (bfd_error_bad_value);
6070           return FALSE;
6071         }
6072
6073       /* Make this the JALX opcode.  */
6074       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
6075     }
6076
6077   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
6078      range.  */
6079   if (!info->relocatable
6080       && !cross_mode_jump_p
6081       && ((JAL_TO_BAL_P (input_bfd)
6082            && r_type == R_MIPS_26
6083            && (x >> 26) == 0x3)         /* jal addr */
6084           || (JALR_TO_BAL_P (input_bfd)
6085               && r_type == R_MIPS_JALR
6086               && x == 0x0320f809)       /* jalr t9 */
6087           || (JR_TO_B_P (input_bfd)
6088               && r_type == R_MIPS_JALR
6089               && x == 0x03200008)))     /* jr t9 */
6090     {
6091       bfd_vma addr;
6092       bfd_vma dest;
6093       bfd_signed_vma off;
6094
6095       addr = (input_section->output_section->vma
6096               + input_section->output_offset
6097               + relocation->r_offset
6098               + 4);
6099       if (r_type == R_MIPS_26)
6100         dest = (value << 2) | ((addr >> 28) << 28);
6101       else
6102         dest = value;
6103       off = dest - addr;
6104       if (off <= 0x1ffff && off >= -0x20000)
6105         {
6106           if (x == 0x03200008)  /* jr t9 */
6107             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
6108           else
6109             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
6110         }
6111     }
6112
6113   /* Put the value into the output.  */
6114   bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location);
6115
6116   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !info->relocatable,
6117                                location);
6118
6119   return TRUE;
6120 }
6121 \f
6122 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
6123    is the original relocation, which is now being transformed into a
6124    dynamic relocation.  The ADDENDP is adjusted if necessary; the
6125    caller should store the result in place of the original addend.  */
6126
6127 static bfd_boolean
6128 mips_elf_create_dynamic_relocation (bfd *output_bfd,
6129                                     struct bfd_link_info *info,
6130                                     const Elf_Internal_Rela *rel,
6131                                     struct mips_elf_link_hash_entry *h,
6132                                     asection *sec, bfd_vma symbol,
6133                                     bfd_vma *addendp, asection *input_section)
6134 {
6135   Elf_Internal_Rela outrel[3];
6136   asection *sreloc;
6137   bfd *dynobj;
6138   int r_type;
6139   long indx;
6140   bfd_boolean defined_p;
6141   struct mips_elf_link_hash_table *htab;
6142
6143   htab = mips_elf_hash_table (info);
6144   BFD_ASSERT (htab != NULL);
6145
6146   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
6147   dynobj = elf_hash_table (info)->dynobj;
6148   sreloc = mips_elf_rel_dyn_section (info, FALSE);
6149   BFD_ASSERT (sreloc != NULL);
6150   BFD_ASSERT (sreloc->contents != NULL);
6151   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
6152               < sreloc->size);
6153
6154   outrel[0].r_offset =
6155     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
6156   if (ABI_64_P (output_bfd))
6157     {
6158       outrel[1].r_offset =
6159         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
6160       outrel[2].r_offset =
6161         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
6162     }
6163
6164   if (outrel[0].r_offset == MINUS_ONE)
6165     /* The relocation field has been deleted.  */
6166     return TRUE;
6167
6168   if (outrel[0].r_offset == MINUS_TWO)
6169     {
6170       /* The relocation field has been converted into a relative value of
6171          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
6172          the field to be fully relocated, so add in the symbol's value.  */
6173       *addendp += symbol;
6174       return TRUE;
6175     }
6176
6177   /* We must now calculate the dynamic symbol table index to use
6178      in the relocation.  */
6179   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
6180     {
6181       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
6182       indx = h->root.dynindx;
6183       if (SGI_COMPAT (output_bfd))
6184         defined_p = h->root.def_regular;
6185       else
6186         /* ??? glibc's ld.so just adds the final GOT entry to the
6187            relocation field.  It therefore treats relocs against
6188            defined symbols in the same way as relocs against
6189            undefined symbols.  */
6190         defined_p = FALSE;
6191     }
6192   else
6193     {
6194       if (sec != NULL && bfd_is_abs_section (sec))
6195         indx = 0;
6196       else if (sec == NULL || sec->owner == NULL)
6197         {
6198           bfd_set_error (bfd_error_bad_value);
6199           return FALSE;
6200         }
6201       else
6202         {
6203           indx = elf_section_data (sec->output_section)->dynindx;
6204           if (indx == 0)
6205             {
6206               asection *osec = htab->root.text_index_section;
6207               indx = elf_section_data (osec)->dynindx;
6208             }
6209           if (indx == 0)
6210             abort ();
6211         }
6212
6213       /* Instead of generating a relocation using the section
6214          symbol, we may as well make it a fully relative
6215          relocation.  We want to avoid generating relocations to
6216          local symbols because we used to generate them
6217          incorrectly, without adding the original symbol value,
6218          which is mandated by the ABI for section symbols.  In
6219          order to give dynamic loaders and applications time to
6220          phase out the incorrect use, we refrain from emitting
6221          section-relative relocations.  It's not like they're
6222          useful, after all.  This should be a bit more efficient
6223          as well.  */
6224       /* ??? Although this behavior is compatible with glibc's ld.so,
6225          the ABI says that relocations against STN_UNDEF should have
6226          a symbol value of 0.  Irix rld honors this, so relocations
6227          against STN_UNDEF have no effect.  */
6228       if (!SGI_COMPAT (output_bfd))
6229         indx = 0;
6230       defined_p = TRUE;
6231     }
6232
6233   /* If the relocation was previously an absolute relocation and
6234      this symbol will not be referred to by the relocation, we must
6235      adjust it by the value we give it in the dynamic symbol table.
6236      Otherwise leave the job up to the dynamic linker.  */
6237   if (defined_p && r_type != R_MIPS_REL32)
6238     *addendp += symbol;
6239
6240   if (htab->is_vxworks)
6241     /* VxWorks uses non-relative relocations for this.  */
6242     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
6243   else
6244     /* The relocation is always an REL32 relocation because we don't
6245        know where the shared library will wind up at load-time.  */
6246     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
6247                                    R_MIPS_REL32);
6248
6249   /* For strict adherence to the ABI specification, we should
6250      generate a R_MIPS_64 relocation record by itself before the
6251      _REL32/_64 record as well, such that the addend is read in as
6252      a 64-bit value (REL32 is a 32-bit relocation, after all).
6253      However, since none of the existing ELF64 MIPS dynamic
6254      loaders seems to care, we don't waste space with these
6255      artificial relocations.  If this turns out to not be true,
6256      mips_elf_allocate_dynamic_relocation() should be tweaked so
6257      as to make room for a pair of dynamic relocations per
6258      invocation if ABI_64_P, and here we should generate an
6259      additional relocation record with R_MIPS_64 by itself for a
6260      NULL symbol before this relocation record.  */
6261   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
6262                                  ABI_64_P (output_bfd)
6263                                  ? R_MIPS_64
6264                                  : R_MIPS_NONE);
6265   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
6266
6267   /* Adjust the output offset of the relocation to reference the
6268      correct location in the output file.  */
6269   outrel[0].r_offset += (input_section->output_section->vma
6270                          + input_section->output_offset);
6271   outrel[1].r_offset += (input_section->output_section->vma
6272                          + input_section->output_offset);
6273   outrel[2].r_offset += (input_section->output_section->vma
6274                          + input_section->output_offset);
6275
6276   /* Put the relocation back out.  We have to use the special
6277      relocation outputter in the 64-bit case since the 64-bit
6278      relocation format is non-standard.  */
6279   if (ABI_64_P (output_bfd))
6280     {
6281       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
6282         (output_bfd, &outrel[0],
6283          (sreloc->contents
6284           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
6285     }
6286   else if (htab->is_vxworks)
6287     {
6288       /* VxWorks uses RELA rather than REL dynamic relocations.  */
6289       outrel[0].r_addend = *addendp;
6290       bfd_elf32_swap_reloca_out
6291         (output_bfd, &outrel[0],
6292          (sreloc->contents
6293           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
6294     }
6295   else
6296     bfd_elf32_swap_reloc_out
6297       (output_bfd, &outrel[0],
6298        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
6299
6300   /* We've now added another relocation.  */
6301   ++sreloc->reloc_count;
6302
6303   /* Make sure the output section is writable.  The dynamic linker
6304      will be writing to it.  */
6305   elf_section_data (input_section->output_section)->this_hdr.sh_flags
6306     |= SHF_WRITE;
6307
6308   /* On IRIX5, make an entry of compact relocation info.  */
6309   if (IRIX_COMPAT (output_bfd) == ict_irix5)
6310     {
6311       asection *scpt = bfd_get_linker_section (dynobj, ".compact_rel");
6312       bfd_byte *cr;
6313
6314       if (scpt)
6315         {
6316           Elf32_crinfo cptrel;
6317
6318           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
6319           cptrel.vaddr = (rel->r_offset
6320                           + input_section->output_section->vma
6321                           + input_section->output_offset);
6322           if (r_type == R_MIPS_REL32)
6323             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
6324           else
6325             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
6326           mips_elf_set_cr_dist2to (cptrel, 0);
6327           cptrel.konst = *addendp;
6328
6329           cr = (scpt->contents
6330                 + sizeof (Elf32_External_compact_rel));
6331           mips_elf_set_cr_relvaddr (cptrel, 0);
6332           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
6333                                      ((Elf32_External_crinfo *) cr
6334                                       + scpt->reloc_count));
6335           ++scpt->reloc_count;
6336         }
6337     }
6338
6339   /* If we've written this relocation for a readonly section,
6340      we need to set DF_TEXTREL again, so that we do not delete the
6341      DT_TEXTREL tag.  */
6342   if (MIPS_ELF_READONLY_SECTION (input_section))
6343     info->flags |= DF_TEXTREL;
6344
6345   return TRUE;
6346 }
6347 \f
6348 /* Return the MACH for a MIPS e_flags value.  */
6349
6350 unsigned long
6351 _bfd_elf_mips_mach (flagword flags)
6352 {
6353   switch (flags & EF_MIPS_MACH)
6354     {
6355     case E_MIPS_MACH_3900:
6356       return bfd_mach_mips3900;
6357
6358     case E_MIPS_MACH_4010:
6359       return bfd_mach_mips4010;
6360
6361     case E_MIPS_MACH_4100:
6362       return bfd_mach_mips4100;
6363
6364     case E_MIPS_MACH_4111:
6365       return bfd_mach_mips4111;
6366
6367     case E_MIPS_MACH_4120:
6368       return bfd_mach_mips4120;
6369
6370     case E_MIPS_MACH_4650:
6371       return bfd_mach_mips4650;
6372
6373     case E_MIPS_MACH_5400:
6374       return bfd_mach_mips5400;
6375
6376     case E_MIPS_MACH_5500:
6377       return bfd_mach_mips5500;
6378
6379     case E_MIPS_MACH_5900:
6380       return bfd_mach_mips5900;
6381
6382     case E_MIPS_MACH_9000:
6383       return bfd_mach_mips9000;
6384
6385     case E_MIPS_MACH_SB1:
6386       return bfd_mach_mips_sb1;
6387
6388     case E_MIPS_MACH_LS2E:
6389       return bfd_mach_mips_loongson_2e;
6390
6391     case E_MIPS_MACH_LS2F:
6392       return bfd_mach_mips_loongson_2f;
6393
6394     case E_MIPS_MACH_LS3A:
6395       return bfd_mach_mips_loongson_3a;
6396
6397     case E_MIPS_MACH_OCTEON2:
6398       return bfd_mach_mips_octeon2;
6399
6400     case E_MIPS_MACH_OCTEON:
6401       return bfd_mach_mips_octeon;
6402
6403     case E_MIPS_MACH_XLR:
6404       return bfd_mach_mips_xlr;
6405
6406     default:
6407       switch (flags & EF_MIPS_ARCH)
6408         {
6409         default:
6410         case E_MIPS_ARCH_1:
6411           return bfd_mach_mips3000;
6412
6413         case E_MIPS_ARCH_2:
6414           return bfd_mach_mips6000;
6415
6416         case E_MIPS_ARCH_3:
6417           return bfd_mach_mips4000;
6418
6419         case E_MIPS_ARCH_4:
6420           return bfd_mach_mips8000;
6421
6422         case E_MIPS_ARCH_5:
6423           return bfd_mach_mips5;
6424
6425         case E_MIPS_ARCH_32:
6426           return bfd_mach_mipsisa32;
6427
6428         case E_MIPS_ARCH_64:
6429           return bfd_mach_mipsisa64;
6430
6431         case E_MIPS_ARCH_32R2:
6432           return bfd_mach_mipsisa32r2;
6433
6434         case E_MIPS_ARCH_64R2:
6435           return bfd_mach_mipsisa64r2;
6436         }
6437     }
6438
6439   return 0;
6440 }
6441
6442 /* Return printable name for ABI.  */
6443
6444 static INLINE char *
6445 elf_mips_abi_name (bfd *abfd)
6446 {
6447   flagword flags;
6448
6449   flags = elf_elfheader (abfd)->e_flags;
6450   switch (flags & EF_MIPS_ABI)
6451     {
6452     case 0:
6453       if (ABI_N32_P (abfd))
6454         return "N32";
6455       else if (ABI_64_P (abfd))
6456         return "64";
6457       else
6458         return "none";
6459     case E_MIPS_ABI_O32:
6460       return "O32";
6461     case E_MIPS_ABI_O64:
6462       return "O64";
6463     case E_MIPS_ABI_EABI32:
6464       return "EABI32";
6465     case E_MIPS_ABI_EABI64:
6466       return "EABI64";
6467     default:
6468       return "unknown abi";
6469     }
6470 }
6471 \f
6472 /* MIPS ELF uses two common sections.  One is the usual one, and the
6473    other is for small objects.  All the small objects are kept
6474    together, and then referenced via the gp pointer, which yields
6475    faster assembler code.  This is what we use for the small common
6476    section.  This approach is copied from ecoff.c.  */
6477 static asection mips_elf_scom_section;
6478 static asymbol mips_elf_scom_symbol;
6479 static asymbol *mips_elf_scom_symbol_ptr;
6480
6481 /* MIPS ELF also uses an acommon section, which represents an
6482    allocated common symbol which may be overridden by a
6483    definition in a shared library.  */
6484 static asection mips_elf_acom_section;
6485 static asymbol mips_elf_acom_symbol;
6486 static asymbol *mips_elf_acom_symbol_ptr;
6487
6488 /* This is used for both the 32-bit and the 64-bit ABI.  */
6489
6490 void
6491 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6492 {
6493   elf_symbol_type *elfsym;
6494
6495   /* Handle the special MIPS section numbers that a symbol may use.  */
6496   elfsym = (elf_symbol_type *) asym;
6497   switch (elfsym->internal_elf_sym.st_shndx)
6498     {
6499     case SHN_MIPS_ACOMMON:
6500       /* This section is used in a dynamically linked executable file.
6501          It is an allocated common section.  The dynamic linker can
6502          either resolve these symbols to something in a shared
6503          library, or it can just leave them here.  For our purposes,
6504          we can consider these symbols to be in a new section.  */
6505       if (mips_elf_acom_section.name == NULL)
6506         {
6507           /* Initialize the acommon section.  */
6508           mips_elf_acom_section.name = ".acommon";
6509           mips_elf_acom_section.flags = SEC_ALLOC;
6510           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6511           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6512           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6513           mips_elf_acom_symbol.name = ".acommon";
6514           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6515           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6516           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6517         }
6518       asym->section = &mips_elf_acom_section;
6519       break;
6520
6521     case SHN_COMMON:
6522       /* Common symbols less than the GP size are automatically
6523          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6524       if (asym->value > elf_gp_size (abfd)
6525           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6526           || IRIX_COMPAT (abfd) == ict_irix6)
6527         break;
6528       /* Fall through.  */
6529     case SHN_MIPS_SCOMMON:
6530       if (mips_elf_scom_section.name == NULL)
6531         {
6532           /* Initialize the small common section.  */
6533           mips_elf_scom_section.name = ".scommon";
6534           mips_elf_scom_section.flags = SEC_IS_COMMON;
6535           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6536           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6537           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6538           mips_elf_scom_symbol.name = ".scommon";
6539           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6540           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6541           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6542         }
6543       asym->section = &mips_elf_scom_section;
6544       asym->value = elfsym->internal_elf_sym.st_size;
6545       break;
6546
6547     case SHN_MIPS_SUNDEFINED:
6548       asym->section = bfd_und_section_ptr;
6549       break;
6550
6551     case SHN_MIPS_TEXT:
6552       {
6553         asection *section = bfd_get_section_by_name (abfd, ".text");
6554
6555         if (section != NULL)
6556           {
6557             asym->section = section;
6558             /* MIPS_TEXT is a bit special, the address is not an offset
6559                to the base of the .text section.  So substract the section
6560                base address to make it an offset.  */
6561             asym->value -= section->vma;
6562           }
6563       }
6564       break;
6565
6566     case SHN_MIPS_DATA:
6567       {
6568         asection *section = bfd_get_section_by_name (abfd, ".data");
6569
6570         if (section != NULL)
6571           {
6572             asym->section = section;
6573             /* MIPS_DATA is a bit special, the address is not an offset
6574                to the base of the .data section.  So substract the section
6575                base address to make it an offset.  */
6576             asym->value -= section->vma;
6577           }
6578       }
6579       break;
6580     }
6581
6582   /* If this is an odd-valued function symbol, assume it's a MIPS16
6583      or microMIPS one.  */
6584   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6585       && (asym->value & 1) != 0)
6586     {
6587       asym->value--;
6588       if (MICROMIPS_P (abfd))
6589         elfsym->internal_elf_sym.st_other
6590           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6591       else
6592         elfsym->internal_elf_sym.st_other
6593           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6594     }
6595 }
6596 \f
6597 /* Implement elf_backend_eh_frame_address_size.  This differs from
6598    the default in the way it handles EABI64.
6599
6600    EABI64 was originally specified as an LP64 ABI, and that is what
6601    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6602    historically accepted the combination of -mabi=eabi and -mlong32,
6603    and this ILP32 variation has become semi-official over time.
6604    Both forms use elf32 and have pointer-sized FDE addresses.
6605
6606    If an EABI object was generated by GCC 4.0 or above, it will have
6607    an empty .gcc_compiled_longXX section, where XX is the size of longs
6608    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6609    have no special marking to distinguish them from LP64 objects.
6610
6611    We don't want users of the official LP64 ABI to be punished for the
6612    existence of the ILP32 variant, but at the same time, we don't want
6613    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6614    We therefore take the following approach:
6615
6616       - If ABFD contains a .gcc_compiled_longXX section, use it to
6617         determine the pointer size.
6618
6619       - Otherwise check the type of the first relocation.  Assume that
6620         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
6621
6622       - Otherwise punt.
6623
6624    The second check is enough to detect LP64 objects generated by pre-4.0
6625    compilers because, in the kind of output generated by those compilers,
6626    the first relocation will be associated with either a CIE personality
6627    routine or an FDE start address.  Furthermore, the compilers never
6628    used a special (non-pointer) encoding for this ABI.
6629
6630    Checking the relocation type should also be safe because there is no
6631    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
6632    did so.  */
6633
6634 unsigned int
6635 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
6636 {
6637   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
6638     return 8;
6639   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
6640     {
6641       bfd_boolean long32_p, long64_p;
6642
6643       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
6644       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
6645       if (long32_p && long64_p)
6646         return 0;
6647       if (long32_p)
6648         return 4;
6649       if (long64_p)
6650         return 8;
6651
6652       if (sec->reloc_count > 0
6653           && elf_section_data (sec)->relocs != NULL
6654           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
6655               == R_MIPS_64))
6656         return 8;
6657
6658       return 0;
6659     }
6660   return 4;
6661 }
6662 \f
6663 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
6664    relocations against two unnamed section symbols to resolve to the
6665    same address.  For example, if we have code like:
6666
6667         lw      $4,%got_disp(.data)($gp)
6668         lw      $25,%got_disp(.text)($gp)
6669         jalr    $25
6670
6671    then the linker will resolve both relocations to .data and the program
6672    will jump there rather than to .text.
6673
6674    We can work around this problem by giving names to local section symbols.
6675    This is also what the MIPSpro tools do.  */
6676
6677 bfd_boolean
6678 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
6679 {
6680   return SGI_COMPAT (abfd);
6681 }
6682 \f
6683 /* Work over a section just before writing it out.  This routine is
6684    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
6685    sections that need the SHF_MIPS_GPREL flag by name; there has to be
6686    a better way.  */
6687
6688 bfd_boolean
6689 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
6690 {
6691   if (hdr->sh_type == SHT_MIPS_REGINFO
6692       && hdr->sh_size > 0)
6693     {
6694       bfd_byte buf[4];
6695
6696       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
6697       BFD_ASSERT (hdr->contents == NULL);
6698
6699       if (bfd_seek (abfd,
6700                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
6701                     SEEK_SET) != 0)
6702         return FALSE;
6703       H_PUT_32 (abfd, elf_gp (abfd), buf);
6704       if (bfd_bwrite (buf, 4, abfd) != 4)
6705         return FALSE;
6706     }
6707
6708   if (hdr->sh_type == SHT_MIPS_OPTIONS
6709       && hdr->bfd_section != NULL
6710       && mips_elf_section_data (hdr->bfd_section) != NULL
6711       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
6712     {
6713       bfd_byte *contents, *l, *lend;
6714
6715       /* We stored the section contents in the tdata field in the
6716          set_section_contents routine.  We save the section contents
6717          so that we don't have to read them again.
6718          At this point we know that elf_gp is set, so we can look
6719          through the section contents to see if there is an
6720          ODK_REGINFO structure.  */
6721
6722       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
6723       l = contents;
6724       lend = contents + hdr->sh_size;
6725       while (l + sizeof (Elf_External_Options) <= lend)
6726         {
6727           Elf_Internal_Options intopt;
6728
6729           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6730                                         &intopt);
6731           if (intopt.size < sizeof (Elf_External_Options))
6732             {
6733               (*_bfd_error_handler)
6734                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6735                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6736               break;
6737             }
6738           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6739             {
6740               bfd_byte buf[8];
6741
6742               if (bfd_seek (abfd,
6743                             (hdr->sh_offset
6744                              + (l - contents)
6745                              + sizeof (Elf_External_Options)
6746                              + (sizeof (Elf64_External_RegInfo) - 8)),
6747                              SEEK_SET) != 0)
6748                 return FALSE;
6749               H_PUT_64 (abfd, elf_gp (abfd), buf);
6750               if (bfd_bwrite (buf, 8, abfd) != 8)
6751                 return FALSE;
6752             }
6753           else if (intopt.kind == ODK_REGINFO)
6754             {
6755               bfd_byte buf[4];
6756
6757               if (bfd_seek (abfd,
6758                             (hdr->sh_offset
6759                              + (l - contents)
6760                              + sizeof (Elf_External_Options)
6761                              + (sizeof (Elf32_External_RegInfo) - 4)),
6762                             SEEK_SET) != 0)
6763                 return FALSE;
6764               H_PUT_32 (abfd, elf_gp (abfd), buf);
6765               if (bfd_bwrite (buf, 4, abfd) != 4)
6766                 return FALSE;
6767             }
6768           l += intopt.size;
6769         }
6770     }
6771
6772   if (hdr->bfd_section != NULL)
6773     {
6774       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
6775
6776       /* .sbss is not handled specially here because the GNU/Linux
6777          prelinker can convert .sbss from NOBITS to PROGBITS and
6778          changing it back to NOBITS breaks the binary.  The entry in
6779          _bfd_mips_elf_special_sections will ensure the correct flags
6780          are set on .sbss if BFD creates it without reading it from an
6781          input file, and without special handling here the flags set
6782          on it in an input file will be followed.  */
6783       if (strcmp (name, ".sdata") == 0
6784           || strcmp (name, ".lit8") == 0
6785           || strcmp (name, ".lit4") == 0)
6786         {
6787           hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
6788           hdr->sh_type = SHT_PROGBITS;
6789         }
6790       else if (strcmp (name, ".srdata") == 0)
6791         {
6792           hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
6793           hdr->sh_type = SHT_PROGBITS;
6794         }
6795       else if (strcmp (name, ".compact_rel") == 0)
6796         {
6797           hdr->sh_flags = 0;
6798           hdr->sh_type = SHT_PROGBITS;
6799         }
6800       else if (strcmp (name, ".rtproc") == 0)
6801         {
6802           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
6803             {
6804               unsigned int adjust;
6805
6806               adjust = hdr->sh_size % hdr->sh_addralign;
6807               if (adjust != 0)
6808                 hdr->sh_size += hdr->sh_addralign - adjust;
6809             }
6810         }
6811     }
6812
6813   return TRUE;
6814 }
6815
6816 /* Handle a MIPS specific section when reading an object file.  This
6817    is called when elfcode.h finds a section with an unknown type.
6818    This routine supports both the 32-bit and 64-bit ELF ABI.
6819
6820    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
6821    how to.  */
6822
6823 bfd_boolean
6824 _bfd_mips_elf_section_from_shdr (bfd *abfd,
6825                                  Elf_Internal_Shdr *hdr,
6826                                  const char *name,
6827                                  int shindex)
6828 {
6829   flagword flags = 0;
6830
6831   /* There ought to be a place to keep ELF backend specific flags, but
6832      at the moment there isn't one.  We just keep track of the
6833      sections by their name, instead.  Fortunately, the ABI gives
6834      suggested names for all the MIPS specific sections, so we will
6835      probably get away with this.  */
6836   switch (hdr->sh_type)
6837     {
6838     case SHT_MIPS_LIBLIST:
6839       if (strcmp (name, ".liblist") != 0)
6840         return FALSE;
6841       break;
6842     case SHT_MIPS_MSYM:
6843       if (strcmp (name, ".msym") != 0)
6844         return FALSE;
6845       break;
6846     case SHT_MIPS_CONFLICT:
6847       if (strcmp (name, ".conflict") != 0)
6848         return FALSE;
6849       break;
6850     case SHT_MIPS_GPTAB:
6851       if (! CONST_STRNEQ (name, ".gptab."))
6852         return FALSE;
6853       break;
6854     case SHT_MIPS_UCODE:
6855       if (strcmp (name, ".ucode") != 0)
6856         return FALSE;
6857       break;
6858     case SHT_MIPS_DEBUG:
6859       if (strcmp (name, ".mdebug") != 0)
6860         return FALSE;
6861       flags = SEC_DEBUGGING;
6862       break;
6863     case SHT_MIPS_REGINFO:
6864       if (strcmp (name, ".reginfo") != 0
6865           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
6866         return FALSE;
6867       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6868       break;
6869     case SHT_MIPS_IFACE:
6870       if (strcmp (name, ".MIPS.interfaces") != 0)
6871         return FALSE;
6872       break;
6873     case SHT_MIPS_CONTENT:
6874       if (! CONST_STRNEQ (name, ".MIPS.content"))
6875         return FALSE;
6876       break;
6877     case SHT_MIPS_OPTIONS:
6878       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6879         return FALSE;
6880       break;
6881     case SHT_MIPS_DWARF:
6882       if (! CONST_STRNEQ (name, ".debug_")
6883           && ! CONST_STRNEQ (name, ".zdebug_"))
6884         return FALSE;
6885       break;
6886     case SHT_MIPS_SYMBOL_LIB:
6887       if (strcmp (name, ".MIPS.symlib") != 0)
6888         return FALSE;
6889       break;
6890     case SHT_MIPS_EVENTS:
6891       if (! CONST_STRNEQ (name, ".MIPS.events")
6892           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
6893         return FALSE;
6894       break;
6895     default:
6896       break;
6897     }
6898
6899   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
6900     return FALSE;
6901
6902   if (flags)
6903     {
6904       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
6905                                    (bfd_get_section_flags (abfd,
6906                                                            hdr->bfd_section)
6907                                     | flags)))
6908         return FALSE;
6909     }
6910
6911   /* FIXME: We should record sh_info for a .gptab section.  */
6912
6913   /* For a .reginfo section, set the gp value in the tdata information
6914      from the contents of this section.  We need the gp value while
6915      processing relocs, so we just get it now.  The .reginfo section
6916      is not used in the 64-bit MIPS ELF ABI.  */
6917   if (hdr->sh_type == SHT_MIPS_REGINFO)
6918     {
6919       Elf32_External_RegInfo ext;
6920       Elf32_RegInfo s;
6921
6922       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
6923                                       &ext, 0, sizeof ext))
6924         return FALSE;
6925       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
6926       elf_gp (abfd) = s.ri_gp_value;
6927     }
6928
6929   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
6930      set the gp value based on what we find.  We may see both
6931      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
6932      they should agree.  */
6933   if (hdr->sh_type == SHT_MIPS_OPTIONS)
6934     {
6935       bfd_byte *contents, *l, *lend;
6936
6937       contents = bfd_malloc (hdr->sh_size);
6938       if (contents == NULL)
6939         return FALSE;
6940       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
6941                                       0, hdr->sh_size))
6942         {
6943           free (contents);
6944           return FALSE;
6945         }
6946       l = contents;
6947       lend = contents + hdr->sh_size;
6948       while (l + sizeof (Elf_External_Options) <= lend)
6949         {
6950           Elf_Internal_Options intopt;
6951
6952           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6953                                         &intopt);
6954           if (intopt.size < sizeof (Elf_External_Options))
6955             {
6956               (*_bfd_error_handler)
6957                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6958                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6959               break;
6960             }
6961           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6962             {
6963               Elf64_Internal_RegInfo intreg;
6964
6965               bfd_mips_elf64_swap_reginfo_in
6966                 (abfd,
6967                  ((Elf64_External_RegInfo *)
6968                   (l + sizeof (Elf_External_Options))),
6969                  &intreg);
6970               elf_gp (abfd) = intreg.ri_gp_value;
6971             }
6972           else if (intopt.kind == ODK_REGINFO)
6973             {
6974               Elf32_RegInfo intreg;
6975
6976               bfd_mips_elf32_swap_reginfo_in
6977                 (abfd,
6978                  ((Elf32_External_RegInfo *)
6979                   (l + sizeof (Elf_External_Options))),
6980                  &intreg);
6981               elf_gp (abfd) = intreg.ri_gp_value;
6982             }
6983           l += intopt.size;
6984         }
6985       free (contents);
6986     }
6987
6988   return TRUE;
6989 }
6990
6991 /* Set the correct type for a MIPS ELF section.  We do this by the
6992    section name, which is a hack, but ought to work.  This routine is
6993    used by both the 32-bit and the 64-bit ABI.  */
6994
6995 bfd_boolean
6996 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
6997 {
6998   const char *name = bfd_get_section_name (abfd, sec);
6999
7000   if (strcmp (name, ".liblist") == 0)
7001     {
7002       hdr->sh_type = SHT_MIPS_LIBLIST;
7003       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
7004       /* The sh_link field is set in final_write_processing.  */
7005     }
7006   else if (strcmp (name, ".conflict") == 0)
7007     hdr->sh_type = SHT_MIPS_CONFLICT;
7008   else if (CONST_STRNEQ (name, ".gptab."))
7009     {
7010       hdr->sh_type = SHT_MIPS_GPTAB;
7011       hdr->sh_entsize = sizeof (Elf32_External_gptab);
7012       /* The sh_info field is set in final_write_processing.  */
7013     }
7014   else if (strcmp (name, ".ucode") == 0)
7015     hdr->sh_type = SHT_MIPS_UCODE;
7016   else if (strcmp (name, ".mdebug") == 0)
7017     {
7018       hdr->sh_type = SHT_MIPS_DEBUG;
7019       /* In a shared object on IRIX 5.3, the .mdebug section has an
7020          entsize of 0.  FIXME: Does this matter?  */
7021       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
7022         hdr->sh_entsize = 0;
7023       else
7024         hdr->sh_entsize = 1;
7025     }
7026   else if (strcmp (name, ".reginfo") == 0)
7027     {
7028       hdr->sh_type = SHT_MIPS_REGINFO;
7029       /* In a shared object on IRIX 5.3, the .reginfo section has an
7030          entsize of 0x18.  FIXME: Does this matter?  */
7031       if (SGI_COMPAT (abfd))
7032         {
7033           if ((abfd->flags & DYNAMIC) != 0)
7034             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
7035           else
7036             hdr->sh_entsize = 1;
7037         }
7038       else
7039         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
7040     }
7041   else if (SGI_COMPAT (abfd)
7042            && (strcmp (name, ".hash") == 0
7043                || strcmp (name, ".dynamic") == 0
7044                || strcmp (name, ".dynstr") == 0))
7045     {
7046       if (SGI_COMPAT (abfd))
7047         hdr->sh_entsize = 0;
7048 #if 0
7049       /* This isn't how the IRIX6 linker behaves.  */
7050       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
7051 #endif
7052     }
7053   else if (strcmp (name, ".got") == 0
7054            || strcmp (name, ".srdata") == 0
7055            || strcmp (name, ".sdata") == 0
7056            || strcmp (name, ".sbss") == 0
7057            || strcmp (name, ".lit4") == 0
7058            || strcmp (name, ".lit8") == 0)
7059     hdr->sh_flags |= SHF_MIPS_GPREL;
7060   else if (strcmp (name, ".MIPS.interfaces") == 0)
7061     {
7062       hdr->sh_type = SHT_MIPS_IFACE;
7063       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7064     }
7065   else if (CONST_STRNEQ (name, ".MIPS.content"))
7066     {
7067       hdr->sh_type = SHT_MIPS_CONTENT;
7068       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7069       /* The sh_info field is set in final_write_processing.  */
7070     }
7071   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
7072     {
7073       hdr->sh_type = SHT_MIPS_OPTIONS;
7074       hdr->sh_entsize = 1;
7075       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7076     }
7077   else if (CONST_STRNEQ (name, ".debug_")
7078            || CONST_STRNEQ (name, ".zdebug_"))
7079     {
7080       hdr->sh_type = SHT_MIPS_DWARF;
7081
7082       /* Irix facilities such as libexc expect a single .debug_frame
7083          per executable, the system ones have NOSTRIP set and the linker
7084          doesn't merge sections with different flags so ...  */
7085       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
7086         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7087     }
7088   else if (strcmp (name, ".MIPS.symlib") == 0)
7089     {
7090       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
7091       /* The sh_link and sh_info fields are set in
7092          final_write_processing.  */
7093     }
7094   else if (CONST_STRNEQ (name, ".MIPS.events")
7095            || CONST_STRNEQ (name, ".MIPS.post_rel"))
7096     {
7097       hdr->sh_type = SHT_MIPS_EVENTS;
7098       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7099       /* The sh_link field is set in final_write_processing.  */
7100     }
7101   else if (strcmp (name, ".msym") == 0)
7102     {
7103       hdr->sh_type = SHT_MIPS_MSYM;
7104       hdr->sh_flags |= SHF_ALLOC;
7105       hdr->sh_entsize = 8;
7106     }
7107
7108   /* The generic elf_fake_sections will set up REL_HDR using the default
7109    kind of relocations.  We used to set up a second header for the
7110    non-default kind of relocations here, but only NewABI would use
7111    these, and the IRIX ld doesn't like resulting empty RELA sections.
7112    Thus we create those header only on demand now.  */
7113
7114   return TRUE;
7115 }
7116
7117 /* Given a BFD section, try to locate the corresponding ELF section
7118    index.  This is used by both the 32-bit and the 64-bit ABI.
7119    Actually, it's not clear to me that the 64-bit ABI supports these,
7120    but for non-PIC objects we will certainly want support for at least
7121    the .scommon section.  */
7122
7123 bfd_boolean
7124 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
7125                                         asection *sec, int *retval)
7126 {
7127   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
7128     {
7129       *retval = SHN_MIPS_SCOMMON;
7130       return TRUE;
7131     }
7132   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
7133     {
7134       *retval = SHN_MIPS_ACOMMON;
7135       return TRUE;
7136     }
7137   return FALSE;
7138 }
7139 \f
7140 /* Hook called by the linker routine which adds symbols from an object
7141    file.  We must handle the special MIPS section numbers here.  */
7142
7143 bfd_boolean
7144 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
7145                                Elf_Internal_Sym *sym, const char **namep,
7146                                flagword *flagsp ATTRIBUTE_UNUSED,
7147                                asection **secp, bfd_vma *valp)
7148 {
7149   if (SGI_COMPAT (abfd)
7150       && (abfd->flags & DYNAMIC) != 0
7151       && strcmp (*namep, "_rld_new_interface") == 0)
7152     {
7153       /* Skip IRIX5 rld entry name.  */
7154       *namep = NULL;
7155       return TRUE;
7156     }
7157
7158   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
7159      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
7160      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
7161      a magic symbol resolved by the linker, we ignore this bogus definition
7162      of _gp_disp.  New ABI objects do not suffer from this problem so this
7163      is not done for them. */
7164   if (!NEWABI_P(abfd)
7165       && (sym->st_shndx == SHN_ABS)
7166       && (strcmp (*namep, "_gp_disp") == 0))
7167     {
7168       *namep = NULL;
7169       return TRUE;
7170     }
7171
7172   switch (sym->st_shndx)
7173     {
7174     case SHN_COMMON:
7175       /* Common symbols less than the GP size are automatically
7176          treated as SHN_MIPS_SCOMMON symbols.  */
7177       if (sym->st_size > elf_gp_size (abfd)
7178           || ELF_ST_TYPE (sym->st_info) == STT_TLS
7179           || IRIX_COMPAT (abfd) == ict_irix6)
7180         break;
7181       /* Fall through.  */
7182     case SHN_MIPS_SCOMMON:
7183       *secp = bfd_make_section_old_way (abfd, ".scommon");
7184       (*secp)->flags |= SEC_IS_COMMON;
7185       *valp = sym->st_size;
7186       break;
7187
7188     case SHN_MIPS_TEXT:
7189       /* This section is used in a shared object.  */
7190       if (mips_elf_tdata (abfd)->elf_text_section == NULL)
7191         {
7192           asymbol *elf_text_symbol;
7193           asection *elf_text_section;
7194           bfd_size_type amt = sizeof (asection);
7195
7196           elf_text_section = bfd_zalloc (abfd, amt);
7197           if (elf_text_section == NULL)
7198             return FALSE;
7199
7200           amt = sizeof (asymbol);
7201           elf_text_symbol = bfd_zalloc (abfd, amt);
7202           if (elf_text_symbol == NULL)
7203             return FALSE;
7204
7205           /* Initialize the section.  */
7206
7207           mips_elf_tdata (abfd)->elf_text_section = elf_text_section;
7208           mips_elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
7209
7210           elf_text_section->symbol = elf_text_symbol;
7211           elf_text_section->symbol_ptr_ptr = &mips_elf_tdata (abfd)->elf_text_symbol;
7212
7213           elf_text_section->name = ".text";
7214           elf_text_section->flags = SEC_NO_FLAGS;
7215           elf_text_section->output_section = NULL;
7216           elf_text_section->owner = abfd;
7217           elf_text_symbol->name = ".text";
7218           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7219           elf_text_symbol->section = elf_text_section;
7220         }
7221       /* This code used to do *secp = bfd_und_section_ptr if
7222          info->shared.  I don't know why, and that doesn't make sense,
7223          so I took it out.  */
7224       *secp = mips_elf_tdata (abfd)->elf_text_section;
7225       break;
7226
7227     case SHN_MIPS_ACOMMON:
7228       /* Fall through. XXX Can we treat this as allocated data?  */
7229     case SHN_MIPS_DATA:
7230       /* This section is used in a shared object.  */
7231       if (mips_elf_tdata (abfd)->elf_data_section == NULL)
7232         {
7233           asymbol *elf_data_symbol;
7234           asection *elf_data_section;
7235           bfd_size_type amt = sizeof (asection);
7236
7237           elf_data_section = bfd_zalloc (abfd, amt);
7238           if (elf_data_section == NULL)
7239             return FALSE;
7240
7241           amt = sizeof (asymbol);
7242           elf_data_symbol = bfd_zalloc (abfd, amt);
7243           if (elf_data_symbol == NULL)
7244             return FALSE;
7245
7246           /* Initialize the section.  */
7247
7248           mips_elf_tdata (abfd)->elf_data_section = elf_data_section;
7249           mips_elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
7250
7251           elf_data_section->symbol = elf_data_symbol;
7252           elf_data_section->symbol_ptr_ptr = &mips_elf_tdata (abfd)->elf_data_symbol;
7253
7254           elf_data_section->name = ".data";
7255           elf_data_section->flags = SEC_NO_FLAGS;
7256           elf_data_section->output_section = NULL;
7257           elf_data_section->owner = abfd;
7258           elf_data_symbol->name = ".data";
7259           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7260           elf_data_symbol->section = elf_data_section;
7261         }
7262       /* This code used to do *secp = bfd_und_section_ptr if
7263          info->shared.  I don't know why, and that doesn't make sense,
7264          so I took it out.  */
7265       *secp = mips_elf_tdata (abfd)->elf_data_section;
7266       break;
7267
7268     case SHN_MIPS_SUNDEFINED:
7269       *secp = bfd_und_section_ptr;
7270       break;
7271     }
7272
7273   if (SGI_COMPAT (abfd)
7274       && ! info->shared
7275       && info->output_bfd->xvec == abfd->xvec
7276       && strcmp (*namep, "__rld_obj_head") == 0)
7277     {
7278       struct elf_link_hash_entry *h;
7279       struct bfd_link_hash_entry *bh;
7280
7281       /* Mark __rld_obj_head as dynamic.  */
7282       bh = NULL;
7283       if (! (_bfd_generic_link_add_one_symbol
7284              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
7285               get_elf_backend_data (abfd)->collect, &bh)))
7286         return FALSE;
7287
7288       h = (struct elf_link_hash_entry *) bh;
7289       h->non_elf = 0;
7290       h->def_regular = 1;
7291       h->type = STT_OBJECT;
7292
7293       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7294         return FALSE;
7295
7296       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
7297       mips_elf_hash_table (info)->rld_symbol = h;
7298     }
7299
7300   /* If this is a mips16 text symbol, add 1 to the value to make it
7301      odd.  This will cause something like .word SYM to come up with
7302      the right value when it is loaded into the PC.  */
7303   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7304     ++*valp;
7305
7306   return TRUE;
7307 }
7308
7309 /* This hook function is called before the linker writes out a global
7310    symbol.  We mark symbols as small common if appropriate.  This is
7311    also where we undo the increment of the value for a mips16 symbol.  */
7312
7313 int
7314 _bfd_mips_elf_link_output_symbol_hook
7315   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
7316    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
7317    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
7318 {
7319   /* If we see a common symbol, which implies a relocatable link, then
7320      if a symbol was small common in an input file, mark it as small
7321      common in the output file.  */
7322   if (sym->st_shndx == SHN_COMMON
7323       && strcmp (input_sec->name, ".scommon") == 0)
7324     sym->st_shndx = SHN_MIPS_SCOMMON;
7325
7326   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7327     sym->st_value &= ~1;
7328
7329   return 1;
7330 }
7331 \f
7332 /* Functions for the dynamic linker.  */
7333
7334 /* Create dynamic sections when linking against a dynamic object.  */
7335
7336 bfd_boolean
7337 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
7338 {
7339   struct elf_link_hash_entry *h;
7340   struct bfd_link_hash_entry *bh;
7341   flagword flags;
7342   register asection *s;
7343   const char * const *namep;
7344   struct mips_elf_link_hash_table *htab;
7345
7346   htab = mips_elf_hash_table (info);
7347   BFD_ASSERT (htab != NULL);
7348
7349   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
7350            | SEC_LINKER_CREATED | SEC_READONLY);
7351
7352   /* The psABI requires a read-only .dynamic section, but the VxWorks
7353      EABI doesn't.  */
7354   if (!htab->is_vxworks)
7355     {
7356       s = bfd_get_linker_section (abfd, ".dynamic");
7357       if (s != NULL)
7358         {
7359           if (! bfd_set_section_flags (abfd, s, flags))
7360             return FALSE;
7361         }
7362     }
7363
7364   /* We need to create .got section.  */
7365   if (!mips_elf_create_got_section (abfd, info))
7366     return FALSE;
7367
7368   if (! mips_elf_rel_dyn_section (info, TRUE))
7369     return FALSE;
7370
7371   /* Create .stub section.  */
7372   s = bfd_make_section_anyway_with_flags (abfd,
7373                                           MIPS_ELF_STUB_SECTION_NAME (abfd),
7374                                           flags | SEC_CODE);
7375   if (s == NULL
7376       || ! bfd_set_section_alignment (abfd, s,
7377                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7378     return FALSE;
7379   htab->sstubs = s;
7380
7381   if (!mips_elf_hash_table (info)->use_rld_obj_head
7382       && !info->shared
7383       && bfd_get_linker_section (abfd, ".rld_map") == NULL)
7384     {
7385       s = bfd_make_section_anyway_with_flags (abfd, ".rld_map",
7386                                               flags &~ (flagword) SEC_READONLY);
7387       if (s == NULL
7388           || ! bfd_set_section_alignment (abfd, s,
7389                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7390         return FALSE;
7391     }
7392
7393   /* On IRIX5, we adjust add some additional symbols and change the
7394      alignments of several sections.  There is no ABI documentation
7395      indicating that this is necessary on IRIX6, nor any evidence that
7396      the linker takes such action.  */
7397   if (IRIX_COMPAT (abfd) == ict_irix5)
7398     {
7399       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7400         {
7401           bh = NULL;
7402           if (! (_bfd_generic_link_add_one_symbol
7403                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7404                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7405             return FALSE;
7406
7407           h = (struct elf_link_hash_entry *) bh;
7408           h->non_elf = 0;
7409           h->def_regular = 1;
7410           h->type = STT_SECTION;
7411
7412           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7413             return FALSE;
7414         }
7415
7416       /* We need to create a .compact_rel section.  */
7417       if (SGI_COMPAT (abfd))
7418         {
7419           if (!mips_elf_create_compact_rel_section (abfd, info))
7420             return FALSE;
7421         }
7422
7423       /* Change alignments of some sections.  */
7424       s = bfd_get_linker_section (abfd, ".hash");
7425       if (s != NULL)
7426         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7427
7428       s = bfd_get_linker_section (abfd, ".dynsym");
7429       if (s != NULL)
7430         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7431
7432       s = bfd_get_linker_section (abfd, ".dynstr");
7433       if (s != NULL)
7434         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7435
7436       /* ??? */
7437       s = bfd_get_section_by_name (abfd, ".reginfo");
7438       if (s != NULL)
7439         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7440
7441       s = bfd_get_linker_section (abfd, ".dynamic");
7442       if (s != NULL)
7443         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7444     }
7445
7446   if (!info->shared)
7447     {
7448       const char *name;
7449
7450       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7451       bh = NULL;
7452       if (!(_bfd_generic_link_add_one_symbol
7453             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7454              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7455         return FALSE;
7456
7457       h = (struct elf_link_hash_entry *) bh;
7458       h->non_elf = 0;
7459       h->def_regular = 1;
7460       h->type = STT_SECTION;
7461
7462       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7463         return FALSE;
7464
7465       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7466         {
7467           /* __rld_map is a four byte word located in the .data section
7468              and is filled in by the rtld to contain a pointer to
7469              the _r_debug structure. Its symbol value will be set in
7470              _bfd_mips_elf_finish_dynamic_symbol.  */
7471           s = bfd_get_linker_section (abfd, ".rld_map");
7472           BFD_ASSERT (s != NULL);
7473
7474           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7475           bh = NULL;
7476           if (!(_bfd_generic_link_add_one_symbol
7477                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7478                  get_elf_backend_data (abfd)->collect, &bh)))
7479             return FALSE;
7480
7481           h = (struct elf_link_hash_entry *) bh;
7482           h->non_elf = 0;
7483           h->def_regular = 1;
7484           h->type = STT_OBJECT;
7485
7486           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7487             return FALSE;
7488           mips_elf_hash_table (info)->rld_symbol = h;
7489         }
7490     }
7491
7492   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7493      Also, on VxWorks, create the _PROCEDURE_LINKAGE_TABLE_ symbol.  */
7494   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7495     return FALSE;
7496
7497   /* Cache the sections created above.  */
7498   htab->splt = bfd_get_linker_section (abfd, ".plt");
7499   htab->sdynbss = bfd_get_linker_section (abfd, ".dynbss");
7500   if (htab->is_vxworks)
7501     {
7502       htab->srelbss = bfd_get_linker_section (abfd, ".rela.bss");
7503       htab->srelplt = bfd_get_linker_section (abfd, ".rela.plt");
7504     }
7505   else
7506     htab->srelplt = bfd_get_linker_section (abfd, ".rel.plt");
7507   if (!htab->sdynbss
7508       || (htab->is_vxworks && !htab->srelbss && !info->shared)
7509       || !htab->srelplt
7510       || !htab->splt)
7511     abort ();
7512
7513   /* Do the usual VxWorks handling.  */
7514   if (htab->is_vxworks
7515       && !elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7516     return FALSE;
7517
7518   return TRUE;
7519 }
7520 \f
7521 /* Return true if relocation REL against section SEC is a REL rather than
7522    RELA relocation.  RELOCS is the first relocation in the section and
7523    ABFD is the bfd that contains SEC.  */
7524
7525 static bfd_boolean
7526 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7527                            const Elf_Internal_Rela *relocs,
7528                            const Elf_Internal_Rela *rel)
7529 {
7530   Elf_Internal_Shdr *rel_hdr;
7531   const struct elf_backend_data *bed;
7532
7533   /* To determine which flavor of relocation this is, we depend on the
7534      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7535   rel_hdr = elf_section_data (sec)->rel.hdr;
7536   if (rel_hdr == NULL)
7537     return FALSE;
7538   bed = get_elf_backend_data (abfd);
7539   return ((size_t) (rel - relocs)
7540           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7541 }
7542
7543 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7544    HOWTO is the relocation's howto and CONTENTS points to the contents
7545    of the section that REL is against.  */
7546
7547 static bfd_vma
7548 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7549                           reloc_howto_type *howto, bfd_byte *contents)
7550 {
7551   bfd_byte *location;
7552   unsigned int r_type;
7553   bfd_vma addend;
7554
7555   r_type = ELF_R_TYPE (abfd, rel->r_info);
7556   location = contents + rel->r_offset;
7557
7558   /* Get the addend, which is stored in the input file.  */
7559   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7560   addend = mips_elf_obtain_contents (howto, rel, abfd, contents);
7561   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7562
7563   return addend & howto->src_mask;
7564 }
7565
7566 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7567    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7568    and update *ADDEND with the final addend.  Return true on success
7569    or false if the LO16 could not be found.  RELEND is the exclusive
7570    upper bound on the relocations for REL's section.  */
7571
7572 static bfd_boolean
7573 mips_elf_add_lo16_rel_addend (bfd *abfd,
7574                               const Elf_Internal_Rela *rel,
7575                               const Elf_Internal_Rela *relend,
7576                               bfd_byte *contents, bfd_vma *addend)
7577 {
7578   unsigned int r_type, lo16_type;
7579   const Elf_Internal_Rela *lo16_relocation;
7580   reloc_howto_type *lo16_howto;
7581   bfd_vma l;
7582
7583   r_type = ELF_R_TYPE (abfd, rel->r_info);
7584   if (mips16_reloc_p (r_type))
7585     lo16_type = R_MIPS16_LO16;
7586   else if (micromips_reloc_p (r_type))
7587     lo16_type = R_MICROMIPS_LO16;
7588   else
7589     lo16_type = R_MIPS_LO16;
7590
7591   /* The combined value is the sum of the HI16 addend, left-shifted by
7592      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7593      code does a `lui' of the HI16 value, and then an `addiu' of the
7594      LO16 value.)
7595
7596      Scan ahead to find a matching LO16 relocation.
7597
7598      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7599      be immediately following.  However, for the IRIX6 ABI, the next
7600      relocation may be a composed relocation consisting of several
7601      relocations for the same address.  In that case, the R_MIPS_LO16
7602      relocation may occur as one of these.  We permit a similar
7603      extension in general, as that is useful for GCC.
7604
7605      In some cases GCC dead code elimination removes the LO16 but keeps
7606      the corresponding HI16.  This is strictly speaking a violation of
7607      the ABI but not immediately harmful.  */
7608   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
7609   if (lo16_relocation == NULL)
7610     return FALSE;
7611
7612   /* Obtain the addend kept there.  */
7613   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
7614   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
7615
7616   l <<= lo16_howto->rightshift;
7617   l = _bfd_mips_elf_sign_extend (l, 16);
7618
7619   *addend <<= 16;
7620   *addend += l;
7621   return TRUE;
7622 }
7623
7624 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
7625    store the contents in *CONTENTS on success.  Assume that *CONTENTS
7626    already holds the contents if it is nonull on entry.  */
7627
7628 static bfd_boolean
7629 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
7630 {
7631   if (*contents)
7632     return TRUE;
7633
7634   /* Get cached copy if it exists.  */
7635   if (elf_section_data (sec)->this_hdr.contents != NULL)
7636     {
7637       *contents = elf_section_data (sec)->this_hdr.contents;
7638       return TRUE;
7639     }
7640
7641   return bfd_malloc_and_get_section (abfd, sec, contents);
7642 }
7643
7644 /* Make a new PLT record to keep internal data.  */
7645
7646 static struct plt_entry *
7647 mips_elf_make_plt_record (bfd *abfd)
7648 {
7649   struct plt_entry *entry;
7650
7651   entry = bfd_zalloc (abfd, sizeof (*entry));
7652   if (entry == NULL)
7653     return NULL;
7654
7655   entry->stub_offset = MINUS_ONE;
7656   entry->mips_offset = MINUS_ONE;
7657   entry->comp_offset = MINUS_ONE;
7658   entry->gotplt_index = MINUS_ONE;
7659   return entry;
7660 }
7661
7662 /* Look through the relocs for a section during the first phase, and
7663    allocate space in the global offset table and record the need for
7664    standard MIPS and compressed procedure linkage table entries.  */
7665
7666 bfd_boolean
7667 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
7668                             asection *sec, const Elf_Internal_Rela *relocs)
7669 {
7670   const char *name;
7671   bfd *dynobj;
7672   Elf_Internal_Shdr *symtab_hdr;
7673   struct elf_link_hash_entry **sym_hashes;
7674   size_t extsymoff;
7675   const Elf_Internal_Rela *rel;
7676   const Elf_Internal_Rela *rel_end;
7677   asection *sreloc;
7678   const struct elf_backend_data *bed;
7679   struct mips_elf_link_hash_table *htab;
7680   bfd_byte *contents;
7681   bfd_vma addend;
7682   reloc_howto_type *howto;
7683
7684   if (info->relocatable)
7685     return TRUE;
7686
7687   htab = mips_elf_hash_table (info);
7688   BFD_ASSERT (htab != NULL);
7689
7690   dynobj = elf_hash_table (info)->dynobj;
7691   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7692   sym_hashes = elf_sym_hashes (abfd);
7693   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
7694
7695   bed = get_elf_backend_data (abfd);
7696   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
7697
7698   /* Check for the mips16 stub sections.  */
7699
7700   name = bfd_get_section_name (abfd, sec);
7701   if (FN_STUB_P (name))
7702     {
7703       unsigned long r_symndx;
7704
7705       /* Look at the relocation information to figure out which symbol
7706          this is for.  */
7707
7708       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7709       if (r_symndx == 0)
7710         {
7711           (*_bfd_error_handler)
7712             (_("%B: Warning: cannot determine the target function for"
7713                " stub section `%s'"),
7714              abfd, name);
7715           bfd_set_error (bfd_error_bad_value);
7716           return FALSE;
7717         }
7718
7719       if (r_symndx < extsymoff
7720           || sym_hashes[r_symndx - extsymoff] == NULL)
7721         {
7722           asection *o;
7723
7724           /* This stub is for a local symbol.  This stub will only be
7725              needed if there is some relocation in this BFD, other
7726              than a 16 bit function call, which refers to this symbol.  */
7727           for (o = abfd->sections; o != NULL; o = o->next)
7728             {
7729               Elf_Internal_Rela *sec_relocs;
7730               const Elf_Internal_Rela *r, *rend;
7731
7732               /* We can ignore stub sections when looking for relocs.  */
7733               if ((o->flags & SEC_RELOC) == 0
7734                   || o->reloc_count == 0
7735                   || section_allows_mips16_refs_p (o))
7736                 continue;
7737
7738               sec_relocs
7739                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7740                                              info->keep_memory);
7741               if (sec_relocs == NULL)
7742                 return FALSE;
7743
7744               rend = sec_relocs + o->reloc_count;
7745               for (r = sec_relocs; r < rend; r++)
7746                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7747                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
7748                   break;
7749
7750               if (elf_section_data (o)->relocs != sec_relocs)
7751                 free (sec_relocs);
7752
7753               if (r < rend)
7754                 break;
7755             }
7756
7757           if (o == NULL)
7758             {
7759               /* There is no non-call reloc for this stub, so we do
7760                  not need it.  Since this function is called before
7761                  the linker maps input sections to output sections, we
7762                  can easily discard it by setting the SEC_EXCLUDE
7763                  flag.  */
7764               sec->flags |= SEC_EXCLUDE;
7765               return TRUE;
7766             }
7767
7768           /* Record this stub in an array of local symbol stubs for
7769              this BFD.  */
7770           if (mips_elf_tdata (abfd)->local_stubs == NULL)
7771             {
7772               unsigned long symcount;
7773               asection **n;
7774               bfd_size_type amt;
7775
7776               if (elf_bad_symtab (abfd))
7777                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7778               else
7779                 symcount = symtab_hdr->sh_info;
7780               amt = symcount * sizeof (asection *);
7781               n = bfd_zalloc (abfd, amt);
7782               if (n == NULL)
7783                 return FALSE;
7784               mips_elf_tdata (abfd)->local_stubs = n;
7785             }
7786
7787           sec->flags |= SEC_KEEP;
7788           mips_elf_tdata (abfd)->local_stubs[r_symndx] = sec;
7789
7790           /* We don't need to set mips16_stubs_seen in this case.
7791              That flag is used to see whether we need to look through
7792              the global symbol table for stubs.  We don't need to set
7793              it here, because we just have a local stub.  */
7794         }
7795       else
7796         {
7797           struct mips_elf_link_hash_entry *h;
7798
7799           h = ((struct mips_elf_link_hash_entry *)
7800                sym_hashes[r_symndx - extsymoff]);
7801
7802           while (h->root.root.type == bfd_link_hash_indirect
7803                  || h->root.root.type == bfd_link_hash_warning)
7804             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
7805
7806           /* H is the symbol this stub is for.  */
7807
7808           /* If we already have an appropriate stub for this function, we
7809              don't need another one, so we can discard this one.  Since
7810              this function is called before the linker maps input sections
7811              to output sections, we can easily discard it by setting the
7812              SEC_EXCLUDE flag.  */
7813           if (h->fn_stub != NULL)
7814             {
7815               sec->flags |= SEC_EXCLUDE;
7816               return TRUE;
7817             }
7818
7819           sec->flags |= SEC_KEEP;
7820           h->fn_stub = sec;
7821           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7822         }
7823     }
7824   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
7825     {
7826       unsigned long r_symndx;
7827       struct mips_elf_link_hash_entry *h;
7828       asection **loc;
7829
7830       /* Look at the relocation information to figure out which symbol
7831          this is for.  */
7832
7833       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7834       if (r_symndx == 0)
7835         {
7836           (*_bfd_error_handler)
7837             (_("%B: Warning: cannot determine the target function for"
7838                " stub section `%s'"),
7839              abfd, name);
7840           bfd_set_error (bfd_error_bad_value);
7841           return FALSE;
7842         }
7843
7844       if (r_symndx < extsymoff
7845           || sym_hashes[r_symndx - extsymoff] == NULL)
7846         {
7847           asection *o;
7848
7849           /* This stub is for a local symbol.  This stub will only be
7850              needed if there is some relocation (R_MIPS16_26) in this BFD
7851              that refers to this symbol.  */
7852           for (o = abfd->sections; o != NULL; o = o->next)
7853             {
7854               Elf_Internal_Rela *sec_relocs;
7855               const Elf_Internal_Rela *r, *rend;
7856
7857               /* We can ignore stub sections when looking for relocs.  */
7858               if ((o->flags & SEC_RELOC) == 0
7859                   || o->reloc_count == 0
7860                   || section_allows_mips16_refs_p (o))
7861                 continue;
7862
7863               sec_relocs
7864                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7865                                              info->keep_memory);
7866               if (sec_relocs == NULL)
7867                 return FALSE;
7868
7869               rend = sec_relocs + o->reloc_count;
7870               for (r = sec_relocs; r < rend; r++)
7871                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7872                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
7873                     break;
7874
7875               if (elf_section_data (o)->relocs != sec_relocs)
7876                 free (sec_relocs);
7877
7878               if (r < rend)
7879                 break;
7880             }
7881
7882           if (o == NULL)
7883             {
7884               /* There is no non-call reloc for this stub, so we do
7885                  not need it.  Since this function is called before
7886                  the linker maps input sections to output sections, we
7887                  can easily discard it by setting the SEC_EXCLUDE
7888                  flag.  */
7889               sec->flags |= SEC_EXCLUDE;
7890               return TRUE;
7891             }
7892
7893           /* Record this stub in an array of local symbol call_stubs for
7894              this BFD.  */
7895           if (mips_elf_tdata (abfd)->local_call_stubs == NULL)
7896             {
7897               unsigned long symcount;
7898               asection **n;
7899               bfd_size_type amt;
7900
7901               if (elf_bad_symtab (abfd))
7902                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7903               else
7904                 symcount = symtab_hdr->sh_info;
7905               amt = symcount * sizeof (asection *);
7906               n = bfd_zalloc (abfd, amt);
7907               if (n == NULL)
7908                 return FALSE;
7909               mips_elf_tdata (abfd)->local_call_stubs = n;
7910             }
7911
7912           sec->flags |= SEC_KEEP;
7913           mips_elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
7914
7915           /* We don't need to set mips16_stubs_seen in this case.
7916              That flag is used to see whether we need to look through
7917              the global symbol table for stubs.  We don't need to set
7918              it here, because we just have a local stub.  */
7919         }
7920       else
7921         {
7922           h = ((struct mips_elf_link_hash_entry *)
7923                sym_hashes[r_symndx - extsymoff]);
7924
7925           /* H is the symbol this stub is for.  */
7926
7927           if (CALL_FP_STUB_P (name))
7928             loc = &h->call_fp_stub;
7929           else
7930             loc = &h->call_stub;
7931
7932           /* If we already have an appropriate stub for this function, we
7933              don't need another one, so we can discard this one.  Since
7934              this function is called before the linker maps input sections
7935              to output sections, we can easily discard it by setting the
7936              SEC_EXCLUDE flag.  */
7937           if (*loc != NULL)
7938             {
7939               sec->flags |= SEC_EXCLUDE;
7940               return TRUE;
7941             }
7942
7943           sec->flags |= SEC_KEEP;
7944           *loc = sec;
7945           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7946         }
7947     }
7948
7949   sreloc = NULL;
7950   contents = NULL;
7951   for (rel = relocs; rel < rel_end; ++rel)
7952     {
7953       unsigned long r_symndx;
7954       unsigned int r_type;
7955       struct elf_link_hash_entry *h;
7956       bfd_boolean can_make_dynamic_p;
7957
7958       r_symndx = ELF_R_SYM (abfd, rel->r_info);
7959       r_type = ELF_R_TYPE (abfd, rel->r_info);
7960
7961       if (r_symndx < extsymoff)
7962         h = NULL;
7963       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
7964         {
7965           (*_bfd_error_handler)
7966             (_("%B: Malformed reloc detected for section %s"),
7967              abfd, name);
7968           bfd_set_error (bfd_error_bad_value);
7969           return FALSE;
7970         }
7971       else
7972         {
7973           h = sym_hashes[r_symndx - extsymoff];
7974           if (h != NULL)
7975             {
7976               while (h->root.type == bfd_link_hash_indirect
7977                      || h->root.type == bfd_link_hash_warning)
7978                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
7979
7980               /* PR15323, ref flags aren't set for references in the
7981                  same object.  */
7982               h->root.non_ir_ref = 1;
7983             }
7984         }
7985
7986       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
7987          relocation into a dynamic one.  */
7988       can_make_dynamic_p = FALSE;
7989       switch (r_type)
7990         {
7991         case R_MIPS_GOT16:
7992         case R_MIPS_CALL16:
7993         case R_MIPS_CALL_HI16:
7994         case R_MIPS_CALL_LO16:
7995         case R_MIPS_GOT_HI16:
7996         case R_MIPS_GOT_LO16:
7997         case R_MIPS_GOT_PAGE:
7998         case R_MIPS_GOT_OFST:
7999         case R_MIPS_GOT_DISP:
8000         case R_MIPS_TLS_GOTTPREL:
8001         case R_MIPS_TLS_GD:
8002         case R_MIPS_TLS_LDM:
8003         case R_MIPS16_GOT16:
8004         case R_MIPS16_CALL16:
8005         case R_MIPS16_TLS_GOTTPREL:
8006         case R_MIPS16_TLS_GD:
8007         case R_MIPS16_TLS_LDM:
8008         case R_MICROMIPS_GOT16:
8009         case R_MICROMIPS_CALL16:
8010         case R_MICROMIPS_CALL_HI16:
8011         case R_MICROMIPS_CALL_LO16:
8012         case R_MICROMIPS_GOT_HI16:
8013         case R_MICROMIPS_GOT_LO16:
8014         case R_MICROMIPS_GOT_PAGE:
8015         case R_MICROMIPS_GOT_OFST:
8016         case R_MICROMIPS_GOT_DISP:
8017         case R_MICROMIPS_TLS_GOTTPREL:
8018         case R_MICROMIPS_TLS_GD:
8019         case R_MICROMIPS_TLS_LDM:
8020           if (dynobj == NULL)
8021             elf_hash_table (info)->dynobj = dynobj = abfd;
8022           if (!mips_elf_create_got_section (dynobj, info))
8023             return FALSE;
8024           if (htab->is_vxworks && !info->shared)
8025             {
8026               (*_bfd_error_handler)
8027                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
8028                  abfd, (unsigned long) rel->r_offset);
8029               bfd_set_error (bfd_error_bad_value);
8030               return FALSE;
8031             }
8032           break;
8033
8034           /* This is just a hint; it can safely be ignored.  Don't set
8035              has_static_relocs for the corresponding symbol.  */
8036         case R_MIPS_JALR:
8037         case R_MICROMIPS_JALR:
8038           break;
8039
8040         case R_MIPS_32:
8041         case R_MIPS_REL32:
8042         case R_MIPS_64:
8043           /* In VxWorks executables, references to external symbols
8044              must be handled using copy relocs or PLT entries; it is not
8045              possible to convert this relocation into a dynamic one.
8046
8047              For executables that use PLTs and copy-relocs, we have a
8048              choice between converting the relocation into a dynamic
8049              one or using copy relocations or PLT entries.  It is
8050              usually better to do the former, unless the relocation is
8051              against a read-only section.  */
8052           if ((info->shared
8053                || (h != NULL
8054                    && !htab->is_vxworks
8055                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
8056                    && !(!info->nocopyreloc
8057                         && !PIC_OBJECT_P (abfd)
8058                         && MIPS_ELF_READONLY_SECTION (sec))))
8059               && (sec->flags & SEC_ALLOC) != 0)
8060             {
8061               can_make_dynamic_p = TRUE;
8062               if (dynobj == NULL)
8063                 elf_hash_table (info)->dynobj = dynobj = abfd;
8064               break;
8065             }
8066           /* For sections that are not SEC_ALLOC a copy reloc would be
8067              output if possible (implying questionable semantics for
8068              read-only data objects) or otherwise the final link would
8069              fail as ld.so will not process them and could not therefore
8070              handle any outstanding dynamic relocations.
8071
8072              For such sections that are also SEC_DEBUGGING, we can avoid
8073              these problems by simply ignoring any relocs as these
8074              sections have a predefined use and we know it is safe to do
8075              so.
8076
8077              This is needed in cases such as a global symbol definition
8078              in a shared library causing a common symbol from an object
8079              file to be converted to an undefined reference.  If that
8080              happens, then all the relocations against this symbol from
8081              SEC_DEBUGGING sections in the object file will resolve to
8082              nil.  */
8083           if ((sec->flags & SEC_DEBUGGING) != 0)
8084             break;
8085           /* Fall through.  */
8086
8087         default:
8088           /* Most static relocations require pointer equality, except
8089              for branches.  */
8090           if (h)
8091             h->pointer_equality_needed = TRUE;
8092           /* Fall through.  */
8093
8094         case R_MIPS_26:
8095         case R_MIPS_PC16:
8096         case R_MIPS16_26:
8097         case R_MICROMIPS_26_S1:
8098         case R_MICROMIPS_PC7_S1:
8099         case R_MICROMIPS_PC10_S1:
8100         case R_MICROMIPS_PC16_S1:
8101         case R_MICROMIPS_PC23_S2:
8102           if (h)
8103             ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = TRUE;
8104           break;
8105         }
8106
8107       if (h)
8108         {
8109           /* Relocations against the special VxWorks __GOTT_BASE__ and
8110              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
8111              room for them in .rela.dyn.  */
8112           if (is_gott_symbol (info, h))
8113             {
8114               if (sreloc == NULL)
8115                 {
8116                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8117                   if (sreloc == NULL)
8118                     return FALSE;
8119                 }
8120               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8121               if (MIPS_ELF_READONLY_SECTION (sec))
8122                 /* We tell the dynamic linker that there are
8123                    relocations against the text segment.  */
8124                 info->flags |= DF_TEXTREL;
8125             }
8126         }
8127       else if (call_lo16_reloc_p (r_type)
8128                || got_lo16_reloc_p (r_type)
8129                || got_disp_reloc_p (r_type)
8130                || (got16_reloc_p (r_type) && htab->is_vxworks))
8131         {
8132           /* We may need a local GOT entry for this relocation.  We
8133              don't count R_MIPS_GOT_PAGE because we can estimate the
8134              maximum number of pages needed by looking at the size of
8135              the segment.  Similar comments apply to R_MIPS*_GOT16 and
8136              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
8137              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
8138              R_MIPS_CALL_HI16 because these are always followed by an
8139              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
8140           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8141                                                  rel->r_addend, info, r_type))
8142             return FALSE;
8143         }
8144
8145       if (h != NULL
8146           && mips_elf_relocation_needs_la25_stub (abfd, r_type,
8147                                                   ELF_ST_IS_MIPS16 (h->other)))
8148         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
8149
8150       switch (r_type)
8151         {
8152         case R_MIPS_CALL16:
8153         case R_MIPS16_CALL16:
8154         case R_MICROMIPS_CALL16:
8155           if (h == NULL)
8156             {
8157               (*_bfd_error_handler)
8158                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
8159                  abfd, (unsigned long) rel->r_offset);
8160               bfd_set_error (bfd_error_bad_value);
8161               return FALSE;
8162             }
8163           /* Fall through.  */
8164
8165         case R_MIPS_CALL_HI16:
8166         case R_MIPS_CALL_LO16:
8167         case R_MICROMIPS_CALL_HI16:
8168         case R_MICROMIPS_CALL_LO16:
8169           if (h != NULL)
8170             {
8171               /* Make sure there is room in the regular GOT to hold the
8172                  function's address.  We may eliminate it in favour of
8173                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
8174               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE,
8175                                                       r_type))
8176                 return FALSE;
8177
8178               /* We need a stub, not a plt entry for the undefined
8179                  function.  But we record it as if it needs plt.  See
8180                  _bfd_elf_adjust_dynamic_symbol.  */
8181               h->needs_plt = 1;
8182               h->type = STT_FUNC;
8183             }
8184           break;
8185
8186         case R_MIPS_GOT_PAGE:
8187         case R_MICROMIPS_GOT_PAGE:
8188         case R_MIPS16_GOT16:
8189         case R_MIPS_GOT16:
8190         case R_MIPS_GOT_HI16:
8191         case R_MIPS_GOT_LO16:
8192         case R_MICROMIPS_GOT16:
8193         case R_MICROMIPS_GOT_HI16:
8194         case R_MICROMIPS_GOT_LO16:
8195           if (!h || got_page_reloc_p (r_type))
8196             {
8197               /* This relocation needs (or may need, if h != NULL) a
8198                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
8199                  know for sure until we know whether the symbol is
8200                  preemptible.  */
8201               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
8202                 {
8203                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
8204                     return FALSE;
8205                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8206                   addend = mips_elf_read_rel_addend (abfd, rel,
8207                                                      howto, contents);
8208                   if (got16_reloc_p (r_type))
8209                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
8210                                                   contents, &addend);
8211                   else
8212                     addend <<= howto->rightshift;
8213                 }
8214               else
8215                 addend = rel->r_addend;
8216               if (!mips_elf_record_got_page_ref (info, abfd, r_symndx,
8217                                                  h, addend))
8218                 return FALSE;
8219
8220               if (h)
8221                 {
8222                   struct mips_elf_link_hash_entry *hmips =
8223                     (struct mips_elf_link_hash_entry *) h;
8224
8225                   /* This symbol is definitely not overridable.  */
8226                   if (hmips->root.def_regular
8227                       && ! (info->shared && ! info->symbolic
8228                             && ! hmips->root.forced_local))
8229                     h = NULL;
8230                 }
8231             }
8232           /* If this is a global, overridable symbol, GOT_PAGE will
8233              decay to GOT_DISP, so we'll need a GOT entry for it.  */
8234           /* Fall through.  */
8235
8236         case R_MIPS_GOT_DISP:
8237         case R_MICROMIPS_GOT_DISP:
8238           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8239                                                        FALSE, r_type))
8240             return FALSE;
8241           break;
8242
8243         case R_MIPS_TLS_GOTTPREL:
8244         case R_MIPS16_TLS_GOTTPREL:
8245         case R_MICROMIPS_TLS_GOTTPREL:
8246           if (info->shared)
8247             info->flags |= DF_STATIC_TLS;
8248           /* Fall through */
8249
8250         case R_MIPS_TLS_LDM:
8251         case R_MIPS16_TLS_LDM:
8252         case R_MICROMIPS_TLS_LDM:
8253           if (tls_ldm_reloc_p (r_type))
8254             {
8255               r_symndx = STN_UNDEF;
8256               h = NULL;
8257             }
8258           /* Fall through */
8259
8260         case R_MIPS_TLS_GD:
8261         case R_MIPS16_TLS_GD:
8262         case R_MICROMIPS_TLS_GD:
8263           /* This symbol requires a global offset table entry, or two
8264              for TLS GD relocations.  */
8265           if (h != NULL)
8266             {
8267               if (!mips_elf_record_global_got_symbol (h, abfd, info,
8268                                                       FALSE, r_type))
8269                 return FALSE;
8270             }
8271           else
8272             {
8273               if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8274                                                      rel->r_addend,
8275                                                      info, r_type))
8276                 return FALSE;
8277             }
8278           break;
8279
8280         case R_MIPS_32:
8281         case R_MIPS_REL32:
8282         case R_MIPS_64:
8283           /* In VxWorks executables, references to external symbols
8284              are handled using copy relocs or PLT stubs, so there's
8285              no need to add a .rela.dyn entry for this relocation.  */
8286           if (can_make_dynamic_p)
8287             {
8288               if (sreloc == NULL)
8289                 {
8290                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8291                   if (sreloc == NULL)
8292                     return FALSE;
8293                 }
8294               if (info->shared && h == NULL)
8295                 {
8296                   /* When creating a shared object, we must copy these
8297                      reloc types into the output file as R_MIPS_REL32
8298                      relocs.  Make room for this reloc in .rel(a).dyn.  */
8299                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8300                   if (MIPS_ELF_READONLY_SECTION (sec))
8301                     /* We tell the dynamic linker that there are
8302                        relocations against the text segment.  */
8303                     info->flags |= DF_TEXTREL;
8304                 }
8305               else
8306                 {
8307                   struct mips_elf_link_hash_entry *hmips;
8308
8309                   /* For a shared object, we must copy this relocation
8310                      unless the symbol turns out to be undefined and
8311                      weak with non-default visibility, in which case
8312                      it will be left as zero.
8313
8314                      We could elide R_MIPS_REL32 for locally binding symbols
8315                      in shared libraries, but do not yet do so.
8316
8317                      For an executable, we only need to copy this
8318                      reloc if the symbol is defined in a dynamic
8319                      object.  */
8320                   hmips = (struct mips_elf_link_hash_entry *) h;
8321                   ++hmips->possibly_dynamic_relocs;
8322                   if (MIPS_ELF_READONLY_SECTION (sec))
8323                     /* We need it to tell the dynamic linker if there
8324                        are relocations against the text segment.  */
8325                     hmips->readonly_reloc = TRUE;
8326                 }
8327             }
8328
8329           if (SGI_COMPAT (abfd))
8330             mips_elf_hash_table (info)->compact_rel_size +=
8331               sizeof (Elf32_External_crinfo);
8332           break;
8333
8334         case R_MIPS_26:
8335         case R_MIPS_GPREL16:
8336         case R_MIPS_LITERAL:
8337         case R_MIPS_GPREL32:
8338         case R_MICROMIPS_26_S1:
8339         case R_MICROMIPS_GPREL16:
8340         case R_MICROMIPS_LITERAL:
8341         case R_MICROMIPS_GPREL7_S2:
8342           if (SGI_COMPAT (abfd))
8343             mips_elf_hash_table (info)->compact_rel_size +=
8344               sizeof (Elf32_External_crinfo);
8345           break;
8346
8347           /* This relocation describes the C++ object vtable hierarchy.
8348              Reconstruct it for later use during GC.  */
8349         case R_MIPS_GNU_VTINHERIT:
8350           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
8351             return FALSE;
8352           break;
8353
8354           /* This relocation describes which C++ vtable entries are actually
8355              used.  Record for later use during GC.  */
8356         case R_MIPS_GNU_VTENTRY:
8357           BFD_ASSERT (h != NULL);
8358           if (h != NULL
8359               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
8360             return FALSE;
8361           break;
8362
8363         default:
8364           break;
8365         }
8366
8367       /* Record the need for a PLT entry.  At this point we don't know
8368          yet if we are going to create a PLT in the first place, but
8369          we only record whether the relocation requires a standard MIPS
8370          or a compressed code entry anyway.  If we don't make a PLT after
8371          all, then we'll just ignore these arrangements.  Likewise if
8372          a PLT entry is not created because the symbol is satisfied
8373          locally.  */
8374       if (h != NULL
8375           && jal_reloc_p (r_type)
8376           && !SYMBOL_CALLS_LOCAL (info, h))
8377         {
8378           if (h->plt.plist == NULL)
8379             h->plt.plist = mips_elf_make_plt_record (abfd);
8380           if (h->plt.plist == NULL)
8381             return FALSE;
8382
8383           if (r_type == R_MIPS_26)
8384             h->plt.plist->need_mips = TRUE;
8385           else
8386             h->plt.plist->need_comp = TRUE;
8387         }
8388
8389       /* We must not create a stub for a symbol that has relocations
8390          related to taking the function's address.  This doesn't apply to
8391          VxWorks, where CALL relocs refer to a .got.plt entry instead of
8392          a normal .got entry.  */
8393       if (!htab->is_vxworks && h != NULL)
8394         switch (r_type)
8395           {
8396           default:
8397             ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8398             break;
8399           case R_MIPS16_CALL16:
8400           case R_MIPS_CALL16:
8401           case R_MIPS_CALL_HI16:
8402           case R_MIPS_CALL_LO16:
8403           case R_MIPS_JALR:
8404           case R_MICROMIPS_CALL16:
8405           case R_MICROMIPS_CALL_HI16:
8406           case R_MICROMIPS_CALL_LO16:
8407           case R_MICROMIPS_JALR:
8408             break;
8409           }
8410
8411       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8412          if there is one.  We only need to handle global symbols here;
8413          we decide whether to keep or delete stubs for local symbols
8414          when processing the stub's relocations.  */
8415       if (h != NULL
8416           && !mips16_call_reloc_p (r_type)
8417           && !section_allows_mips16_refs_p (sec))
8418         {
8419           struct mips_elf_link_hash_entry *mh;
8420
8421           mh = (struct mips_elf_link_hash_entry *) h;
8422           mh->need_fn_stub = TRUE;
8423         }
8424
8425       /* Refuse some position-dependent relocations when creating a
8426          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8427          not PIC, but we can create dynamic relocations and the result
8428          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8429          combined with R_MIPS_GOT16.  */
8430       if (info->shared)
8431         {
8432           switch (r_type)
8433             {
8434             case R_MIPS16_HI16:
8435             case R_MIPS_HI16:
8436             case R_MIPS_HIGHER:
8437             case R_MIPS_HIGHEST:
8438             case R_MICROMIPS_HI16:
8439             case R_MICROMIPS_HIGHER:
8440             case R_MICROMIPS_HIGHEST:
8441               /* Don't refuse a high part relocation if it's against
8442                  no symbol (e.g. part of a compound relocation).  */
8443               if (r_symndx == STN_UNDEF)
8444                 break;
8445
8446               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8447                  and has a special meaning.  */
8448               if (!NEWABI_P (abfd) && h != NULL
8449                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8450                 break;
8451
8452               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8453               if (is_gott_symbol (info, h))
8454                 break;
8455
8456               /* FALLTHROUGH */
8457
8458             case R_MIPS16_26:
8459             case R_MIPS_26:
8460             case R_MICROMIPS_26_S1:
8461               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8462               (*_bfd_error_handler)
8463                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8464                  abfd, howto->name,
8465                  (h) ? h->root.root.string : "a local symbol");
8466               bfd_set_error (bfd_error_bad_value);
8467               return FALSE;
8468             default:
8469               break;
8470             }
8471         }
8472     }
8473
8474   return TRUE;
8475 }
8476 \f
8477 bfd_boolean
8478 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8479                          struct bfd_link_info *link_info,
8480                          bfd_boolean *again)
8481 {
8482   Elf_Internal_Rela *internal_relocs;
8483   Elf_Internal_Rela *irel, *irelend;
8484   Elf_Internal_Shdr *symtab_hdr;
8485   bfd_byte *contents = NULL;
8486   size_t extsymoff;
8487   bfd_boolean changed_contents = FALSE;
8488   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8489   Elf_Internal_Sym *isymbuf = NULL;
8490
8491   /* We are not currently changing any sizes, so only one pass.  */
8492   *again = FALSE;
8493
8494   if (link_info->relocatable)
8495     return TRUE;
8496
8497   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8498                                                link_info->keep_memory);
8499   if (internal_relocs == NULL)
8500     return TRUE;
8501
8502   irelend = internal_relocs + sec->reloc_count
8503     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8504   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8505   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8506
8507   for (irel = internal_relocs; irel < irelend; irel++)
8508     {
8509       bfd_vma symval;
8510       bfd_signed_vma sym_offset;
8511       unsigned int r_type;
8512       unsigned long r_symndx;
8513       asection *sym_sec;
8514       unsigned long instruction;
8515
8516       /* Turn jalr into bgezal, and jr into beq, if they're marked
8517          with a JALR relocation, that indicate where they jump to.
8518          This saves some pipeline bubbles.  */
8519       r_type = ELF_R_TYPE (abfd, irel->r_info);
8520       if (r_type != R_MIPS_JALR)
8521         continue;
8522
8523       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8524       /* Compute the address of the jump target.  */
8525       if (r_symndx >= extsymoff)
8526         {
8527           struct mips_elf_link_hash_entry *h
8528             = ((struct mips_elf_link_hash_entry *)
8529                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8530
8531           while (h->root.root.type == bfd_link_hash_indirect
8532                  || h->root.root.type == bfd_link_hash_warning)
8533             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8534
8535           /* If a symbol is undefined, or if it may be overridden,
8536              skip it.  */
8537           if (! ((h->root.root.type == bfd_link_hash_defined
8538                   || h->root.root.type == bfd_link_hash_defweak)
8539                  && h->root.root.u.def.section)
8540               || (link_info->shared && ! link_info->symbolic
8541                   && !h->root.forced_local))
8542             continue;
8543
8544           sym_sec = h->root.root.u.def.section;
8545           if (sym_sec->output_section)
8546             symval = (h->root.root.u.def.value
8547                       + sym_sec->output_section->vma
8548                       + sym_sec->output_offset);
8549           else
8550             symval = h->root.root.u.def.value;
8551         }
8552       else
8553         {
8554           Elf_Internal_Sym *isym;
8555
8556           /* Read this BFD's symbols if we haven't done so already.  */
8557           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8558             {
8559               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8560               if (isymbuf == NULL)
8561                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8562                                                 symtab_hdr->sh_info, 0,
8563                                                 NULL, NULL, NULL);
8564               if (isymbuf == NULL)
8565                 goto relax_return;
8566             }
8567
8568           isym = isymbuf + r_symndx;
8569           if (isym->st_shndx == SHN_UNDEF)
8570             continue;
8571           else if (isym->st_shndx == SHN_ABS)
8572             sym_sec = bfd_abs_section_ptr;
8573           else if (isym->st_shndx == SHN_COMMON)
8574             sym_sec = bfd_com_section_ptr;
8575           else
8576             sym_sec
8577               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8578           symval = isym->st_value
8579             + sym_sec->output_section->vma
8580             + sym_sec->output_offset;
8581         }
8582
8583       /* Compute branch offset, from delay slot of the jump to the
8584          branch target.  */
8585       sym_offset = (symval + irel->r_addend)
8586         - (sec_start + irel->r_offset + 4);
8587
8588       /* Branch offset must be properly aligned.  */
8589       if ((sym_offset & 3) != 0)
8590         continue;
8591
8592       sym_offset >>= 2;
8593
8594       /* Check that it's in range.  */
8595       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
8596         continue;
8597
8598       /* Get the section contents if we haven't done so already.  */
8599       if (!mips_elf_get_section_contents (abfd, sec, &contents))
8600         goto relax_return;
8601
8602       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
8603
8604       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
8605       if ((instruction & 0xfc1fffff) == 0x0000f809)
8606         instruction = 0x04110000;
8607       /* If it was jr <reg>, turn it into b <target>.  */
8608       else if ((instruction & 0xfc1fffff) == 0x00000008)
8609         instruction = 0x10000000;
8610       else
8611         continue;
8612
8613       instruction |= (sym_offset & 0xffff);
8614       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
8615       changed_contents = TRUE;
8616     }
8617
8618   if (contents != NULL
8619       && elf_section_data (sec)->this_hdr.contents != contents)
8620     {
8621       if (!changed_contents && !link_info->keep_memory)
8622         free (contents);
8623       else
8624         {
8625           /* Cache the section contents for elf_link_input_bfd.  */
8626           elf_section_data (sec)->this_hdr.contents = contents;
8627         }
8628     }
8629   return TRUE;
8630
8631  relax_return:
8632   if (contents != NULL
8633       && elf_section_data (sec)->this_hdr.contents != contents)
8634     free (contents);
8635   return FALSE;
8636 }
8637 \f
8638 /* Allocate space for global sym dynamic relocs.  */
8639
8640 static bfd_boolean
8641 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
8642 {
8643   struct bfd_link_info *info = inf;
8644   bfd *dynobj;
8645   struct mips_elf_link_hash_entry *hmips;
8646   struct mips_elf_link_hash_table *htab;
8647
8648   htab = mips_elf_hash_table (info);
8649   BFD_ASSERT (htab != NULL);
8650
8651   dynobj = elf_hash_table (info)->dynobj;
8652   hmips = (struct mips_elf_link_hash_entry *) h;
8653
8654   /* VxWorks executables are handled elsewhere; we only need to
8655      allocate relocations in shared objects.  */
8656   if (htab->is_vxworks && !info->shared)
8657     return TRUE;
8658
8659   /* Ignore indirect symbols.  All relocations against such symbols
8660      will be redirected to the target symbol.  */
8661   if (h->root.type == bfd_link_hash_indirect)
8662     return TRUE;
8663
8664   /* If this symbol is defined in a dynamic object, or we are creating
8665      a shared library, we will need to copy any R_MIPS_32 or
8666      R_MIPS_REL32 relocs against it into the output file.  */
8667   if (! info->relocatable
8668       && hmips->possibly_dynamic_relocs != 0
8669       && (h->root.type == bfd_link_hash_defweak
8670           || (!h->def_regular && !ELF_COMMON_DEF_P (h))
8671           || info->shared))
8672     {
8673       bfd_boolean do_copy = TRUE;
8674
8675       if (h->root.type == bfd_link_hash_undefweak)
8676         {
8677           /* Do not copy relocations for undefined weak symbols with
8678              non-default visibility.  */
8679           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
8680             do_copy = FALSE;
8681
8682           /* Make sure undefined weak symbols are output as a dynamic
8683              symbol in PIEs.  */
8684           else if (h->dynindx == -1 && !h->forced_local)
8685             {
8686               if (! bfd_elf_link_record_dynamic_symbol (info, h))
8687                 return FALSE;
8688             }
8689         }
8690
8691       if (do_copy)
8692         {
8693           /* Even though we don't directly need a GOT entry for this symbol,
8694              the SVR4 psABI requires it to have a dynamic symbol table
8695              index greater that DT_MIPS_GOTSYM if there are dynamic
8696              relocations against it.
8697
8698              VxWorks does not enforce the same mapping between the GOT
8699              and the symbol table, so the same requirement does not
8700              apply there.  */
8701           if (!htab->is_vxworks)
8702             {
8703               if (hmips->global_got_area > GGA_RELOC_ONLY)
8704                 hmips->global_got_area = GGA_RELOC_ONLY;
8705               hmips->got_only_for_calls = FALSE;
8706             }
8707
8708           mips_elf_allocate_dynamic_relocations
8709             (dynobj, info, hmips->possibly_dynamic_relocs);
8710           if (hmips->readonly_reloc)
8711             /* We tell the dynamic linker that there are relocations
8712                against the text segment.  */
8713             info->flags |= DF_TEXTREL;
8714         }
8715     }
8716
8717   return TRUE;
8718 }
8719
8720 /* Adjust a symbol defined by a dynamic object and referenced by a
8721    regular object.  The current definition is in some section of the
8722    dynamic object, but we're not including those sections.  We have to
8723    change the definition to something the rest of the link can
8724    understand.  */
8725
8726 bfd_boolean
8727 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
8728                                      struct elf_link_hash_entry *h)
8729 {
8730   bfd *dynobj;
8731   struct mips_elf_link_hash_entry *hmips;
8732   struct mips_elf_link_hash_table *htab;
8733
8734   htab = mips_elf_hash_table (info);
8735   BFD_ASSERT (htab != NULL);
8736
8737   dynobj = elf_hash_table (info)->dynobj;
8738   hmips = (struct mips_elf_link_hash_entry *) h;
8739
8740   /* Make sure we know what is going on here.  */
8741   BFD_ASSERT (dynobj != NULL
8742               && (h->needs_plt
8743                   || h->u.weakdef != NULL
8744                   || (h->def_dynamic
8745                       && h->ref_regular
8746                       && !h->def_regular)));
8747
8748   hmips = (struct mips_elf_link_hash_entry *) h;
8749
8750   /* If there are call relocations against an externally-defined symbol,
8751      see whether we can create a MIPS lazy-binding stub for it.  We can
8752      only do this if all references to the function are through call
8753      relocations, and in that case, the traditional lazy-binding stubs
8754      are much more efficient than PLT entries.
8755
8756      Traditional stubs are only available on SVR4 psABI-based systems;
8757      VxWorks always uses PLTs instead.  */
8758   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
8759     {
8760       if (! elf_hash_table (info)->dynamic_sections_created)
8761         return TRUE;
8762
8763       /* If this symbol is not defined in a regular file, then set
8764          the symbol to the stub location.  This is required to make
8765          function pointers compare as equal between the normal
8766          executable and the shared library.  */
8767       if (!h->def_regular)
8768         {
8769           hmips->needs_lazy_stub = TRUE;
8770           htab->lazy_stub_count++;
8771           return TRUE;
8772         }
8773     }
8774   /* As above, VxWorks requires PLT entries for externally-defined
8775      functions that are only accessed through call relocations.
8776
8777      Both VxWorks and non-VxWorks targets also need PLT entries if there
8778      are static-only relocations against an externally-defined function.
8779      This can technically occur for shared libraries if there are
8780      branches to the symbol, although it is unlikely that this will be
8781      used in practice due to the short ranges involved.  It can occur
8782      for any relative or absolute relocation in executables; in that
8783      case, the PLT entry becomes the function's canonical address.  */
8784   else if (((h->needs_plt && !hmips->no_fn_stub)
8785             || (h->type == STT_FUNC && hmips->has_static_relocs))
8786            && htab->use_plts_and_copy_relocs
8787            && !SYMBOL_CALLS_LOCAL (info, h)
8788            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
8789                 && h->root.type == bfd_link_hash_undefweak))
8790     {
8791       bfd_boolean micromips_p = MICROMIPS_P (info->output_bfd);
8792       bfd_boolean newabi_p = NEWABI_P (info->output_bfd);
8793
8794       /* If this is the first symbol to need a PLT entry, then make some
8795          basic setup.  Also work out PLT entry sizes.  We'll need them
8796          for PLT offset calculations.  */
8797       if (htab->plt_mips_offset + htab->plt_comp_offset == 0)
8798         {
8799           BFD_ASSERT (htab->sgotplt->size == 0);
8800           BFD_ASSERT (htab->plt_got_index == 0);
8801
8802           /* If we're using the PLT additions to the psABI, each PLT
8803              entry is 16 bytes and the PLT0 entry is 32 bytes.
8804              Encourage better cache usage by aligning.  We do this
8805              lazily to avoid pessimizing traditional objects.  */
8806           if (!htab->is_vxworks
8807               && !bfd_set_section_alignment (dynobj, htab->splt, 5))
8808             return FALSE;
8809
8810           /* Make sure that .got.plt is word-aligned.  We do this lazily
8811              for the same reason as above.  */
8812           if (!bfd_set_section_alignment (dynobj, htab->sgotplt,
8813                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
8814             return FALSE;
8815
8816           /* On non-VxWorks targets, the first two entries in .got.plt
8817              are reserved.  */
8818           if (!htab->is_vxworks)
8819             htab->plt_got_index
8820               += (get_elf_backend_data (dynobj)->got_header_size
8821                   / MIPS_ELF_GOT_SIZE (dynobj));
8822
8823           /* On VxWorks, also allocate room for the header's
8824              .rela.plt.unloaded entries.  */
8825           if (htab->is_vxworks && !info->shared)
8826             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
8827
8828           /* Now work out the sizes of individual PLT entries.  */
8829           if (htab->is_vxworks && info->shared)
8830             htab->plt_mips_entry_size
8831               = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
8832           else if (htab->is_vxworks)
8833             htab->plt_mips_entry_size
8834               = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
8835           else if (newabi_p)
8836             htab->plt_mips_entry_size
8837               = 4 * ARRAY_SIZE (mips_exec_plt_entry);
8838           else if (!micromips_p)
8839             {
8840               htab->plt_mips_entry_size
8841                 = 4 * ARRAY_SIZE (mips_exec_plt_entry);
8842               htab->plt_comp_entry_size
8843                 = 2 * ARRAY_SIZE (mips16_o32_exec_plt_entry);
8844             }
8845           else if (htab->insn32)
8846             {
8847               htab->plt_mips_entry_size
8848                 = 4 * ARRAY_SIZE (mips_exec_plt_entry);
8849               htab->plt_comp_entry_size
8850                 = 2 * ARRAY_SIZE (micromips_insn32_o32_exec_plt_entry);
8851             }
8852           else
8853             {
8854               htab->plt_mips_entry_size
8855                 = 4 * ARRAY_SIZE (mips_exec_plt_entry);
8856               htab->plt_comp_entry_size
8857                 = 2 * ARRAY_SIZE (micromips_o32_exec_plt_entry);
8858             }
8859         }
8860
8861       if (h->plt.plist == NULL)
8862         h->plt.plist = mips_elf_make_plt_record (dynobj);
8863       if (h->plt.plist == NULL)
8864         return FALSE;
8865
8866       /* There are no defined MIPS16 or microMIPS PLT entries for VxWorks,
8867          n32 or n64, so always use a standard entry there.
8868
8869          If the symbol has a MIPS16 call stub and gets a PLT entry, then
8870          all MIPS16 calls will go via that stub, and there is no benefit
8871          to having a MIPS16 entry.  And in the case of call_stub a
8872          standard entry actually has to be used as the stub ends with a J
8873          instruction.  */
8874       if (newabi_p
8875           || htab->is_vxworks
8876           || hmips->call_stub
8877           || hmips->call_fp_stub)
8878         {
8879           h->plt.plist->need_mips = TRUE;
8880           h->plt.plist->need_comp = FALSE;
8881         }
8882
8883       /* Otherwise, if there are no direct calls to the function, we
8884          have a free choice of whether to use standard or compressed
8885          entries.  Prefer microMIPS entries if the object is known to
8886          contain microMIPS code, so that it becomes possible to create
8887          pure microMIPS binaries.  Prefer standard entries otherwise,
8888          because MIPS16 ones are no smaller and are usually slower.  */
8889       if (!h->plt.plist->need_mips && !h->plt.plist->need_comp)
8890         {
8891           if (micromips_p)
8892             h->plt.plist->need_comp = TRUE;
8893           else
8894             h->plt.plist->need_mips = TRUE;
8895         }
8896
8897       if (h->plt.plist->need_mips)
8898         {
8899           h->plt.plist->mips_offset = htab->plt_mips_offset;
8900           htab->plt_mips_offset += htab->plt_mips_entry_size;
8901         }
8902       if (h->plt.plist->need_comp)
8903         {
8904           h->plt.plist->comp_offset = htab->plt_comp_offset;
8905           htab->plt_comp_offset += htab->plt_comp_entry_size;
8906         }
8907
8908       /* Reserve the corresponding .got.plt entry now too.  */
8909       h->plt.plist->gotplt_index = htab->plt_got_index++;
8910
8911       /* If the output file has no definition of the symbol, set the
8912          symbol's value to the address of the stub.  */
8913       if (!info->shared && !h->def_regular)
8914         hmips->use_plt_entry = TRUE;
8915
8916       /* Make room for the R_MIPS_JUMP_SLOT relocation.  */
8917       htab->srelplt->size += (htab->is_vxworks
8918                               ? MIPS_ELF_RELA_SIZE (dynobj)
8919                               : MIPS_ELF_REL_SIZE (dynobj));
8920
8921       /* Make room for the .rela.plt.unloaded relocations.  */
8922       if (htab->is_vxworks && !info->shared)
8923         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
8924
8925       /* All relocations against this symbol that could have been made
8926          dynamic will now refer to the PLT entry instead.  */
8927       hmips->possibly_dynamic_relocs = 0;
8928
8929       return TRUE;
8930     }
8931
8932   /* If this is a weak symbol, and there is a real definition, the
8933      processor independent code will have arranged for us to see the
8934      real definition first, and we can just use the same value.  */
8935   if (h->u.weakdef != NULL)
8936     {
8937       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
8938                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
8939       h->root.u.def.section = h->u.weakdef->root.u.def.section;
8940       h->root.u.def.value = h->u.weakdef->root.u.def.value;
8941       return TRUE;
8942     }
8943
8944   /* Otherwise, there is nothing further to do for symbols defined
8945      in regular objects.  */
8946   if (h->def_regular)
8947     return TRUE;
8948
8949   /* There's also nothing more to do if we'll convert all relocations
8950      against this symbol into dynamic relocations.  */
8951   if (!hmips->has_static_relocs)
8952     return TRUE;
8953
8954   /* We're now relying on copy relocations.  Complain if we have
8955      some that we can't convert.  */
8956   if (!htab->use_plts_and_copy_relocs || info->shared)
8957     {
8958       (*_bfd_error_handler) (_("non-dynamic relocations refer to "
8959                                "dynamic symbol %s"),
8960                              h->root.root.string);
8961       bfd_set_error (bfd_error_bad_value);
8962       return FALSE;
8963     }
8964
8965   /* We must allocate the symbol in our .dynbss section, which will
8966      become part of the .bss section of the executable.  There will be
8967      an entry for this symbol in the .dynsym section.  The dynamic
8968      object will contain position independent code, so all references
8969      from the dynamic object to this symbol will go through the global
8970      offset table.  The dynamic linker will use the .dynsym entry to
8971      determine the address it must put in the global offset table, so
8972      both the dynamic object and the regular object will refer to the
8973      same memory location for the variable.  */
8974
8975   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
8976     {
8977       if (htab->is_vxworks)
8978         htab->srelbss->size += sizeof (Elf32_External_Rela);
8979       else
8980         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8981       h->needs_copy = 1;
8982     }
8983
8984   /* All relocations against this symbol that could have been made
8985      dynamic will now refer to the local copy instead.  */
8986   hmips->possibly_dynamic_relocs = 0;
8987
8988   return _bfd_elf_adjust_dynamic_copy (h, htab->sdynbss);
8989 }
8990 \f
8991 /* This function is called after all the input files have been read,
8992    and the input sections have been assigned to output sections.  We
8993    check for any mips16 stub sections that we can discard.  */
8994
8995 bfd_boolean
8996 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
8997                                     struct bfd_link_info *info)
8998 {
8999   asection *ri;
9000   struct mips_elf_link_hash_table *htab;
9001   struct mips_htab_traverse_info hti;
9002
9003   htab = mips_elf_hash_table (info);
9004   BFD_ASSERT (htab != NULL);
9005
9006   /* The .reginfo section has a fixed size.  */
9007   ri = bfd_get_section_by_name (output_bfd, ".reginfo");
9008   if (ri != NULL)
9009     bfd_set_section_size (output_bfd, ri, sizeof (Elf32_External_RegInfo));
9010
9011   hti.info = info;
9012   hti.output_bfd = output_bfd;
9013   hti.error = FALSE;
9014   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
9015                                mips_elf_check_symbols, &hti);
9016   if (hti.error)
9017     return FALSE;
9018
9019   return TRUE;
9020 }
9021
9022 /* If the link uses a GOT, lay it out and work out its size.  */
9023
9024 static bfd_boolean
9025 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
9026 {
9027   bfd *dynobj;
9028   asection *s;
9029   struct mips_got_info *g;
9030   bfd_size_type loadable_size = 0;
9031   bfd_size_type page_gotno;
9032   bfd *ibfd;
9033   struct mips_elf_traverse_got_arg tga;
9034   struct mips_elf_link_hash_table *htab;
9035
9036   htab = mips_elf_hash_table (info);
9037   BFD_ASSERT (htab != NULL);
9038
9039   s = htab->sgot;
9040   if (s == NULL)
9041     return TRUE;
9042
9043   dynobj = elf_hash_table (info)->dynobj;
9044   g = htab->got_info;
9045
9046   /* Allocate room for the reserved entries.  VxWorks always reserves
9047      3 entries; other objects only reserve 2 entries.  */
9048   BFD_ASSERT (g->assigned_gotno == 0);
9049   if (htab->is_vxworks)
9050     htab->reserved_gotno = 3;
9051   else
9052     htab->reserved_gotno = 2;
9053   g->local_gotno += htab->reserved_gotno;
9054   g->assigned_gotno = htab->reserved_gotno;
9055
9056   /* Decide which symbols need to go in the global part of the GOT and
9057      count the number of reloc-only GOT symbols.  */
9058   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
9059
9060   if (!mips_elf_resolve_final_got_entries (info, g))
9061     return FALSE;
9062
9063   /* Calculate the total loadable size of the output.  That
9064      will give us the maximum number of GOT_PAGE entries
9065      required.  */
9066   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
9067     {
9068       asection *subsection;
9069
9070       for (subsection = ibfd->sections;
9071            subsection;
9072            subsection = subsection->next)
9073         {
9074           if ((subsection->flags & SEC_ALLOC) == 0)
9075             continue;
9076           loadable_size += ((subsection->size + 0xf)
9077                             &~ (bfd_size_type) 0xf);
9078         }
9079     }
9080
9081   if (htab->is_vxworks)
9082     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
9083        relocations against local symbols evaluate to "G", and the EABI does
9084        not include R_MIPS_GOT_PAGE.  */
9085     page_gotno = 0;
9086   else
9087     /* Assume there are two loadable segments consisting of contiguous
9088        sections.  Is 5 enough?  */
9089     page_gotno = (loadable_size >> 16) + 5;
9090
9091   /* Choose the smaller of the two page estimates; both are intended to be
9092      conservative.  */
9093   if (page_gotno > g->page_gotno)
9094     page_gotno = g->page_gotno;
9095
9096   g->local_gotno += page_gotno;
9097
9098   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
9099   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
9100   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
9101
9102   /* VxWorks does not support multiple GOTs.  It initializes $gp to
9103      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
9104      dynamic loader.  */
9105   if (!htab->is_vxworks && s->size > MIPS_ELF_GOT_MAX_SIZE (info))
9106     {
9107       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
9108         return FALSE;
9109     }
9110   else
9111     {
9112       /* Record that all bfds use G.  This also has the effect of freeing
9113          the per-bfd GOTs, which we no longer need.  */
9114       for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
9115         if (mips_elf_bfd_got (ibfd, FALSE))
9116           mips_elf_replace_bfd_got (ibfd, g);
9117       mips_elf_replace_bfd_got (output_bfd, g);
9118
9119       /* Set up TLS entries.  */
9120       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
9121       tga.info = info;
9122       tga.g = g;
9123       tga.value = MIPS_ELF_GOT_SIZE (output_bfd);
9124       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
9125       if (!tga.g)
9126         return FALSE;
9127       BFD_ASSERT (g->tls_assigned_gotno
9128                   == g->global_gotno + g->local_gotno + g->tls_gotno);
9129
9130       /* Each VxWorks GOT entry needs an explicit relocation.  */
9131       if (htab->is_vxworks && info->shared)
9132         g->relocs += g->global_gotno + g->local_gotno - htab->reserved_gotno;
9133
9134       /* Allocate room for the TLS relocations.  */
9135       if (g->relocs)
9136         mips_elf_allocate_dynamic_relocations (dynobj, info, g->relocs);
9137     }
9138
9139   return TRUE;
9140 }
9141
9142 /* Estimate the size of the .MIPS.stubs section.  */
9143
9144 static void
9145 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
9146 {
9147   struct mips_elf_link_hash_table *htab;
9148   bfd_size_type dynsymcount;
9149
9150   htab = mips_elf_hash_table (info);
9151   BFD_ASSERT (htab != NULL);
9152
9153   if (htab->lazy_stub_count == 0)
9154     return;
9155
9156   /* IRIX rld assumes that a function stub isn't at the end of the .text
9157      section, so add a dummy entry to the end.  */
9158   htab->lazy_stub_count++;
9159
9160   /* Get a worst-case estimate of the number of dynamic symbols needed.
9161      At this point, dynsymcount does not account for section symbols
9162      and count_section_dynsyms may overestimate the number that will
9163      be needed.  */
9164   dynsymcount = (elf_hash_table (info)->dynsymcount
9165                  + count_section_dynsyms (output_bfd, info));
9166
9167   /* Determine the size of one stub entry.  There's no disadvantage
9168      from using microMIPS code here, so for the sake of pure-microMIPS
9169      binaries we prefer it whenever there's any microMIPS code in
9170      output produced at all.  This has a benefit of stubs being
9171      shorter by 4 bytes each too, unless in the insn32 mode.  */
9172   if (!MICROMIPS_P (output_bfd))
9173     htab->function_stub_size = (dynsymcount > 0x10000
9174                                 ? MIPS_FUNCTION_STUB_BIG_SIZE
9175                                 : MIPS_FUNCTION_STUB_NORMAL_SIZE);
9176   else if (htab->insn32)
9177     htab->function_stub_size = (dynsymcount > 0x10000
9178                                 ? MICROMIPS_INSN32_FUNCTION_STUB_BIG_SIZE
9179                                 : MICROMIPS_INSN32_FUNCTION_STUB_NORMAL_SIZE);
9180   else
9181     htab->function_stub_size = (dynsymcount > 0x10000
9182                                 ? MICROMIPS_FUNCTION_STUB_BIG_SIZE
9183                                 : MICROMIPS_FUNCTION_STUB_NORMAL_SIZE);
9184
9185   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
9186 }
9187
9188 /* A mips_elf_link_hash_traverse callback for which DATA points to a
9189    mips_htab_traverse_info.  If H needs a traditional MIPS lazy-binding
9190    stub, allocate an entry in the stubs section.  */
9191
9192 static bfd_boolean
9193 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void *data)
9194 {
9195   struct mips_htab_traverse_info *hti = data;
9196   struct mips_elf_link_hash_table *htab;
9197   struct bfd_link_info *info;
9198   bfd *output_bfd;
9199
9200   info = hti->info;
9201   output_bfd = hti->output_bfd;
9202   htab = mips_elf_hash_table (info);
9203   BFD_ASSERT (htab != NULL);
9204
9205   if (h->needs_lazy_stub)
9206     {
9207       bfd_boolean micromips_p = MICROMIPS_P (output_bfd);
9208       unsigned int other = micromips_p ? STO_MICROMIPS : 0;
9209       bfd_vma isa_bit = micromips_p;
9210
9211       BFD_ASSERT (htab->root.dynobj != NULL);
9212       if (h->root.plt.plist == NULL)
9213         h->root.plt.plist = mips_elf_make_plt_record (htab->sstubs->owner);
9214       if (h->root.plt.plist == NULL)
9215         {
9216           hti->error = TRUE;
9217           return FALSE;
9218         }
9219       h->root.root.u.def.section = htab->sstubs;
9220       h->root.root.u.def.value = htab->sstubs->size + isa_bit;
9221       h->root.plt.plist->stub_offset = htab->sstubs->size;
9222       h->root.other = other;
9223       htab->sstubs->size += htab->function_stub_size;
9224     }
9225   return TRUE;
9226 }
9227
9228 /* Allocate offsets in the stubs section to each symbol that needs one.
9229    Set the final size of the .MIPS.stub section.  */
9230
9231 static bfd_boolean
9232 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
9233 {
9234   bfd *output_bfd = info->output_bfd;
9235   bfd_boolean micromips_p = MICROMIPS_P (output_bfd);
9236   unsigned int other = micromips_p ? STO_MICROMIPS : 0;
9237   bfd_vma isa_bit = micromips_p;
9238   struct mips_elf_link_hash_table *htab;
9239   struct mips_htab_traverse_info hti;
9240   struct elf_link_hash_entry *h;
9241   bfd *dynobj;
9242
9243   htab = mips_elf_hash_table (info);
9244   BFD_ASSERT (htab != NULL);
9245
9246   if (htab->lazy_stub_count == 0)
9247     return TRUE;
9248
9249   htab->sstubs->size = 0;
9250   hti.info = info;
9251   hti.output_bfd = output_bfd;
9252   hti.error = FALSE;
9253   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, &hti);
9254   if (hti.error)
9255     return FALSE;
9256   htab->sstubs->size += htab->function_stub_size;
9257   BFD_ASSERT (htab->sstubs->size
9258               == htab->lazy_stub_count * htab->function_stub_size);
9259
9260   dynobj = elf_hash_table (info)->dynobj;
9261   BFD_ASSERT (dynobj != NULL);
9262   h = _bfd_elf_define_linkage_sym (dynobj, info, htab->sstubs, "_MIPS_STUBS_");
9263   if (h == NULL)
9264     return FALSE;
9265   h->root.u.def.value = isa_bit;
9266   h->other = other;
9267   h->type = STT_FUNC;
9268
9269   return TRUE;
9270 }
9271
9272 /* A mips_elf_link_hash_traverse callback for which DATA points to a
9273    bfd_link_info.  If H uses the address of a PLT entry as the value
9274    of the symbol, then set the entry in the symbol table now.  Prefer
9275    a standard MIPS PLT entry.  */
9276
9277 static bfd_boolean
9278 mips_elf_set_plt_sym_value (struct mips_elf_link_hash_entry *h, void *data)
9279 {
9280   struct bfd_link_info *info = data;
9281   bfd_boolean micromips_p = MICROMIPS_P (info->output_bfd);
9282   struct mips_elf_link_hash_table *htab;
9283   unsigned int other;
9284   bfd_vma isa_bit;
9285   bfd_vma val;
9286
9287   htab = mips_elf_hash_table (info);
9288   BFD_ASSERT (htab != NULL);
9289
9290   if (h->use_plt_entry)
9291     {
9292       BFD_ASSERT (h->root.plt.plist != NULL);
9293       BFD_ASSERT (h->root.plt.plist->mips_offset != MINUS_ONE
9294                   || h->root.plt.plist->comp_offset != MINUS_ONE);
9295
9296       val = htab->plt_header_size;
9297       if (h->root.plt.plist->mips_offset != MINUS_ONE)
9298         {
9299           isa_bit = 0;
9300           val += h->root.plt.plist->mips_offset;
9301           other = 0;
9302         }
9303       else
9304         {
9305           isa_bit = 1;
9306           val += htab->plt_mips_offset + h->root.plt.plist->comp_offset;
9307           other = micromips_p ? STO_MICROMIPS : STO_MIPS16;
9308         }
9309       val += isa_bit;
9310       /* For VxWorks, point at the PLT load stub rather than the lazy
9311          resolution stub; this stub will become the canonical function
9312          address.  */
9313       if (htab->is_vxworks)
9314         val += 8;
9315
9316       h->root.root.u.def.section = htab->splt;
9317       h->root.root.u.def.value = val;
9318       h->root.other = other;
9319     }
9320
9321   return TRUE;
9322 }
9323
9324 /* Set the sizes of the dynamic sections.  */
9325
9326 bfd_boolean
9327 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
9328                                      struct bfd_link_info *info)
9329 {
9330   bfd *dynobj;
9331   asection *s, *sreldyn;
9332   bfd_boolean reltext;
9333   struct mips_elf_link_hash_table *htab;
9334
9335   htab = mips_elf_hash_table (info);
9336   BFD_ASSERT (htab != NULL);
9337   dynobj = elf_hash_table (info)->dynobj;
9338   BFD_ASSERT (dynobj != NULL);
9339
9340   if (elf_hash_table (info)->dynamic_sections_created)
9341     {
9342       /* Set the contents of the .interp section to the interpreter.  */
9343       if (info->executable)
9344         {
9345           s = bfd_get_linker_section (dynobj, ".interp");
9346           BFD_ASSERT (s != NULL);
9347           s->size
9348             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
9349           s->contents
9350             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
9351         }
9352
9353       /* Figure out the size of the PLT header if we know that we
9354          are using it.  For the sake of cache alignment always use
9355          a standard header whenever any standard entries are present
9356          even if microMIPS entries are present as well.  This also
9357          lets the microMIPS header rely on the value of $v0 only set
9358          by microMIPS entries, for a small size reduction.
9359
9360          Set symbol table entry values for symbols that use the
9361          address of their PLT entry now that we can calculate it.
9362
9363          Also create the _PROCEDURE_LINKAGE_TABLE_ symbol if we
9364          haven't already in _bfd_elf_create_dynamic_sections.  */
9365       if (htab->splt && htab->plt_mips_offset + htab->plt_comp_offset != 0)
9366         {
9367           bfd_boolean micromips_p = (MICROMIPS_P (output_bfd)
9368                                      && !htab->plt_mips_offset);
9369           unsigned int other = micromips_p ? STO_MICROMIPS : 0;
9370           bfd_vma isa_bit = micromips_p;
9371           struct elf_link_hash_entry *h;
9372           bfd_vma size;
9373
9374           BFD_ASSERT (htab->use_plts_and_copy_relocs);
9375           BFD_ASSERT (htab->sgotplt->size == 0);
9376           BFD_ASSERT (htab->splt->size == 0);
9377
9378           if (htab->is_vxworks && info->shared)
9379             size = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
9380           else if (htab->is_vxworks)
9381             size = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
9382           else if (ABI_64_P (output_bfd))
9383             size = 4 * ARRAY_SIZE (mips_n64_exec_plt0_entry);
9384           else if (ABI_N32_P (output_bfd))
9385             size = 4 * ARRAY_SIZE (mips_n32_exec_plt0_entry);
9386           else if (!micromips_p)
9387             size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
9388           else if (htab->insn32)
9389             size = 2 * ARRAY_SIZE (micromips_insn32_o32_exec_plt0_entry);
9390           else
9391             size = 2 * ARRAY_SIZE (micromips_o32_exec_plt0_entry);
9392
9393           htab->plt_header_is_comp = micromips_p;
9394           htab->plt_header_size = size;
9395           htab->splt->size = (size
9396                               + htab->plt_mips_offset
9397                               + htab->plt_comp_offset);
9398           htab->sgotplt->size = (htab->plt_got_index
9399                                  * MIPS_ELF_GOT_SIZE (dynobj));
9400
9401           mips_elf_link_hash_traverse (htab, mips_elf_set_plt_sym_value, info);
9402
9403           if (htab->root.hplt == NULL)
9404             {
9405               h = _bfd_elf_define_linkage_sym (dynobj, info, htab->splt,
9406                                                "_PROCEDURE_LINKAGE_TABLE_");
9407               htab->root.hplt = h;
9408               if (h == NULL)
9409                 return FALSE;
9410             }
9411
9412           h = htab->root.hplt;
9413           h->root.u.def.value = isa_bit;
9414           h->other = other;
9415           h->type = STT_FUNC;
9416         }
9417     }
9418
9419   /* Allocate space for global sym dynamic relocs.  */
9420   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, info);
9421
9422   mips_elf_estimate_stub_size (output_bfd, info);
9423
9424   if (!mips_elf_lay_out_got (output_bfd, info))
9425     return FALSE;
9426
9427   mips_elf_lay_out_lazy_stubs (info);
9428
9429   /* The check_relocs and adjust_dynamic_symbol entry points have
9430      determined the sizes of the various dynamic sections.  Allocate
9431      memory for them.  */
9432   reltext = FALSE;
9433   for (s = dynobj->sections; s != NULL; s = s->next)
9434     {
9435       const char *name;
9436
9437       /* It's OK to base decisions on the section name, because none
9438          of the dynobj section names depend upon the input files.  */
9439       name = bfd_get_section_name (dynobj, s);
9440
9441       if ((s->flags & SEC_LINKER_CREATED) == 0)
9442         continue;
9443
9444       if (CONST_STRNEQ (name, ".rel"))
9445         {
9446           if (s->size != 0)
9447             {
9448               const char *outname;
9449               asection *target;
9450
9451               /* If this relocation section applies to a read only
9452                  section, then we probably need a DT_TEXTREL entry.
9453                  If the relocation section is .rel(a).dyn, we always
9454                  assert a DT_TEXTREL entry rather than testing whether
9455                  there exists a relocation to a read only section or
9456                  not.  */
9457               outname = bfd_get_section_name (output_bfd,
9458                                               s->output_section);
9459               target = bfd_get_section_by_name (output_bfd, outname + 4);
9460               if ((target != NULL
9461                    && (target->flags & SEC_READONLY) != 0
9462                    && (target->flags & SEC_ALLOC) != 0)
9463                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
9464                 reltext = TRUE;
9465
9466               /* We use the reloc_count field as a counter if we need
9467                  to copy relocs into the output file.  */
9468               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
9469                 s->reloc_count = 0;
9470
9471               /* If combreloc is enabled, elf_link_sort_relocs() will
9472                  sort relocations, but in a different way than we do,
9473                  and before we're done creating relocations.  Also, it
9474                  will move them around between input sections'
9475                  relocation's contents, so our sorting would be
9476                  broken, so don't let it run.  */
9477               info->combreloc = 0;
9478             }
9479         }
9480       else if (! info->shared
9481                && ! mips_elf_hash_table (info)->use_rld_obj_head
9482                && CONST_STRNEQ (name, ".rld_map"))
9483         {
9484           /* We add a room for __rld_map.  It will be filled in by the
9485              rtld to contain a pointer to the _r_debug structure.  */
9486           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
9487         }
9488       else if (SGI_COMPAT (output_bfd)
9489                && CONST_STRNEQ (name, ".compact_rel"))
9490         s->size += mips_elf_hash_table (info)->compact_rel_size;
9491       else if (s == htab->splt)
9492         {
9493           /* If the last PLT entry has a branch delay slot, allocate
9494              room for an extra nop to fill the delay slot.  This is
9495              for CPUs without load interlocking.  */
9496           if (! LOAD_INTERLOCKS_P (output_bfd)
9497               && ! htab->is_vxworks && s->size > 0)
9498             s->size += 4;
9499         }
9500       else if (! CONST_STRNEQ (name, ".init")
9501                && s != htab->sgot
9502                && s != htab->sgotplt
9503                && s != htab->sstubs
9504                && s != htab->sdynbss)
9505         {
9506           /* It's not one of our sections, so don't allocate space.  */
9507           continue;
9508         }
9509
9510       if (s->size == 0)
9511         {
9512           s->flags |= SEC_EXCLUDE;
9513           continue;
9514         }
9515
9516       if ((s->flags & SEC_HAS_CONTENTS) == 0)
9517         continue;
9518
9519       /* Allocate memory for the section contents.  */
9520       s->contents = bfd_zalloc (dynobj, s->size);
9521       if (s->contents == NULL)
9522         {
9523           bfd_set_error (bfd_error_no_memory);
9524           return FALSE;
9525         }
9526     }
9527
9528   if (elf_hash_table (info)->dynamic_sections_created)
9529     {
9530       /* Add some entries to the .dynamic section.  We fill in the
9531          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
9532          must add the entries now so that we get the correct size for
9533          the .dynamic section.  */
9534
9535       /* SGI object has the equivalence of DT_DEBUG in the
9536          DT_MIPS_RLD_MAP entry.  This must come first because glibc
9537          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and some tools
9538          may only look at the first one they see.  */
9539       if (!info->shared
9540           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
9541         return FALSE;
9542
9543       /* The DT_DEBUG entry may be filled in by the dynamic linker and
9544          used by the debugger.  */
9545       if (info->executable
9546           && !SGI_COMPAT (output_bfd)
9547           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
9548         return FALSE;
9549
9550       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
9551         info->flags |= DF_TEXTREL;
9552
9553       if ((info->flags & DF_TEXTREL) != 0)
9554         {
9555           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
9556             return FALSE;
9557
9558           /* Clear the DF_TEXTREL flag.  It will be set again if we
9559              write out an actual text relocation; we may not, because
9560              at this point we do not know whether e.g. any .eh_frame
9561              absolute relocations have been converted to PC-relative.  */
9562           info->flags &= ~DF_TEXTREL;
9563         }
9564
9565       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
9566         return FALSE;
9567
9568       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
9569       if (htab->is_vxworks)
9570         {
9571           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
9572              use any of the DT_MIPS_* tags.  */
9573           if (sreldyn && sreldyn->size > 0)
9574             {
9575               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
9576                 return FALSE;
9577
9578               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
9579                 return FALSE;
9580
9581               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
9582                 return FALSE;
9583             }
9584         }
9585       else
9586         {
9587           if (sreldyn && sreldyn->size > 0)
9588             {
9589               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
9590                 return FALSE;
9591
9592               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
9593                 return FALSE;
9594
9595               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
9596                 return FALSE;
9597             }
9598
9599           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
9600             return FALSE;
9601
9602           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
9603             return FALSE;
9604
9605           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
9606             return FALSE;
9607
9608           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
9609             return FALSE;
9610
9611           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
9612             return FALSE;
9613
9614           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
9615             return FALSE;
9616
9617           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
9618             return FALSE;
9619
9620           if (IRIX_COMPAT (dynobj) == ict_irix5
9621               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
9622             return FALSE;
9623
9624           if (IRIX_COMPAT (dynobj) == ict_irix6
9625               && (bfd_get_section_by_name
9626                   (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
9627               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
9628             return FALSE;
9629         }
9630       if (htab->splt->size > 0)
9631         {
9632           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
9633             return FALSE;
9634
9635           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
9636             return FALSE;
9637
9638           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
9639             return FALSE;
9640
9641           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
9642             return FALSE;
9643         }
9644       if (htab->is_vxworks
9645           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
9646         return FALSE;
9647     }
9648
9649   return TRUE;
9650 }
9651 \f
9652 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
9653    Adjust its R_ADDEND field so that it is correct for the output file.
9654    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
9655    and sections respectively; both use symbol indexes.  */
9656
9657 static void
9658 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
9659                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
9660                         asection **local_sections, Elf_Internal_Rela *rel)
9661 {
9662   unsigned int r_type, r_symndx;
9663   Elf_Internal_Sym *sym;
9664   asection *sec;
9665
9666   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9667     {
9668       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9669       if (gprel16_reloc_p (r_type)
9670           || r_type == R_MIPS_GPREL32
9671           || literal_reloc_p (r_type))
9672         {
9673           rel->r_addend += _bfd_get_gp_value (input_bfd);
9674           rel->r_addend -= _bfd_get_gp_value (output_bfd);
9675         }
9676
9677       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
9678       sym = local_syms + r_symndx;
9679
9680       /* Adjust REL's addend to account for section merging.  */
9681       if (!info->relocatable)
9682         {
9683           sec = local_sections[r_symndx];
9684           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
9685         }
9686
9687       /* This would normally be done by the rela_normal code in elflink.c.  */
9688       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
9689         rel->r_addend += local_sections[r_symndx]->output_offset;
9690     }
9691 }
9692
9693 /* Handle relocations against symbols from removed linkonce sections,
9694    or sections discarded by a linker script.  We use this wrapper around
9695    RELOC_AGAINST_DISCARDED_SECTION to handle triplets of compound relocs
9696    on 64-bit ELF targets.  In this case for any relocation handled, which
9697    always be the first in a triplet, the remaining two have to be processed
9698    together with the first, even if they are R_MIPS_NONE.  It is the symbol
9699    index referred by the first reloc that applies to all the three and the
9700    remaining two never refer to an object symbol.  And it is the final
9701    relocation (the last non-null one) that determines the output field of
9702    the whole relocation so retrieve the corresponding howto structure for
9703    the relocatable field to be cleared by RELOC_AGAINST_DISCARDED_SECTION.
9704
9705    Note that RELOC_AGAINST_DISCARDED_SECTION is a macro that uses "continue"
9706    and therefore requires to be pasted in a loop.  It also defines a block
9707    and does not protect any of its arguments, hence the extra brackets.  */
9708
9709 static void
9710 mips_reloc_against_discarded_section (bfd *output_bfd,
9711                                       struct bfd_link_info *info,
9712                                       bfd *input_bfd, asection *input_section,
9713                                       Elf_Internal_Rela **rel,
9714                                       const Elf_Internal_Rela **relend,
9715                                       bfd_boolean rel_reloc,
9716                                       reloc_howto_type *howto,
9717                                       bfd_byte *contents)
9718 {
9719   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
9720   int count = bed->s->int_rels_per_ext_rel;
9721   unsigned int r_type;
9722   int i;
9723
9724   for (i = count - 1; i > 0; i--)
9725     {
9726       r_type = ELF_R_TYPE (output_bfd, (*rel)[i].r_info);
9727       if (r_type != R_MIPS_NONE)
9728         {
9729           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9730           break;
9731         }
9732     }
9733   do
9734     {
9735        RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
9736                                         (*rel), count, (*relend),
9737                                         howto, i, contents);
9738     }
9739   while (0);
9740 }
9741
9742 /* Relocate a MIPS ELF section.  */
9743
9744 bfd_boolean
9745 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
9746                                 bfd *input_bfd, asection *input_section,
9747                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
9748                                 Elf_Internal_Sym *local_syms,
9749                                 asection **local_sections)
9750 {
9751   Elf_Internal_Rela *rel;
9752   const Elf_Internal_Rela *relend;
9753   bfd_vma addend = 0;
9754   bfd_boolean use_saved_addend_p = FALSE;
9755   const struct elf_backend_data *bed;
9756
9757   bed = get_elf_backend_data (output_bfd);
9758   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
9759   for (rel = relocs; rel < relend; ++rel)
9760     {
9761       const char *name;
9762       bfd_vma value = 0;
9763       reloc_howto_type *howto;
9764       bfd_boolean cross_mode_jump_p = FALSE;
9765       /* TRUE if the relocation is a RELA relocation, rather than a
9766          REL relocation.  */
9767       bfd_boolean rela_relocation_p = TRUE;
9768       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9769       const char *msg;
9770       unsigned long r_symndx;
9771       asection *sec;
9772       Elf_Internal_Shdr *symtab_hdr;
9773       struct elf_link_hash_entry *h;
9774       bfd_boolean rel_reloc;
9775
9776       rel_reloc = (NEWABI_P (input_bfd)
9777                    && mips_elf_rel_relocation_p (input_bfd, input_section,
9778                                                  relocs, rel));
9779       /* Find the relocation howto for this relocation.  */
9780       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9781
9782       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
9783       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9784       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9785         {
9786           sec = local_sections[r_symndx];
9787           h = NULL;
9788         }
9789       else
9790         {
9791           unsigned long extsymoff;
9792
9793           extsymoff = 0;
9794           if (!elf_bad_symtab (input_bfd))
9795             extsymoff = symtab_hdr->sh_info;
9796           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
9797           while (h->root.type == bfd_link_hash_indirect
9798                  || h->root.type == bfd_link_hash_warning)
9799             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9800
9801           sec = NULL;
9802           if (h->root.type == bfd_link_hash_defined
9803               || h->root.type == bfd_link_hash_defweak)
9804             sec = h->root.u.def.section;
9805         }
9806
9807       if (sec != NULL && discarded_section (sec))
9808         {
9809           mips_reloc_against_discarded_section (output_bfd, info, input_bfd,
9810                                                 input_section, &rel, &relend,
9811                                                 rel_reloc, howto, contents);
9812           continue;
9813         }
9814
9815       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
9816         {
9817           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
9818              64-bit code, but make sure all their addresses are in the
9819              lowermost or uppermost 32-bit section of the 64-bit address
9820              space.  Thus, when they use an R_MIPS_64 they mean what is
9821              usually meant by R_MIPS_32, with the exception that the
9822              stored value is sign-extended to 64 bits.  */
9823           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
9824
9825           /* On big-endian systems, we need to lie about the position
9826              of the reloc.  */
9827           if (bfd_big_endian (input_bfd))
9828             rel->r_offset += 4;
9829         }
9830
9831       if (!use_saved_addend_p)
9832         {
9833           /* If these relocations were originally of the REL variety,
9834              we must pull the addend out of the field that will be
9835              relocated.  Otherwise, we simply use the contents of the
9836              RELA relocation.  */
9837           if (mips_elf_rel_relocation_p (input_bfd, input_section,
9838                                          relocs, rel))
9839             {
9840               rela_relocation_p = FALSE;
9841               addend = mips_elf_read_rel_addend (input_bfd, rel,
9842                                                  howto, contents);
9843               if (hi16_reloc_p (r_type)
9844                   || (got16_reloc_p (r_type)
9845                       && mips_elf_local_relocation_p (input_bfd, rel,
9846                                                       local_sections)))
9847                 {
9848                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
9849                                                      contents, &addend))
9850                     {
9851                       if (h)
9852                         name = h->root.root.string;
9853                       else
9854                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9855                                                  local_syms + r_symndx,
9856                                                  sec);
9857                       (*_bfd_error_handler)
9858                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
9859                          input_bfd, input_section, name, howto->name,
9860                          rel->r_offset);
9861                     }
9862                 }
9863               else
9864                 addend <<= howto->rightshift;
9865             }
9866           else
9867             addend = rel->r_addend;
9868           mips_elf_adjust_addend (output_bfd, info, input_bfd,
9869                                   local_syms, local_sections, rel);
9870         }
9871
9872       if (info->relocatable)
9873         {
9874           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
9875               && bfd_big_endian (input_bfd))
9876             rel->r_offset -= 4;
9877
9878           if (!rela_relocation_p && rel->r_addend)
9879             {
9880               addend += rel->r_addend;
9881               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
9882                 addend = mips_elf_high (addend);
9883               else if (r_type == R_MIPS_HIGHER)
9884                 addend = mips_elf_higher (addend);
9885               else if (r_type == R_MIPS_HIGHEST)
9886                 addend = mips_elf_highest (addend);
9887               else
9888                 addend >>= howto->rightshift;
9889
9890               /* We use the source mask, rather than the destination
9891                  mask because the place to which we are writing will be
9892                  source of the addend in the final link.  */
9893               addend &= howto->src_mask;
9894
9895               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9896                 /* See the comment above about using R_MIPS_64 in the 32-bit
9897                    ABI.  Here, we need to update the addend.  It would be
9898                    possible to get away with just using the R_MIPS_32 reloc
9899                    but for endianness.  */
9900                 {
9901                   bfd_vma sign_bits;
9902                   bfd_vma low_bits;
9903                   bfd_vma high_bits;
9904
9905                   if (addend & ((bfd_vma) 1 << 31))
9906 #ifdef BFD64
9907                     sign_bits = ((bfd_vma) 1 << 32) - 1;
9908 #else
9909                     sign_bits = -1;
9910 #endif
9911                   else
9912                     sign_bits = 0;
9913
9914                   /* If we don't know that we have a 64-bit type,
9915                      do two separate stores.  */
9916                   if (bfd_big_endian (input_bfd))
9917                     {
9918                       /* Store the sign-bits (which are most significant)
9919                          first.  */
9920                       low_bits = sign_bits;
9921                       high_bits = addend;
9922                     }
9923                   else
9924                     {
9925                       low_bits = addend;
9926                       high_bits = sign_bits;
9927                     }
9928                   bfd_put_32 (input_bfd, low_bits,
9929                               contents + rel->r_offset);
9930                   bfd_put_32 (input_bfd, high_bits,
9931                               contents + rel->r_offset + 4);
9932                   continue;
9933                 }
9934
9935               if (! mips_elf_perform_relocation (info, howto, rel, addend,
9936                                                  input_bfd, input_section,
9937                                                  contents, FALSE))
9938                 return FALSE;
9939             }
9940
9941           /* Go on to the next relocation.  */
9942           continue;
9943         }
9944
9945       /* In the N32 and 64-bit ABIs there may be multiple consecutive
9946          relocations for the same offset.  In that case we are
9947          supposed to treat the output of each relocation as the addend
9948          for the next.  */
9949       if (rel + 1 < relend
9950           && rel->r_offset == rel[1].r_offset
9951           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
9952         use_saved_addend_p = TRUE;
9953       else
9954         use_saved_addend_p = FALSE;
9955
9956       /* Figure out what value we are supposed to relocate.  */
9957       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
9958                                              input_section, info, rel,
9959                                              addend, howto, local_syms,
9960                                              local_sections, &value,
9961                                              &name, &cross_mode_jump_p,
9962                                              use_saved_addend_p))
9963         {
9964         case bfd_reloc_continue:
9965           /* There's nothing to do.  */
9966           continue;
9967
9968         case bfd_reloc_undefined:
9969           /* mips_elf_calculate_relocation already called the
9970              undefined_symbol callback.  There's no real point in
9971              trying to perform the relocation at this point, so we
9972              just skip ahead to the next relocation.  */
9973           continue;
9974
9975         case bfd_reloc_notsupported:
9976           msg = _("internal error: unsupported relocation error");
9977           info->callbacks->warning
9978             (info, msg, name, input_bfd, input_section, rel->r_offset);
9979           return FALSE;
9980
9981         case bfd_reloc_overflow:
9982           if (use_saved_addend_p)
9983             /* Ignore overflow until we reach the last relocation for
9984                a given location.  */
9985             ;
9986           else
9987             {
9988               struct mips_elf_link_hash_table *htab;
9989
9990               htab = mips_elf_hash_table (info);
9991               BFD_ASSERT (htab != NULL);
9992               BFD_ASSERT (name != NULL);
9993               if (!htab->small_data_overflow_reported
9994                   && (gprel16_reloc_p (howto->type)
9995                       || literal_reloc_p (howto->type)))
9996                 {
9997                   msg = _("small-data section exceeds 64KB;"
9998                           " lower small-data size limit (see option -G)");
9999
10000                   htab->small_data_overflow_reported = TRUE;
10001                   (*info->callbacks->einfo) ("%P: %s\n", msg);
10002                 }
10003               if (! ((*info->callbacks->reloc_overflow)
10004                      (info, NULL, name, howto->name, (bfd_vma) 0,
10005                       input_bfd, input_section, rel->r_offset)))
10006                 return FALSE;
10007             }
10008           break;
10009
10010         case bfd_reloc_ok:
10011           break;
10012
10013         case bfd_reloc_outofrange:
10014           if (jal_reloc_p (howto->type))
10015             {
10016               msg = _("JALX to a non-word-aligned address");
10017               info->callbacks->warning
10018                 (info, msg, name, input_bfd, input_section, rel->r_offset);
10019               return FALSE;
10020             }
10021           /* Fall through.  */
10022
10023         default:
10024           abort ();
10025           break;
10026         }
10027
10028       /* If we've got another relocation for the address, keep going
10029          until we reach the last one.  */
10030       if (use_saved_addend_p)
10031         {
10032           addend = value;
10033           continue;
10034         }
10035
10036       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
10037         /* See the comment above about using R_MIPS_64 in the 32-bit
10038            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
10039            that calculated the right value.  Now, however, we
10040            sign-extend the 32-bit result to 64-bits, and store it as a
10041            64-bit value.  We are especially generous here in that we
10042            go to extreme lengths to support this usage on systems with
10043            only a 32-bit VMA.  */
10044         {
10045           bfd_vma sign_bits;
10046           bfd_vma low_bits;
10047           bfd_vma high_bits;
10048
10049           if (value & ((bfd_vma) 1 << 31))
10050 #ifdef BFD64
10051             sign_bits = ((bfd_vma) 1 << 32) - 1;
10052 #else
10053             sign_bits = -1;
10054 #endif
10055           else
10056             sign_bits = 0;
10057
10058           /* If we don't know that we have a 64-bit type,
10059              do two separate stores.  */
10060           if (bfd_big_endian (input_bfd))
10061             {
10062               /* Undo what we did above.  */
10063               rel->r_offset -= 4;
10064               /* Store the sign-bits (which are most significant)
10065                  first.  */
10066               low_bits = sign_bits;
10067               high_bits = value;
10068             }
10069           else
10070             {
10071               low_bits = value;
10072               high_bits = sign_bits;
10073             }
10074           bfd_put_32 (input_bfd, low_bits,
10075                       contents + rel->r_offset);
10076           bfd_put_32 (input_bfd, high_bits,
10077                       contents + rel->r_offset + 4);
10078           continue;
10079         }
10080
10081       /* Actually perform the relocation.  */
10082       if (! mips_elf_perform_relocation (info, howto, rel, value,
10083                                          input_bfd, input_section,
10084                                          contents, cross_mode_jump_p))
10085         return FALSE;
10086     }
10087
10088   return TRUE;
10089 }
10090 \f
10091 /* A function that iterates over each entry in la25_stubs and fills
10092    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
10093
10094 static int
10095 mips_elf_create_la25_stub (void **slot, void *data)
10096 {
10097   struct mips_htab_traverse_info *hti;
10098   struct mips_elf_link_hash_table *htab;
10099   struct mips_elf_la25_stub *stub;
10100   asection *s;
10101   bfd_byte *loc;
10102   bfd_vma offset, target, target_high, target_low;
10103
10104   stub = (struct mips_elf_la25_stub *) *slot;
10105   hti = (struct mips_htab_traverse_info *) data;
10106   htab = mips_elf_hash_table (hti->info);
10107   BFD_ASSERT (htab != NULL);
10108
10109   /* Create the section contents, if we haven't already.  */
10110   s = stub->stub_section;
10111   loc = s->contents;
10112   if (loc == NULL)
10113     {
10114       loc = bfd_malloc (s->size);
10115       if (loc == NULL)
10116         {
10117           hti->error = TRUE;
10118           return FALSE;
10119         }
10120       s->contents = loc;
10121     }
10122
10123   /* Work out where in the section this stub should go.  */
10124   offset = stub->offset;
10125
10126   /* Work out the target address.  */
10127   target = mips_elf_get_la25_target (stub, &s);
10128   target += s->output_section->vma + s->output_offset;
10129
10130   target_high = ((target + 0x8000) >> 16) & 0xffff;
10131   target_low = (target & 0xffff);
10132
10133   if (stub->stub_section != htab->strampoline)
10134     {
10135       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
10136          of the section and write the two instructions at the end.  */
10137       memset (loc, 0, offset);
10138       loc += offset;
10139       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
10140         {
10141           bfd_put_micromips_32 (hti->output_bfd,
10142                                 LA25_LUI_MICROMIPS (target_high),
10143                                 loc);
10144           bfd_put_micromips_32 (hti->output_bfd,
10145                                 LA25_ADDIU_MICROMIPS (target_low),
10146                                 loc + 4);
10147         }
10148       else
10149         {
10150           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
10151           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
10152         }
10153     }
10154   else
10155     {
10156       /* This is trampoline.  */
10157       loc += offset;
10158       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
10159         {
10160           bfd_put_micromips_32 (hti->output_bfd,
10161                                 LA25_LUI_MICROMIPS (target_high), loc);
10162           bfd_put_micromips_32 (hti->output_bfd,
10163                                 LA25_J_MICROMIPS (target), loc + 4);
10164           bfd_put_micromips_32 (hti->output_bfd,
10165                                 LA25_ADDIU_MICROMIPS (target_low), loc + 8);
10166           bfd_put_32 (hti->output_bfd, 0, loc + 12);
10167         }
10168       else
10169         {
10170           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
10171           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
10172           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
10173           bfd_put_32 (hti->output_bfd, 0, loc + 12);
10174         }
10175     }
10176   return TRUE;
10177 }
10178
10179 /* If NAME is one of the special IRIX6 symbols defined by the linker,
10180    adjust it appropriately now.  */
10181
10182 static void
10183 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
10184                                       const char *name, Elf_Internal_Sym *sym)
10185 {
10186   /* The linker script takes care of providing names and values for
10187      these, but we must place them into the right sections.  */
10188   static const char* const text_section_symbols[] = {
10189     "_ftext",
10190     "_etext",
10191     "__dso_displacement",
10192     "__elf_header",
10193     "__program_header_table",
10194     NULL
10195   };
10196
10197   static const char* const data_section_symbols[] = {
10198     "_fdata",
10199     "_edata",
10200     "_end",
10201     "_fbss",
10202     NULL
10203   };
10204
10205   const char* const *p;
10206   int i;
10207
10208   for (i = 0; i < 2; ++i)
10209     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
10210          *p;
10211          ++p)
10212       if (strcmp (*p, name) == 0)
10213         {
10214           /* All of these symbols are given type STT_SECTION by the
10215              IRIX6 linker.  */
10216           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10217           sym->st_other = STO_PROTECTED;
10218
10219           /* The IRIX linker puts these symbols in special sections.  */
10220           if (i == 0)
10221             sym->st_shndx = SHN_MIPS_TEXT;
10222           else
10223             sym->st_shndx = SHN_MIPS_DATA;
10224
10225           break;
10226         }
10227 }
10228
10229 /* Finish up dynamic symbol handling.  We set the contents of various
10230    dynamic sections here.  */
10231
10232 bfd_boolean
10233 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
10234                                      struct bfd_link_info *info,
10235                                      struct elf_link_hash_entry *h,
10236                                      Elf_Internal_Sym *sym)
10237 {
10238   bfd *dynobj;
10239   asection *sgot;
10240   struct mips_got_info *g, *gg;
10241   const char *name;
10242   int idx;
10243   struct mips_elf_link_hash_table *htab;
10244   struct mips_elf_link_hash_entry *hmips;
10245
10246   htab = mips_elf_hash_table (info);
10247   BFD_ASSERT (htab != NULL);
10248   dynobj = elf_hash_table (info)->dynobj;
10249   hmips = (struct mips_elf_link_hash_entry *) h;
10250
10251   BFD_ASSERT (!htab->is_vxworks);
10252
10253   if (h->plt.plist != NULL
10254       && (h->plt.plist->mips_offset != MINUS_ONE
10255           || h->plt.plist->comp_offset != MINUS_ONE))
10256     {
10257       /* We've decided to create a PLT entry for this symbol.  */
10258       bfd_byte *loc;
10259       bfd_vma header_address, got_address;
10260       bfd_vma got_address_high, got_address_low, load;
10261       bfd_vma got_index;
10262       bfd_vma isa_bit;
10263
10264       got_index = h->plt.plist->gotplt_index;
10265
10266       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10267       BFD_ASSERT (h->dynindx != -1);
10268       BFD_ASSERT (htab->splt != NULL);
10269       BFD_ASSERT (got_index != MINUS_ONE);
10270       BFD_ASSERT (!h->def_regular);
10271
10272       /* Calculate the address of the PLT header.  */
10273       isa_bit = htab->plt_header_is_comp;
10274       header_address = (htab->splt->output_section->vma
10275                         + htab->splt->output_offset + isa_bit);
10276
10277       /* Calculate the address of the .got.plt entry.  */
10278       got_address = (htab->sgotplt->output_section->vma
10279                      + htab->sgotplt->output_offset
10280                      + got_index * MIPS_ELF_GOT_SIZE (dynobj));
10281
10282       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10283       got_address_low = got_address & 0xffff;
10284
10285       /* Initially point the .got.plt entry at the PLT header.  */
10286       loc = (htab->sgotplt->contents + got_index * MIPS_ELF_GOT_SIZE (dynobj));
10287       if (ABI_64_P (output_bfd))
10288         bfd_put_64 (output_bfd, header_address, loc);
10289       else
10290         bfd_put_32 (output_bfd, header_address, loc);
10291
10292       /* Now handle the PLT itself.  First the standard entry (the order
10293          does not matter, we just have to pick one).  */
10294       if (h->plt.plist->mips_offset != MINUS_ONE)
10295         {
10296           const bfd_vma *plt_entry;
10297           bfd_vma plt_offset;
10298
10299           plt_offset = htab->plt_header_size + h->plt.plist->mips_offset;
10300
10301           BFD_ASSERT (plt_offset <= htab->splt->size);
10302
10303           /* Find out where the .plt entry should go.  */
10304           loc = htab->splt->contents + plt_offset;
10305
10306           /* Pick the load opcode.  */
10307           load = MIPS_ELF_LOAD_WORD (output_bfd);
10308
10309           /* Fill in the PLT entry itself.  */
10310           plt_entry = mips_exec_plt_entry;
10311           bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
10312           bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load,
10313                       loc + 4);
10314
10315           if (! LOAD_INTERLOCKS_P (output_bfd))
10316             {
10317               bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
10318               bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10319             }
10320           else
10321             {
10322               bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
10323               bfd_put_32 (output_bfd, plt_entry[2] | got_address_low,
10324                           loc + 12);
10325             }
10326         }
10327
10328       /* Now the compressed entry.  They come after any standard ones.  */
10329       if (h->plt.plist->comp_offset != MINUS_ONE)
10330         {
10331           bfd_vma plt_offset;
10332
10333           plt_offset = (htab->plt_header_size + htab->plt_mips_offset
10334                         + h->plt.plist->comp_offset);
10335
10336           BFD_ASSERT (plt_offset <= htab->splt->size);
10337
10338           /* Find out where the .plt entry should go.  */
10339           loc = htab->splt->contents + plt_offset;
10340
10341           /* Fill in the PLT entry itself.  */
10342           if (!MICROMIPS_P (output_bfd))
10343             {
10344               const bfd_vma *plt_entry = mips16_o32_exec_plt_entry;
10345
10346               bfd_put_16 (output_bfd, plt_entry[0], loc);
10347               bfd_put_16 (output_bfd, plt_entry[1], loc + 2);
10348               bfd_put_16 (output_bfd, plt_entry[2], loc + 4);
10349               bfd_put_16 (output_bfd, plt_entry[3], loc + 6);
10350               bfd_put_16 (output_bfd, plt_entry[4], loc + 8);
10351               bfd_put_16 (output_bfd, plt_entry[5], loc + 10);
10352               bfd_put_32 (output_bfd, got_address, loc + 12);
10353             }
10354           else if (htab->insn32)
10355             {
10356               const bfd_vma *plt_entry = micromips_insn32_o32_exec_plt_entry;
10357
10358               bfd_put_16 (output_bfd, plt_entry[0], loc);
10359               bfd_put_16 (output_bfd, got_address_high, loc + 2);
10360               bfd_put_16 (output_bfd, plt_entry[2], loc + 4);
10361               bfd_put_16 (output_bfd, got_address_low, loc + 6);
10362               bfd_put_16 (output_bfd, plt_entry[4], loc + 8);
10363               bfd_put_16 (output_bfd, plt_entry[5], loc + 10);
10364               bfd_put_16 (output_bfd, plt_entry[6], loc + 12);
10365               bfd_put_16 (output_bfd, got_address_low, loc + 14);
10366             }
10367           else
10368             {
10369               const bfd_vma *plt_entry = micromips_o32_exec_plt_entry;
10370               bfd_signed_vma gotpc_offset;
10371               bfd_vma loc_address;
10372
10373               BFD_ASSERT (got_address % 4 == 0);
10374
10375               loc_address = (htab->splt->output_section->vma
10376                              + htab->splt->output_offset + plt_offset);
10377               gotpc_offset = got_address - ((loc_address | 3) ^ 3);
10378
10379               /* ADDIUPC has a span of +/-16MB, check we're in range.  */
10380               if (gotpc_offset + 0x1000000 >= 0x2000000)
10381                 {
10382                   (*_bfd_error_handler)
10383                     (_("%B: `%A' offset of %ld from `%A' "
10384                        "beyond the range of ADDIUPC"),
10385                      output_bfd,
10386                      htab->sgotplt->output_section,
10387                      htab->splt->output_section,
10388                      (long) gotpc_offset);
10389                   bfd_set_error (bfd_error_no_error);
10390                   return FALSE;
10391                 }
10392               bfd_put_16 (output_bfd,
10393                           plt_entry[0] | ((gotpc_offset >> 18) & 0x7f), loc);
10394               bfd_put_16 (output_bfd, (gotpc_offset >> 2) & 0xffff, loc + 2);
10395               bfd_put_16 (output_bfd, plt_entry[2], loc + 4);
10396               bfd_put_16 (output_bfd, plt_entry[3], loc + 6);
10397               bfd_put_16 (output_bfd, plt_entry[4], loc + 8);
10398               bfd_put_16 (output_bfd, plt_entry[5], loc + 10);
10399             }
10400         }
10401
10402       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10403       mips_elf_output_dynamic_relocation (output_bfd, htab->srelplt,
10404                                           got_index - 2, h->dynindx,
10405                                           R_MIPS_JUMP_SLOT, got_address);
10406
10407       /* We distinguish between PLT entries and lazy-binding stubs by
10408          giving the former an st_other value of STO_MIPS_PLT.  Set the
10409          flag and leave the value if there are any relocations in the
10410          binary where pointer equality matters.  */
10411       sym->st_shndx = SHN_UNDEF;
10412       if (h->pointer_equality_needed)
10413         sym->st_other = ELF_ST_SET_MIPS_PLT (sym->st_other);
10414       else
10415         {
10416           sym->st_value = 0;
10417           sym->st_other = 0;
10418         }
10419     }
10420
10421   if (h->plt.plist != NULL && h->plt.plist->stub_offset != MINUS_ONE)
10422     {
10423       /* We've decided to create a lazy-binding stub.  */
10424       bfd_boolean micromips_p = MICROMIPS_P (output_bfd);
10425       unsigned int other = micromips_p ? STO_MICROMIPS : 0;
10426       bfd_vma stub_size = htab->function_stub_size;
10427       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
10428       bfd_vma isa_bit = micromips_p;
10429       bfd_vma stub_big_size;
10430
10431       if (!micromips_p)
10432         stub_big_size = MIPS_FUNCTION_STUB_BIG_SIZE;
10433       else if (htab->insn32)
10434         stub_big_size = MICROMIPS_INSN32_FUNCTION_STUB_BIG_SIZE;
10435       else
10436         stub_big_size = MICROMIPS_FUNCTION_STUB_BIG_SIZE;
10437
10438       /* This symbol has a stub.  Set it up.  */
10439
10440       BFD_ASSERT (h->dynindx != -1);
10441
10442       BFD_ASSERT (stub_size == stub_big_size || h->dynindx <= 0xffff);
10443
10444       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
10445          sign extension at runtime in the stub, resulting in a negative
10446          index value.  */
10447       if (h->dynindx & ~0x7fffffff)
10448         return FALSE;
10449
10450       /* Fill the stub.  */
10451       if (micromips_p)
10452         {
10453           idx = 0;
10454           bfd_put_micromips_32 (output_bfd, STUB_LW_MICROMIPS (output_bfd),
10455                                 stub + idx);
10456           idx += 4;
10457           if (htab->insn32)
10458             {
10459               bfd_put_micromips_32 (output_bfd,
10460                                     STUB_MOVE32_MICROMIPS (output_bfd),
10461                                     stub + idx);
10462               idx += 4;
10463             }
10464           else
10465             {
10466               bfd_put_16 (output_bfd, STUB_MOVE_MICROMIPS, stub + idx);
10467               idx += 2;
10468             }
10469           if (stub_size == stub_big_size)
10470             {
10471               long dynindx_hi = (h->dynindx >> 16) & 0x7fff;
10472
10473               bfd_put_micromips_32 (output_bfd,
10474                                     STUB_LUI_MICROMIPS (dynindx_hi),
10475                                     stub + idx);
10476               idx += 4;
10477             }
10478           if (htab->insn32)
10479             {
10480               bfd_put_micromips_32 (output_bfd, STUB_JALR32_MICROMIPS,
10481                                     stub + idx);
10482               idx += 4;
10483             }
10484           else
10485             {
10486               bfd_put_16 (output_bfd, STUB_JALR_MICROMIPS, stub + idx);
10487               idx += 2;
10488             }
10489
10490           /* If a large stub is not required and sign extension is not a
10491              problem, then use legacy code in the stub.  */
10492           if (stub_size == stub_big_size)
10493             bfd_put_micromips_32 (output_bfd,
10494                                   STUB_ORI_MICROMIPS (h->dynindx & 0xffff),
10495                                   stub + idx);
10496           else if (h->dynindx & ~0x7fff)
10497             bfd_put_micromips_32 (output_bfd,
10498                                   STUB_LI16U_MICROMIPS (h->dynindx & 0xffff),
10499                                   stub + idx);
10500           else
10501             bfd_put_micromips_32 (output_bfd,
10502                                   STUB_LI16S_MICROMIPS (output_bfd,
10503                                                         h->dynindx),
10504                                   stub + idx);
10505         }
10506       else
10507         {
10508           idx = 0;
10509           bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
10510           idx += 4;
10511           bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + idx);
10512           idx += 4;
10513           if (stub_size == stub_big_size)
10514             {
10515               bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
10516                           stub + idx);
10517               idx += 4;
10518             }
10519           bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
10520           idx += 4;
10521
10522           /* If a large stub is not required and sign extension is not a
10523              problem, then use legacy code in the stub.  */
10524           if (stub_size == stub_big_size)
10525             bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff),
10526                         stub + idx);
10527           else if (h->dynindx & ~0x7fff)
10528             bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff),
10529                         stub + idx);
10530           else
10531             bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
10532                         stub + idx);
10533         }
10534
10535       BFD_ASSERT (h->plt.plist->stub_offset <= htab->sstubs->size);
10536       memcpy (htab->sstubs->contents + h->plt.plist->stub_offset,
10537               stub, stub_size);
10538
10539       /* Mark the symbol as undefined.  stub_offset != -1 occurs
10540          only for the referenced symbol.  */
10541       sym->st_shndx = SHN_UNDEF;
10542
10543       /* The run-time linker uses the st_value field of the symbol
10544          to reset the global offset table entry for this external
10545          to its stub address when unlinking a shared object.  */
10546       sym->st_value = (htab->sstubs->output_section->vma
10547                        + htab->sstubs->output_offset
10548                        + h->plt.plist->stub_offset
10549                        + isa_bit);
10550       sym->st_other = other;
10551     }
10552
10553   /* If we have a MIPS16 function with a stub, the dynamic symbol must
10554      refer to the stub, since only the stub uses the standard calling
10555      conventions.  */
10556   if (h->dynindx != -1 && hmips->fn_stub != NULL)
10557     {
10558       BFD_ASSERT (hmips->need_fn_stub);
10559       sym->st_value = (hmips->fn_stub->output_section->vma
10560                        + hmips->fn_stub->output_offset);
10561       sym->st_size = hmips->fn_stub->size;
10562       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
10563     }
10564
10565   BFD_ASSERT (h->dynindx != -1
10566               || h->forced_local);
10567
10568   sgot = htab->sgot;
10569   g = htab->got_info;
10570   BFD_ASSERT (g != NULL);
10571
10572   /* Run through the global symbol table, creating GOT entries for all
10573      the symbols that need them.  */
10574   if (hmips->global_got_area != GGA_NONE)
10575     {
10576       bfd_vma offset;
10577       bfd_vma value;
10578
10579       value = sym->st_value;
10580       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
10581       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
10582     }
10583
10584   if (hmips->global_got_area != GGA_NONE && g->next)
10585     {
10586       struct mips_got_entry e, *p;
10587       bfd_vma entry;
10588       bfd_vma offset;
10589
10590       gg = g;
10591
10592       e.abfd = output_bfd;
10593       e.symndx = -1;
10594       e.d.h = hmips;
10595       e.tls_type = GOT_TLS_NONE;
10596
10597       for (g = g->next; g->next != gg; g = g->next)
10598         {
10599           if (g->got_entries
10600               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
10601                                                            &e)))
10602             {
10603               offset = p->gotidx;
10604               BFD_ASSERT (offset > 0 && offset < htab->sgot->size);
10605               if (info->shared
10606                   || (elf_hash_table (info)->dynamic_sections_created
10607                       && p->d.h != NULL
10608                       && p->d.h->root.def_dynamic
10609                       && !p->d.h->root.def_regular))
10610                 {
10611                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
10612                      the various compatibility problems, it's easier to mock
10613                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
10614                      mips_elf_create_dynamic_relocation to calculate the
10615                      appropriate addend.  */
10616                   Elf_Internal_Rela rel[3];
10617
10618                   memset (rel, 0, sizeof (rel));
10619                   if (ABI_64_P (output_bfd))
10620                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
10621                   else
10622                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
10623                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
10624
10625                   entry = 0;
10626                   if (! (mips_elf_create_dynamic_relocation
10627                          (output_bfd, info, rel,
10628                           e.d.h, NULL, sym->st_value, &entry, sgot)))
10629                     return FALSE;
10630                 }
10631               else
10632                 entry = sym->st_value;
10633               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
10634             }
10635         }
10636     }
10637
10638   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
10639   name = h->root.root.string;
10640   if (h == elf_hash_table (info)->hdynamic
10641       || h == elf_hash_table (info)->hgot)
10642     sym->st_shndx = SHN_ABS;
10643   else if (strcmp (name, "_DYNAMIC_LINK") == 0
10644            || strcmp (name, "_DYNAMIC_LINKING") == 0)
10645     {
10646       sym->st_shndx = SHN_ABS;
10647       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10648       sym->st_value = 1;
10649     }
10650   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
10651     {
10652       sym->st_shndx = SHN_ABS;
10653       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10654       sym->st_value = elf_gp (output_bfd);
10655     }
10656   else if (SGI_COMPAT (output_bfd))
10657     {
10658       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
10659           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
10660         {
10661           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10662           sym->st_other = STO_PROTECTED;
10663           sym->st_value = 0;
10664           sym->st_shndx = SHN_MIPS_DATA;
10665         }
10666       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
10667         {
10668           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10669           sym->st_other = STO_PROTECTED;
10670           sym->st_value = mips_elf_hash_table (info)->procedure_count;
10671           sym->st_shndx = SHN_ABS;
10672         }
10673       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
10674         {
10675           if (h->type == STT_FUNC)
10676             sym->st_shndx = SHN_MIPS_TEXT;
10677           else if (h->type == STT_OBJECT)
10678             sym->st_shndx = SHN_MIPS_DATA;
10679         }
10680     }
10681
10682   /* Emit a copy reloc, if needed.  */
10683   if (h->needs_copy)
10684     {
10685       asection *s;
10686       bfd_vma symval;
10687
10688       BFD_ASSERT (h->dynindx != -1);
10689       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10690
10691       s = mips_elf_rel_dyn_section (info, FALSE);
10692       symval = (h->root.u.def.section->output_section->vma
10693                 + h->root.u.def.section->output_offset
10694                 + h->root.u.def.value);
10695       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
10696                                           h->dynindx, R_MIPS_COPY, symval);
10697     }
10698
10699   /* Handle the IRIX6-specific symbols.  */
10700   if (IRIX_COMPAT (output_bfd) == ict_irix6)
10701     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
10702
10703   /* Keep dynamic compressed symbols odd.  This allows the dynamic linker
10704      to treat compressed symbols like any other.  */
10705   if (ELF_ST_IS_MIPS16 (sym->st_other))
10706     {
10707       BFD_ASSERT (sym->st_value & 1);
10708       sym->st_other -= STO_MIPS16;
10709     }
10710   else if (ELF_ST_IS_MICROMIPS (sym->st_other))
10711     {
10712       BFD_ASSERT (sym->st_value & 1);
10713       sym->st_other -= STO_MICROMIPS;
10714     }
10715
10716   return TRUE;
10717 }
10718
10719 /* Likewise, for VxWorks.  */
10720
10721 bfd_boolean
10722 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
10723                                          struct bfd_link_info *info,
10724                                          struct elf_link_hash_entry *h,
10725                                          Elf_Internal_Sym *sym)
10726 {
10727   bfd *dynobj;
10728   asection *sgot;
10729   struct mips_got_info *g;
10730   struct mips_elf_link_hash_table *htab;
10731   struct mips_elf_link_hash_entry *hmips;
10732
10733   htab = mips_elf_hash_table (info);
10734   BFD_ASSERT (htab != NULL);
10735   dynobj = elf_hash_table (info)->dynobj;
10736   hmips = (struct mips_elf_link_hash_entry *) h;
10737
10738   if (h->plt.plist != NULL && h->plt.plist->mips_offset != MINUS_ONE)
10739     {
10740       bfd_byte *loc;
10741       bfd_vma plt_address, got_address, got_offset, branch_offset;
10742       Elf_Internal_Rela rel;
10743       static const bfd_vma *plt_entry;
10744       bfd_vma gotplt_index;
10745       bfd_vma plt_offset;
10746
10747       plt_offset = htab->plt_header_size + h->plt.plist->mips_offset;
10748       gotplt_index = h->plt.plist->gotplt_index;
10749
10750       BFD_ASSERT (h->dynindx != -1);
10751       BFD_ASSERT (htab->splt != NULL);
10752       BFD_ASSERT (gotplt_index != MINUS_ONE);
10753       BFD_ASSERT (plt_offset <= htab->splt->size);
10754
10755       /* Calculate the address of the .plt entry.  */
10756       plt_address = (htab->splt->output_section->vma
10757                      + htab->splt->output_offset
10758                      + plt_offset);
10759
10760       /* Calculate the address of the .got.plt entry.  */
10761       got_address = (htab->sgotplt->output_section->vma
10762                      + htab->sgotplt->output_offset
10763                      + gotplt_index * MIPS_ELF_GOT_SIZE (output_bfd));
10764
10765       /* Calculate the offset of the .got.plt entry from
10766          _GLOBAL_OFFSET_TABLE_.  */
10767       got_offset = mips_elf_gotplt_index (info, h);
10768
10769       /* Calculate the offset for the branch at the start of the PLT
10770          entry.  The branch jumps to the beginning of .plt.  */
10771       branch_offset = -(plt_offset / 4 + 1) & 0xffff;
10772
10773       /* Fill in the initial value of the .got.plt entry.  */
10774       bfd_put_32 (output_bfd, plt_address,
10775                   (htab->sgotplt->contents
10776                    + gotplt_index * MIPS_ELF_GOT_SIZE (output_bfd)));
10777
10778       /* Find out where the .plt entry should go.  */
10779       loc = htab->splt->contents + plt_offset;
10780
10781       if (info->shared)
10782         {
10783           plt_entry = mips_vxworks_shared_plt_entry;
10784           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10785           bfd_put_32 (output_bfd, plt_entry[1] | gotplt_index, loc + 4);
10786         }
10787       else
10788         {
10789           bfd_vma got_address_high, got_address_low;
10790
10791           plt_entry = mips_vxworks_exec_plt_entry;
10792           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10793           got_address_low = got_address & 0xffff;
10794
10795           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10796           bfd_put_32 (output_bfd, plt_entry[1] | gotplt_index, loc + 4);
10797           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
10798           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
10799           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10800           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10801           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10802           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10803
10804           loc = (htab->srelplt2->contents
10805                  + (gotplt_index * 3 + 2) * sizeof (Elf32_External_Rela));
10806
10807           /* Emit a relocation for the .got.plt entry.  */
10808           rel.r_offset = got_address;
10809           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10810           rel.r_addend = plt_offset;
10811           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10812
10813           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
10814           loc += sizeof (Elf32_External_Rela);
10815           rel.r_offset = plt_address + 8;
10816           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10817           rel.r_addend = got_offset;
10818           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10819
10820           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
10821           loc += sizeof (Elf32_External_Rela);
10822           rel.r_offset += 4;
10823           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10824           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10825         }
10826
10827       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10828       loc = (htab->srelplt->contents
10829              + gotplt_index * sizeof (Elf32_External_Rela));
10830       rel.r_offset = got_address;
10831       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
10832       rel.r_addend = 0;
10833       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10834
10835       if (!h->def_regular)
10836         sym->st_shndx = SHN_UNDEF;
10837     }
10838
10839   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
10840
10841   sgot = htab->sgot;
10842   g = htab->got_info;
10843   BFD_ASSERT (g != NULL);
10844
10845   /* See if this symbol has an entry in the GOT.  */
10846   if (hmips->global_got_area != GGA_NONE)
10847     {
10848       bfd_vma offset;
10849       Elf_Internal_Rela outrel;
10850       bfd_byte *loc;
10851       asection *s;
10852
10853       /* Install the symbol value in the GOT.   */
10854       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
10855       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
10856
10857       /* Add a dynamic relocation for it.  */
10858       s = mips_elf_rel_dyn_section (info, FALSE);
10859       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
10860       outrel.r_offset = (sgot->output_section->vma
10861                          + sgot->output_offset
10862                          + offset);
10863       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
10864       outrel.r_addend = 0;
10865       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
10866     }
10867
10868   /* Emit a copy reloc, if needed.  */
10869   if (h->needs_copy)
10870     {
10871       Elf_Internal_Rela rel;
10872
10873       BFD_ASSERT (h->dynindx != -1);
10874
10875       rel.r_offset = (h->root.u.def.section->output_section->vma
10876                       + h->root.u.def.section->output_offset
10877                       + h->root.u.def.value);
10878       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
10879       rel.r_addend = 0;
10880       bfd_elf32_swap_reloca_out (output_bfd, &rel,
10881                                  htab->srelbss->contents
10882                                  + (htab->srelbss->reloc_count
10883                                     * sizeof (Elf32_External_Rela)));
10884       ++htab->srelbss->reloc_count;
10885     }
10886
10887   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
10888   if (ELF_ST_IS_COMPRESSED (sym->st_other))
10889     sym->st_value &= ~1;
10890
10891   return TRUE;
10892 }
10893
10894 /* Write out a plt0 entry to the beginning of .plt.  */
10895
10896 static bfd_boolean
10897 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10898 {
10899   bfd_byte *loc;
10900   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
10901   static const bfd_vma *plt_entry;
10902   struct mips_elf_link_hash_table *htab;
10903
10904   htab = mips_elf_hash_table (info);
10905   BFD_ASSERT (htab != NULL);
10906
10907   if (ABI_64_P (output_bfd))
10908     plt_entry = mips_n64_exec_plt0_entry;
10909   else if (ABI_N32_P (output_bfd))
10910     plt_entry = mips_n32_exec_plt0_entry;
10911   else if (!htab->plt_header_is_comp)
10912     plt_entry = mips_o32_exec_plt0_entry;
10913   else if (htab->insn32)
10914     plt_entry = micromips_insn32_o32_exec_plt0_entry;
10915   else
10916     plt_entry = micromips_o32_exec_plt0_entry;
10917
10918   /* Calculate the value of .got.plt.  */
10919   gotplt_value = (htab->sgotplt->output_section->vma
10920                   + htab->sgotplt->output_offset);
10921   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
10922   gotplt_value_low = gotplt_value & 0xffff;
10923
10924   /* The PLT sequence is not safe for N64 if .got.plt's address can
10925      not be loaded in two instructions.  */
10926   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
10927               || ~(gotplt_value | 0x7fffffff) == 0);
10928
10929   /* Install the PLT header.  */
10930   loc = htab->splt->contents;
10931   if (plt_entry == micromips_o32_exec_plt0_entry)
10932     {
10933       bfd_vma gotpc_offset;
10934       bfd_vma loc_address;
10935       size_t i;
10936
10937       BFD_ASSERT (gotplt_value % 4 == 0);
10938
10939       loc_address = (htab->splt->output_section->vma
10940                      + htab->splt->output_offset);
10941       gotpc_offset = gotplt_value - ((loc_address | 3) ^ 3);
10942
10943       /* ADDIUPC has a span of +/-16MB, check we're in range.  */
10944       if (gotpc_offset + 0x1000000 >= 0x2000000)
10945         {
10946           (*_bfd_error_handler)
10947             (_("%B: `%A' offset of %ld from `%A' beyond the range of ADDIUPC"),
10948              output_bfd,
10949              htab->sgotplt->output_section,
10950              htab->splt->output_section,
10951              (long) gotpc_offset);
10952           bfd_set_error (bfd_error_no_error);
10953           return FALSE;
10954         }
10955       bfd_put_16 (output_bfd,
10956                   plt_entry[0] | ((gotpc_offset >> 18) & 0x7f), loc);
10957       bfd_put_16 (output_bfd, (gotpc_offset >> 2) & 0xffff, loc + 2);
10958       for (i = 2; i < ARRAY_SIZE (micromips_o32_exec_plt0_entry); i++)
10959         bfd_put_16 (output_bfd, plt_entry[i], loc + (i * 2));
10960     }
10961   else if (plt_entry == micromips_insn32_o32_exec_plt0_entry)
10962     {
10963       size_t i;
10964
10965       bfd_put_16 (output_bfd, plt_entry[0], loc);
10966       bfd_put_16 (output_bfd, gotplt_value_high, loc + 2);
10967       bfd_put_16 (output_bfd, plt_entry[2], loc + 4);
10968       bfd_put_16 (output_bfd, gotplt_value_low, loc + 6);
10969       bfd_put_16 (output_bfd, plt_entry[4], loc + 8);
10970       bfd_put_16 (output_bfd, gotplt_value_low, loc + 10);
10971       for (i = 6; i < ARRAY_SIZE (micromips_insn32_o32_exec_plt0_entry); i++)
10972         bfd_put_16 (output_bfd, plt_entry[i], loc + (i * 2));
10973     }
10974   else
10975     {
10976       bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
10977       bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
10978       bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
10979       bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10980       bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10981       bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10982       bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10983       bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10984     }
10985
10986   return TRUE;
10987 }
10988
10989 /* Install the PLT header for a VxWorks executable and finalize the
10990    contents of .rela.plt.unloaded.  */
10991
10992 static void
10993 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10994 {
10995   Elf_Internal_Rela rela;
10996   bfd_byte *loc;
10997   bfd_vma got_value, got_value_high, got_value_low, plt_address;
10998   static const bfd_vma *plt_entry;
10999   struct mips_elf_link_hash_table *htab;
11000
11001   htab = mips_elf_hash_table (info);
11002   BFD_ASSERT (htab != NULL);
11003
11004   plt_entry = mips_vxworks_exec_plt0_entry;
11005
11006   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
11007   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
11008                + htab->root.hgot->root.u.def.section->output_offset
11009                + htab->root.hgot->root.u.def.value);
11010
11011   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
11012   got_value_low = got_value & 0xffff;
11013
11014   /* Calculate the address of the PLT header.  */
11015   plt_address = htab->splt->output_section->vma + htab->splt->output_offset;
11016
11017   /* Install the PLT header.  */
11018   loc = htab->splt->contents;
11019   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
11020   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
11021   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
11022   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
11023   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
11024   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
11025
11026   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
11027   loc = htab->srelplt2->contents;
11028   rela.r_offset = plt_address;
11029   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
11030   rela.r_addend = 0;
11031   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
11032   loc += sizeof (Elf32_External_Rela);
11033
11034   /* Output the relocation for the following addiu of
11035      %lo(_GLOBAL_OFFSET_TABLE_).  */
11036   rela.r_offset += 4;
11037   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
11038   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
11039   loc += sizeof (Elf32_External_Rela);
11040
11041   /* Fix up the remaining relocations.  They may have the wrong
11042      symbol index for _G_O_T_ or _P_L_T_ depending on the order
11043      in which symbols were output.  */
11044   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
11045     {
11046       Elf_Internal_Rela rel;
11047
11048       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
11049       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
11050       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
11051       loc += sizeof (Elf32_External_Rela);
11052
11053       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
11054       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
11055       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
11056       loc += sizeof (Elf32_External_Rela);
11057
11058       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
11059       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
11060       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
11061       loc += sizeof (Elf32_External_Rela);
11062     }
11063 }
11064
11065 /* Install the PLT header for a VxWorks shared library.  */
11066
11067 static void
11068 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
11069 {
11070   unsigned int i;
11071   struct mips_elf_link_hash_table *htab;
11072
11073   htab = mips_elf_hash_table (info);
11074   BFD_ASSERT (htab != NULL);
11075
11076   /* We just need to copy the entry byte-by-byte.  */
11077   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
11078     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
11079                 htab->splt->contents + i * 4);
11080 }
11081
11082 /* Finish up the dynamic sections.  */
11083
11084 bfd_boolean
11085 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
11086                                        struct bfd_link_info *info)
11087 {
11088   bfd *dynobj;
11089   asection *sdyn;
11090   asection *sgot;
11091   struct mips_got_info *gg, *g;
11092   struct mips_elf_link_hash_table *htab;
11093
11094   htab = mips_elf_hash_table (info);
11095   BFD_ASSERT (htab != NULL);
11096
11097   dynobj = elf_hash_table (info)->dynobj;
11098
11099   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
11100
11101   sgot = htab->sgot;
11102   gg = htab->got_info;
11103
11104   if (elf_hash_table (info)->dynamic_sections_created)
11105     {
11106       bfd_byte *b;
11107       int dyn_to_skip = 0, dyn_skipped = 0;
11108
11109       BFD_ASSERT (sdyn != NULL);
11110       BFD_ASSERT (gg != NULL);
11111
11112       g = mips_elf_bfd_got (output_bfd, FALSE);
11113       BFD_ASSERT (g != NULL);
11114
11115       for (b = sdyn->contents;
11116            b < sdyn->contents + sdyn->size;
11117            b += MIPS_ELF_DYN_SIZE (dynobj))
11118         {
11119           Elf_Internal_Dyn dyn;
11120           const char *name;
11121           size_t elemsize;
11122           asection *s;
11123           bfd_boolean swap_out_p;
11124
11125           /* Read in the current dynamic entry.  */
11126           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
11127
11128           /* Assume that we're going to modify it and write it out.  */
11129           swap_out_p = TRUE;
11130
11131           switch (dyn.d_tag)
11132             {
11133             case DT_RELENT:
11134               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
11135               break;
11136
11137             case DT_RELAENT:
11138               BFD_ASSERT (htab->is_vxworks);
11139               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
11140               break;
11141
11142             case DT_STRSZ:
11143               /* Rewrite DT_STRSZ.  */
11144               dyn.d_un.d_val =
11145                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
11146               break;
11147
11148             case DT_PLTGOT:
11149               s = htab->sgot;
11150               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
11151               break;
11152
11153             case DT_MIPS_PLTGOT:
11154               s = htab->sgotplt;
11155               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
11156               break;
11157
11158             case DT_MIPS_RLD_VERSION:
11159               dyn.d_un.d_val = 1; /* XXX */
11160               break;
11161
11162             case DT_MIPS_FLAGS:
11163               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
11164               break;
11165
11166             case DT_MIPS_TIME_STAMP:
11167               {
11168                 time_t t;
11169                 time (&t);
11170                 dyn.d_un.d_val = t;
11171               }
11172               break;
11173
11174             case DT_MIPS_ICHECKSUM:
11175               /* XXX FIXME: */
11176               swap_out_p = FALSE;
11177               break;
11178
11179             case DT_MIPS_IVERSION:
11180               /* XXX FIXME: */
11181               swap_out_p = FALSE;
11182               break;
11183
11184             case DT_MIPS_BASE_ADDRESS:
11185               s = output_bfd->sections;
11186               BFD_ASSERT (s != NULL);
11187               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
11188               break;
11189
11190             case DT_MIPS_LOCAL_GOTNO:
11191               dyn.d_un.d_val = g->local_gotno;
11192               break;
11193
11194             case DT_MIPS_UNREFEXTNO:
11195               /* The index into the dynamic symbol table which is the
11196                  entry of the first external symbol that is not
11197                  referenced within the same object.  */
11198               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
11199               break;
11200
11201             case DT_MIPS_GOTSYM:
11202               if (htab->global_gotsym)
11203                 {
11204                   dyn.d_un.d_val = htab->global_gotsym->dynindx;
11205                   break;
11206                 }
11207               /* In case if we don't have global got symbols we default
11208                  to setting DT_MIPS_GOTSYM to the same value as
11209                  DT_MIPS_SYMTABNO, so we just fall through.  */
11210
11211             case DT_MIPS_SYMTABNO:
11212               name = ".dynsym";
11213               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
11214               s = bfd_get_section_by_name (output_bfd, name);
11215               BFD_ASSERT (s != NULL);
11216
11217               dyn.d_un.d_val = s->size / elemsize;
11218               break;
11219
11220             case DT_MIPS_HIPAGENO:
11221               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
11222               break;
11223
11224             case DT_MIPS_RLD_MAP:
11225               {
11226                 struct elf_link_hash_entry *h;
11227                 h = mips_elf_hash_table (info)->rld_symbol;
11228                 if (!h)
11229                   {
11230                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
11231                     swap_out_p = FALSE;
11232                     break;
11233                   }
11234                 s = h->root.u.def.section;
11235                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
11236                                   + h->root.u.def.value);
11237               }
11238               break;
11239
11240             case DT_MIPS_OPTIONS:
11241               s = (bfd_get_section_by_name
11242                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
11243               dyn.d_un.d_ptr = s->vma;
11244               break;
11245
11246             case DT_RELASZ:
11247               BFD_ASSERT (htab->is_vxworks);
11248               /* The count does not include the JUMP_SLOT relocations.  */
11249               if (htab->srelplt)
11250                 dyn.d_un.d_val -= htab->srelplt->size;
11251               break;
11252
11253             case DT_PLTREL:
11254               BFD_ASSERT (htab->use_plts_and_copy_relocs);
11255               if (htab->is_vxworks)
11256                 dyn.d_un.d_val = DT_RELA;
11257               else
11258                 dyn.d_un.d_val = DT_REL;
11259               break;
11260
11261             case DT_PLTRELSZ:
11262               BFD_ASSERT (htab->use_plts_and_copy_relocs);
11263               dyn.d_un.d_val = htab->srelplt->size;
11264               break;
11265
11266             case DT_JMPREL:
11267               BFD_ASSERT (htab->use_plts_and_copy_relocs);
11268               dyn.d_un.d_ptr = (htab->srelplt->output_section->vma
11269                                 + htab->srelplt->output_offset);
11270               break;
11271
11272             case DT_TEXTREL:
11273               /* If we didn't need any text relocations after all, delete
11274                  the dynamic tag.  */
11275               if (!(info->flags & DF_TEXTREL))
11276                 {
11277                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
11278                   swap_out_p = FALSE;
11279                 }
11280               break;
11281
11282             case DT_FLAGS:
11283               /* If we didn't need any text relocations after all, clear
11284                  DF_TEXTREL from DT_FLAGS.  */
11285               if (!(info->flags & DF_TEXTREL))
11286                 dyn.d_un.d_val &= ~DF_TEXTREL;
11287               else
11288                 swap_out_p = FALSE;
11289               break;
11290
11291             default:
11292               swap_out_p = FALSE;
11293               if (htab->is_vxworks
11294                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
11295                 swap_out_p = TRUE;
11296               break;
11297             }
11298
11299           if (swap_out_p || dyn_skipped)
11300             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
11301               (dynobj, &dyn, b - dyn_skipped);
11302
11303           if (dyn_to_skip)
11304             {
11305               dyn_skipped += dyn_to_skip;
11306               dyn_to_skip = 0;
11307             }
11308         }
11309
11310       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
11311       if (dyn_skipped > 0)
11312         memset (b - dyn_skipped, 0, dyn_skipped);
11313     }
11314
11315   if (sgot != NULL && sgot->size > 0
11316       && !bfd_is_abs_section (sgot->output_section))
11317     {
11318       if (htab->is_vxworks)
11319         {
11320           /* The first entry of the global offset table points to the
11321              ".dynamic" section.  The second is initialized by the
11322              loader and contains the shared library identifier.
11323              The third is also initialized by the loader and points
11324              to the lazy resolution stub.  */
11325           MIPS_ELF_PUT_WORD (output_bfd,
11326                              sdyn->output_offset + sdyn->output_section->vma,
11327                              sgot->contents);
11328           MIPS_ELF_PUT_WORD (output_bfd, 0,
11329                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
11330           MIPS_ELF_PUT_WORD (output_bfd, 0,
11331                              sgot->contents
11332                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
11333         }
11334       else
11335         {
11336           /* The first entry of the global offset table will be filled at
11337              runtime. The second entry will be used by some runtime loaders.
11338              This isn't the case of IRIX rld.  */
11339           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
11340           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
11341                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
11342         }
11343
11344       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
11345          = MIPS_ELF_GOT_SIZE (output_bfd);
11346     }
11347
11348   /* Generate dynamic relocations for the non-primary gots.  */
11349   if (gg != NULL && gg->next)
11350     {
11351       Elf_Internal_Rela rel[3];
11352       bfd_vma addend = 0;
11353
11354       memset (rel, 0, sizeof (rel));
11355       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
11356
11357       for (g = gg->next; g->next != gg; g = g->next)
11358         {
11359           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
11360             + g->next->tls_gotno;
11361
11362           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
11363                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
11364           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
11365                              sgot->contents
11366                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
11367
11368           if (! info->shared)
11369             continue;
11370
11371           while (got_index < g->assigned_gotno)
11372             {
11373               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
11374                 = got_index++ * MIPS_ELF_GOT_SIZE (output_bfd);
11375               if (!(mips_elf_create_dynamic_relocation
11376                     (output_bfd, info, rel, NULL,
11377                      bfd_abs_section_ptr,
11378                      0, &addend, sgot)))
11379                 return FALSE;
11380               BFD_ASSERT (addend == 0);
11381             }
11382         }
11383     }
11384
11385   /* The generation of dynamic relocations for the non-primary gots
11386      adds more dynamic relocations.  We cannot count them until
11387      here.  */
11388
11389   if (elf_hash_table (info)->dynamic_sections_created)
11390     {
11391       bfd_byte *b;
11392       bfd_boolean swap_out_p;
11393
11394       BFD_ASSERT (sdyn != NULL);
11395
11396       for (b = sdyn->contents;
11397            b < sdyn->contents + sdyn->size;
11398            b += MIPS_ELF_DYN_SIZE (dynobj))
11399         {
11400           Elf_Internal_Dyn dyn;
11401           asection *s;
11402
11403           /* Read in the current dynamic entry.  */
11404           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
11405
11406           /* Assume that we're going to modify it and write it out.  */
11407           swap_out_p = TRUE;
11408
11409           switch (dyn.d_tag)
11410             {
11411             case DT_RELSZ:
11412               /* Reduce DT_RELSZ to account for any relocations we
11413                  decided not to make.  This is for the n64 irix rld,
11414                  which doesn't seem to apply any relocations if there
11415                  are trailing null entries.  */
11416               s = mips_elf_rel_dyn_section (info, FALSE);
11417               dyn.d_un.d_val = (s->reloc_count
11418                                 * (ABI_64_P (output_bfd)
11419                                    ? sizeof (Elf64_Mips_External_Rel)
11420                                    : sizeof (Elf32_External_Rel)));
11421               /* Adjust the section size too.  Tools like the prelinker
11422                  can reasonably expect the values to the same.  */
11423               elf_section_data (s->output_section)->this_hdr.sh_size
11424                 = dyn.d_un.d_val;
11425               break;
11426
11427             default:
11428               swap_out_p = FALSE;
11429               break;
11430             }
11431
11432           if (swap_out_p)
11433             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
11434               (dynobj, &dyn, b);
11435         }
11436     }
11437
11438   {
11439     asection *s;
11440     Elf32_compact_rel cpt;
11441
11442     if (SGI_COMPAT (output_bfd))
11443       {
11444         /* Write .compact_rel section out.  */
11445         s = bfd_get_linker_section (dynobj, ".compact_rel");
11446         if (s != NULL)
11447           {
11448             cpt.id1 = 1;
11449             cpt.num = s->reloc_count;
11450             cpt.id2 = 2;
11451             cpt.offset = (s->output_section->filepos
11452                           + sizeof (Elf32_External_compact_rel));
11453             cpt.reserved0 = 0;
11454             cpt.reserved1 = 0;
11455             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
11456                                             ((Elf32_External_compact_rel *)
11457                                              s->contents));
11458
11459             /* Clean up a dummy stub function entry in .text.  */
11460             if (htab->sstubs != NULL)
11461               {
11462                 file_ptr dummy_offset;
11463
11464                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
11465                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
11466                 memset (htab->sstubs->contents + dummy_offset, 0,
11467                         htab->function_stub_size);
11468               }
11469           }
11470       }
11471
11472     /* The psABI says that the dynamic relocations must be sorted in
11473        increasing order of r_symndx.  The VxWorks EABI doesn't require
11474        this, and because the code below handles REL rather than RELA
11475        relocations, using it for VxWorks would be outright harmful.  */
11476     if (!htab->is_vxworks)
11477       {
11478         s = mips_elf_rel_dyn_section (info, FALSE);
11479         if (s != NULL
11480             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
11481           {
11482             reldyn_sorting_bfd = output_bfd;
11483
11484             if (ABI_64_P (output_bfd))
11485               qsort ((Elf64_External_Rel *) s->contents + 1,
11486                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
11487                      sort_dynamic_relocs_64);
11488             else
11489               qsort ((Elf32_External_Rel *) s->contents + 1,
11490                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
11491                      sort_dynamic_relocs);
11492           }
11493       }
11494   }
11495
11496   if (htab->splt && htab->splt->size > 0)
11497     {
11498       if (htab->is_vxworks)
11499         {
11500           if (info->shared)
11501             mips_vxworks_finish_shared_plt (output_bfd, info);
11502           else
11503             mips_vxworks_finish_exec_plt (output_bfd, info);
11504         }
11505       else
11506         {
11507           BFD_ASSERT (!info->shared);
11508           if (!mips_finish_exec_plt (output_bfd, info))
11509             return FALSE;
11510         }
11511     }
11512   return TRUE;
11513 }
11514
11515
11516 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
11517
11518 static void
11519 mips_set_isa_flags (bfd *abfd)
11520 {
11521   flagword val;
11522
11523   switch (bfd_get_mach (abfd))
11524     {
11525     default:
11526     case bfd_mach_mips3000:
11527       val = E_MIPS_ARCH_1;
11528       break;
11529
11530     case bfd_mach_mips3900:
11531       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
11532       break;
11533
11534     case bfd_mach_mips6000:
11535       val = E_MIPS_ARCH_2;
11536       break;
11537
11538     case bfd_mach_mips4000:
11539     case bfd_mach_mips4300:
11540     case bfd_mach_mips4400:
11541     case bfd_mach_mips4600:
11542       val = E_MIPS_ARCH_3;
11543       break;
11544
11545     case bfd_mach_mips4010:
11546       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
11547       break;
11548
11549     case bfd_mach_mips4100:
11550       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
11551       break;
11552
11553     case bfd_mach_mips4111:
11554       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
11555       break;
11556
11557     case bfd_mach_mips4120:
11558       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
11559       break;
11560
11561     case bfd_mach_mips4650:
11562       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
11563       break;
11564
11565     case bfd_mach_mips5400:
11566       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
11567       break;
11568
11569     case bfd_mach_mips5500:
11570       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
11571       break;
11572
11573     case bfd_mach_mips5900:
11574       val = E_MIPS_ARCH_3 | E_MIPS_MACH_5900;
11575       break;
11576
11577     case bfd_mach_mips9000:
11578       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
11579       break;
11580
11581     case bfd_mach_mips5000:
11582     case bfd_mach_mips7000:
11583     case bfd_mach_mips8000:
11584     case bfd_mach_mips10000:
11585     case bfd_mach_mips12000:
11586     case bfd_mach_mips14000:
11587     case bfd_mach_mips16000:
11588       val = E_MIPS_ARCH_4;
11589       break;
11590
11591     case bfd_mach_mips5:
11592       val = E_MIPS_ARCH_5;
11593       break;
11594
11595     case bfd_mach_mips_loongson_2e:
11596       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
11597       break;
11598
11599     case bfd_mach_mips_loongson_2f:
11600       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
11601       break;
11602
11603     case bfd_mach_mips_sb1:
11604       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
11605       break;
11606
11607     case bfd_mach_mips_loongson_3a:
11608       val = E_MIPS_ARCH_64 | E_MIPS_MACH_LS3A;
11609       break;
11610
11611     case bfd_mach_mips_octeon:
11612     case bfd_mach_mips_octeonp:
11613       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
11614       break;
11615
11616     case bfd_mach_mips_xlr:
11617       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
11618       break;
11619
11620     case bfd_mach_mips_octeon2:
11621       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
11622       break;
11623
11624     case bfd_mach_mipsisa32:
11625       val = E_MIPS_ARCH_32;
11626       break;
11627
11628     case bfd_mach_mipsisa64:
11629       val = E_MIPS_ARCH_64;
11630       break;
11631
11632     case bfd_mach_mipsisa32r2:
11633       val = E_MIPS_ARCH_32R2;
11634       break;
11635
11636     case bfd_mach_mipsisa64r2:
11637       val = E_MIPS_ARCH_64R2;
11638       break;
11639     }
11640   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
11641   elf_elfheader (abfd)->e_flags |= val;
11642
11643 }
11644
11645
11646 /* The final processing done just before writing out a MIPS ELF object
11647    file.  This gets the MIPS architecture right based on the machine
11648    number.  This is used by both the 32-bit and the 64-bit ABI.  */
11649
11650 void
11651 _bfd_mips_elf_final_write_processing (bfd *abfd,
11652                                       bfd_boolean linker ATTRIBUTE_UNUSED)
11653 {
11654   unsigned int i;
11655   Elf_Internal_Shdr **hdrpp;
11656   const char *name;
11657   asection *sec;
11658
11659   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
11660      is nonzero.  This is for compatibility with old objects, which used
11661      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
11662   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
11663     mips_set_isa_flags (abfd);
11664
11665   /* Set the sh_info field for .gptab sections and other appropriate
11666      info for each special section.  */
11667   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
11668        i < elf_numsections (abfd);
11669        i++, hdrpp++)
11670     {
11671       switch ((*hdrpp)->sh_type)
11672         {
11673         case SHT_MIPS_MSYM:
11674         case SHT_MIPS_LIBLIST:
11675           sec = bfd_get_section_by_name (abfd, ".dynstr");
11676           if (sec != NULL)
11677             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11678           break;
11679
11680         case SHT_MIPS_GPTAB:
11681           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11682           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11683           BFD_ASSERT (name != NULL
11684                       && CONST_STRNEQ (name, ".gptab."));
11685           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
11686           BFD_ASSERT (sec != NULL);
11687           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11688           break;
11689
11690         case SHT_MIPS_CONTENT:
11691           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11692           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11693           BFD_ASSERT (name != NULL
11694                       && CONST_STRNEQ (name, ".MIPS.content"));
11695           sec = bfd_get_section_by_name (abfd,
11696                                          name + sizeof ".MIPS.content" - 1);
11697           BFD_ASSERT (sec != NULL);
11698           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11699           break;
11700
11701         case SHT_MIPS_SYMBOL_LIB:
11702           sec = bfd_get_section_by_name (abfd, ".dynsym");
11703           if (sec != NULL)
11704             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11705           sec = bfd_get_section_by_name (abfd, ".liblist");
11706           if (sec != NULL)
11707             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11708           break;
11709
11710         case SHT_MIPS_EVENTS:
11711           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11712           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11713           BFD_ASSERT (name != NULL);
11714           if (CONST_STRNEQ (name, ".MIPS.events"))
11715             sec = bfd_get_section_by_name (abfd,
11716                                            name + sizeof ".MIPS.events" - 1);
11717           else
11718             {
11719               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
11720               sec = bfd_get_section_by_name (abfd,
11721                                              (name
11722                                               + sizeof ".MIPS.post_rel" - 1));
11723             }
11724           BFD_ASSERT (sec != NULL);
11725           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11726           break;
11727
11728         }
11729     }
11730 }
11731 \f
11732 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
11733    segments.  */
11734
11735 int
11736 _bfd_mips_elf_additional_program_headers (bfd *abfd,
11737                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
11738 {
11739   asection *s;
11740   int ret = 0;
11741
11742   /* See if we need a PT_MIPS_REGINFO segment.  */
11743   s = bfd_get_section_by_name (abfd, ".reginfo");
11744   if (s && (s->flags & SEC_LOAD))
11745     ++ret;
11746
11747   /* See if we need a PT_MIPS_OPTIONS segment.  */
11748   if (IRIX_COMPAT (abfd) == ict_irix6
11749       && bfd_get_section_by_name (abfd,
11750                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
11751     ++ret;
11752
11753   /* See if we need a PT_MIPS_RTPROC segment.  */
11754   if (IRIX_COMPAT (abfd) == ict_irix5
11755       && bfd_get_section_by_name (abfd, ".dynamic")
11756       && bfd_get_section_by_name (abfd, ".mdebug"))
11757     ++ret;
11758
11759   /* Allocate a PT_NULL header in dynamic objects.  See
11760      _bfd_mips_elf_modify_segment_map for details.  */
11761   if (!SGI_COMPAT (abfd)
11762       && bfd_get_section_by_name (abfd, ".dynamic"))
11763     ++ret;
11764
11765   return ret;
11766 }
11767
11768 /* Modify the segment map for an IRIX5 executable.  */
11769
11770 bfd_boolean
11771 _bfd_mips_elf_modify_segment_map (bfd *abfd,
11772                                   struct bfd_link_info *info)
11773 {
11774   asection *s;
11775   struct elf_segment_map *m, **pm;
11776   bfd_size_type amt;
11777
11778   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
11779      segment.  */
11780   s = bfd_get_section_by_name (abfd, ".reginfo");
11781   if (s != NULL && (s->flags & SEC_LOAD) != 0)
11782     {
11783       for (m = elf_seg_map (abfd); m != NULL; m = m->next)
11784         if (m->p_type == PT_MIPS_REGINFO)
11785           break;
11786       if (m == NULL)
11787         {
11788           amt = sizeof *m;
11789           m = bfd_zalloc (abfd, amt);
11790           if (m == NULL)
11791             return FALSE;
11792
11793           m->p_type = PT_MIPS_REGINFO;
11794           m->count = 1;
11795           m->sections[0] = s;
11796
11797           /* We want to put it after the PHDR and INTERP segments.  */
11798           pm = &elf_seg_map (abfd);
11799           while (*pm != NULL
11800                  && ((*pm)->p_type == PT_PHDR
11801                      || (*pm)->p_type == PT_INTERP))
11802             pm = &(*pm)->next;
11803
11804           m->next = *pm;
11805           *pm = m;
11806         }
11807     }
11808
11809   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
11810      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
11811      PT_MIPS_OPTIONS segment immediately following the program header
11812      table.  */
11813   if (NEWABI_P (abfd)
11814       /* On non-IRIX6 new abi, we'll have already created a segment
11815          for this section, so don't create another.  I'm not sure this
11816          is not also the case for IRIX 6, but I can't test it right
11817          now.  */
11818       && IRIX_COMPAT (abfd) == ict_irix6)
11819     {
11820       for (s = abfd->sections; s; s = s->next)
11821         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
11822           break;
11823
11824       if (s)
11825         {
11826           struct elf_segment_map *options_segment;
11827
11828           pm = &elf_seg_map (abfd);
11829           while (*pm != NULL
11830                  && ((*pm)->p_type == PT_PHDR
11831                      || (*pm)->p_type == PT_INTERP))
11832             pm = &(*pm)->next;
11833
11834           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
11835             {
11836               amt = sizeof (struct elf_segment_map);
11837               options_segment = bfd_zalloc (abfd, amt);
11838               options_segment->next = *pm;
11839               options_segment->p_type = PT_MIPS_OPTIONS;
11840               options_segment->p_flags = PF_R;
11841               options_segment->p_flags_valid = TRUE;
11842               options_segment->count = 1;
11843               options_segment->sections[0] = s;
11844               *pm = options_segment;
11845             }
11846         }
11847     }
11848   else
11849     {
11850       if (IRIX_COMPAT (abfd) == ict_irix5)
11851         {
11852           /* If there are .dynamic and .mdebug sections, we make a room
11853              for the RTPROC header.  FIXME: Rewrite without section names.  */
11854           if (bfd_get_section_by_name (abfd, ".interp") == NULL
11855               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
11856               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
11857             {
11858               for (m = elf_seg_map (abfd); m != NULL; m = m->next)
11859                 if (m->p_type == PT_MIPS_RTPROC)
11860                   break;
11861               if (m == NULL)
11862                 {
11863                   amt = sizeof *m;
11864                   m = bfd_zalloc (abfd, amt);
11865                   if (m == NULL)
11866                     return FALSE;
11867
11868                   m->p_type = PT_MIPS_RTPROC;
11869
11870                   s = bfd_get_section_by_name (abfd, ".rtproc");
11871                   if (s == NULL)
11872                     {
11873                       m->count = 0;
11874                       m->p_flags = 0;
11875                       m->p_flags_valid = 1;
11876                     }
11877                   else
11878                     {
11879                       m->count = 1;
11880                       m->sections[0] = s;
11881                     }
11882
11883                   /* We want to put it after the DYNAMIC segment.  */
11884                   pm = &elf_seg_map (abfd);
11885                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
11886                     pm = &(*pm)->next;
11887                   if (*pm != NULL)
11888                     pm = &(*pm)->next;
11889
11890                   m->next = *pm;
11891                   *pm = m;
11892                 }
11893             }
11894         }
11895       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
11896          .dynstr, .dynsym, and .hash sections, and everything in
11897          between.  */
11898       for (pm = &elf_seg_map (abfd); *pm != NULL;
11899            pm = &(*pm)->next)
11900         if ((*pm)->p_type == PT_DYNAMIC)
11901           break;
11902       m = *pm;
11903       if (m != NULL && IRIX_COMPAT (abfd) == ict_none)
11904         {
11905           /* For a normal mips executable the permissions for the PT_DYNAMIC
11906              segment are read, write and execute. We do that here since
11907              the code in elf.c sets only the read permission. This matters
11908              sometimes for the dynamic linker.  */
11909           if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
11910             {
11911               m->p_flags = PF_R | PF_W | PF_X;
11912               m->p_flags_valid = 1;
11913             }
11914         }
11915       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
11916          glibc's dynamic linker has traditionally derived the number of
11917          tags from the p_filesz field, and sometimes allocates stack
11918          arrays of that size.  An overly-big PT_DYNAMIC segment can
11919          be actively harmful in such cases.  Making PT_DYNAMIC contain
11920          other sections can also make life hard for the prelinker,
11921          which might move one of the other sections to a different
11922          PT_LOAD segment.  */
11923       if (SGI_COMPAT (abfd)
11924           && m != NULL
11925           && m->count == 1
11926           && strcmp (m->sections[0]->name, ".dynamic") == 0)
11927         {
11928           static const char *sec_names[] =
11929           {
11930             ".dynamic", ".dynstr", ".dynsym", ".hash"
11931           };
11932           bfd_vma low, high;
11933           unsigned int i, c;
11934           struct elf_segment_map *n;
11935
11936           low = ~(bfd_vma) 0;
11937           high = 0;
11938           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
11939             {
11940               s = bfd_get_section_by_name (abfd, sec_names[i]);
11941               if (s != NULL && (s->flags & SEC_LOAD) != 0)
11942                 {
11943                   bfd_size_type sz;
11944
11945                   if (low > s->vma)
11946                     low = s->vma;
11947                   sz = s->size;
11948                   if (high < s->vma + sz)
11949                     high = s->vma + sz;
11950                 }
11951             }
11952
11953           c = 0;
11954           for (s = abfd->sections; s != NULL; s = s->next)
11955             if ((s->flags & SEC_LOAD) != 0
11956                 && s->vma >= low
11957                 && s->vma + s->size <= high)
11958               ++c;
11959
11960           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
11961           n = bfd_zalloc (abfd, amt);
11962           if (n == NULL)
11963             return FALSE;
11964           *n = *m;
11965           n->count = c;
11966
11967           i = 0;
11968           for (s = abfd->sections; s != NULL; s = s->next)
11969             {
11970               if ((s->flags & SEC_LOAD) != 0
11971                   && s->vma >= low
11972                   && s->vma + s->size <= high)
11973                 {
11974                   n->sections[i] = s;
11975                   ++i;
11976                 }
11977             }
11978
11979           *pm = n;
11980         }
11981     }
11982
11983   /* Allocate a spare program header in dynamic objects so that tools
11984      like the prelinker can add an extra PT_LOAD entry.
11985
11986      If the prelinker needs to make room for a new PT_LOAD entry, its
11987      standard procedure is to move the first (read-only) sections into
11988      the new (writable) segment.  However, the MIPS ABI requires
11989      .dynamic to be in a read-only segment, and the section will often
11990      start within sizeof (ElfNN_Phdr) bytes of the last program header.
11991
11992      Although the prelinker could in principle move .dynamic to a
11993      writable segment, it seems better to allocate a spare program
11994      header instead, and avoid the need to move any sections.
11995      There is a long tradition of allocating spare dynamic tags,
11996      so allocating a spare program header seems like a natural
11997      extension.
11998
11999      If INFO is NULL, we may be copying an already prelinked binary
12000      with objcopy or strip, so do not add this header.  */
12001   if (info != NULL
12002       && !SGI_COMPAT (abfd)
12003       && bfd_get_section_by_name (abfd, ".dynamic"))
12004     {
12005       for (pm = &elf_seg_map (abfd); *pm != NULL; pm = &(*pm)->next)
12006         if ((*pm)->p_type == PT_NULL)
12007           break;
12008       if (*pm == NULL)
12009         {
12010           m = bfd_zalloc (abfd, sizeof (*m));
12011           if (m == NULL)
12012             return FALSE;
12013
12014           m->p_type = PT_NULL;
12015           *pm = m;
12016         }
12017     }
12018
12019   return TRUE;
12020 }
12021 \f
12022 /* Return the section that should be marked against GC for a given
12023    relocation.  */
12024
12025 asection *
12026 _bfd_mips_elf_gc_mark_hook (asection *sec,
12027                             struct bfd_link_info *info,
12028                             Elf_Internal_Rela *rel,
12029                             struct elf_link_hash_entry *h,
12030                             Elf_Internal_Sym *sym)
12031 {
12032   /* ??? Do mips16 stub sections need to be handled special?  */
12033
12034   if (h != NULL)
12035     switch (ELF_R_TYPE (sec->owner, rel->r_info))
12036       {
12037       case R_MIPS_GNU_VTINHERIT:
12038       case R_MIPS_GNU_VTENTRY:
12039         return NULL;
12040       }
12041
12042   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
12043 }
12044
12045 /* Update the got entry reference counts for the section being removed.  */
12046
12047 bfd_boolean
12048 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
12049                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
12050                              asection *sec ATTRIBUTE_UNUSED,
12051                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
12052 {
12053 #if 0
12054   Elf_Internal_Shdr *symtab_hdr;
12055   struct elf_link_hash_entry **sym_hashes;
12056   bfd_signed_vma *local_got_refcounts;
12057   const Elf_Internal_Rela *rel, *relend;
12058   unsigned long r_symndx;
12059   struct elf_link_hash_entry *h;
12060
12061   if (info->relocatable)
12062     return TRUE;
12063
12064   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12065   sym_hashes = elf_sym_hashes (abfd);
12066   local_got_refcounts = elf_local_got_refcounts (abfd);
12067
12068   relend = relocs + sec->reloc_count;
12069   for (rel = relocs; rel < relend; rel++)
12070     switch (ELF_R_TYPE (abfd, rel->r_info))
12071       {
12072       case R_MIPS16_GOT16:
12073       case R_MIPS16_CALL16:
12074       case R_MIPS_GOT16:
12075       case R_MIPS_CALL16:
12076       case R_MIPS_CALL_HI16:
12077       case R_MIPS_CALL_LO16:
12078       case R_MIPS_GOT_HI16:
12079       case R_MIPS_GOT_LO16:
12080       case R_MIPS_GOT_DISP:
12081       case R_MIPS_GOT_PAGE:
12082       case R_MIPS_GOT_OFST:
12083       case R_MICROMIPS_GOT16:
12084       case R_MICROMIPS_CALL16:
12085       case R_MICROMIPS_CALL_HI16:
12086       case R_MICROMIPS_CALL_LO16:
12087       case R_MICROMIPS_GOT_HI16:
12088       case R_MICROMIPS_GOT_LO16:
12089       case R_MICROMIPS_GOT_DISP:
12090       case R_MICROMIPS_GOT_PAGE:
12091       case R_MICROMIPS_GOT_OFST:
12092         /* ??? It would seem that the existing MIPS code does no sort
12093            of reference counting or whatnot on its GOT and PLT entries,
12094            so it is not possible to garbage collect them at this time.  */
12095         break;
12096
12097       default:
12098         break;
12099       }
12100 #endif
12101
12102   return TRUE;
12103 }
12104 \f
12105 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
12106    hiding the old indirect symbol.  Process additional relocation
12107    information.  Also called for weakdefs, in which case we just let
12108    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
12109
12110 void
12111 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
12112                                     struct elf_link_hash_entry *dir,
12113                                     struct elf_link_hash_entry *ind)
12114 {
12115   struct mips_elf_link_hash_entry *dirmips, *indmips;
12116
12117   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
12118
12119   dirmips = (struct mips_elf_link_hash_entry *) dir;
12120   indmips = (struct mips_elf_link_hash_entry *) ind;
12121   /* Any absolute non-dynamic relocations against an indirect or weak
12122      definition will be against the target symbol.  */
12123   if (indmips->has_static_relocs)
12124     dirmips->has_static_relocs = TRUE;
12125
12126   if (ind->root.type != bfd_link_hash_indirect)
12127     return;
12128
12129   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
12130   if (indmips->readonly_reloc)
12131     dirmips->readonly_reloc = TRUE;
12132   if (indmips->no_fn_stub)
12133     dirmips->no_fn_stub = TRUE;
12134   if (indmips->fn_stub)
12135     {
12136       dirmips->fn_stub = indmips->fn_stub;
12137       indmips->fn_stub = NULL;
12138     }
12139   if (indmips->need_fn_stub)
12140     {
12141       dirmips->need_fn_stub = TRUE;
12142       indmips->need_fn_stub = FALSE;
12143     }
12144   if (indmips->call_stub)
12145     {
12146       dirmips->call_stub = indmips->call_stub;
12147       indmips->call_stub = NULL;
12148     }
12149   if (indmips->call_fp_stub)
12150     {
12151       dirmips->call_fp_stub = indmips->call_fp_stub;
12152       indmips->call_fp_stub = NULL;
12153     }
12154   if (indmips->global_got_area < dirmips->global_got_area)
12155     dirmips->global_got_area = indmips->global_got_area;
12156   if (indmips->global_got_area < GGA_NONE)
12157     indmips->global_got_area = GGA_NONE;
12158   if (indmips->has_nonpic_branches)
12159     dirmips->has_nonpic_branches = TRUE;
12160 }
12161 \f
12162 #define PDR_SIZE 32
12163
12164 bfd_boolean
12165 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
12166                             struct bfd_link_info *info)
12167 {
12168   asection *o;
12169   bfd_boolean ret = FALSE;
12170   unsigned char *tdata;
12171   size_t i, skip;
12172
12173   o = bfd_get_section_by_name (abfd, ".pdr");
12174   if (! o)
12175     return FALSE;
12176   if (o->size == 0)
12177     return FALSE;
12178   if (o->size % PDR_SIZE != 0)
12179     return FALSE;
12180   if (o->output_section != NULL
12181       && bfd_is_abs_section (o->output_section))
12182     return FALSE;
12183
12184   tdata = bfd_zmalloc (o->size / PDR_SIZE);
12185   if (! tdata)
12186     return FALSE;
12187
12188   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
12189                                             info->keep_memory);
12190   if (!cookie->rels)
12191     {
12192       free (tdata);
12193       return FALSE;
12194     }
12195
12196   cookie->rel = cookie->rels;
12197   cookie->relend = cookie->rels + o->reloc_count;
12198
12199   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
12200     {
12201       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
12202         {
12203           tdata[i] = 1;
12204           skip ++;
12205         }
12206     }
12207
12208   if (skip != 0)
12209     {
12210       mips_elf_section_data (o)->u.tdata = tdata;
12211       o->size -= skip * PDR_SIZE;
12212       ret = TRUE;
12213     }
12214   else
12215     free (tdata);
12216
12217   if (! info->keep_memory)
12218     free (cookie->rels);
12219
12220   return ret;
12221 }
12222
12223 bfd_boolean
12224 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
12225 {
12226   if (strcmp (sec->name, ".pdr") == 0)
12227     return TRUE;
12228   return FALSE;
12229 }
12230
12231 bfd_boolean
12232 _bfd_mips_elf_write_section (bfd *output_bfd,
12233                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
12234                              asection *sec, bfd_byte *contents)
12235 {
12236   bfd_byte *to, *from, *end;
12237   int i;
12238
12239   if (strcmp (sec->name, ".pdr") != 0)
12240     return FALSE;
12241
12242   if (mips_elf_section_data (sec)->u.tdata == NULL)
12243     return FALSE;
12244
12245   to = contents;
12246   end = contents + sec->size;
12247   for (from = contents, i = 0;
12248        from < end;
12249        from += PDR_SIZE, i++)
12250     {
12251       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
12252         continue;
12253       if (to != from)
12254         memcpy (to, from, PDR_SIZE);
12255       to += PDR_SIZE;
12256     }
12257   bfd_set_section_contents (output_bfd, sec->output_section, contents,
12258                             sec->output_offset, sec->size);
12259   return TRUE;
12260 }
12261 \f
12262 /* microMIPS code retains local labels for linker relaxation.  Omit them
12263    from output by default for clarity.  */
12264
12265 bfd_boolean
12266 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
12267 {
12268   return _bfd_elf_is_local_label_name (abfd, sym->name);
12269 }
12270
12271 /* MIPS ELF uses a special find_nearest_line routine in order the
12272    handle the ECOFF debugging information.  */
12273
12274 struct mips_elf_find_line
12275 {
12276   struct ecoff_debug_info d;
12277   struct ecoff_find_line i;
12278 };
12279
12280 bfd_boolean
12281 _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section,
12282                                  asymbol **symbols, bfd_vma offset,
12283                                  const char **filename_ptr,
12284                                  const char **functionname_ptr,
12285                                  unsigned int *line_ptr)
12286 {
12287   asection *msec;
12288
12289   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
12290                                      filename_ptr, functionname_ptr,
12291                                      line_ptr))
12292     return TRUE;
12293
12294   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
12295                                      section, symbols, offset,
12296                                      filename_ptr, functionname_ptr,
12297                                      line_ptr, NULL, ABI_64_P (abfd) ? 8 : 0,
12298                                      &elf_tdata (abfd)->dwarf2_find_line_info))
12299     return TRUE;
12300
12301   msec = bfd_get_section_by_name (abfd, ".mdebug");
12302   if (msec != NULL)
12303     {
12304       flagword origflags;
12305       struct mips_elf_find_line *fi;
12306       const struct ecoff_debug_swap * const swap =
12307         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
12308
12309       /* If we are called during a link, mips_elf_final_link may have
12310          cleared the SEC_HAS_CONTENTS field.  We force it back on here
12311          if appropriate (which it normally will be).  */
12312       origflags = msec->flags;
12313       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
12314         msec->flags |= SEC_HAS_CONTENTS;
12315
12316       fi = mips_elf_tdata (abfd)->find_line_info;
12317       if (fi == NULL)
12318         {
12319           bfd_size_type external_fdr_size;
12320           char *fraw_src;
12321           char *fraw_end;
12322           struct fdr *fdr_ptr;
12323           bfd_size_type amt = sizeof (struct mips_elf_find_line);
12324
12325           fi = bfd_zalloc (abfd, amt);
12326           if (fi == NULL)
12327             {
12328               msec->flags = origflags;
12329               return FALSE;
12330             }
12331
12332           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
12333             {
12334               msec->flags = origflags;
12335               return FALSE;
12336             }
12337
12338           /* Swap in the FDR information.  */
12339           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
12340           fi->d.fdr = bfd_alloc (abfd, amt);
12341           if (fi->d.fdr == NULL)
12342             {
12343               msec->flags = origflags;
12344               return FALSE;
12345             }
12346           external_fdr_size = swap->external_fdr_size;
12347           fdr_ptr = fi->d.fdr;
12348           fraw_src = (char *) fi->d.external_fdr;
12349           fraw_end = (fraw_src
12350                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
12351           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
12352             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
12353
12354           mips_elf_tdata (abfd)->find_line_info = fi;
12355
12356           /* Note that we don't bother to ever free this information.
12357              find_nearest_line is either called all the time, as in
12358              objdump -l, so the information should be saved, or it is
12359              rarely called, as in ld error messages, so the memory
12360              wasted is unimportant.  Still, it would probably be a
12361              good idea for free_cached_info to throw it away.  */
12362         }
12363
12364       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
12365                                   &fi->i, filename_ptr, functionname_ptr,
12366                                   line_ptr))
12367         {
12368           msec->flags = origflags;
12369           return TRUE;
12370         }
12371
12372       msec->flags = origflags;
12373     }
12374
12375   /* Fall back on the generic ELF find_nearest_line routine.  */
12376
12377   return _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
12378                                      filename_ptr, functionname_ptr,
12379                                      line_ptr);
12380 }
12381
12382 bfd_boolean
12383 _bfd_mips_elf_find_inliner_info (bfd *abfd,
12384                                  const char **filename_ptr,
12385                                  const char **functionname_ptr,
12386                                  unsigned int *line_ptr)
12387 {
12388   bfd_boolean found;
12389   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
12390                                          functionname_ptr, line_ptr,
12391                                          & elf_tdata (abfd)->dwarf2_find_line_info);
12392   return found;
12393 }
12394
12395 \f
12396 /* When are writing out the .options or .MIPS.options section,
12397    remember the bytes we are writing out, so that we can install the
12398    GP value in the section_processing routine.  */
12399
12400 bfd_boolean
12401 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
12402                                     const void *location,
12403                                     file_ptr offset, bfd_size_type count)
12404 {
12405   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
12406     {
12407       bfd_byte *c;
12408
12409       if (elf_section_data (section) == NULL)
12410         {
12411           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
12412           section->used_by_bfd = bfd_zalloc (abfd, amt);
12413           if (elf_section_data (section) == NULL)
12414             return FALSE;
12415         }
12416       c = mips_elf_section_data (section)->u.tdata;
12417       if (c == NULL)
12418         {
12419           c = bfd_zalloc (abfd, section->size);
12420           if (c == NULL)
12421             return FALSE;
12422           mips_elf_section_data (section)->u.tdata = c;
12423         }
12424
12425       memcpy (c + offset, location, count);
12426     }
12427
12428   return _bfd_elf_set_section_contents (abfd, section, location, offset,
12429                                         count);
12430 }
12431
12432 /* This is almost identical to bfd_generic_get_... except that some
12433    MIPS relocations need to be handled specially.  Sigh.  */
12434
12435 bfd_byte *
12436 _bfd_elf_mips_get_relocated_section_contents
12437   (bfd *abfd,
12438    struct bfd_link_info *link_info,
12439    struct bfd_link_order *link_order,
12440    bfd_byte *data,
12441    bfd_boolean relocatable,
12442    asymbol **symbols)
12443 {
12444   /* Get enough memory to hold the stuff */
12445   bfd *input_bfd = link_order->u.indirect.section->owner;
12446   asection *input_section = link_order->u.indirect.section;
12447   bfd_size_type sz;
12448
12449   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
12450   arelent **reloc_vector = NULL;
12451   long reloc_count;
12452
12453   if (reloc_size < 0)
12454     goto error_return;
12455
12456   reloc_vector = bfd_malloc (reloc_size);
12457   if (reloc_vector == NULL && reloc_size != 0)
12458     goto error_return;
12459
12460   /* read in the section */
12461   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
12462   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
12463     goto error_return;
12464
12465   reloc_count = bfd_canonicalize_reloc (input_bfd,
12466                                         input_section,
12467                                         reloc_vector,
12468                                         symbols);
12469   if (reloc_count < 0)
12470     goto error_return;
12471
12472   if (reloc_count > 0)
12473     {
12474       arelent **parent;
12475       /* for mips */
12476       int gp_found;
12477       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
12478
12479       {
12480         struct bfd_hash_entry *h;
12481         struct bfd_link_hash_entry *lh;
12482         /* Skip all this stuff if we aren't mixing formats.  */
12483         if (abfd && input_bfd
12484             && abfd->xvec == input_bfd->xvec)
12485           lh = 0;
12486         else
12487           {
12488             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
12489             lh = (struct bfd_link_hash_entry *) h;
12490           }
12491       lookup:
12492         if (lh)
12493           {
12494             switch (lh->type)
12495               {
12496               case bfd_link_hash_undefined:
12497               case bfd_link_hash_undefweak:
12498               case bfd_link_hash_common:
12499                 gp_found = 0;
12500                 break;
12501               case bfd_link_hash_defined:
12502               case bfd_link_hash_defweak:
12503                 gp_found = 1;
12504                 gp = lh->u.def.value;
12505                 break;
12506               case bfd_link_hash_indirect:
12507               case bfd_link_hash_warning:
12508                 lh = lh->u.i.link;
12509                 /* @@FIXME  ignoring warning for now */
12510                 goto lookup;
12511               case bfd_link_hash_new:
12512               default:
12513                 abort ();
12514               }
12515           }
12516         else
12517           gp_found = 0;
12518       }
12519       /* end mips */
12520       for (parent = reloc_vector; *parent != NULL; parent++)
12521         {
12522           char *error_message = NULL;
12523           bfd_reloc_status_type r;
12524
12525           /* Specific to MIPS: Deal with relocation types that require
12526              knowing the gp of the output bfd.  */
12527           asymbol *sym = *(*parent)->sym_ptr_ptr;
12528
12529           /* If we've managed to find the gp and have a special
12530              function for the relocation then go ahead, else default
12531              to the generic handling.  */
12532           if (gp_found
12533               && (*parent)->howto->special_function
12534               == _bfd_mips_elf32_gprel16_reloc)
12535             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
12536                                                input_section, relocatable,
12537                                                data, gp);
12538           else
12539             r = bfd_perform_relocation (input_bfd, *parent, data,
12540                                         input_section,
12541                                         relocatable ? abfd : NULL,
12542                                         &error_message);
12543
12544           if (relocatable)
12545             {
12546               asection *os = input_section->output_section;
12547
12548               /* A partial link, so keep the relocs */
12549               os->orelocation[os->reloc_count] = *parent;
12550               os->reloc_count++;
12551             }
12552
12553           if (r != bfd_reloc_ok)
12554             {
12555               switch (r)
12556                 {
12557                 case bfd_reloc_undefined:
12558                   if (!((*link_info->callbacks->undefined_symbol)
12559                         (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
12560                          input_bfd, input_section, (*parent)->address, TRUE)))
12561                     goto error_return;
12562                   break;
12563                 case bfd_reloc_dangerous:
12564                   BFD_ASSERT (error_message != NULL);
12565                   if (!((*link_info->callbacks->reloc_dangerous)
12566                         (link_info, error_message, input_bfd, input_section,
12567                          (*parent)->address)))
12568                     goto error_return;
12569                   break;
12570                 case bfd_reloc_overflow:
12571                   if (!((*link_info->callbacks->reloc_overflow)
12572                         (link_info, NULL,
12573                          bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
12574                          (*parent)->howto->name, (*parent)->addend,
12575                          input_bfd, input_section, (*parent)->address)))
12576                     goto error_return;
12577                   break;
12578                 case bfd_reloc_outofrange:
12579                 default:
12580                   abort ();
12581                   break;
12582                 }
12583
12584             }
12585         }
12586     }
12587   if (reloc_vector != NULL)
12588     free (reloc_vector);
12589   return data;
12590
12591 error_return:
12592   if (reloc_vector != NULL)
12593     free (reloc_vector);
12594   return NULL;
12595 }
12596 \f
12597 static bfd_boolean
12598 mips_elf_relax_delete_bytes (bfd *abfd,
12599                              asection *sec, bfd_vma addr, int count)
12600 {
12601   Elf_Internal_Shdr *symtab_hdr;
12602   unsigned int sec_shndx;
12603   bfd_byte *contents;
12604   Elf_Internal_Rela *irel, *irelend;
12605   Elf_Internal_Sym *isym;
12606   Elf_Internal_Sym *isymend;
12607   struct elf_link_hash_entry **sym_hashes;
12608   struct elf_link_hash_entry **end_hashes;
12609   struct elf_link_hash_entry **start_hashes;
12610   unsigned int symcount;
12611
12612   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
12613   contents = elf_section_data (sec)->this_hdr.contents;
12614
12615   irel = elf_section_data (sec)->relocs;
12616   irelend = irel + sec->reloc_count;
12617
12618   /* Actually delete the bytes.  */
12619   memmove (contents + addr, contents + addr + count,
12620            (size_t) (sec->size - addr - count));
12621   sec->size -= count;
12622
12623   /* Adjust all the relocs.  */
12624   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
12625     {
12626       /* Get the new reloc address.  */
12627       if (irel->r_offset > addr)
12628         irel->r_offset -= count;
12629     }
12630
12631   BFD_ASSERT (addr % 2 == 0);
12632   BFD_ASSERT (count % 2 == 0);
12633
12634   /* Adjust the local symbols defined in this section.  */
12635   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12636   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
12637   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
12638     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
12639       isym->st_value -= count;
12640
12641   /* Now adjust the global symbols defined in this section.  */
12642   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
12643               - symtab_hdr->sh_info);
12644   sym_hashes = start_hashes = elf_sym_hashes (abfd);
12645   end_hashes = sym_hashes + symcount;
12646
12647   for (; sym_hashes < end_hashes; sym_hashes++)
12648     {
12649       struct elf_link_hash_entry *sym_hash = *sym_hashes;
12650
12651       if ((sym_hash->root.type == bfd_link_hash_defined
12652            || sym_hash->root.type == bfd_link_hash_defweak)
12653           && sym_hash->root.u.def.section == sec)
12654         {
12655           bfd_vma value = sym_hash->root.u.def.value;
12656
12657           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
12658             value &= MINUS_TWO;
12659           if (value > addr)
12660             sym_hash->root.u.def.value -= count;
12661         }
12662     }
12663
12664   return TRUE;
12665 }
12666
12667
12668 /* Opcodes needed for microMIPS relaxation as found in
12669    opcodes/micromips-opc.c.  */
12670
12671 struct opcode_descriptor {
12672   unsigned long match;
12673   unsigned long mask;
12674 };
12675
12676 /* The $ra register aka $31.  */
12677
12678 #define RA 31
12679
12680 /* 32-bit instruction format register fields.  */
12681
12682 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
12683 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
12684
12685 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
12686
12687 #define OP16_VALID_REG(r) \
12688   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
12689
12690
12691 /* 32-bit and 16-bit branches.  */
12692
12693 static const struct opcode_descriptor b_insns_32[] = {
12694   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
12695   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
12696   { 0, 0 }  /* End marker for find_match().  */
12697 };
12698
12699 static const struct opcode_descriptor bc_insn_32 =
12700   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
12701
12702 static const struct opcode_descriptor bz_insn_32 =
12703   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
12704
12705 static const struct opcode_descriptor bzal_insn_32 =
12706   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
12707
12708 static const struct opcode_descriptor beq_insn_32 =
12709   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
12710
12711 static const struct opcode_descriptor b_insn_16 =
12712   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
12713
12714 static const struct opcode_descriptor bz_insn_16 =
12715   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
12716
12717
12718 /* 32-bit and 16-bit branch EQ and NE zero.  */
12719
12720 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
12721    eq and second the ne.  This convention is used when replacing a
12722    32-bit BEQ/BNE with the 16-bit version.  */
12723
12724 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
12725
12726 static const struct opcode_descriptor bz_rs_insns_32[] = {
12727   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
12728   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
12729   { 0, 0 }  /* End marker for find_match().  */
12730 };
12731
12732 static const struct opcode_descriptor bz_rt_insns_32[] = {
12733   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
12734   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
12735   { 0, 0 }  /* End marker for find_match().  */
12736 };
12737
12738 static const struct opcode_descriptor bzc_insns_32[] = {
12739   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
12740   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
12741   { 0, 0 }  /* End marker for find_match().  */
12742 };
12743
12744 static const struct opcode_descriptor bz_insns_16[] = {
12745   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
12746   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
12747   { 0, 0 }  /* End marker for find_match().  */
12748 };
12749
12750 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
12751
12752 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0x17) + 2)
12753 #define BZ16_REG_FIELD(r) \
12754   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 7)
12755
12756
12757 /* 32-bit instructions with a delay slot.  */
12758
12759 static const struct opcode_descriptor jal_insn_32_bd16 =
12760   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
12761
12762 static const struct opcode_descriptor jal_insn_32_bd32 =
12763   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
12764
12765 static const struct opcode_descriptor jal_x_insn_32_bd32 =
12766   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
12767
12768 static const struct opcode_descriptor j_insn_32 =
12769   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
12770
12771 static const struct opcode_descriptor jalr_insn_32 =
12772   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
12773
12774 /* This table can be compacted, because no opcode replacement is made.  */
12775
12776 static const struct opcode_descriptor ds_insns_32_bd16[] = {
12777   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
12778
12779   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
12780   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
12781
12782   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
12783   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
12784   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
12785   { 0, 0 }  /* End marker for find_match().  */
12786 };
12787
12788 /* This table can be compacted, because no opcode replacement is made.  */
12789
12790 static const struct opcode_descriptor ds_insns_32_bd32[] = {
12791   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
12792
12793   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
12794   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
12795   { 0, 0 }  /* End marker for find_match().  */
12796 };
12797
12798
12799 /* 16-bit instructions with a delay slot.  */
12800
12801 static const struct opcode_descriptor jalr_insn_16_bd16 =
12802   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
12803
12804 static const struct opcode_descriptor jalr_insn_16_bd32 =
12805   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
12806
12807 static const struct opcode_descriptor jr_insn_16 =
12808   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
12809
12810 #define JR16_REG(opcode) ((opcode) & 0x1f)
12811
12812 /* This table can be compacted, because no opcode replacement is made.  */
12813
12814 static const struct opcode_descriptor ds_insns_16_bd16[] = {
12815   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
12816
12817   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
12818   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
12819   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
12820   { 0, 0 }  /* End marker for find_match().  */
12821 };
12822
12823
12824 /* LUI instruction.  */
12825
12826 static const struct opcode_descriptor lui_insn =
12827  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
12828
12829
12830 /* ADDIU instruction.  */
12831
12832 static const struct opcode_descriptor addiu_insn =
12833   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
12834
12835 static const struct opcode_descriptor addiupc_insn =
12836   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
12837
12838 #define ADDIUPC_REG_FIELD(r) \
12839   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
12840
12841
12842 /* Relaxable instructions in a JAL delay slot: MOVE.  */
12843
12844 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
12845    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
12846 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
12847 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
12848
12849 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
12850 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
12851
12852 static const struct opcode_descriptor move_insns_32[] = {
12853   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
12854   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
12855   { 0, 0 }  /* End marker for find_match().  */
12856 };
12857
12858 static const struct opcode_descriptor move_insn_16 =
12859   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
12860
12861
12862 /* NOP instructions.  */
12863
12864 static const struct opcode_descriptor nop_insn_32 =
12865   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
12866
12867 static const struct opcode_descriptor nop_insn_16 =
12868   { /* "nop",   "",             */ 0x0c00,     0xffff };
12869
12870
12871 /* Instruction match support.  */
12872
12873 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
12874
12875 static int
12876 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
12877 {
12878   unsigned long indx;
12879
12880   for (indx = 0; insn[indx].mask != 0; indx++)
12881     if (MATCH (opcode, insn[indx]))
12882       return indx;
12883
12884   return -1;
12885 }
12886
12887
12888 /* Branch and delay slot decoding support.  */
12889
12890 /* If PTR points to what *might* be a 16-bit branch or jump, then
12891    return the minimum length of its delay slot, otherwise return 0.
12892    Non-zero results are not definitive as we might be checking against
12893    the second half of another instruction.  */
12894
12895 static int
12896 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
12897 {
12898   unsigned long opcode;
12899   int bdsize;
12900
12901   opcode = bfd_get_16 (abfd, ptr);
12902   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
12903     /* 16-bit branch/jump with a 32-bit delay slot.  */
12904     bdsize = 4;
12905   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
12906            || find_match (opcode, ds_insns_16_bd16) >= 0)
12907     /* 16-bit branch/jump with a 16-bit delay slot.  */
12908     bdsize = 2;
12909   else
12910     /* No delay slot.  */
12911     bdsize = 0;
12912
12913   return bdsize;
12914 }
12915
12916 /* If PTR points to what *might* be a 32-bit branch or jump, then
12917    return the minimum length of its delay slot, otherwise return 0.
12918    Non-zero results are not definitive as we might be checking against
12919    the second half of another instruction.  */
12920
12921 static int
12922 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
12923 {
12924   unsigned long opcode;
12925   int bdsize;
12926
12927   opcode = bfd_get_micromips_32 (abfd, ptr);
12928   if (find_match (opcode, ds_insns_32_bd32) >= 0)
12929     /* 32-bit branch/jump with a 32-bit delay slot.  */
12930     bdsize = 4;
12931   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
12932     /* 32-bit branch/jump with a 16-bit delay slot.  */
12933     bdsize = 2;
12934   else
12935     /* No delay slot.  */
12936     bdsize = 0;
12937
12938   return bdsize;
12939 }
12940
12941 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
12942    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
12943
12944 static bfd_boolean
12945 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12946 {
12947   unsigned long opcode;
12948
12949   opcode = bfd_get_16 (abfd, ptr);
12950   if (MATCH (opcode, b_insn_16)
12951                                                 /* B16  */
12952       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
12953                                                 /* JR16  */
12954       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
12955                                                 /* BEQZ16, BNEZ16  */
12956       || (MATCH (opcode, jalr_insn_16_bd32)
12957                                                 /* JALR16  */
12958           && reg != JR16_REG (opcode) && reg != RA))
12959     return TRUE;
12960
12961   return FALSE;
12962 }
12963
12964 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
12965    then return TRUE, otherwise FALSE.  */
12966
12967 static bfd_boolean
12968 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12969 {
12970   unsigned long opcode;
12971
12972   opcode = bfd_get_micromips_32 (abfd, ptr);
12973   if (MATCH (opcode, j_insn_32)
12974                                                 /* J  */
12975       || MATCH (opcode, bc_insn_32)
12976                                                 /* BC1F, BC1T, BC2F, BC2T  */
12977       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
12978                                                 /* JAL, JALX  */
12979       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
12980                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
12981       || (MATCH (opcode, bzal_insn_32)
12982                                                 /* BGEZAL, BLTZAL  */
12983           && reg != OP32_SREG (opcode) && reg != RA)
12984       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
12985                                                 /* JALR, JALR.HB, BEQ, BNE  */
12986           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
12987     return TRUE;
12988
12989   return FALSE;
12990 }
12991
12992 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
12993    IRELEND) at OFFSET indicate that there must be a compact branch there,
12994    then return TRUE, otherwise FALSE.  */
12995
12996 static bfd_boolean
12997 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
12998                      const Elf_Internal_Rela *internal_relocs,
12999                      const Elf_Internal_Rela *irelend)
13000 {
13001   const Elf_Internal_Rela *irel;
13002   unsigned long opcode;
13003
13004   opcode = bfd_get_micromips_32 (abfd, ptr);
13005   if (find_match (opcode, bzc_insns_32) < 0)
13006     return FALSE;
13007
13008   for (irel = internal_relocs; irel < irelend; irel++)
13009     if (irel->r_offset == offset
13010         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
13011       return TRUE;
13012
13013   return FALSE;
13014 }
13015
13016 /* Bitsize checking.  */
13017 #define IS_BITSIZE(val, N)                                              \
13018   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
13019     - (1ULL << ((N) - 1))) == (val))
13020
13021 \f
13022 bfd_boolean
13023 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
13024                              struct bfd_link_info *link_info,
13025                              bfd_boolean *again)
13026 {
13027   bfd_boolean insn32 = mips_elf_hash_table (link_info)->insn32;
13028   Elf_Internal_Shdr *symtab_hdr;
13029   Elf_Internal_Rela *internal_relocs;
13030   Elf_Internal_Rela *irel, *irelend;
13031   bfd_byte *contents = NULL;
13032   Elf_Internal_Sym *isymbuf = NULL;
13033
13034   /* Assume nothing changes.  */
13035   *again = FALSE;
13036
13037   /* We don't have to do anything for a relocatable link, if
13038      this section does not have relocs, or if this is not a
13039      code section.  */
13040
13041   if (link_info->relocatable
13042       || (sec->flags & SEC_RELOC) == 0
13043       || sec->reloc_count == 0
13044       || (sec->flags & SEC_CODE) == 0)
13045     return TRUE;
13046
13047   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
13048
13049   /* Get a copy of the native relocations.  */
13050   internal_relocs = (_bfd_elf_link_read_relocs
13051                      (abfd, sec, NULL, (Elf_Internal_Rela *) NULL,
13052                       link_info->keep_memory));
13053   if (internal_relocs == NULL)
13054     goto error_return;
13055
13056   /* Walk through them looking for relaxing opportunities.  */
13057   irelend = internal_relocs + sec->reloc_count;
13058   for (irel = internal_relocs; irel < irelend; irel++)
13059     {
13060       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
13061       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
13062       bfd_boolean target_is_micromips_code_p;
13063       unsigned long opcode;
13064       bfd_vma symval;
13065       bfd_vma pcrval;
13066       bfd_byte *ptr;
13067       int fndopc;
13068
13069       /* The number of bytes to delete for relaxation and from where
13070          to delete these bytes starting at irel->r_offset.  */
13071       int delcnt = 0;
13072       int deloff = 0;
13073
13074       /* If this isn't something that can be relaxed, then ignore
13075          this reloc.  */
13076       if (r_type != R_MICROMIPS_HI16
13077           && r_type != R_MICROMIPS_PC16_S1
13078           && r_type != R_MICROMIPS_26_S1)
13079         continue;
13080
13081       /* Get the section contents if we haven't done so already.  */
13082       if (contents == NULL)
13083         {
13084           /* Get cached copy if it exists.  */
13085           if (elf_section_data (sec)->this_hdr.contents != NULL)
13086             contents = elf_section_data (sec)->this_hdr.contents;
13087           /* Go get them off disk.  */
13088           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
13089             goto error_return;
13090         }
13091       ptr = contents + irel->r_offset;
13092
13093       /* Read this BFD's local symbols if we haven't done so already.  */
13094       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
13095         {
13096           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
13097           if (isymbuf == NULL)
13098             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
13099                                             symtab_hdr->sh_info, 0,
13100                                             NULL, NULL, NULL);
13101           if (isymbuf == NULL)
13102             goto error_return;
13103         }
13104
13105       /* Get the value of the symbol referred to by the reloc.  */
13106       if (r_symndx < symtab_hdr->sh_info)
13107         {
13108           /* A local symbol.  */
13109           Elf_Internal_Sym *isym;
13110           asection *sym_sec;
13111
13112           isym = isymbuf + r_symndx;
13113           if (isym->st_shndx == SHN_UNDEF)
13114             sym_sec = bfd_und_section_ptr;
13115           else if (isym->st_shndx == SHN_ABS)
13116             sym_sec = bfd_abs_section_ptr;
13117           else if (isym->st_shndx == SHN_COMMON)
13118             sym_sec = bfd_com_section_ptr;
13119           else
13120             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
13121           symval = (isym->st_value
13122                     + sym_sec->output_section->vma
13123                     + sym_sec->output_offset);
13124           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
13125         }
13126       else
13127         {
13128           unsigned long indx;
13129           struct elf_link_hash_entry *h;
13130
13131           /* An external symbol.  */
13132           indx = r_symndx - symtab_hdr->sh_info;
13133           h = elf_sym_hashes (abfd)[indx];
13134           BFD_ASSERT (h != NULL);
13135
13136           if (h->root.type != bfd_link_hash_defined
13137               && h->root.type != bfd_link_hash_defweak)
13138             /* This appears to be a reference to an undefined
13139                symbol.  Just ignore it -- it will be caught by the
13140                regular reloc processing.  */
13141             continue;
13142
13143           symval = (h->root.u.def.value
13144                     + h->root.u.def.section->output_section->vma
13145                     + h->root.u.def.section->output_offset);
13146           target_is_micromips_code_p = (!h->needs_plt
13147                                         && ELF_ST_IS_MICROMIPS (h->other));
13148         }
13149
13150
13151       /* For simplicity of coding, we are going to modify the
13152          section contents, the section relocs, and the BFD symbol
13153          table.  We must tell the rest of the code not to free up this
13154          information.  It would be possible to instead create a table
13155          of changes which have to be made, as is done in coff-mips.c;
13156          that would be more work, but would require less memory when
13157          the linker is run.  */
13158
13159       /* Only 32-bit instructions relaxed.  */
13160       if (irel->r_offset + 4 > sec->size)
13161         continue;
13162
13163       opcode = bfd_get_micromips_32 (abfd, ptr);
13164
13165       /* This is the pc-relative distance from the instruction the
13166          relocation is applied to, to the symbol referred.  */
13167       pcrval = (symval
13168                 - (sec->output_section->vma + sec->output_offset)
13169                 - irel->r_offset);
13170
13171       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
13172          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
13173          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
13174
13175            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
13176
13177          where pcrval has first to be adjusted to apply against the LO16
13178          location (we make the adjustment later on, when we have figured
13179          out the offset).  */
13180       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
13181         {
13182           bfd_boolean bzc = FALSE;
13183           unsigned long nextopc;
13184           unsigned long reg;
13185           bfd_vma offset;
13186
13187           /* Give up if the previous reloc was a HI16 against this symbol
13188              too.  */
13189           if (irel > internal_relocs
13190               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
13191               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
13192             continue;
13193
13194           /* Or if the next reloc is not a LO16 against this symbol.  */
13195           if (irel + 1 >= irelend
13196               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
13197               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
13198             continue;
13199
13200           /* Or if the second next reloc is a LO16 against this symbol too.  */
13201           if (irel + 2 >= irelend
13202               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
13203               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
13204             continue;
13205
13206           /* See if the LUI instruction *might* be in a branch delay slot.
13207              We check whether what looks like a 16-bit branch or jump is
13208              actually an immediate argument to a compact branch, and let
13209              it through if so.  */
13210           if (irel->r_offset >= 2
13211               && check_br16_dslot (abfd, ptr - 2)
13212               && !(irel->r_offset >= 4
13213                    && (bzc = check_relocated_bzc (abfd,
13214                                                   ptr - 4, irel->r_offset - 4,
13215                                                   internal_relocs, irelend))))
13216             continue;
13217           if (irel->r_offset >= 4
13218               && !bzc
13219               && check_br32_dslot (abfd, ptr - 4))
13220             continue;
13221
13222           reg = OP32_SREG (opcode);
13223
13224           /* We only relax adjacent instructions or ones separated with
13225              a branch or jump that has a delay slot.  The branch or jump
13226              must not fiddle with the register used to hold the address.
13227              Subtract 4 for the LUI itself.  */
13228           offset = irel[1].r_offset - irel[0].r_offset;
13229           switch (offset - 4)
13230             {
13231             case 0:
13232               break;
13233             case 2:
13234               if (check_br16 (abfd, ptr + 4, reg))
13235                 break;
13236               continue;
13237             case 4:
13238               if (check_br32 (abfd, ptr + 4, reg))
13239                 break;
13240               continue;
13241             default:
13242               continue;
13243             }
13244
13245           nextopc = bfd_get_micromips_32 (abfd, contents + irel[1].r_offset);
13246
13247           /* Give up unless the same register is used with both
13248              relocations.  */
13249           if (OP32_SREG (nextopc) != reg)
13250             continue;
13251
13252           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
13253              and rounding up to take masking of the two LSBs into account.  */
13254           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
13255
13256           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
13257           if (IS_BITSIZE (symval, 16))
13258             {
13259               /* Fix the relocation's type.  */
13260               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
13261
13262               /* Instructions using R_MICROMIPS_LO16 have the base or
13263                  source register in bits 20:16.  This register becomes $0
13264                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
13265               nextopc &= ~0x001f0000;
13266               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
13267                           contents + irel[1].r_offset);
13268             }
13269
13270           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
13271              We add 4 to take LUI deletion into account while checking
13272              the PC-relative distance.  */
13273           else if (symval % 4 == 0
13274                    && IS_BITSIZE (pcrval + 4, 25)
13275                    && MATCH (nextopc, addiu_insn)
13276                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
13277                    && OP16_VALID_REG (OP32_TREG (nextopc)))
13278             {
13279               /* Fix the relocation's type.  */
13280               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
13281
13282               /* Replace ADDIU with the ADDIUPC version.  */
13283               nextopc = (addiupc_insn.match
13284                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
13285
13286               bfd_put_micromips_32 (abfd, nextopc,
13287                                     contents + irel[1].r_offset);
13288             }
13289
13290           /* Can't do anything, give up, sigh...  */
13291           else
13292             continue;
13293
13294           /* Fix the relocation's type.  */
13295           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
13296
13297           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
13298           delcnt = 4;
13299           deloff = 0;
13300         }
13301
13302       /* Compact branch relaxation -- due to the multitude of macros
13303          employed by the compiler/assembler, compact branches are not
13304          always generated.  Obviously, this can/will be fixed elsewhere,
13305          but there is no drawback in double checking it here.  */
13306       else if (r_type == R_MICROMIPS_PC16_S1
13307                && irel->r_offset + 5 < sec->size
13308                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
13309                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
13310                && ((!insn32
13311                     && (delcnt = MATCH (bfd_get_16 (abfd, ptr + 4),
13312                                         nop_insn_16) ? 2 : 0))
13313                    || (irel->r_offset + 7 < sec->size
13314                        && (delcnt = MATCH (bfd_get_micromips_32 (abfd,
13315                                                                  ptr + 4),
13316                                            nop_insn_32) ? 4 : 0))))
13317         {
13318           unsigned long reg;
13319
13320           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
13321
13322           /* Replace BEQZ/BNEZ with the compact version.  */
13323           opcode = (bzc_insns_32[fndopc].match
13324                     | BZC32_REG_FIELD (reg)
13325                     | (opcode & 0xffff));               /* Addend value.  */
13326
13327           bfd_put_micromips_32 (abfd, opcode, ptr);
13328
13329           /* Delete the delay slot NOP: two or four bytes from
13330              irel->offset + 4; delcnt has already been set above.  */
13331           deloff = 4;
13332         }
13333
13334       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
13335          to check the distance from the next instruction, so subtract 2.  */
13336       else if (!insn32
13337                && r_type == R_MICROMIPS_PC16_S1
13338                && IS_BITSIZE (pcrval - 2, 11)
13339                && find_match (opcode, b_insns_32) >= 0)
13340         {
13341           /* Fix the relocation's type.  */
13342           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
13343
13344           /* Replace the 32-bit opcode with a 16-bit opcode.  */
13345           bfd_put_16 (abfd,
13346                       (b_insn_16.match
13347                        | (opcode & 0x3ff)),             /* Addend value.  */
13348                       ptr);
13349
13350           /* Delete 2 bytes from irel->r_offset + 2.  */
13351           delcnt = 2;
13352           deloff = 2;
13353         }
13354
13355       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
13356          to check the distance from the next instruction, so subtract 2.  */
13357       else if (!insn32
13358                && r_type == R_MICROMIPS_PC16_S1
13359                && IS_BITSIZE (pcrval - 2, 8)
13360                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
13361                     && OP16_VALID_REG (OP32_SREG (opcode)))
13362                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
13363                        && OP16_VALID_REG (OP32_TREG (opcode)))))
13364         {
13365           unsigned long reg;
13366
13367           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
13368
13369           /* Fix the relocation's type.  */
13370           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
13371
13372           /* Replace the 32-bit opcode with a 16-bit opcode.  */
13373           bfd_put_16 (abfd,
13374                       (bz_insns_16[fndopc].match
13375                        | BZ16_REG_FIELD (reg)
13376                        | (opcode & 0x7f)),              /* Addend value.  */
13377                       ptr);
13378
13379           /* Delete 2 bytes from irel->r_offset + 2.  */
13380           delcnt = 2;
13381           deloff = 2;
13382         }
13383
13384       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
13385       else if (!insn32
13386                && r_type == R_MICROMIPS_26_S1
13387                && target_is_micromips_code_p
13388                && irel->r_offset + 7 < sec->size
13389                && MATCH (opcode, jal_insn_32_bd32))
13390         {
13391           unsigned long n32opc;
13392           bfd_boolean relaxed = FALSE;
13393
13394           n32opc = bfd_get_micromips_32 (abfd, ptr + 4);
13395
13396           if (MATCH (n32opc, nop_insn_32))
13397             {
13398               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
13399               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
13400
13401               relaxed = TRUE;
13402             }
13403           else if (find_match (n32opc, move_insns_32) >= 0)
13404             {
13405               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
13406               bfd_put_16 (abfd,
13407                           (move_insn_16.match
13408                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
13409                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
13410                           ptr + 4);
13411
13412               relaxed = TRUE;
13413             }
13414           /* Other 32-bit instructions relaxable to 16-bit
13415              instructions will be handled here later.  */
13416
13417           if (relaxed)
13418             {
13419               /* JAL with 32-bit delay slot that is changed to a JALS
13420                  with 16-bit delay slot.  */
13421               bfd_put_micromips_32 (abfd, jal_insn_32_bd16.match, ptr);
13422
13423               /* Delete 2 bytes from irel->r_offset + 6.  */
13424               delcnt = 2;
13425               deloff = 6;
13426             }
13427         }
13428
13429       if (delcnt != 0)
13430         {
13431           /* Note that we've changed the relocs, section contents, etc.  */
13432           elf_section_data (sec)->relocs = internal_relocs;
13433           elf_section_data (sec)->this_hdr.contents = contents;
13434           symtab_hdr->contents = (unsigned char *) isymbuf;
13435
13436           /* Delete bytes depending on the delcnt and deloff.  */
13437           if (!mips_elf_relax_delete_bytes (abfd, sec,
13438                                             irel->r_offset + deloff, delcnt))
13439             goto error_return;
13440
13441           /* That will change things, so we should relax again.
13442              Note that this is not required, and it may be slow.  */
13443           *again = TRUE;
13444         }
13445     }
13446
13447   if (isymbuf != NULL
13448       && symtab_hdr->contents != (unsigned char *) isymbuf)
13449     {
13450       if (! link_info->keep_memory)
13451         free (isymbuf);
13452       else
13453         {
13454           /* Cache the symbols for elf_link_input_bfd.  */
13455           symtab_hdr->contents = (unsigned char *) isymbuf;
13456         }
13457     }
13458
13459   if (contents != NULL
13460       && elf_section_data (sec)->this_hdr.contents != contents)
13461     {
13462       if (! link_info->keep_memory)
13463         free (contents);
13464       else
13465         {
13466           /* Cache the section contents for elf_link_input_bfd.  */
13467           elf_section_data (sec)->this_hdr.contents = contents;
13468         }
13469     }
13470
13471   if (internal_relocs != NULL
13472       && elf_section_data (sec)->relocs != internal_relocs)
13473     free (internal_relocs);
13474
13475   return TRUE;
13476
13477  error_return:
13478   if (isymbuf != NULL
13479       && symtab_hdr->contents != (unsigned char *) isymbuf)
13480     free (isymbuf);
13481   if (contents != NULL
13482       && elf_section_data (sec)->this_hdr.contents != contents)
13483     free (contents);
13484   if (internal_relocs != NULL
13485       && elf_section_data (sec)->relocs != internal_relocs)
13486     free (internal_relocs);
13487
13488   return FALSE;
13489 }
13490 \f
13491 /* Create a MIPS ELF linker hash table.  */
13492
13493 struct bfd_link_hash_table *
13494 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
13495 {
13496   struct mips_elf_link_hash_table *ret;
13497   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
13498
13499   ret = bfd_zmalloc (amt);
13500   if (ret == NULL)
13501     return NULL;
13502
13503   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
13504                                       mips_elf_link_hash_newfunc,
13505                                       sizeof (struct mips_elf_link_hash_entry),
13506                                       MIPS_ELF_DATA))
13507     {
13508       free (ret);
13509       return NULL;
13510     }
13511   ret->root.init_plt_refcount.plist = NULL;
13512   ret->root.init_plt_offset.plist = NULL;
13513
13514   return &ret->root.root;
13515 }
13516
13517 /* Likewise, but indicate that the target is VxWorks.  */
13518
13519 struct bfd_link_hash_table *
13520 _bfd_mips_vxworks_link_hash_table_create (bfd *abfd)
13521 {
13522   struct bfd_link_hash_table *ret;
13523
13524   ret = _bfd_mips_elf_link_hash_table_create (abfd);
13525   if (ret)
13526     {
13527       struct mips_elf_link_hash_table *htab;
13528
13529       htab = (struct mips_elf_link_hash_table *) ret;
13530       htab->use_plts_and_copy_relocs = TRUE;
13531       htab->is_vxworks = TRUE;
13532     }
13533   return ret;
13534 }
13535
13536 /* A function that the linker calls if we are allowed to use PLTs
13537    and copy relocs.  */
13538
13539 void
13540 _bfd_mips_elf_use_plts_and_copy_relocs (struct bfd_link_info *info)
13541 {
13542   mips_elf_hash_table (info)->use_plts_and_copy_relocs = TRUE;
13543 }
13544
13545 /* A function that the linker calls to select between all or only
13546    32-bit microMIPS instructions.  */
13547
13548 void
13549 _bfd_mips_elf_insn32 (struct bfd_link_info *info, bfd_boolean on)
13550 {
13551   mips_elf_hash_table (info)->insn32 = on;
13552 }
13553 \f
13554 /* We need to use a special link routine to handle the .reginfo and
13555    the .mdebug sections.  We need to merge all instances of these
13556    sections together, not write them all out sequentially.  */
13557
13558 bfd_boolean
13559 _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info)
13560 {
13561   asection *o;
13562   struct bfd_link_order *p;
13563   asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec;
13564   asection *rtproc_sec;
13565   Elf32_RegInfo reginfo;
13566   struct ecoff_debug_info debug;
13567   struct mips_htab_traverse_info hti;
13568   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13569   const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap;
13570   HDRR *symhdr = &debug.symbolic_header;
13571   void *mdebug_handle = NULL;
13572   asection *s;
13573   EXTR esym;
13574   unsigned int i;
13575   bfd_size_type amt;
13576   struct mips_elf_link_hash_table *htab;
13577
13578   static const char * const secname[] =
13579   {
13580     ".text", ".init", ".fini", ".data",
13581     ".rodata", ".sdata", ".sbss", ".bss"
13582   };
13583   static const int sc[] =
13584   {
13585     scText, scInit, scFini, scData,
13586     scRData, scSData, scSBss, scBss
13587   };
13588
13589   /* Sort the dynamic symbols so that those with GOT entries come after
13590      those without.  */
13591   htab = mips_elf_hash_table (info);
13592   BFD_ASSERT (htab != NULL);
13593
13594   if (!mips_elf_sort_hash_table (abfd, info))
13595     return FALSE;
13596
13597   /* Create any scheduled LA25 stubs.  */
13598   hti.info = info;
13599   hti.output_bfd = abfd;
13600   hti.error = FALSE;
13601   htab_traverse (htab->la25_stubs, mips_elf_create_la25_stub, &hti);
13602   if (hti.error)
13603     return FALSE;
13604
13605   /* Get a value for the GP register.  */
13606   if (elf_gp (abfd) == 0)
13607     {
13608       struct bfd_link_hash_entry *h;
13609
13610       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
13611       if (h != NULL && h->type == bfd_link_hash_defined)
13612         elf_gp (abfd) = (h->u.def.value
13613                          + h->u.def.section->output_section->vma
13614                          + h->u.def.section->output_offset);
13615       else if (htab->is_vxworks
13616                && (h = bfd_link_hash_lookup (info->hash,
13617                                              "_GLOBAL_OFFSET_TABLE_",
13618                                              FALSE, FALSE, TRUE))
13619                && h->type == bfd_link_hash_defined)
13620         elf_gp (abfd) = (h->u.def.section->output_section->vma
13621                          + h->u.def.section->output_offset
13622                          + h->u.def.value);
13623       else if (info->relocatable)
13624         {
13625           bfd_vma lo = MINUS_ONE;
13626
13627           /* Find the GP-relative section with the lowest offset.  */
13628           for (o = abfd->sections; o != NULL; o = o->next)
13629             if (o->vma < lo
13630                 && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL))
13631               lo = o->vma;
13632
13633           /* And calculate GP relative to that.  */
13634           elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (info);
13635         }
13636       else
13637         {
13638           /* If the relocate_section function needs to do a reloc
13639              involving the GP value, it should make a reloc_dangerous
13640              callback to warn that GP is not defined.  */
13641         }
13642     }
13643
13644   /* Go through the sections and collect the .reginfo and .mdebug
13645      information.  */
13646   reginfo_sec = NULL;
13647   mdebug_sec = NULL;
13648   gptab_data_sec = NULL;
13649   gptab_bss_sec = NULL;
13650   for (o = abfd->sections; o != NULL; o = o->next)
13651     {
13652       if (strcmp (o->name, ".reginfo") == 0)
13653         {
13654           memset (&reginfo, 0, sizeof reginfo);
13655
13656           /* We have found the .reginfo section in the output file.
13657              Look through all the link_orders comprising it and merge
13658              the information together.  */
13659           for (p = o->map_head.link_order; p != NULL; p = p->next)
13660             {
13661               asection *input_section;
13662               bfd *input_bfd;
13663               Elf32_External_RegInfo ext;
13664               Elf32_RegInfo sub;
13665
13666               if (p->type != bfd_indirect_link_order)
13667                 {
13668                   if (p->type == bfd_data_link_order)
13669                     continue;
13670                   abort ();
13671                 }
13672
13673               input_section = p->u.indirect.section;
13674               input_bfd = input_section->owner;
13675
13676               if (! bfd_get_section_contents (input_bfd, input_section,
13677                                               &ext, 0, sizeof ext))
13678                 return FALSE;
13679
13680               bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub);
13681
13682               reginfo.ri_gprmask |= sub.ri_gprmask;
13683               reginfo.ri_cprmask[0] |= sub.ri_cprmask[0];
13684               reginfo.ri_cprmask[1] |= sub.ri_cprmask[1];
13685               reginfo.ri_cprmask[2] |= sub.ri_cprmask[2];
13686               reginfo.ri_cprmask[3] |= sub.ri_cprmask[3];
13687
13688               /* ri_gp_value is set by the function
13689                  mips_elf32_section_processing when the section is
13690                  finally written out.  */
13691
13692               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13693                  elf_link_input_bfd ignores this section.  */
13694               input_section->flags &= ~SEC_HAS_CONTENTS;
13695             }
13696
13697           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
13698           BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo));
13699
13700           /* Skip this section later on (I don't think this currently
13701              matters, but someday it might).  */
13702           o->map_head.link_order = NULL;
13703
13704           reginfo_sec = o;
13705         }
13706
13707       if (strcmp (o->name, ".mdebug") == 0)
13708         {
13709           struct extsym_info einfo;
13710           bfd_vma last;
13711
13712           /* We have found the .mdebug section in the output file.
13713              Look through all the link_orders comprising it and merge
13714              the information together.  */
13715           symhdr->magic = swap->sym_magic;
13716           /* FIXME: What should the version stamp be?  */
13717           symhdr->vstamp = 0;
13718           symhdr->ilineMax = 0;
13719           symhdr->cbLine = 0;
13720           symhdr->idnMax = 0;
13721           symhdr->ipdMax = 0;
13722           symhdr->isymMax = 0;
13723           symhdr->ioptMax = 0;
13724           symhdr->iauxMax = 0;
13725           symhdr->issMax = 0;
13726           symhdr->issExtMax = 0;
13727           symhdr->ifdMax = 0;
13728           symhdr->crfd = 0;
13729           symhdr->iextMax = 0;
13730
13731           /* We accumulate the debugging information itself in the
13732              debug_info structure.  */
13733           debug.line = NULL;
13734           debug.external_dnr = NULL;
13735           debug.external_pdr = NULL;
13736           debug.external_sym = NULL;
13737           debug.external_opt = NULL;
13738           debug.external_aux = NULL;
13739           debug.ss = NULL;
13740           debug.ssext = debug.ssext_end = NULL;
13741           debug.external_fdr = NULL;
13742           debug.external_rfd = NULL;
13743           debug.external_ext = debug.external_ext_end = NULL;
13744
13745           mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info);
13746           if (mdebug_handle == NULL)
13747             return FALSE;
13748
13749           esym.jmptbl = 0;
13750           esym.cobol_main = 0;
13751           esym.weakext = 0;
13752           esym.reserved = 0;
13753           esym.ifd = ifdNil;
13754           esym.asym.iss = issNil;
13755           esym.asym.st = stLocal;
13756           esym.asym.reserved = 0;
13757           esym.asym.index = indexNil;
13758           last = 0;
13759           for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++)
13760             {
13761               esym.asym.sc = sc[i];
13762               s = bfd_get_section_by_name (abfd, secname[i]);
13763               if (s != NULL)
13764                 {
13765                   esym.asym.value = s->vma;
13766                   last = s->vma + s->size;
13767                 }
13768               else
13769                 esym.asym.value = last;
13770               if (!bfd_ecoff_debug_one_external (abfd, &debug, swap,
13771                                                  secname[i], &esym))
13772                 return FALSE;
13773             }
13774
13775           for (p = o->map_head.link_order; p != NULL; p = p->next)
13776             {
13777               asection *input_section;
13778               bfd *input_bfd;
13779               const struct ecoff_debug_swap *input_swap;
13780               struct ecoff_debug_info input_debug;
13781               char *eraw_src;
13782               char *eraw_end;
13783
13784               if (p->type != bfd_indirect_link_order)
13785                 {
13786                   if (p->type == bfd_data_link_order)
13787                     continue;
13788                   abort ();
13789                 }
13790
13791               input_section = p->u.indirect.section;
13792               input_bfd = input_section->owner;
13793
13794               if (!is_mips_elf (input_bfd))
13795                 {
13796                   /* I don't know what a non MIPS ELF bfd would be
13797                      doing with a .mdebug section, but I don't really
13798                      want to deal with it.  */
13799                   continue;
13800                 }
13801
13802               input_swap = (get_elf_backend_data (input_bfd)
13803                             ->elf_backend_ecoff_debug_swap);
13804
13805               BFD_ASSERT (p->size == input_section->size);
13806
13807               /* The ECOFF linking code expects that we have already
13808                  read in the debugging information and set up an
13809                  ecoff_debug_info structure, so we do that now.  */
13810               if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section,
13811                                                    &input_debug))
13812                 return FALSE;
13813
13814               if (! (bfd_ecoff_debug_accumulate
13815                      (mdebug_handle, abfd, &debug, swap, input_bfd,
13816                       &input_debug, input_swap, info)))
13817                 return FALSE;
13818
13819               /* Loop through the external symbols.  For each one with
13820                  interesting information, try to find the symbol in
13821                  the linker global hash table and save the information
13822                  for the output external symbols.  */
13823               eraw_src = input_debug.external_ext;
13824               eraw_end = (eraw_src
13825                           + (input_debug.symbolic_header.iextMax
13826                              * input_swap->external_ext_size));
13827               for (;
13828                    eraw_src < eraw_end;
13829                    eraw_src += input_swap->external_ext_size)
13830                 {
13831                   EXTR ext;
13832                   const char *name;
13833                   struct mips_elf_link_hash_entry *h;
13834
13835                   (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext);
13836                   if (ext.asym.sc == scNil
13837                       || ext.asym.sc == scUndefined
13838                       || ext.asym.sc == scSUndefined)
13839                     continue;
13840
13841                   name = input_debug.ssext + ext.asym.iss;
13842                   h = mips_elf_link_hash_lookup (mips_elf_hash_table (info),
13843                                                  name, FALSE, FALSE, TRUE);
13844                   if (h == NULL || h->esym.ifd != -2)
13845                     continue;
13846
13847                   if (ext.ifd != -1)
13848                     {
13849                       BFD_ASSERT (ext.ifd
13850                                   < input_debug.symbolic_header.ifdMax);
13851                       ext.ifd = input_debug.ifdmap[ext.ifd];
13852                     }
13853
13854                   h->esym = ext;
13855                 }
13856
13857               /* Free up the information we just read.  */
13858               free (input_debug.line);
13859               free (input_debug.external_dnr);
13860               free (input_debug.external_pdr);
13861               free (input_debug.external_sym);
13862               free (input_debug.external_opt);
13863               free (input_debug.external_aux);
13864               free (input_debug.ss);
13865               free (input_debug.ssext);
13866               free (input_debug.external_fdr);
13867               free (input_debug.external_rfd);
13868               free (input_debug.external_ext);
13869
13870               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13871                  elf_link_input_bfd ignores this section.  */
13872               input_section->flags &= ~SEC_HAS_CONTENTS;
13873             }
13874
13875           if (SGI_COMPAT (abfd) && info->shared)
13876             {
13877               /* Create .rtproc section.  */
13878               rtproc_sec = bfd_get_linker_section (abfd, ".rtproc");
13879               if (rtproc_sec == NULL)
13880                 {
13881                   flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
13882                                     | SEC_LINKER_CREATED | SEC_READONLY);
13883
13884                   rtproc_sec = bfd_make_section_anyway_with_flags (abfd,
13885                                                                    ".rtproc",
13886                                                                    flags);
13887                   if (rtproc_sec == NULL
13888                       || ! bfd_set_section_alignment (abfd, rtproc_sec, 4))
13889                     return FALSE;
13890                 }
13891
13892               if (! mips_elf_create_procedure_table (mdebug_handle, abfd,
13893                                                      info, rtproc_sec,
13894                                                      &debug))
13895                 return FALSE;
13896             }
13897
13898           /* Build the external symbol information.  */
13899           einfo.abfd = abfd;
13900           einfo.info = info;
13901           einfo.debug = &debug;
13902           einfo.swap = swap;
13903           einfo.failed = FALSE;
13904           mips_elf_link_hash_traverse (mips_elf_hash_table (info),
13905                                        mips_elf_output_extsym, &einfo);
13906           if (einfo.failed)
13907             return FALSE;
13908
13909           /* Set the size of the .mdebug section.  */
13910           o->size = bfd_ecoff_debug_size (abfd, &debug, swap);
13911
13912           /* Skip this section later on (I don't think this currently
13913              matters, but someday it might).  */
13914           o->map_head.link_order = NULL;
13915
13916           mdebug_sec = o;
13917         }
13918
13919       if (CONST_STRNEQ (o->name, ".gptab."))
13920         {
13921           const char *subname;
13922           unsigned int c;
13923           Elf32_gptab *tab;
13924           Elf32_External_gptab *ext_tab;
13925           unsigned int j;
13926
13927           /* The .gptab.sdata and .gptab.sbss sections hold
13928              information describing how the small data area would
13929              change depending upon the -G switch.  These sections
13930              not used in executables files.  */
13931           if (! info->relocatable)
13932             {
13933               for (p = o->map_head.link_order; p != NULL; p = p->next)
13934                 {
13935                   asection *input_section;
13936
13937                   if (p->type != bfd_indirect_link_order)
13938                     {
13939                       if (p->type == bfd_data_link_order)
13940                         continue;
13941                       abort ();
13942                     }
13943
13944                   input_section = p->u.indirect.section;
13945
13946                   /* Hack: reset the SEC_HAS_CONTENTS flag so that
13947                      elf_link_input_bfd ignores this section.  */
13948                   input_section->flags &= ~SEC_HAS_CONTENTS;
13949                 }
13950
13951               /* Skip this section later on (I don't think this
13952                  currently matters, but someday it might).  */
13953               o->map_head.link_order = NULL;
13954
13955               /* Really remove the section.  */
13956               bfd_section_list_remove (abfd, o);
13957               --abfd->section_count;
13958
13959               continue;
13960             }
13961
13962           /* There is one gptab for initialized data, and one for
13963              uninitialized data.  */
13964           if (strcmp (o->name, ".gptab.sdata") == 0)
13965             gptab_data_sec = o;
13966           else if (strcmp (o->name, ".gptab.sbss") == 0)
13967             gptab_bss_sec = o;
13968           else
13969             {
13970               (*_bfd_error_handler)
13971                 (_("%s: illegal section name `%s'"),
13972                  bfd_get_filename (abfd), o->name);
13973               bfd_set_error (bfd_error_nonrepresentable_section);
13974               return FALSE;
13975             }
13976
13977           /* The linker script always combines .gptab.data and
13978              .gptab.sdata into .gptab.sdata, and likewise for
13979              .gptab.bss and .gptab.sbss.  It is possible that there is
13980              no .sdata or .sbss section in the output file, in which
13981              case we must change the name of the output section.  */
13982           subname = o->name + sizeof ".gptab" - 1;
13983           if (bfd_get_section_by_name (abfd, subname) == NULL)
13984             {
13985               if (o == gptab_data_sec)
13986                 o->name = ".gptab.data";
13987               else
13988                 o->name = ".gptab.bss";
13989               subname = o->name + sizeof ".gptab" - 1;
13990               BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL);
13991             }
13992
13993           /* Set up the first entry.  */
13994           c = 1;
13995           amt = c * sizeof (Elf32_gptab);
13996           tab = bfd_malloc (amt);
13997           if (tab == NULL)
13998             return FALSE;
13999           tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd);
14000           tab[0].gt_header.gt_unused = 0;
14001
14002           /* Combine the input sections.  */
14003           for (p = o->map_head.link_order; p != NULL; p = p->next)
14004             {
14005               asection *input_section;
14006               bfd *input_bfd;
14007               bfd_size_type size;
14008               unsigned long last;
14009               bfd_size_type gpentry;
14010
14011               if (p->type != bfd_indirect_link_order)
14012                 {
14013                   if (p->type == bfd_data_link_order)
14014                     continue;
14015                   abort ();
14016                 }
14017
14018               input_section = p->u.indirect.section;
14019               input_bfd = input_section->owner;
14020
14021               /* Combine the gptab entries for this input section one
14022                  by one.  We know that the input gptab entries are
14023                  sorted by ascending -G value.  */
14024               size = input_section->size;
14025               last = 0;
14026               for (gpentry = sizeof (Elf32_External_gptab);
14027                    gpentry < size;
14028                    gpentry += sizeof (Elf32_External_gptab))
14029                 {
14030                   Elf32_External_gptab ext_gptab;
14031                   Elf32_gptab int_gptab;
14032                   unsigned long val;
14033                   unsigned long add;
14034                   bfd_boolean exact;
14035                   unsigned int look;
14036
14037                   if (! (bfd_get_section_contents
14038                          (input_bfd, input_section, &ext_gptab, gpentry,
14039                           sizeof (Elf32_External_gptab))))
14040                     {
14041                       free (tab);
14042                       return FALSE;
14043                     }
14044
14045                   bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab,
14046                                                 &int_gptab);
14047                   val = int_gptab.gt_entry.gt_g_value;
14048                   add = int_gptab.gt_entry.gt_bytes - last;
14049
14050                   exact = FALSE;
14051                   for (look = 1; look < c; look++)
14052                     {
14053                       if (tab[look].gt_entry.gt_g_value >= val)
14054                         tab[look].gt_entry.gt_bytes += add;
14055
14056                       if (tab[look].gt_entry.gt_g_value == val)
14057                         exact = TRUE;
14058                     }
14059
14060                   if (! exact)
14061                     {
14062                       Elf32_gptab *new_tab;
14063                       unsigned int max;
14064
14065                       /* We need a new table entry.  */
14066                       amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab);
14067                       new_tab = bfd_realloc (tab, amt);
14068                       if (new_tab == NULL)
14069                         {
14070                           free (tab);
14071                           return FALSE;
14072                         }
14073                       tab = new_tab;
14074                       tab[c].gt_entry.gt_g_value = val;
14075                       tab[c].gt_entry.gt_bytes = add;
14076
14077                       /* Merge in the size for the next smallest -G
14078                          value, since that will be implied by this new
14079                          value.  */
14080                       max = 0;
14081                       for (look = 1; look < c; look++)
14082                         {
14083                           if (tab[look].gt_entry.gt_g_value < val
14084                               && (max == 0
14085                                   || (tab[look].gt_entry.gt_g_value
14086                                       > tab[max].gt_entry.gt_g_value)))
14087                             max = look;
14088                         }
14089                       if (max != 0)
14090                         tab[c].gt_entry.gt_bytes +=
14091                           tab[max].gt_entry.gt_bytes;
14092
14093                       ++c;
14094                     }
14095
14096                   last = int_gptab.gt_entry.gt_bytes;
14097                 }
14098
14099               /* Hack: reset the SEC_HAS_CONTENTS flag so that
14100                  elf_link_input_bfd ignores this section.  */
14101               input_section->flags &= ~SEC_HAS_CONTENTS;
14102             }
14103
14104           /* The table must be sorted by -G value.  */
14105           if (c > 2)
14106             qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare);
14107
14108           /* Swap out the table.  */
14109           amt = (bfd_size_type) c * sizeof (Elf32_External_gptab);
14110           ext_tab = bfd_alloc (abfd, amt);
14111           if (ext_tab == NULL)
14112             {
14113               free (tab);
14114               return FALSE;
14115             }
14116
14117           for (j = 0; j < c; j++)
14118             bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j);
14119           free (tab);
14120
14121           o->size = c * sizeof (Elf32_External_gptab);
14122           o->contents = (bfd_byte *) ext_tab;
14123
14124           /* Skip this section later on (I don't think this currently
14125              matters, but someday it might).  */
14126           o->map_head.link_order = NULL;
14127         }
14128     }
14129
14130   /* Invoke the regular ELF backend linker to do all the work.  */
14131   if (!bfd_elf_final_link (abfd, info))
14132     return FALSE;
14133
14134   /* Now write out the computed sections.  */
14135
14136   if (reginfo_sec != NULL)
14137     {
14138       Elf32_External_RegInfo ext;
14139
14140       bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext);
14141       if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext))
14142         return FALSE;
14143     }
14144
14145   if (mdebug_sec != NULL)
14146     {
14147       BFD_ASSERT (abfd->output_has_begun);
14148       if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug,
14149                                                swap, info,
14150                                                mdebug_sec->filepos))
14151         return FALSE;
14152
14153       bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info);
14154     }
14155
14156   if (gptab_data_sec != NULL)
14157     {
14158       if (! bfd_set_section_contents (abfd, gptab_data_sec,
14159                                       gptab_data_sec->contents,
14160                                       0, gptab_data_sec->size))
14161         return FALSE;
14162     }
14163
14164   if (gptab_bss_sec != NULL)
14165     {
14166       if (! bfd_set_section_contents (abfd, gptab_bss_sec,
14167                                       gptab_bss_sec->contents,
14168                                       0, gptab_bss_sec->size))
14169         return FALSE;
14170     }
14171
14172   if (SGI_COMPAT (abfd))
14173     {
14174       rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
14175       if (rtproc_sec != NULL)
14176         {
14177           if (! bfd_set_section_contents (abfd, rtproc_sec,
14178                                           rtproc_sec->contents,
14179                                           0, rtproc_sec->size))
14180             return FALSE;
14181         }
14182     }
14183
14184   return TRUE;
14185 }
14186 \f
14187 /* Structure for saying that BFD machine EXTENSION extends BASE.  */
14188
14189 struct mips_mach_extension
14190 {
14191   unsigned long extension, base;
14192 };
14193
14194
14195 /* An array describing how BFD machines relate to one another.  The entries
14196    are ordered topologically with MIPS I extensions listed last.  */
14197
14198 static const struct mips_mach_extension mips_mach_extensions[] =
14199 {
14200   /* MIPS64r2 extensions.  */
14201   { bfd_mach_mips_octeon2, bfd_mach_mips_octeonp },
14202   { bfd_mach_mips_octeonp, bfd_mach_mips_octeon },
14203   { bfd_mach_mips_octeon, bfd_mach_mipsisa64r2 },
14204
14205   /* MIPS64 extensions.  */
14206   { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 },
14207   { bfd_mach_mips_sb1, bfd_mach_mipsisa64 },
14208   { bfd_mach_mips_xlr, bfd_mach_mipsisa64 },
14209   { bfd_mach_mips_loongson_3a, bfd_mach_mipsisa64 },
14210
14211   /* MIPS V extensions.  */
14212   { bfd_mach_mipsisa64, bfd_mach_mips5 },
14213
14214   /* R10000 extensions.  */
14215   { bfd_mach_mips12000, bfd_mach_mips10000 },
14216   { bfd_mach_mips14000, bfd_mach_mips10000 },
14217   { bfd_mach_mips16000, bfd_mach_mips10000 },
14218
14219   /* R5000 extensions.  Note: the vr5500 ISA is an extension of the core
14220      vr5400 ISA, but doesn't include the multimedia stuff.  It seems
14221      better to allow vr5400 and vr5500 code to be merged anyway, since
14222      many libraries will just use the core ISA.  Perhaps we could add
14223      some sort of ASE flag if this ever proves a problem.  */
14224   { bfd_mach_mips5500, bfd_mach_mips5400 },
14225   { bfd_mach_mips5400, bfd_mach_mips5000 },
14226
14227   /* MIPS IV extensions.  */
14228   { bfd_mach_mips5, bfd_mach_mips8000 },
14229   { bfd_mach_mips10000, bfd_mach_mips8000 },
14230   { bfd_mach_mips5000, bfd_mach_mips8000 },
14231   { bfd_mach_mips7000, bfd_mach_mips8000 },
14232   { bfd_mach_mips9000, bfd_mach_mips8000 },
14233
14234   /* VR4100 extensions.  */
14235   { bfd_mach_mips4120, bfd_mach_mips4100 },
14236   { bfd_mach_mips4111, bfd_mach_mips4100 },
14237
14238   /* MIPS III extensions.  */
14239   { bfd_mach_mips_loongson_2e, bfd_mach_mips4000 },
14240   { bfd_mach_mips_loongson_2f, bfd_mach_mips4000 },
14241   { bfd_mach_mips8000, bfd_mach_mips4000 },
14242   { bfd_mach_mips4650, bfd_mach_mips4000 },
14243   { bfd_mach_mips4600, bfd_mach_mips4000 },
14244   { bfd_mach_mips4400, bfd_mach_mips4000 },
14245   { bfd_mach_mips4300, bfd_mach_mips4000 },
14246   { bfd_mach_mips4100, bfd_mach_mips4000 },
14247   { bfd_mach_mips4010, bfd_mach_mips4000 },
14248   { bfd_mach_mips5900, bfd_mach_mips4000 },
14249
14250   /* MIPS32 extensions.  */
14251   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
14252
14253   /* MIPS II extensions.  */
14254   { bfd_mach_mips4000, bfd_mach_mips6000 },
14255   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
14256
14257   /* MIPS I extensions.  */
14258   { bfd_mach_mips6000, bfd_mach_mips3000 },
14259   { bfd_mach_mips3900, bfd_mach_mips3000 }
14260 };
14261
14262
14263 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
14264
14265 static bfd_boolean
14266 mips_mach_extends_p (unsigned long base, unsigned long extension)
14267 {
14268   size_t i;
14269
14270   if (extension == base)
14271     return TRUE;
14272
14273   if (base == bfd_mach_mipsisa32
14274       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
14275     return TRUE;
14276
14277   if (base == bfd_mach_mipsisa32r2
14278       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
14279     return TRUE;
14280
14281   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
14282     if (extension == mips_mach_extensions[i].extension)
14283       {
14284         extension = mips_mach_extensions[i].base;
14285         if (extension == base)
14286           return TRUE;
14287       }
14288
14289   return FALSE;
14290 }
14291
14292
14293 /* Return true if the given ELF header flags describe a 32-bit binary.  */
14294
14295 static bfd_boolean
14296 mips_32bit_flags_p (flagword flags)
14297 {
14298   return ((flags & EF_MIPS_32BITMODE) != 0
14299           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
14300           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
14301           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
14302           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
14303           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
14304           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2);
14305 }
14306
14307
14308 /* Merge object attributes from IBFD into OBFD.  Raise an error if
14309    there are conflicting attributes.  */
14310 static bfd_boolean
14311 mips_elf_merge_obj_attributes (bfd *ibfd, bfd *obfd)
14312 {
14313   obj_attribute *in_attr;
14314   obj_attribute *out_attr;
14315   bfd *abi_fp_bfd;
14316
14317   abi_fp_bfd = mips_elf_tdata (obfd)->abi_fp_bfd;
14318   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
14319   if (!abi_fp_bfd && in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
14320     mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
14321
14322   if (!elf_known_obj_attributes_proc (obfd)[0].i)
14323     {
14324       /* This is the first object.  Copy the attributes.  */
14325       _bfd_elf_copy_obj_attributes (ibfd, obfd);
14326
14327       /* Use the Tag_null value to indicate the attributes have been
14328          initialized.  */
14329       elf_known_obj_attributes_proc (obfd)[0].i = 1;
14330
14331       return TRUE;
14332     }
14333
14334   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
14335      non-conflicting ones.  */
14336   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
14337   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
14338     {
14339       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
14340       if (out_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
14341         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
14342       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
14343         switch (out_attr[Tag_GNU_MIPS_ABI_FP].i)
14344           {
14345           case 1:
14346             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
14347               {
14348               case 2:
14349                 _bfd_error_handler
14350                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14351                    obfd, abi_fp_bfd, ibfd, "-mdouble-float", "-msingle-float");
14352                 break;
14353
14354               case 3:
14355                 _bfd_error_handler
14356                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14357                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
14358                 break;
14359
14360               case 4:
14361                 _bfd_error_handler
14362                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14363                    obfd, abi_fp_bfd, ibfd,
14364                    "-mdouble-float", "-mips32r2 -mfp64");
14365                 break;
14366
14367               default:
14368                 _bfd_error_handler
14369                   (_("Warning: %B uses %s (set by %B), "
14370                      "%B uses unknown floating point ABI %d"),
14371                    obfd, abi_fp_bfd, ibfd,
14372                    "-mdouble-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
14373                 break;
14374               }
14375             break;
14376
14377           case 2:
14378             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
14379               {
14380               case 1:
14381                 _bfd_error_handler
14382                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14383                    obfd, abi_fp_bfd, ibfd, "-msingle-float", "-mdouble-float");
14384                 break;
14385
14386               case 3:
14387                 _bfd_error_handler
14388                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14389                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
14390                 break;
14391
14392               case 4:
14393                 _bfd_error_handler
14394                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14395                    obfd, abi_fp_bfd, ibfd,
14396                    "-msingle-float", "-mips32r2 -mfp64");
14397                 break;
14398
14399               default:
14400                 _bfd_error_handler
14401                   (_("Warning: %B uses %s (set by %B), "
14402                      "%B uses unknown floating point ABI %d"),
14403                    obfd, abi_fp_bfd, ibfd,
14404                    "-msingle-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
14405                 break;
14406               }
14407             break;
14408
14409           case 3:
14410             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
14411               {
14412               case 1:
14413               case 2:
14414               case 4:
14415                 _bfd_error_handler
14416                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14417                    obfd, abi_fp_bfd, ibfd, "-msoft-float", "-mhard-float");
14418                 break;
14419
14420               default:
14421                 _bfd_error_handler
14422                   (_("Warning: %B uses %s (set by %B), "
14423                      "%B uses unknown floating point ABI %d"),
14424                    obfd, abi_fp_bfd, ibfd,
14425                    "-msoft-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
14426                 break;
14427               }
14428             break;
14429
14430           case 4:
14431             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
14432               {
14433               case 1:
14434                 _bfd_error_handler
14435                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14436                    obfd, abi_fp_bfd, ibfd,
14437                    "-mips32r2 -mfp64", "-mdouble-float");
14438                 break;
14439
14440               case 2:
14441                 _bfd_error_handler
14442                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14443                    obfd, abi_fp_bfd, ibfd,
14444                    "-mips32r2 -mfp64", "-msingle-float");
14445                 break;
14446
14447               case 3:
14448                 _bfd_error_handler
14449                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
14450                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
14451                 break;
14452
14453               default:
14454                 _bfd_error_handler
14455                   (_("Warning: %B uses %s (set by %B), "
14456                      "%B uses unknown floating point ABI %d"),
14457                    obfd, abi_fp_bfd, ibfd,
14458                    "-mips32r2 -mfp64", in_attr[Tag_GNU_MIPS_ABI_FP].i);
14459                 break;
14460               }
14461             break;
14462
14463           default:
14464             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
14465               {
14466               case 1:
14467                 _bfd_error_handler
14468                   (_("Warning: %B uses unknown floating point ABI %d "
14469                      "(set by %B), %B uses %s"),
14470                    obfd, abi_fp_bfd, ibfd,
14471                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mdouble-float");
14472                 break;
14473
14474               case 2:
14475                 _bfd_error_handler
14476                   (_("Warning: %B uses unknown floating point ABI %d "
14477                      "(set by %B), %B uses %s"),
14478                    obfd, abi_fp_bfd, ibfd,
14479                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msingle-float");
14480                 break;
14481
14482               case 3:
14483                 _bfd_error_handler
14484                   (_("Warning: %B uses unknown floating point ABI %d "
14485                      "(set by %B), %B uses %s"),
14486                    obfd, abi_fp_bfd, ibfd,
14487                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msoft-float");
14488                 break;
14489
14490               case 4:
14491                 _bfd_error_handler
14492                   (_("Warning: %B uses unknown floating point ABI %d "
14493                      "(set by %B), %B uses %s"),
14494                    obfd, abi_fp_bfd, ibfd,
14495                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mips32r2 -mfp64");
14496                 break;
14497
14498               default:
14499                 _bfd_error_handler
14500                   (_("Warning: %B uses unknown floating point ABI %d "
14501                      "(set by %B), %B uses unknown floating point ABI %d"),
14502                    obfd, abi_fp_bfd, ibfd,
14503                    out_attr[Tag_GNU_MIPS_ABI_FP].i,
14504                    in_attr[Tag_GNU_MIPS_ABI_FP].i);
14505                 break;
14506               }
14507             break;
14508           }
14509     }
14510
14511   /* Merge Tag_compatibility attributes and any common GNU ones.  */
14512   _bfd_elf_merge_object_attributes (ibfd, obfd);
14513
14514   return TRUE;
14515 }
14516
14517 /* Merge backend specific data from an object file to the output
14518    object file when linking.  */
14519
14520 bfd_boolean
14521 _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
14522 {
14523   flagword old_flags;
14524   flagword new_flags;
14525   bfd_boolean ok;
14526   bfd_boolean null_input_bfd = TRUE;
14527   asection *sec;
14528
14529   /* Check if we have the same endianness.  */
14530   if (! _bfd_generic_verify_endian_match (ibfd, obfd))
14531     {
14532       (*_bfd_error_handler)
14533         (_("%B: endianness incompatible with that of the selected emulation"),
14534          ibfd);
14535       return FALSE;
14536     }
14537
14538   if (!is_mips_elf (ibfd) || !is_mips_elf (obfd))
14539     return TRUE;
14540
14541   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
14542     {
14543       (*_bfd_error_handler)
14544         (_("%B: ABI is incompatible with that of the selected emulation"),
14545          ibfd);
14546       return FALSE;
14547     }
14548
14549   if (!mips_elf_merge_obj_attributes (ibfd, obfd))
14550     return FALSE;
14551
14552   new_flags = elf_elfheader (ibfd)->e_flags;
14553   elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER;
14554   old_flags = elf_elfheader (obfd)->e_flags;
14555
14556   if (! elf_flags_init (obfd))
14557     {
14558       elf_flags_init (obfd) = TRUE;
14559       elf_elfheader (obfd)->e_flags = new_flags;
14560       elf_elfheader (obfd)->e_ident[EI_CLASS]
14561         = elf_elfheader (ibfd)->e_ident[EI_CLASS];
14562
14563       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
14564           && (bfd_get_arch_info (obfd)->the_default
14565               || mips_mach_extends_p (bfd_get_mach (obfd),
14566                                       bfd_get_mach (ibfd))))
14567         {
14568           if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
14569                                    bfd_get_mach (ibfd)))
14570             return FALSE;
14571         }
14572
14573       return TRUE;
14574     }
14575
14576   /* Check flag compatibility.  */
14577
14578   new_flags &= ~EF_MIPS_NOREORDER;
14579   old_flags &= ~EF_MIPS_NOREORDER;
14580
14581   /* Some IRIX 6 BSD-compatibility objects have this bit set.  It
14582      doesn't seem to matter.  */
14583   new_flags &= ~EF_MIPS_XGOT;
14584   old_flags &= ~EF_MIPS_XGOT;
14585
14586   /* MIPSpro generates ucode info in n64 objects.  Again, we should
14587      just be able to ignore this.  */
14588   new_flags &= ~EF_MIPS_UCODE;
14589   old_flags &= ~EF_MIPS_UCODE;
14590
14591   /* DSOs should only be linked with CPIC code.  */
14592   if ((ibfd->flags & DYNAMIC) != 0)
14593     new_flags |= EF_MIPS_PIC | EF_MIPS_CPIC;
14594
14595   if (new_flags == old_flags)
14596     return TRUE;
14597
14598   /* Check to see if the input BFD actually contains any sections.
14599      If not, its flags may not have been initialised either, but it cannot
14600      actually cause any incompatibility.  */
14601   for (sec = ibfd->sections; sec != NULL; sec = sec->next)
14602     {
14603       /* Ignore synthetic sections and empty .text, .data and .bss sections
14604          which are automatically generated by gas.  Also ignore fake
14605          (s)common sections, since merely defining a common symbol does
14606          not affect compatibility.  */
14607       if ((sec->flags & SEC_IS_COMMON) == 0
14608           && strcmp (sec->name, ".reginfo")
14609           && strcmp (sec->name, ".mdebug")
14610           && (sec->size != 0
14611               || (strcmp (sec->name, ".text")
14612                   && strcmp (sec->name, ".data")
14613                   && strcmp (sec->name, ".bss"))))
14614         {
14615           null_input_bfd = FALSE;
14616           break;
14617         }
14618     }
14619   if (null_input_bfd)
14620     return TRUE;
14621
14622   ok = TRUE;
14623
14624   if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)
14625       != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0))
14626     {
14627       (*_bfd_error_handler)
14628         (_("%B: warning: linking abicalls files with non-abicalls files"),
14629          ibfd);
14630       ok = TRUE;
14631     }
14632
14633   if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC))
14634     elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC;
14635   if (! (new_flags & EF_MIPS_PIC))
14636     elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC;
14637
14638   new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
14639   old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
14640
14641   /* Compare the ISAs.  */
14642   if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags))
14643     {
14644       (*_bfd_error_handler)
14645         (_("%B: linking 32-bit code with 64-bit code"),
14646          ibfd);
14647       ok = FALSE;
14648     }
14649   else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd)))
14650     {
14651       /* OBFD's ISA isn't the same as, or an extension of, IBFD's.  */
14652       if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd)))
14653         {
14654           /* Copy the architecture info from IBFD to OBFD.  Also copy
14655              the 32-bit flag (if set) so that we continue to recognise
14656              OBFD as a 32-bit binary.  */
14657           bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd));
14658           elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
14659           elf_elfheader (obfd)->e_flags
14660             |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14661
14662           /* Copy across the ABI flags if OBFD doesn't use them
14663              and if that was what caused us to treat IBFD as 32-bit.  */
14664           if ((old_flags & EF_MIPS_ABI) == 0
14665               && mips_32bit_flags_p (new_flags)
14666               && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI))
14667             elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI;
14668         }
14669       else
14670         {
14671           /* The ISAs aren't compatible.  */
14672           (*_bfd_error_handler)
14673             (_("%B: linking %s module with previous %s modules"),
14674              ibfd,
14675              bfd_printable_name (ibfd),
14676              bfd_printable_name (obfd));
14677           ok = FALSE;
14678         }
14679     }
14680
14681   new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14682   old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14683
14684   /* Compare ABIs.  The 64-bit ABI does not use EF_MIPS_ABI.  But, it
14685      does set EI_CLASS differently from any 32-bit ABI.  */
14686   if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI)
14687       || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14688           != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14689     {
14690       /* Only error if both are set (to different values).  */
14691       if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI))
14692           || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14693               != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14694         {
14695           (*_bfd_error_handler)
14696             (_("%B: ABI mismatch: linking %s module with previous %s modules"),
14697              ibfd,
14698              elf_mips_abi_name (ibfd),
14699              elf_mips_abi_name (obfd));
14700           ok = FALSE;
14701         }
14702       new_flags &= ~EF_MIPS_ABI;
14703       old_flags &= ~EF_MIPS_ABI;
14704     }
14705
14706   /* Compare ASEs.  Forbid linking MIPS16 and microMIPS ASE modules together
14707      and allow arbitrary mixing of the remaining ASEs (retain the union).  */
14708   if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE))
14709     {
14710       int old_micro = old_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14711       int new_micro = new_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14712       int old_m16 = old_flags & EF_MIPS_ARCH_ASE_M16;
14713       int new_m16 = new_flags & EF_MIPS_ARCH_ASE_M16;
14714       int micro_mis = old_m16 && new_micro;
14715       int m16_mis = old_micro && new_m16;
14716
14717       if (m16_mis || micro_mis)
14718         {
14719           (*_bfd_error_handler)
14720             (_("%B: ASE mismatch: linking %s module with previous %s modules"),
14721              ibfd,
14722              m16_mis ? "MIPS16" : "microMIPS",
14723              m16_mis ? "microMIPS" : "MIPS16");
14724           ok = FALSE;
14725         }
14726
14727       elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE;
14728
14729       new_flags &= ~ EF_MIPS_ARCH_ASE;
14730       old_flags &= ~ EF_MIPS_ARCH_ASE;
14731     }
14732
14733   /* Warn about any other mismatches */
14734   if (new_flags != old_flags)
14735     {
14736       (*_bfd_error_handler)
14737         (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"),
14738          ibfd, (unsigned long) new_flags,
14739          (unsigned long) old_flags);
14740       ok = FALSE;
14741     }
14742
14743   if (! ok)
14744     {
14745       bfd_set_error (bfd_error_bad_value);
14746       return FALSE;
14747     }
14748
14749   return TRUE;
14750 }
14751
14752 /* Function to keep MIPS specific file flags like as EF_MIPS_PIC.  */
14753
14754 bfd_boolean
14755 _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags)
14756 {
14757   BFD_ASSERT (!elf_flags_init (abfd)
14758               || elf_elfheader (abfd)->e_flags == flags);
14759
14760   elf_elfheader (abfd)->e_flags = flags;
14761   elf_flags_init (abfd) = TRUE;
14762   return TRUE;
14763 }
14764
14765 char *
14766 _bfd_mips_elf_get_target_dtag (bfd_vma dtag)
14767 {
14768   switch (dtag)
14769     {
14770     default: return "";
14771     case DT_MIPS_RLD_VERSION:
14772       return "MIPS_RLD_VERSION";
14773     case DT_MIPS_TIME_STAMP:
14774       return "MIPS_TIME_STAMP";
14775     case DT_MIPS_ICHECKSUM:
14776       return "MIPS_ICHECKSUM";
14777     case DT_MIPS_IVERSION:
14778       return "MIPS_IVERSION";
14779     case DT_MIPS_FLAGS:
14780       return "MIPS_FLAGS";
14781     case DT_MIPS_BASE_ADDRESS:
14782       return "MIPS_BASE_ADDRESS";
14783     case DT_MIPS_MSYM:
14784       return "MIPS_MSYM";
14785     case DT_MIPS_CONFLICT:
14786       return "MIPS_CONFLICT";
14787     case DT_MIPS_LIBLIST:
14788       return "MIPS_LIBLIST";
14789     case DT_MIPS_LOCAL_GOTNO:
14790       return "MIPS_LOCAL_GOTNO";
14791     case DT_MIPS_CONFLICTNO:
14792       return "MIPS_CONFLICTNO";
14793     case DT_MIPS_LIBLISTNO:
14794       return "MIPS_LIBLISTNO";
14795     case DT_MIPS_SYMTABNO:
14796       return "MIPS_SYMTABNO";
14797     case DT_MIPS_UNREFEXTNO:
14798       return "MIPS_UNREFEXTNO";
14799     case DT_MIPS_GOTSYM:
14800       return "MIPS_GOTSYM";
14801     case DT_MIPS_HIPAGENO:
14802       return "MIPS_HIPAGENO";
14803     case DT_MIPS_RLD_MAP:
14804       return "MIPS_RLD_MAP";
14805     case DT_MIPS_DELTA_CLASS:
14806       return "MIPS_DELTA_CLASS";
14807     case DT_MIPS_DELTA_CLASS_NO:
14808       return "MIPS_DELTA_CLASS_NO";
14809     case DT_MIPS_DELTA_INSTANCE:
14810       return "MIPS_DELTA_INSTANCE";
14811     case DT_MIPS_DELTA_INSTANCE_NO:
14812       return "MIPS_DELTA_INSTANCE_NO";
14813     case DT_MIPS_DELTA_RELOC:
14814       return "MIPS_DELTA_RELOC";
14815     case DT_MIPS_DELTA_RELOC_NO:
14816       return "MIPS_DELTA_RELOC_NO";
14817     case DT_MIPS_DELTA_SYM:
14818       return "MIPS_DELTA_SYM";
14819     case DT_MIPS_DELTA_SYM_NO:
14820       return "MIPS_DELTA_SYM_NO";
14821     case DT_MIPS_DELTA_CLASSSYM:
14822       return "MIPS_DELTA_CLASSSYM";
14823     case DT_MIPS_DELTA_CLASSSYM_NO:
14824       return "MIPS_DELTA_CLASSSYM_NO";
14825     case DT_MIPS_CXX_FLAGS:
14826       return "MIPS_CXX_FLAGS";
14827     case DT_MIPS_PIXIE_INIT:
14828       return "MIPS_PIXIE_INIT";
14829     case DT_MIPS_SYMBOL_LIB:
14830       return "MIPS_SYMBOL_LIB";
14831     case DT_MIPS_LOCALPAGE_GOTIDX:
14832       return "MIPS_LOCALPAGE_GOTIDX";
14833     case DT_MIPS_LOCAL_GOTIDX:
14834       return "MIPS_LOCAL_GOTIDX";
14835     case DT_MIPS_HIDDEN_GOTIDX:
14836       return "MIPS_HIDDEN_GOTIDX";
14837     case DT_MIPS_PROTECTED_GOTIDX:
14838       return "MIPS_PROTECTED_GOT_IDX";
14839     case DT_MIPS_OPTIONS:
14840       return "MIPS_OPTIONS";
14841     case DT_MIPS_INTERFACE:
14842       return "MIPS_INTERFACE";
14843     case DT_MIPS_DYNSTR_ALIGN:
14844       return "DT_MIPS_DYNSTR_ALIGN";
14845     case DT_MIPS_INTERFACE_SIZE:
14846       return "DT_MIPS_INTERFACE_SIZE";
14847     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
14848       return "DT_MIPS_RLD_TEXT_RESOLVE_ADDR";
14849     case DT_MIPS_PERF_SUFFIX:
14850       return "DT_MIPS_PERF_SUFFIX";
14851     case DT_MIPS_COMPACT_SIZE:
14852       return "DT_MIPS_COMPACT_SIZE";
14853     case DT_MIPS_GP_VALUE:
14854       return "DT_MIPS_GP_VALUE";
14855     case DT_MIPS_AUX_DYNAMIC:
14856       return "DT_MIPS_AUX_DYNAMIC";
14857     case DT_MIPS_PLTGOT:
14858       return "DT_MIPS_PLTGOT";
14859     case DT_MIPS_RWPLT:
14860       return "DT_MIPS_RWPLT";
14861     }
14862 }
14863
14864 bfd_boolean
14865 _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr)
14866 {
14867   FILE *file = ptr;
14868
14869   BFD_ASSERT (abfd != NULL && ptr != NULL);
14870
14871   /* Print normal ELF private data.  */
14872   _bfd_elf_print_private_bfd_data (abfd, ptr);
14873
14874   /* xgettext:c-format */
14875   fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
14876
14877   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
14878     fprintf (file, _(" [abi=O32]"));
14879   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64)
14880     fprintf (file, _(" [abi=O64]"));
14881   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32)
14882     fprintf (file, _(" [abi=EABI32]"));
14883   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
14884     fprintf (file, _(" [abi=EABI64]"));
14885   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI))
14886     fprintf (file, _(" [abi unknown]"));
14887   else if (ABI_N32_P (abfd))
14888     fprintf (file, _(" [abi=N32]"));
14889   else if (ABI_64_P (abfd))
14890     fprintf (file, _(" [abi=64]"));
14891   else
14892     fprintf (file, _(" [no abi set]"));
14893
14894   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1)
14895     fprintf (file, " [mips1]");
14896   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2)
14897     fprintf (file, " [mips2]");
14898   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3)
14899     fprintf (file, " [mips3]");
14900   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4)
14901     fprintf (file, " [mips4]");
14902   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5)
14903     fprintf (file, " [mips5]");
14904   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32)
14905     fprintf (file, " [mips32]");
14906   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64)
14907     fprintf (file, " [mips64]");
14908   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2)
14909     fprintf (file, " [mips32r2]");
14910   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2)
14911     fprintf (file, " [mips64r2]");
14912   else
14913     fprintf (file, _(" [unknown ISA]"));
14914
14915   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
14916     fprintf (file, " [mdmx]");
14917
14918   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
14919     fprintf (file, " [mips16]");
14920
14921   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
14922     fprintf (file, " [micromips]");
14923
14924   if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE)
14925     fprintf (file, " [32bitmode]");
14926   else
14927     fprintf (file, _(" [not 32bitmode]"));
14928
14929   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NOREORDER)
14930     fprintf (file, " [noreorder]");
14931
14932   if (elf_elfheader (abfd)->e_flags & EF_MIPS_PIC)
14933     fprintf (file, " [PIC]");
14934
14935   if (elf_elfheader (abfd)->e_flags & EF_MIPS_CPIC)
14936     fprintf (file, " [CPIC]");
14937
14938   if (elf_elfheader (abfd)->e_flags & EF_MIPS_XGOT)
14939     fprintf (file, " [XGOT]");
14940
14941   if (elf_elfheader (abfd)->e_flags & EF_MIPS_UCODE)
14942     fprintf (file, " [UCODE]");
14943
14944   fputc ('\n', file);
14945
14946   return TRUE;
14947 }
14948
14949 const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] =
14950 {
14951   { STRING_COMMA_LEN (".lit4"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14952   { STRING_COMMA_LEN (".lit8"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14953   { STRING_COMMA_LEN (".mdebug"), 0, SHT_MIPS_DEBUG, 0 },
14954   { STRING_COMMA_LEN (".sbss"),  -2, SHT_NOBITS,     SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14955   { STRING_COMMA_LEN (".sdata"), -2, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14956   { STRING_COMMA_LEN (".ucode"),  0, SHT_MIPS_UCODE, 0 },
14957   { NULL,                     0,  0, 0,              0 }
14958 };
14959
14960 /* Merge non visibility st_other attributes.  Ensure that the
14961    STO_OPTIONAL flag is copied into h->other, even if this is not a
14962    definiton of the symbol.  */
14963 void
14964 _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
14965                                       const Elf_Internal_Sym *isym,
14966                                       bfd_boolean definition,
14967                                       bfd_boolean dynamic ATTRIBUTE_UNUSED)
14968 {
14969   if ((isym->st_other & ~ELF_ST_VISIBILITY (-1)) != 0)
14970     {
14971       unsigned char other;
14972
14973       other = (definition ? isym->st_other : h->other);
14974       other &= ~ELF_ST_VISIBILITY (-1);
14975       h->other = other | ELF_ST_VISIBILITY (h->other);
14976     }
14977
14978   if (!definition
14979       && ELF_MIPS_IS_OPTIONAL (isym->st_other))
14980     h->other |= STO_OPTIONAL;
14981 }
14982
14983 /* Decide whether an undefined symbol is special and can be ignored.
14984    This is the case for OPTIONAL symbols on IRIX.  */
14985 bfd_boolean
14986 _bfd_mips_elf_ignore_undef_symbol (struct elf_link_hash_entry *h)
14987 {
14988   return ELF_MIPS_IS_OPTIONAL (h->other) ? TRUE : FALSE;
14989 }
14990
14991 bfd_boolean
14992 _bfd_mips_elf_common_definition (Elf_Internal_Sym *sym)
14993 {
14994   return (sym->st_shndx == SHN_COMMON
14995           || sym->st_shndx == SHN_MIPS_ACOMMON
14996           || sym->st_shndx == SHN_MIPS_SCOMMON);
14997 }
14998
14999 /* Return address for Ith PLT stub in section PLT, for relocation REL
15000    or (bfd_vma) -1 if it should not be included.  */
15001
15002 bfd_vma
15003 _bfd_mips_elf_plt_sym_val (bfd_vma i, const asection *plt,
15004                            const arelent *rel ATTRIBUTE_UNUSED)
15005 {
15006   return (plt->vma
15007           + 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry)
15008           + i * 4 * ARRAY_SIZE (mips_exec_plt_entry));
15009 }
15010
15011 /* Build a table of synthetic symbols to represent the PLT.  As with MIPS16
15012    and microMIPS PLT slots we may have a many-to-one mapping between .plt
15013    and .got.plt and also the slots may be of a different size each we walk
15014    the PLT manually fetching instructions and matching them against known
15015    patterns.  To make things easier standard MIPS slots, if any, always come
15016    first.  As we don't create proper ELF symbols we use the UDATA.I member
15017    of ASYMBOL to carry ISA annotation.  The encoding used is the same as
15018    with the ST_OTHER member of the ELF symbol.  */
15019
15020 long
15021 _bfd_mips_elf_get_synthetic_symtab (bfd *abfd,
15022                                     long symcount ATTRIBUTE_UNUSED,
15023                                     asymbol **syms ATTRIBUTE_UNUSED,
15024                                     long dynsymcount, asymbol **dynsyms,
15025                                     asymbol **ret)
15026 {
15027   static const char pltname[] = "_PROCEDURE_LINKAGE_TABLE_";
15028   static const char microsuffix[] = "@micromipsplt";
15029   static const char m16suffix[] = "@mips16plt";
15030   static const char mipssuffix[] = "@plt";
15031
15032   bfd_boolean (*slurp_relocs) (bfd *, asection *, asymbol **, bfd_boolean);
15033   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
15034   bfd_boolean micromips_p = MICROMIPS_P (abfd);
15035   Elf_Internal_Shdr *hdr;
15036   bfd_byte *plt_data;
15037   bfd_vma plt_offset;
15038   unsigned int other;
15039   bfd_vma entry_size;
15040   bfd_vma plt0_size;
15041   asection *relplt;
15042   bfd_vma opcode;
15043   asection *plt;
15044   asymbol *send;
15045   size_t size;
15046   char *names;
15047   long counti;
15048   arelent *p;
15049   asymbol *s;
15050   char *nend;
15051   long count;
15052   long pi;
15053   long i;
15054   long n;
15055
15056   *ret = NULL;
15057
15058   if ((abfd->flags & (DYNAMIC | EXEC_P)) == 0 || dynsymcount <= 0)
15059     return 0;
15060
15061   relplt = bfd_get_section_by_name (abfd, ".rel.plt");
15062   if (relplt == NULL)
15063     return 0;
15064
15065   hdr = &elf_section_data (relplt)->this_hdr;
15066   if (hdr->sh_link != elf_dynsymtab (abfd) || hdr->sh_type != SHT_REL)
15067     return 0;
15068
15069   plt = bfd_get_section_by_name (abfd, ".plt");
15070   if (plt == NULL)
15071     return 0;
15072
15073   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
15074   if (!(*slurp_relocs) (abfd, relplt, dynsyms, TRUE))
15075     return -1;
15076   p = relplt->relocation;
15077
15078   /* Calculating the exact amount of space required for symbols would
15079      require two passes over the PLT, so just pessimise assuming two
15080      PLT slots per relocation.  */
15081   count = relplt->size / hdr->sh_entsize;
15082   counti = count * bed->s->int_rels_per_ext_rel;
15083   size = 2 * count * sizeof (asymbol);
15084   size += count * (sizeof (mipssuffix) +
15085                    (micromips_p ? sizeof (microsuffix) : sizeof (m16suffix)));
15086   for (pi = 0; pi < counti; pi += bed->s->int_rels_per_ext_rel)
15087     size += 2 * strlen ((*p[pi].sym_ptr_ptr)->name);
15088
15089   /* Add the size of "_PROCEDURE_LINKAGE_TABLE_" too.  */
15090   size += sizeof (asymbol) + sizeof (pltname);
15091
15092   if (!bfd_malloc_and_get_section (abfd, plt, &plt_data))
15093     return -1;
15094
15095   if (plt->size < 16)
15096     return -1;
15097
15098   s = *ret = bfd_malloc (size);
15099   if (s == NULL)
15100     return -1;
15101   send = s + 2 * count + 1;
15102
15103   names = (char *) send;
15104   nend = (char *) s + size;
15105   n = 0;
15106
15107   opcode = bfd_get_micromips_32 (abfd, plt_data + 12);
15108   if (opcode == 0x3302fffe)
15109     {
15110       if (!micromips_p)
15111         return -1;
15112       plt0_size = 2 * ARRAY_SIZE (micromips_o32_exec_plt0_entry);
15113       other = STO_MICROMIPS;
15114     }
15115   else if (opcode == 0x0398c1d0)
15116     {
15117       if (!micromips_p)
15118         return -1;
15119       plt0_size = 2 * ARRAY_SIZE (micromips_insn32_o32_exec_plt0_entry);
15120       other = STO_MICROMIPS;
15121     }
15122   else
15123     {
15124       plt0_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
15125       other = 0;
15126     }
15127
15128   s->the_bfd = abfd;
15129   s->flags = BSF_SYNTHETIC | BSF_FUNCTION | BSF_LOCAL;
15130   s->section = plt;
15131   s->value = 0;
15132   s->name = names;
15133   s->udata.i = other;
15134   memcpy (names, pltname, sizeof (pltname));
15135   names += sizeof (pltname);
15136   ++s, ++n;
15137
15138   pi = 0;
15139   for (plt_offset = plt0_size;
15140        plt_offset + 8 <= plt->size && s < send;
15141        plt_offset += entry_size)
15142     {
15143       bfd_vma gotplt_addr;
15144       const char *suffix;
15145       bfd_vma gotplt_hi;
15146       bfd_vma gotplt_lo;
15147       size_t suffixlen;
15148
15149       opcode = bfd_get_micromips_32 (abfd, plt_data + plt_offset + 4);
15150
15151       /* Check if the second word matches the expected MIPS16 instruction.  */
15152       if (opcode == 0x651aeb00)
15153         {
15154           if (micromips_p)
15155             return -1;
15156           /* Truncated table???  */
15157           if (plt_offset + 16 > plt->size)
15158             break;
15159           gotplt_addr = bfd_get_32 (abfd, plt_data + plt_offset + 12);
15160           entry_size = 2 * ARRAY_SIZE (mips16_o32_exec_plt_entry);
15161           suffixlen = sizeof (m16suffix);
15162           suffix = m16suffix;
15163           other = STO_MIPS16;
15164         }
15165       /* Likewise the expected microMIPS instruction (no insn32 mode).  */
15166       else if (opcode == 0xff220000)
15167         {
15168           if (!micromips_p)
15169             return -1;
15170           gotplt_hi = bfd_get_16 (abfd, plt_data + plt_offset) & 0x7f;
15171           gotplt_lo = bfd_get_16 (abfd, plt_data + plt_offset + 2) & 0xffff;
15172           gotplt_hi = ((gotplt_hi ^ 0x40) - 0x40) << 18;
15173           gotplt_lo <<= 2;
15174           gotplt_addr = gotplt_hi + gotplt_lo;
15175           gotplt_addr += ((plt->vma + plt_offset) | 3) ^ 3;
15176           entry_size = 2 * ARRAY_SIZE (micromips_o32_exec_plt_entry);
15177           suffixlen = sizeof (microsuffix);
15178           suffix = microsuffix;
15179           other = STO_MICROMIPS;
15180         }
15181       /* Likewise the expected microMIPS instruction (insn32 mode).  */
15182       else if ((opcode & 0xffff0000) == 0xff2f0000)
15183         {
15184           gotplt_hi = bfd_get_16 (abfd, plt_data + plt_offset + 2) & 0xffff;
15185           gotplt_lo = bfd_get_16 (abfd, plt_data + plt_offset + 6) & 0xffff;
15186           gotplt_hi = ((gotplt_hi ^ 0x8000) - 0x8000) << 16;
15187           gotplt_lo = (gotplt_lo ^ 0x8000) - 0x8000;
15188           gotplt_addr = gotplt_hi + gotplt_lo;
15189           entry_size = 2 * ARRAY_SIZE (micromips_insn32_o32_exec_plt_entry);
15190           suffixlen = sizeof (microsuffix);
15191           suffix = microsuffix;
15192           other = STO_MICROMIPS;
15193         }
15194       /* Otherwise assume standard MIPS code.  */
15195       else
15196         {
15197           gotplt_hi = bfd_get_32 (abfd, plt_data + plt_offset) & 0xffff;
15198           gotplt_lo = bfd_get_32 (abfd, plt_data + plt_offset + 4) & 0xffff;
15199           gotplt_hi = ((gotplt_hi ^ 0x8000) - 0x8000) << 16;
15200           gotplt_lo = (gotplt_lo ^ 0x8000) - 0x8000;
15201           gotplt_addr = gotplt_hi + gotplt_lo;
15202           entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
15203           suffixlen = sizeof (mipssuffix);
15204           suffix = mipssuffix;
15205           other = 0;
15206         }
15207       /* Truncated table???  */
15208       if (plt_offset + entry_size > plt->size)
15209         break;
15210
15211       for (i = 0;
15212            i < count && p[pi].address != gotplt_addr;
15213            i++, pi = (pi + bed->s->int_rels_per_ext_rel) % counti);
15214
15215       if (i < count)
15216         {
15217           size_t namelen;
15218           size_t len;
15219
15220           *s = **p[pi].sym_ptr_ptr;
15221           /* Undefined syms won't have BSF_LOCAL or BSF_GLOBAL set.  Since
15222              we are defining a symbol, ensure one of them is set.  */
15223           if ((s->flags & BSF_LOCAL) == 0)
15224             s->flags |= BSF_GLOBAL;
15225           s->flags |= BSF_SYNTHETIC;
15226           s->section = plt;
15227           s->value = plt_offset;
15228           s->name = names;
15229           s->udata.i = other;
15230
15231           len = strlen ((*p[pi].sym_ptr_ptr)->name);
15232           namelen = len + suffixlen;
15233           if (names + namelen > nend)
15234             break;
15235
15236           memcpy (names, (*p[pi].sym_ptr_ptr)->name, len);
15237           names += len;
15238           memcpy (names, suffix, suffixlen);
15239           names += suffixlen;
15240
15241           ++s, ++n;
15242           pi = (pi + bed->s->int_rels_per_ext_rel) % counti;
15243         }
15244     }
15245
15246   free (plt_data);
15247
15248   return n;
15249 }
15250
15251 void
15252 _bfd_mips_post_process_headers (bfd *abfd, struct bfd_link_info *link_info)
15253 {
15254   struct mips_elf_link_hash_table *htab;
15255   Elf_Internal_Ehdr *i_ehdrp;
15256
15257   i_ehdrp = elf_elfheader (abfd);
15258   if (link_info)
15259     {
15260       htab = mips_elf_hash_table (link_info);
15261       BFD_ASSERT (htab != NULL);
15262
15263       if (htab->use_plts_and_copy_relocs && !htab->is_vxworks)
15264         i_ehdrp->e_ident[EI_ABIVERSION] = 1;
15265     }
15266 }