MIPS: Fix a .pdr section linker buffer overrun
[platform/upstream/binutils.git] / bfd / elfxx-mips.c
1 /* MIPS-specific support for ELF
2    Copyright (C) 1993-2014 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 first unused local .got entry.  */
172   unsigned int assigned_low_gotno;
173   /* The last unused local .got entry.  */
174   unsigned int assigned_high_gotno;
175   /* A hash table holding members of the got.  */
176   struct htab *got_entries;
177   /* A hash table holding mips_got_page_ref structures.  */
178   struct htab *got_page_refs;
179   /* A hash table of mips_got_page_entry structures.  */
180   struct htab *got_page_entries;
181   /* In multi-got links, a pointer to the next got (err, rather, most
182      of the time, it points to the previous got).  */
183   struct mips_got_info *next;
184 };
185
186 /* Structure passed when merging bfds' gots.  */
187
188 struct mips_elf_got_per_bfd_arg
189 {
190   /* The output bfd.  */
191   bfd *obfd;
192   /* The link information.  */
193   struct bfd_link_info *info;
194   /* A pointer to the primary got, i.e., the one that's going to get
195      the implicit relocations from DT_MIPS_LOCAL_GOTNO and
196      DT_MIPS_GOTSYM.  */
197   struct mips_got_info *primary;
198   /* A non-primary got we're trying to merge with other input bfd's
199      gots.  */
200   struct mips_got_info *current;
201   /* The maximum number of got entries that can be addressed with a
202      16-bit offset.  */
203   unsigned int max_count;
204   /* The maximum number of page entries needed by each got.  */
205   unsigned int max_pages;
206   /* The total number of global entries which will live in the
207      primary got and be automatically relocated.  This includes
208      those not referenced by the primary GOT but included in
209      the "master" GOT.  */
210   unsigned int global_count;
211 };
212
213 /* A structure used to pass information to htab_traverse callbacks
214    when laying out the GOT.  */
215
216 struct mips_elf_traverse_got_arg
217 {
218   struct bfd_link_info *info;
219   struct mips_got_info *g;
220   int value;
221 };
222
223 struct _mips_elf_section_data
224 {
225   struct bfd_elf_section_data elf;
226   union
227   {
228     bfd_byte *tdata;
229   } u;
230 };
231
232 #define mips_elf_section_data(sec) \
233   ((struct _mips_elf_section_data *) elf_section_data (sec))
234
235 #define is_mips_elf(bfd)                                \
236   (bfd_get_flavour (bfd) == bfd_target_elf_flavour      \
237    && elf_tdata (bfd) != NULL                           \
238    && elf_object_id (bfd) == MIPS_ELF_DATA)
239
240 /* The ABI says that every symbol used by dynamic relocations must have
241    a global GOT entry.  Among other things, this provides the dynamic
242    linker with a free, directly-indexed cache.  The GOT can therefore
243    contain symbols that are not referenced by GOT relocations themselves
244    (in other words, it may have symbols that are not referenced by things
245    like R_MIPS_GOT16 and R_MIPS_GOT_PAGE).
246
247    GOT relocations are less likely to overflow if we put the associated
248    GOT entries towards the beginning.  We therefore divide the global
249    GOT entries into two areas: "normal" and "reloc-only".  Entries in
250    the first area can be used for both dynamic relocations and GP-relative
251    accesses, while those in the "reloc-only" area are for dynamic
252    relocations only.
253
254    These GGA_* ("Global GOT Area") values are organised so that lower
255    values are more general than higher values.  Also, non-GGA_NONE
256    values are ordered by the position of the area in the GOT.  */
257 #define GGA_NORMAL 0
258 #define GGA_RELOC_ONLY 1
259 #define GGA_NONE 2
260
261 /* Information about a non-PIC interface to a PIC function.  There are
262    two ways of creating these interfaces.  The first is to add:
263
264         lui     $25,%hi(func)
265         addiu   $25,$25,%lo(func)
266
267    immediately before a PIC function "func".  The second is to add:
268
269         lui     $25,%hi(func)
270         j       func
271         addiu   $25,$25,%lo(func)
272
273    to a separate trampoline section.
274
275    Stubs of the first kind go in a new section immediately before the
276    target function.  Stubs of the second kind go in a single section
277    pointed to by the hash table's "strampoline" field.  */
278 struct mips_elf_la25_stub {
279   /* The generated section that contains this stub.  */
280   asection *stub_section;
281
282   /* The offset of the stub from the start of STUB_SECTION.  */
283   bfd_vma offset;
284
285   /* One symbol for the original function.  Its location is available
286      in H->root.root.u.def.  */
287   struct mips_elf_link_hash_entry *h;
288 };
289
290 /* Macros for populating a mips_elf_la25_stub.  */
291
292 #define LA25_LUI(VAL) (0x3c190000 | (VAL))      /* lui t9,VAL */
293 #define LA25_J(VAL) (0x08000000 | (((VAL) >> 2) & 0x3ffffff)) /* j VAL */
294 #define LA25_ADDIU(VAL) (0x27390000 | (VAL))    /* addiu t9,t9,VAL */
295 #define LA25_LUI_MICROMIPS(VAL)                                         \
296   (0x41b90000 | (VAL))                          /* lui t9,VAL */
297 #define LA25_J_MICROMIPS(VAL)                                           \
298   (0xd4000000 | (((VAL) >> 1) & 0x3ffffff))     /* j VAL */
299 #define LA25_ADDIU_MICROMIPS(VAL)                                       \
300   (0x33390000 | (VAL))                          /* addiu t9,t9,VAL */
301
302 /* This structure is passed to mips_elf_sort_hash_table_f when sorting
303    the dynamic symbols.  */
304
305 struct mips_elf_hash_sort_data
306 {
307   /* The symbol in the global GOT with the lowest dynamic symbol table
308      index.  */
309   struct elf_link_hash_entry *low;
310   /* The least dynamic symbol table index corresponding to a non-TLS
311      symbol with a GOT entry.  */
312   long min_got_dynindx;
313   /* The greatest dynamic symbol table index corresponding to a symbol
314      with a GOT entry that is not referenced (e.g., a dynamic symbol
315      with dynamic relocations pointing to it from non-primary GOTs).  */
316   long max_unref_got_dynindx;
317   /* The greatest dynamic symbol table index not corresponding to a
318      symbol without a GOT entry.  */
319   long max_non_got_dynindx;
320 };
321
322 /* We make up to two PLT entries if needed, one for standard MIPS code
323    and one for compressed code, either a MIPS16 or microMIPS one.  We
324    keep a separate record of traditional lazy-binding stubs, for easier
325    processing.  */
326
327 struct plt_entry
328 {
329   /* Traditional SVR4 stub offset, or -1 if none.  */
330   bfd_vma stub_offset;
331
332   /* Standard PLT entry offset, or -1 if none.  */
333   bfd_vma mips_offset;
334
335   /* Compressed PLT entry offset, or -1 if none.  */
336   bfd_vma comp_offset;
337
338   /* The corresponding .got.plt index, or -1 if none.  */
339   bfd_vma gotplt_index;
340
341   /* Whether we need a standard PLT entry.  */
342   unsigned int need_mips : 1;
343
344   /* Whether we need a compressed PLT entry.  */
345   unsigned int need_comp : 1;
346 };
347
348 /* The MIPS ELF linker needs additional information for each symbol in
349    the global hash table.  */
350
351 struct mips_elf_link_hash_entry
352 {
353   struct elf_link_hash_entry root;
354
355   /* External symbol information.  */
356   EXTR esym;
357
358   /* The la25 stub we have created for ths symbol, if any.  */
359   struct mips_elf_la25_stub *la25_stub;
360
361   /* Number of R_MIPS_32, R_MIPS_REL32, or R_MIPS_64 relocs against
362      this symbol.  */
363   unsigned int possibly_dynamic_relocs;
364
365   /* If there is a stub that 32 bit functions should use to call this
366      16 bit function, this points to the section containing the stub.  */
367   asection *fn_stub;
368
369   /* If there is a stub that 16 bit functions should use to call this
370      32 bit function, this points to the section containing the stub.  */
371   asection *call_stub;
372
373   /* This is like the call_stub field, but it is used if the function
374      being called returns a floating point value.  */
375   asection *call_fp_stub;
376
377   /* The highest GGA_* value that satisfies all references to this symbol.  */
378   unsigned int global_got_area : 2;
379
380   /* True if all GOT relocations against this symbol are for calls.  This is
381      a looser condition than no_fn_stub below, because there may be other
382      non-call non-GOT relocations against the symbol.  */
383   unsigned int got_only_for_calls : 1;
384
385   /* True if one of the relocations described by possibly_dynamic_relocs
386      is against a readonly section.  */
387   unsigned int readonly_reloc : 1;
388
389   /* True if there is a relocation against this symbol that must be
390      resolved by the static linker (in other words, if the relocation
391      cannot possibly be made dynamic).  */
392   unsigned int has_static_relocs : 1;
393
394   /* True if we must not create a .MIPS.stubs entry for this symbol.
395      This is set, for example, if there are relocations related to
396      taking the function's address, i.e. any but R_MIPS_CALL*16 ones.
397      See "MIPS ABI Supplement, 3rd Edition", p. 4-20.  */
398   unsigned int no_fn_stub : 1;
399
400   /* Whether we need the fn_stub; this is true if this symbol appears
401      in any relocs other than a 16 bit call.  */
402   unsigned int need_fn_stub : 1;
403
404   /* True if this symbol is referenced by branch relocations from
405      any non-PIC input file.  This is used to determine whether an
406      la25 stub is required.  */
407   unsigned int has_nonpic_branches : 1;
408
409   /* Does this symbol need a traditional MIPS lazy-binding stub
410      (as opposed to a PLT entry)?  */
411   unsigned int needs_lazy_stub : 1;
412
413   /* Does this symbol resolve to a PLT entry?  */
414   unsigned int use_plt_entry : 1;
415 };
416
417 /* MIPS ELF linker hash table.  */
418
419 struct mips_elf_link_hash_table
420 {
421   struct elf_link_hash_table root;
422
423   /* The number of .rtproc entries.  */
424   bfd_size_type procedure_count;
425
426   /* The size of the .compact_rel section (if SGI_COMPAT).  */
427   bfd_size_type compact_rel_size;
428
429   /* This flag indicates that the value of DT_MIPS_RLD_MAP dynamic entry
430      is set to the address of __rld_obj_head as in IRIX5 and IRIX6.  */
431   bfd_boolean use_rld_obj_head;
432
433   /* The  __rld_map or __rld_obj_head symbol. */
434   struct elf_link_hash_entry *rld_symbol;
435
436   /* This is set if we see any mips16 stub sections.  */
437   bfd_boolean mips16_stubs_seen;
438
439   /* True if we can generate copy relocs and PLTs.  */
440   bfd_boolean use_plts_and_copy_relocs;
441
442   /* True if we can only use 32-bit microMIPS instructions.  */
443   bfd_boolean insn32;
444
445   /* True if we're generating code for VxWorks.  */
446   bfd_boolean is_vxworks;
447
448   /* True if we already reported the small-data section overflow.  */
449   bfd_boolean small_data_overflow_reported;
450
451   /* Shortcuts to some dynamic sections, or NULL if they are not
452      being used.  */
453   asection *srelbss;
454   asection *sdynbss;
455   asection *srelplt;
456   asection *srelplt2;
457   asection *sgotplt;
458   asection *splt;
459   asection *sstubs;
460   asection *sgot;
461
462   /* The master GOT information.  */
463   struct mips_got_info *got_info;
464
465   /* The global symbol in the GOT with the lowest index in the dynamic
466      symbol table.  */
467   struct elf_link_hash_entry *global_gotsym;
468
469   /* The size of the PLT header in bytes.  */
470   bfd_vma plt_header_size;
471
472   /* The size of a standard PLT entry in bytes.  */
473   bfd_vma plt_mips_entry_size;
474
475   /* The size of a compressed PLT entry in bytes.  */
476   bfd_vma plt_comp_entry_size;
477
478   /* The offset of the next standard PLT entry to create.  */
479   bfd_vma plt_mips_offset;
480
481   /* The offset of the next compressed PLT entry to create.  */
482   bfd_vma plt_comp_offset;
483
484   /* The index of the next .got.plt entry to create.  */
485   bfd_vma plt_got_index;
486
487   /* The number of functions that need a lazy-binding stub.  */
488   bfd_vma lazy_stub_count;
489
490   /* The size of a function stub entry in bytes.  */
491   bfd_vma function_stub_size;
492
493   /* The number of reserved entries at the beginning of the GOT.  */
494   unsigned int reserved_gotno;
495
496   /* The section used for mips_elf_la25_stub trampolines.
497      See the comment above that structure for details.  */
498   asection *strampoline;
499
500   /* A table of mips_elf_la25_stubs, indexed by (input_section, offset)
501      pairs.  */
502   htab_t la25_stubs;
503
504   /* A function FN (NAME, IS, OS) that creates a new input section
505      called NAME and links it to output section OS.  If IS is nonnull,
506      the new section should go immediately before it, otherwise it
507      should go at the (current) beginning of OS.
508
509      The function returns the new section on success, otherwise it
510      returns null.  */
511   asection *(*add_stub_section) (const char *, asection *, asection *);
512
513   /* Small local sym cache.  */
514   struct sym_cache sym_cache;
515
516   /* Is the PLT header compressed?  */
517   unsigned int plt_header_is_comp : 1;
518 };
519
520 /* Get the MIPS ELF linker hash table from a link_info structure.  */
521
522 #define mips_elf_hash_table(p) \
523   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
524   == MIPS_ELF_DATA ? ((struct mips_elf_link_hash_table *) ((p)->hash)) : NULL)
525
526 /* A structure used to communicate with htab_traverse callbacks.  */
527 struct mips_htab_traverse_info
528 {
529   /* The usual link-wide information.  */
530   struct bfd_link_info *info;
531   bfd *output_bfd;
532
533   /* Starts off FALSE and is set to TRUE if the link should be aborted.  */
534   bfd_boolean error;
535 };
536
537 /* MIPS ELF private object data.  */
538
539 struct mips_elf_obj_tdata
540 {
541   /* Generic ELF private object data.  */
542   struct elf_obj_tdata root;
543
544   /* Input BFD providing Tag_GNU_MIPS_ABI_FP attribute for output.  */
545   bfd *abi_fp_bfd;
546
547   /* Input BFD providing Tag_GNU_MIPS_ABI_MSA attribute for output.  */
548   bfd *abi_msa_bfd;
549
550   /* The abiflags for this object.  */
551   Elf_Internal_ABIFlags_v0 abiflags;
552   bfd_boolean abiflags_valid;
553
554   /* The GOT requirements of input bfds.  */
555   struct mips_got_info *got;
556
557   /* Used by _bfd_mips_elf_find_nearest_line.  The structure could be
558      included directly in this one, but there's no point to wasting
559      the memory just for the infrequently called find_nearest_line.  */
560   struct mips_elf_find_line *find_line_info;
561
562   /* An array of stub sections indexed by symbol number.  */
563   asection **local_stubs;
564   asection **local_call_stubs;
565
566   /* The Irix 5 support uses two virtual sections, which represent
567      text/data symbols defined in dynamic objects.  */
568   asymbol *elf_data_symbol;
569   asymbol *elf_text_symbol;
570   asection *elf_data_section;
571   asection *elf_text_section;
572 };
573
574 /* Get MIPS ELF private object data from BFD's tdata.  */
575
576 #define mips_elf_tdata(bfd) \
577   ((struct mips_elf_obj_tdata *) (bfd)->tdata.any)
578
579 #define TLS_RELOC_P(r_type) \
580   (r_type == R_MIPS_TLS_DTPMOD32                \
581    || r_type == R_MIPS_TLS_DTPMOD64             \
582    || r_type == R_MIPS_TLS_DTPREL32             \
583    || r_type == R_MIPS_TLS_DTPREL64             \
584    || r_type == R_MIPS_TLS_GD                   \
585    || r_type == R_MIPS_TLS_LDM                  \
586    || r_type == R_MIPS_TLS_DTPREL_HI16          \
587    || r_type == R_MIPS_TLS_DTPREL_LO16          \
588    || r_type == R_MIPS_TLS_GOTTPREL             \
589    || r_type == R_MIPS_TLS_TPREL32              \
590    || r_type == R_MIPS_TLS_TPREL64              \
591    || r_type == R_MIPS_TLS_TPREL_HI16           \
592    || r_type == R_MIPS_TLS_TPREL_LO16           \
593    || r_type == R_MIPS16_TLS_GD                 \
594    || r_type == R_MIPS16_TLS_LDM                \
595    || r_type == R_MIPS16_TLS_DTPREL_HI16        \
596    || r_type == R_MIPS16_TLS_DTPREL_LO16        \
597    || r_type == R_MIPS16_TLS_GOTTPREL           \
598    || r_type == R_MIPS16_TLS_TPREL_HI16         \
599    || r_type == R_MIPS16_TLS_TPREL_LO16         \
600    || r_type == R_MICROMIPS_TLS_GD              \
601    || r_type == R_MICROMIPS_TLS_LDM             \
602    || r_type == R_MICROMIPS_TLS_DTPREL_HI16     \
603    || r_type == R_MICROMIPS_TLS_DTPREL_LO16     \
604    || r_type == R_MICROMIPS_TLS_GOTTPREL        \
605    || r_type == R_MICROMIPS_TLS_TPREL_HI16      \
606    || r_type == R_MICROMIPS_TLS_TPREL_LO16)
607
608 /* Structure used to pass information to mips_elf_output_extsym.  */
609
610 struct extsym_info
611 {
612   bfd *abfd;
613   struct bfd_link_info *info;
614   struct ecoff_debug_info *debug;
615   const struct ecoff_debug_swap *swap;
616   bfd_boolean failed;
617 };
618
619 /* The names of the runtime procedure table symbols used on IRIX5.  */
620
621 static const char * const mips_elf_dynsym_rtproc_names[] =
622 {
623   "_procedure_table",
624   "_procedure_string_table",
625   "_procedure_table_size",
626   NULL
627 };
628
629 /* These structures are used to generate the .compact_rel section on
630    IRIX5.  */
631
632 typedef struct
633 {
634   unsigned long id1;            /* Always one?  */
635   unsigned long num;            /* Number of compact relocation entries.  */
636   unsigned long id2;            /* Always two?  */
637   unsigned long offset;         /* The file offset of the first relocation.  */
638   unsigned long reserved0;      /* Zero?  */
639   unsigned long reserved1;      /* Zero?  */
640 } Elf32_compact_rel;
641
642 typedef struct
643 {
644   bfd_byte id1[4];
645   bfd_byte num[4];
646   bfd_byte id2[4];
647   bfd_byte offset[4];
648   bfd_byte reserved0[4];
649   bfd_byte reserved1[4];
650 } Elf32_External_compact_rel;
651
652 typedef struct
653 {
654   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
655   unsigned int rtype : 4;       /* Relocation types. See below.  */
656   unsigned int dist2to : 8;
657   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
658   unsigned long konst;          /* KONST field. See below.  */
659   unsigned long vaddr;          /* VADDR to be relocated.  */
660 } Elf32_crinfo;
661
662 typedef struct
663 {
664   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
665   unsigned int rtype : 4;       /* Relocation types. See below.  */
666   unsigned int dist2to : 8;
667   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
668   unsigned long konst;          /* KONST field. See below.  */
669 } Elf32_crinfo2;
670
671 typedef struct
672 {
673   bfd_byte info[4];
674   bfd_byte konst[4];
675   bfd_byte vaddr[4];
676 } Elf32_External_crinfo;
677
678 typedef struct
679 {
680   bfd_byte info[4];
681   bfd_byte konst[4];
682 } Elf32_External_crinfo2;
683
684 /* These are the constants used to swap the bitfields in a crinfo.  */
685
686 #define CRINFO_CTYPE (0x1)
687 #define CRINFO_CTYPE_SH (31)
688 #define CRINFO_RTYPE (0xf)
689 #define CRINFO_RTYPE_SH (27)
690 #define CRINFO_DIST2TO (0xff)
691 #define CRINFO_DIST2TO_SH (19)
692 #define CRINFO_RELVADDR (0x7ffff)
693 #define CRINFO_RELVADDR_SH (0)
694
695 /* A compact relocation info has long (3 words) or short (2 words)
696    formats.  A short format doesn't have VADDR field and relvaddr
697    fields contains ((VADDR - vaddr of the previous entry) >> 2).  */
698 #define CRF_MIPS_LONG                   1
699 #define CRF_MIPS_SHORT                  0
700
701 /* There are 4 types of compact relocation at least. The value KONST
702    has different meaning for each type:
703
704    (type)               (konst)
705    CT_MIPS_REL32        Address in data
706    CT_MIPS_WORD         Address in word (XXX)
707    CT_MIPS_GPHI_LO      GP - vaddr
708    CT_MIPS_JMPAD        Address to jump
709    */
710
711 #define CRT_MIPS_REL32                  0xa
712 #define CRT_MIPS_WORD                   0xb
713 #define CRT_MIPS_GPHI_LO                0xc
714 #define CRT_MIPS_JMPAD                  0xd
715
716 #define mips_elf_set_cr_format(x,format)        ((x).ctype = (format))
717 #define mips_elf_set_cr_type(x,type)            ((x).rtype = (type))
718 #define mips_elf_set_cr_dist2to(x,v)            ((x).dist2to = (v))
719 #define mips_elf_set_cr_relvaddr(x,d)           ((x).relvaddr = (d)<<2)
720 \f
721 /* The structure of the runtime procedure descriptor created by the
722    loader for use by the static exception system.  */
723
724 typedef struct runtime_pdr {
725         bfd_vma adr;            /* Memory address of start of procedure.  */
726         long    regmask;        /* Save register mask.  */
727         long    regoffset;      /* Save register offset.  */
728         long    fregmask;       /* Save floating point register mask.  */
729         long    fregoffset;     /* Save floating point register offset.  */
730         long    frameoffset;    /* Frame size.  */
731         short   framereg;       /* Frame pointer register.  */
732         short   pcreg;          /* Offset or reg of return pc.  */
733         long    irpss;          /* Index into the runtime string table.  */
734         long    reserved;
735         struct exception_info *exception_info;/* Pointer to exception array.  */
736 } RPDR, *pRPDR;
737 #define cbRPDR sizeof (RPDR)
738 #define rpdNil ((pRPDR) 0)
739 \f
740 static struct mips_got_entry *mips_elf_create_local_got_entry
741   (bfd *, struct bfd_link_info *, bfd *, bfd_vma, unsigned long,
742    struct mips_elf_link_hash_entry *, int);
743 static bfd_boolean mips_elf_sort_hash_table_f
744   (struct mips_elf_link_hash_entry *, void *);
745 static bfd_vma mips_elf_high
746   (bfd_vma);
747 static bfd_boolean mips_elf_create_dynamic_relocation
748   (bfd *, struct bfd_link_info *, const Elf_Internal_Rela *,
749    struct mips_elf_link_hash_entry *, asection *, bfd_vma,
750    bfd_vma *, asection *);
751 static bfd_vma mips_elf_adjust_gp
752   (bfd *, struct mips_got_info *, bfd *);
753
754 /* This will be used when we sort the dynamic relocation records.  */
755 static bfd *reldyn_sorting_bfd;
756
757 /* True if ABFD is for CPUs with load interlocking that include
758    non-MIPS1 CPUs and R3900.  */
759 #define LOAD_INTERLOCKS_P(abfd) \
760   (   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) != E_MIPS_ARCH_1) \
761    || ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_3900))
762
763 /* True if ABFD is for CPUs that are faster if JAL is converted to BAL.
764    This should be safe for all architectures.  We enable this predicate
765    for RM9000 for now.  */
766 #define JAL_TO_BAL_P(abfd) \
767   ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_9000)
768
769 /* True if ABFD is for CPUs that are faster if JALR is converted to BAL.
770    This should be safe for all architectures.  We enable this predicate for
771    all CPUs.  */
772 #define JALR_TO_BAL_P(abfd) 1
773
774 /* True if ABFD is for CPUs that are faster if JR is converted to B.
775    This should be safe for all architectures.  We enable this predicate for
776    all CPUs.  */
777 #define JR_TO_B_P(abfd) 1
778
779 /* True if ABFD is a PIC object.  */
780 #define PIC_OBJECT_P(abfd) \
781   ((elf_elfheader (abfd)->e_flags & EF_MIPS_PIC) != 0)
782
783 /* Nonzero if ABFD is using the O32 ABI.  */
784 #define ABI_O32_P(abfd) \
785   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
786
787 /* Nonzero if ABFD is using the N32 ABI.  */
788 #define ABI_N32_P(abfd) \
789   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI2) != 0)
790
791 /* Nonzero if ABFD is using the N64 ABI.  */
792 #define ABI_64_P(abfd) \
793   (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS64)
794
795 /* Nonzero if ABFD is using NewABI conventions.  */
796 #define NEWABI_P(abfd) (ABI_N32_P (abfd) || ABI_64_P (abfd))
797
798 /* Nonzero if ABFD has microMIPS code.  */
799 #define MICROMIPS_P(abfd) \
800   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS) != 0)
801
802 /* The IRIX compatibility level we are striving for.  */
803 #define IRIX_COMPAT(abfd) \
804   (get_elf_backend_data (abfd)->elf_backend_mips_irix_compat (abfd))
805
806 /* Whether we are trying to be compatible with IRIX at all.  */
807 #define SGI_COMPAT(abfd) \
808   (IRIX_COMPAT (abfd) != ict_none)
809
810 /* The name of the options section.  */
811 #define MIPS_ELF_OPTIONS_SECTION_NAME(abfd) \
812   (NEWABI_P (abfd) ? ".MIPS.options" : ".options")
813
814 /* True if NAME is the recognized name of any SHT_MIPS_OPTIONS section.
815    Some IRIX system files do not use MIPS_ELF_OPTIONS_SECTION_NAME.  */
816 #define MIPS_ELF_OPTIONS_SECTION_NAME_P(NAME) \
817   (strcmp (NAME, ".MIPS.options") == 0 || strcmp (NAME, ".options") == 0)
818
819 /* True if NAME is the recognized name of any SHT_MIPS_ABIFLAGS section.  */
820 #define MIPS_ELF_ABIFLAGS_SECTION_NAME_P(NAME) \
821   (strcmp (NAME, ".MIPS.abiflags") == 0)
822
823 /* Whether the section is readonly.  */
824 #define MIPS_ELF_READONLY_SECTION(sec) \
825   ((sec->flags & (SEC_ALLOC | SEC_LOAD | SEC_READONLY))         \
826    == (SEC_ALLOC | SEC_LOAD | SEC_READONLY))
827
828 /* The name of the stub section.  */
829 #define MIPS_ELF_STUB_SECTION_NAME(abfd) ".MIPS.stubs"
830
831 /* The size of an external REL relocation.  */
832 #define MIPS_ELF_REL_SIZE(abfd) \
833   (get_elf_backend_data (abfd)->s->sizeof_rel)
834
835 /* The size of an external RELA relocation.  */
836 #define MIPS_ELF_RELA_SIZE(abfd) \
837   (get_elf_backend_data (abfd)->s->sizeof_rela)
838
839 /* The size of an external dynamic table entry.  */
840 #define MIPS_ELF_DYN_SIZE(abfd) \
841   (get_elf_backend_data (abfd)->s->sizeof_dyn)
842
843 /* The size of a GOT entry.  */
844 #define MIPS_ELF_GOT_SIZE(abfd) \
845   (get_elf_backend_data (abfd)->s->arch_size / 8)
846
847 /* The size of the .rld_map section. */
848 #define MIPS_ELF_RLD_MAP_SIZE(abfd) \
849   (get_elf_backend_data (abfd)->s->arch_size / 8)
850
851 /* The size of a symbol-table entry.  */
852 #define MIPS_ELF_SYM_SIZE(abfd) \
853   (get_elf_backend_data (abfd)->s->sizeof_sym)
854
855 /* The default alignment for sections, as a power of two.  */
856 #define MIPS_ELF_LOG_FILE_ALIGN(abfd)                           \
857   (get_elf_backend_data (abfd)->s->log_file_align)
858
859 /* Get word-sized data.  */
860 #define MIPS_ELF_GET_WORD(abfd, ptr) \
861   (ABI_64_P (abfd) ? bfd_get_64 (abfd, ptr) : bfd_get_32 (abfd, ptr))
862
863 /* Put out word-sized data.  */
864 #define MIPS_ELF_PUT_WORD(abfd, val, ptr)       \
865   (ABI_64_P (abfd)                              \
866    ? bfd_put_64 (abfd, val, ptr)                \
867    : bfd_put_32 (abfd, val, ptr))
868
869 /* The opcode for word-sized loads (LW or LD).  */
870 #define MIPS_ELF_LOAD_WORD(abfd) \
871   (ABI_64_P (abfd) ? 0xdc000000 : 0x8c000000)
872
873 /* Add a dynamic symbol table-entry.  */
874 #define MIPS_ELF_ADD_DYNAMIC_ENTRY(info, tag, val)      \
875   _bfd_elf_add_dynamic_entry (info, tag, val)
876
877 #define MIPS_ELF_RTYPE_TO_HOWTO(abfd, rtype, rela)                      \
878   (get_elf_backend_data (abfd)->elf_backend_mips_rtype_to_howto (rtype, rela))
879
880 /* The name of the dynamic relocation section.  */
881 #define MIPS_ELF_REL_DYN_NAME(INFO) \
882   (mips_elf_hash_table (INFO)->is_vxworks ? ".rela.dyn" : ".rel.dyn")
883
884 /* In case we're on a 32-bit machine, construct a 64-bit "-1" value
885    from smaller values.  Start with zero, widen, *then* decrement.  */
886 #define MINUS_ONE       (((bfd_vma)0) - 1)
887 #define MINUS_TWO       (((bfd_vma)0) - 2)
888
889 /* The value to write into got[1] for SVR4 targets, to identify it is
890    a GNU object.  The dynamic linker can then use got[1] to store the
891    module pointer.  */
892 #define MIPS_ELF_GNU_GOT1_MASK(abfd) \
893   ((bfd_vma) 1 << (ABI_64_P (abfd) ? 63 : 31))
894
895 /* The offset of $gp from the beginning of the .got section.  */
896 #define ELF_MIPS_GP_OFFSET(INFO) \
897   (mips_elf_hash_table (INFO)->is_vxworks ? 0x0 : 0x7ff0)
898
899 /* The maximum size of the GOT for it to be addressable using 16-bit
900    offsets from $gp.  */
901 #define MIPS_ELF_GOT_MAX_SIZE(INFO) (ELF_MIPS_GP_OFFSET (INFO) + 0x7fff)
902
903 /* Instructions which appear in a stub.  */
904 #define STUB_LW(abfd)                                                   \
905   ((ABI_64_P (abfd)                                                     \
906     ? 0xdf998010                                /* ld t9,0x8010(gp) */  \
907     : 0x8f998010))                              /* lw t9,0x8010(gp) */
908 #define STUB_MOVE(abfd)                                                 \
909    ((ABI_64_P (abfd)                                                    \
910      ? 0x03e0782d                               /* daddu t7,ra */       \
911      : 0x03e07821))                             /* addu t7,ra */
912 #define STUB_LUI(VAL) (0x3c180000 + (VAL))      /* lui t8,VAL */
913 #define STUB_JALR 0x0320f809                    /* jalr t9,ra */
914 #define STUB_ORI(VAL) (0x37180000 + (VAL))      /* ori t8,t8,VAL */
915 #define STUB_LI16U(VAL) (0x34180000 + (VAL))    /* ori t8,zero,VAL unsigned */
916 #define STUB_LI16S(abfd, VAL)                                           \
917    ((ABI_64_P (abfd)                                                    \
918     ? (0x64180000 + (VAL))      /* daddiu t8,zero,VAL sign extended */  \
919     : (0x24180000 + (VAL))))    /* addiu t8,zero,VAL sign extended */
920
921 /* Likewise for the microMIPS ASE.  */
922 #define STUB_LW_MICROMIPS(abfd)                                         \
923   (ABI_64_P (abfd)                                                      \
924    ? 0xdf3c8010                                 /* ld t9,0x8010(gp) */  \
925    : 0xff3c8010)                                /* lw t9,0x8010(gp) */
926 #define STUB_MOVE_MICROMIPS 0x0dff              /* move t7,ra */
927 #define STUB_MOVE32_MICROMIPS(abfd)                                     \
928    (ABI_64_P (abfd)                                                     \
929     ? 0x581f7950                                /* daddu t7,ra,zero */  \
930     : 0x001f7950)                               /* addu t7,ra,zero */
931 #define STUB_LUI_MICROMIPS(VAL)                                         \
932    (0x41b80000 + (VAL))                         /* lui t8,VAL */
933 #define STUB_JALR_MICROMIPS 0x45d9              /* jalr t9 */
934 #define STUB_JALR32_MICROMIPS 0x03f90f3c        /* jalr ra,t9 */
935 #define STUB_ORI_MICROMIPS(VAL)                                         \
936   (0x53180000 + (VAL))                          /* ori t8,t8,VAL */
937 #define STUB_LI16U_MICROMIPS(VAL)                                       \
938   (0x53000000 + (VAL))                          /* ori t8,zero,VAL unsigned */
939 #define STUB_LI16S_MICROMIPS(abfd, VAL)                                 \
940    (ABI_64_P (abfd)                                                     \
941     ? 0x5f000000 + (VAL)        /* daddiu t8,zero,VAL sign extended */  \
942     : 0x33000000 + (VAL))       /* addiu t8,zero,VAL sign extended */
943
944 #define MIPS_FUNCTION_STUB_NORMAL_SIZE 16
945 #define MIPS_FUNCTION_STUB_BIG_SIZE 20
946 #define MICROMIPS_FUNCTION_STUB_NORMAL_SIZE 12
947 #define MICROMIPS_FUNCTION_STUB_BIG_SIZE 16
948 #define MICROMIPS_INSN32_FUNCTION_STUB_NORMAL_SIZE 16
949 #define MICROMIPS_INSN32_FUNCTION_STUB_BIG_SIZE 20
950
951 /* The name of the dynamic interpreter.  This is put in the .interp
952    section.  */
953
954 #define ELF_DYNAMIC_INTERPRETER(abfd)           \
955    (ABI_N32_P (abfd) ? "/usr/lib32/libc.so.1"   \
956     : ABI_64_P (abfd) ? "/usr/lib64/libc.so.1"  \
957     : "/usr/lib/libc.so.1")
958
959 #ifdef BFD64
960 #define MNAME(bfd,pre,pos) \
961   (ABI_64_P (bfd) ? CONCAT4 (pre,64,_,pos) : CONCAT4 (pre,32,_,pos))
962 #define ELF_R_SYM(bfd, i)                                       \
963   (ABI_64_P (bfd) ? ELF64_R_SYM (i) : ELF32_R_SYM (i))
964 #define ELF_R_TYPE(bfd, i)                                      \
965   (ABI_64_P (bfd) ? ELF64_MIPS_R_TYPE (i) : ELF32_R_TYPE (i))
966 #define ELF_R_INFO(bfd, s, t)                                   \
967   (ABI_64_P (bfd) ? ELF64_R_INFO (s, t) : ELF32_R_INFO (s, t))
968 #else
969 #define MNAME(bfd,pre,pos) CONCAT4 (pre,32,_,pos)
970 #define ELF_R_SYM(bfd, i)                                       \
971   (ELF32_R_SYM (i))
972 #define ELF_R_TYPE(bfd, i)                                      \
973   (ELF32_R_TYPE (i))
974 #define ELF_R_INFO(bfd, s, t)                                   \
975   (ELF32_R_INFO (s, t))
976 #endif
977 \f
978   /* The mips16 compiler uses a couple of special sections to handle
979      floating point arguments.
980
981      Section names that look like .mips16.fn.FNNAME contain stubs that
982      copy floating point arguments from the fp regs to the gp regs and
983      then jump to FNNAME.  If any 32 bit function calls FNNAME, the
984      call should be redirected to the stub instead.  If no 32 bit
985      function calls FNNAME, the stub should be discarded.  We need to
986      consider any reference to the function, not just a call, because
987      if the address of the function is taken we will need the stub,
988      since the address might be passed to a 32 bit function.
989
990      Section names that look like .mips16.call.FNNAME contain stubs
991      that copy floating point arguments from the gp regs to the fp
992      regs and then jump to FNNAME.  If FNNAME is a 32 bit function,
993      then any 16 bit function that calls FNNAME should be redirected
994      to the stub instead.  If FNNAME is not a 32 bit function, the
995      stub should be discarded.
996
997      .mips16.call.fp.FNNAME sections are similar, but contain stubs
998      which call FNNAME and then copy the return value from the fp regs
999      to the gp regs.  These stubs store the return value in $18 while
1000      calling FNNAME; any function which might call one of these stubs
1001      must arrange to save $18 around the call.  (This case is not
1002      needed for 32 bit functions that call 16 bit functions, because
1003      16 bit functions always return floating point values in both
1004      $f0/$f1 and $2/$3.)
1005
1006      Note that in all cases FNNAME might be defined statically.
1007      Therefore, FNNAME is not used literally.  Instead, the relocation
1008      information will indicate which symbol the section is for.
1009
1010      We record any stubs that we find in the symbol table.  */
1011
1012 #define FN_STUB ".mips16.fn."
1013 #define CALL_STUB ".mips16.call."
1014 #define CALL_FP_STUB ".mips16.call.fp."
1015
1016 #define FN_STUB_P(name) CONST_STRNEQ (name, FN_STUB)
1017 #define CALL_STUB_P(name) CONST_STRNEQ (name, CALL_STUB)
1018 #define CALL_FP_STUB_P(name) CONST_STRNEQ (name, CALL_FP_STUB)
1019 \f
1020 /* The format of the first PLT entry in an O32 executable.  */
1021 static const bfd_vma mips_o32_exec_plt0_entry[] =
1022 {
1023   0x3c1c0000,   /* lui $28, %hi(&GOTPLT[0])                             */
1024   0x8f990000,   /* lw $25, %lo(&GOTPLT[0])($28)                         */
1025   0x279c0000,   /* addiu $28, $28, %lo(&GOTPLT[0])                      */
1026   0x031cc023,   /* subu $24, $24, $28                                   */
1027   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
1028   0x0018c082,   /* srl $24, $24, 2                                      */
1029   0x0320f809,   /* jalr $25                                             */
1030   0x2718fffe    /* subu $24, $24, 2                                     */
1031 };
1032
1033 /* The format of the first PLT entry in an N32 executable.  Different
1034    because gp ($28) is not available; we use t2 ($14) instead.  */
1035 static const bfd_vma mips_n32_exec_plt0_entry[] =
1036 {
1037   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
1038   0x8dd90000,   /* lw $25, %lo(&GOTPLT[0])($14)                         */
1039   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
1040   0x030ec023,   /* subu $24, $24, $14                                   */
1041   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
1042   0x0018c082,   /* srl $24, $24, 2                                      */
1043   0x0320f809,   /* jalr $25                                             */
1044   0x2718fffe    /* subu $24, $24, 2                                     */
1045 };
1046
1047 /* The format of the first PLT entry in an N64 executable.  Different
1048    from N32 because of the increased size of GOT entries.  */
1049 static const bfd_vma mips_n64_exec_plt0_entry[] =
1050 {
1051   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
1052   0xddd90000,   /* ld $25, %lo(&GOTPLT[0])($14)                         */
1053   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
1054   0x030ec023,   /* subu $24, $24, $14                                   */
1055   0x03e0782d,   /* move $15, $31        # 64-bit move (daddu)           */
1056   0x0018c0c2,   /* srl $24, $24, 3                                      */
1057   0x0320f809,   /* jalr $25                                             */
1058   0x2718fffe    /* subu $24, $24, 2                                     */
1059 };
1060
1061 /* The format of the microMIPS first PLT entry in an O32 executable.
1062    We rely on v0 ($2) rather than t8 ($24) to contain the address
1063    of the GOTPLT entry handled, so this stub may only be used when
1064    all the subsequent PLT entries are microMIPS code too.
1065
1066    The trailing NOP is for alignment and correct disassembly only.  */
1067 static const bfd_vma micromips_o32_exec_plt0_entry[] =
1068 {
1069   0x7980, 0x0000,       /* addiupc $3, (&GOTPLT[0]) - .                 */
1070   0xff23, 0x0000,       /* lw $25, 0($3)                                */
1071   0x0535,               /* subu $2, $2, $3                              */
1072   0x2525,               /* srl $2, $2, 2                                */
1073   0x3302, 0xfffe,       /* subu $24, $2, 2                              */
1074   0x0dff,               /* move $15, $31                                */
1075   0x45f9,               /* jalrs $25                                    */
1076   0x0f83,               /* move $28, $3                                 */
1077   0x0c00                /* nop                                          */
1078 };
1079
1080 /* The format of the microMIPS first PLT entry in an O32 executable
1081    in the insn32 mode.  */
1082 static const bfd_vma micromips_insn32_o32_exec_plt0_entry[] =
1083 {
1084   0x41bc, 0x0000,       /* lui $28, %hi(&GOTPLT[0])                     */
1085   0xff3c, 0x0000,       /* lw $25, %lo(&GOTPLT[0])($28)                 */
1086   0x339c, 0x0000,       /* addiu $28, $28, %lo(&GOTPLT[0])              */
1087   0x0398, 0xc1d0,       /* subu $24, $24, $28                           */
1088   0x001f, 0x7950,       /* move $15, $31                                */
1089   0x0318, 0x1040,       /* srl $24, $24, 2                              */
1090   0x03f9, 0x0f3c,       /* jalr $25                                     */
1091   0x3318, 0xfffe        /* subu $24, $24, 2                             */
1092 };
1093
1094 /* The format of subsequent standard PLT entries.  */
1095 static const bfd_vma mips_exec_plt_entry[] =
1096 {
1097   0x3c0f0000,   /* lui $15, %hi(.got.plt entry)                 */
1098   0x01f90000,   /* l[wd] $25, %lo(.got.plt entry)($15)          */
1099   0x25f80000,   /* addiu $24, $15, %lo(.got.plt entry)          */
1100   0x03200008    /* jr $25                                       */
1101 };
1102
1103 /* The format of subsequent MIPS16 o32 PLT entries.  We use v0 ($2)
1104    and v1 ($3) as temporaries because t8 ($24) and t9 ($25) are not
1105    directly addressable.  */
1106 static const bfd_vma mips16_o32_exec_plt_entry[] =
1107 {
1108   0xb203,               /* lw $2, 12($pc)                       */
1109   0x9a60,               /* lw $3, 0($2)                         */
1110   0x651a,               /* move $24, $2                         */
1111   0xeb00,               /* jr $3                                */
1112   0x653b,               /* move $25, $3                         */
1113   0x6500,               /* nop                                  */
1114   0x0000, 0x0000        /* .word (.got.plt entry)               */
1115 };
1116
1117 /* The format of subsequent microMIPS o32 PLT entries.  We use v0 ($2)
1118    as a temporary because t8 ($24) is not addressable with ADDIUPC.  */
1119 static const bfd_vma micromips_o32_exec_plt_entry[] =
1120 {
1121   0x7900, 0x0000,       /* addiupc $2, (.got.plt entry) - .     */
1122   0xff22, 0x0000,       /* lw $25, 0($2)                        */
1123   0x4599,               /* jr $25                               */
1124   0x0f02                /* move $24, $2                         */
1125 };
1126
1127 /* The format of subsequent microMIPS o32 PLT entries in the insn32 mode.  */
1128 static const bfd_vma micromips_insn32_o32_exec_plt_entry[] =
1129 {
1130   0x41af, 0x0000,       /* lui $15, %hi(.got.plt entry)         */
1131   0xff2f, 0x0000,       /* lw $25, %lo(.got.plt entry)($15)     */
1132   0x0019, 0x0f3c,       /* jr $25                               */
1133   0x330f, 0x0000        /* addiu $24, $15, %lo(.got.plt entry)  */
1134 };
1135
1136 /* The format of the first PLT entry in a VxWorks executable.  */
1137 static const bfd_vma mips_vxworks_exec_plt0_entry[] =
1138 {
1139   0x3c190000,   /* lui t9, %hi(_GLOBAL_OFFSET_TABLE_)           */
1140   0x27390000,   /* addiu t9, t9, %lo(_GLOBAL_OFFSET_TABLE_)     */
1141   0x8f390008,   /* lw t9, 8(t9)                                 */
1142   0x00000000,   /* nop                                          */
1143   0x03200008,   /* jr t9                                        */
1144   0x00000000    /* nop                                          */
1145 };
1146
1147 /* The format of subsequent PLT entries.  */
1148 static const bfd_vma mips_vxworks_exec_plt_entry[] =
1149 {
1150   0x10000000,   /* b .PLT_resolver                      */
1151   0x24180000,   /* li t8, <pltindex>                    */
1152   0x3c190000,   /* lui t9, %hi(<.got.plt slot>)         */
1153   0x27390000,   /* addiu t9, t9, %lo(<.got.plt slot>)   */
1154   0x8f390000,   /* lw t9, 0(t9)                         */
1155   0x00000000,   /* nop                                  */
1156   0x03200008,   /* jr t9                                */
1157   0x00000000    /* nop                                  */
1158 };
1159
1160 /* The format of the first PLT entry in a VxWorks shared object.  */
1161 static const bfd_vma mips_vxworks_shared_plt0_entry[] =
1162 {
1163   0x8f990008,   /* lw t9, 8(gp)         */
1164   0x00000000,   /* nop                  */
1165   0x03200008,   /* jr t9                */
1166   0x00000000,   /* nop                  */
1167   0x00000000,   /* nop                  */
1168   0x00000000    /* nop                  */
1169 };
1170
1171 /* The format of subsequent PLT entries.  */
1172 static const bfd_vma mips_vxworks_shared_plt_entry[] =
1173 {
1174   0x10000000,   /* b .PLT_resolver      */
1175   0x24180000    /* li t8, <pltindex>    */
1176 };
1177 \f
1178 /* microMIPS 32-bit opcode helper installer.  */
1179
1180 static void
1181 bfd_put_micromips_32 (const bfd *abfd, bfd_vma opcode, bfd_byte *ptr)
1182 {
1183   bfd_put_16 (abfd, (opcode >> 16) & 0xffff, ptr);
1184   bfd_put_16 (abfd,  opcode        & 0xffff, ptr + 2);
1185 }
1186
1187 /* microMIPS 32-bit opcode helper retriever.  */
1188
1189 static bfd_vma
1190 bfd_get_micromips_32 (const bfd *abfd, const bfd_byte *ptr)
1191 {
1192   return (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
1193 }
1194 \f
1195 /* Look up an entry in a MIPS ELF linker hash table.  */
1196
1197 #define mips_elf_link_hash_lookup(table, string, create, copy, follow)  \
1198   ((struct mips_elf_link_hash_entry *)                                  \
1199    elf_link_hash_lookup (&(table)->root, (string), (create),            \
1200                          (copy), (follow)))
1201
1202 /* Traverse a MIPS ELF linker hash table.  */
1203
1204 #define mips_elf_link_hash_traverse(table, func, info)                  \
1205   (elf_link_hash_traverse                                               \
1206    (&(table)->root,                                                     \
1207     (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func),    \
1208     (info)))
1209
1210 /* Find the base offsets for thread-local storage in this object,
1211    for GD/LD and IE/LE respectively.  */
1212
1213 #define TP_OFFSET 0x7000
1214 #define DTP_OFFSET 0x8000
1215
1216 static bfd_vma
1217 dtprel_base (struct bfd_link_info *info)
1218 {
1219   /* If tls_sec is NULL, we should have signalled an error already.  */
1220   if (elf_hash_table (info)->tls_sec == NULL)
1221     return 0;
1222   return elf_hash_table (info)->tls_sec->vma + DTP_OFFSET;
1223 }
1224
1225 static bfd_vma
1226 tprel_base (struct bfd_link_info *info)
1227 {
1228   /* If tls_sec is NULL, we should have signalled an error already.  */
1229   if (elf_hash_table (info)->tls_sec == NULL)
1230     return 0;
1231   return elf_hash_table (info)->tls_sec->vma + TP_OFFSET;
1232 }
1233
1234 /* Create an entry in a MIPS ELF linker hash table.  */
1235
1236 static struct bfd_hash_entry *
1237 mips_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
1238                             struct bfd_hash_table *table, const char *string)
1239 {
1240   struct mips_elf_link_hash_entry *ret =
1241     (struct mips_elf_link_hash_entry *) entry;
1242
1243   /* Allocate the structure if it has not already been allocated by a
1244      subclass.  */
1245   if (ret == NULL)
1246     ret = bfd_hash_allocate (table, sizeof (struct mips_elf_link_hash_entry));
1247   if (ret == NULL)
1248     return (struct bfd_hash_entry *) ret;
1249
1250   /* Call the allocation method of the superclass.  */
1251   ret = ((struct mips_elf_link_hash_entry *)
1252          _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret,
1253                                      table, string));
1254   if (ret != NULL)
1255     {
1256       /* Set local fields.  */
1257       memset (&ret->esym, 0, sizeof (EXTR));
1258       /* We use -2 as a marker to indicate that the information has
1259          not been set.  -1 means there is no associated ifd.  */
1260       ret->esym.ifd = -2;
1261       ret->la25_stub = 0;
1262       ret->possibly_dynamic_relocs = 0;
1263       ret->fn_stub = NULL;
1264       ret->call_stub = NULL;
1265       ret->call_fp_stub = NULL;
1266       ret->global_got_area = GGA_NONE;
1267       ret->got_only_for_calls = TRUE;
1268       ret->readonly_reloc = FALSE;
1269       ret->has_static_relocs = FALSE;
1270       ret->no_fn_stub = FALSE;
1271       ret->need_fn_stub = FALSE;
1272       ret->has_nonpic_branches = FALSE;
1273       ret->needs_lazy_stub = FALSE;
1274       ret->use_plt_entry = FALSE;
1275     }
1276
1277   return (struct bfd_hash_entry *) ret;
1278 }
1279
1280 /* Allocate MIPS ELF private object data.  */
1281
1282 bfd_boolean
1283 _bfd_mips_elf_mkobject (bfd *abfd)
1284 {
1285   return bfd_elf_allocate_object (abfd, sizeof (struct mips_elf_obj_tdata),
1286                                   MIPS_ELF_DATA);
1287 }
1288
1289 bfd_boolean
1290 _bfd_mips_elf_new_section_hook (bfd *abfd, asection *sec)
1291 {
1292   if (!sec->used_by_bfd)
1293     {
1294       struct _mips_elf_section_data *sdata;
1295       bfd_size_type amt = sizeof (*sdata);
1296
1297       sdata = bfd_zalloc (abfd, amt);
1298       if (sdata == NULL)
1299         return FALSE;
1300       sec->used_by_bfd = sdata;
1301     }
1302
1303   return _bfd_elf_new_section_hook (abfd, sec);
1304 }
1305 \f
1306 /* Read ECOFF debugging information from a .mdebug section into a
1307    ecoff_debug_info structure.  */
1308
1309 bfd_boolean
1310 _bfd_mips_elf_read_ecoff_info (bfd *abfd, asection *section,
1311                                struct ecoff_debug_info *debug)
1312 {
1313   HDRR *symhdr;
1314   const struct ecoff_debug_swap *swap;
1315   char *ext_hdr;
1316
1317   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1318   memset (debug, 0, sizeof (*debug));
1319
1320   ext_hdr = bfd_malloc (swap->external_hdr_size);
1321   if (ext_hdr == NULL && swap->external_hdr_size != 0)
1322     goto error_return;
1323
1324   if (! bfd_get_section_contents (abfd, section, ext_hdr, 0,
1325                                   swap->external_hdr_size))
1326     goto error_return;
1327
1328   symhdr = &debug->symbolic_header;
1329   (*swap->swap_hdr_in) (abfd, ext_hdr, symhdr);
1330
1331   /* The symbolic header contains absolute file offsets and sizes to
1332      read.  */
1333 #define READ(ptr, offset, count, size, type)                            \
1334   if (symhdr->count == 0)                                               \
1335     debug->ptr = NULL;                                                  \
1336   else                                                                  \
1337     {                                                                   \
1338       bfd_size_type amt = (bfd_size_type) size * symhdr->count;         \
1339       debug->ptr = bfd_malloc (amt);                                    \
1340       if (debug->ptr == NULL)                                           \
1341         goto error_return;                                              \
1342       if (bfd_seek (abfd, symhdr->offset, SEEK_SET) != 0                \
1343           || bfd_bread (debug->ptr, amt, abfd) != amt)                  \
1344         goto error_return;                                              \
1345     }
1346
1347   READ (line, cbLineOffset, cbLine, sizeof (unsigned char), unsigned char *);
1348   READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *);
1349   READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *);
1350   READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *);
1351   READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *);
1352   READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext),
1353         union aux_ext *);
1354   READ (ss, cbSsOffset, issMax, sizeof (char), char *);
1355   READ (ssext, cbSsExtOffset, issExtMax, sizeof (char), char *);
1356   READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *);
1357   READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *);
1358   READ (external_ext, cbExtOffset, iextMax, swap->external_ext_size, void *);
1359 #undef READ
1360
1361   debug->fdr = NULL;
1362
1363   return TRUE;
1364
1365  error_return:
1366   if (ext_hdr != NULL)
1367     free (ext_hdr);
1368   if (debug->line != NULL)
1369     free (debug->line);
1370   if (debug->external_dnr != NULL)
1371     free (debug->external_dnr);
1372   if (debug->external_pdr != NULL)
1373     free (debug->external_pdr);
1374   if (debug->external_sym != NULL)
1375     free (debug->external_sym);
1376   if (debug->external_opt != NULL)
1377     free (debug->external_opt);
1378   if (debug->external_aux != NULL)
1379     free (debug->external_aux);
1380   if (debug->ss != NULL)
1381     free (debug->ss);
1382   if (debug->ssext != NULL)
1383     free (debug->ssext);
1384   if (debug->external_fdr != NULL)
1385     free (debug->external_fdr);
1386   if (debug->external_rfd != NULL)
1387     free (debug->external_rfd);
1388   if (debug->external_ext != NULL)
1389     free (debug->external_ext);
1390   return FALSE;
1391 }
1392 \f
1393 /* Swap RPDR (runtime procedure table entry) for output.  */
1394
1395 static void
1396 ecoff_swap_rpdr_out (bfd *abfd, const RPDR *in, struct rpdr_ext *ex)
1397 {
1398   H_PUT_S32 (abfd, in->adr, ex->p_adr);
1399   H_PUT_32 (abfd, in->regmask, ex->p_regmask);
1400   H_PUT_32 (abfd, in->regoffset, ex->p_regoffset);
1401   H_PUT_32 (abfd, in->fregmask, ex->p_fregmask);
1402   H_PUT_32 (abfd, in->fregoffset, ex->p_fregoffset);
1403   H_PUT_32 (abfd, in->frameoffset, ex->p_frameoffset);
1404
1405   H_PUT_16 (abfd, in->framereg, ex->p_framereg);
1406   H_PUT_16 (abfd, in->pcreg, ex->p_pcreg);
1407
1408   H_PUT_32 (abfd, in->irpss, ex->p_irpss);
1409 }
1410
1411 /* Create a runtime procedure table from the .mdebug section.  */
1412
1413 static bfd_boolean
1414 mips_elf_create_procedure_table (void *handle, bfd *abfd,
1415                                  struct bfd_link_info *info, asection *s,
1416                                  struct ecoff_debug_info *debug)
1417 {
1418   const struct ecoff_debug_swap *swap;
1419   HDRR *hdr = &debug->symbolic_header;
1420   RPDR *rpdr, *rp;
1421   struct rpdr_ext *erp;
1422   void *rtproc;
1423   struct pdr_ext *epdr;
1424   struct sym_ext *esym;
1425   char *ss, **sv;
1426   char *str;
1427   bfd_size_type size;
1428   bfd_size_type count;
1429   unsigned long sindex;
1430   unsigned long i;
1431   PDR pdr;
1432   SYMR sym;
1433   const char *no_name_func = _("static procedure (no name)");
1434
1435   epdr = NULL;
1436   rpdr = NULL;
1437   esym = NULL;
1438   ss = NULL;
1439   sv = NULL;
1440
1441   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1442
1443   sindex = strlen (no_name_func) + 1;
1444   count = hdr->ipdMax;
1445   if (count > 0)
1446     {
1447       size = swap->external_pdr_size;
1448
1449       epdr = bfd_malloc (size * count);
1450       if (epdr == NULL)
1451         goto error_return;
1452
1453       if (! _bfd_ecoff_get_accumulated_pdr (handle, (bfd_byte *) epdr))
1454         goto error_return;
1455
1456       size = sizeof (RPDR);
1457       rp = rpdr = bfd_malloc (size * count);
1458       if (rpdr == NULL)
1459         goto error_return;
1460
1461       size = sizeof (char *);
1462       sv = bfd_malloc (size * count);
1463       if (sv == NULL)
1464         goto error_return;
1465
1466       count = hdr->isymMax;
1467       size = swap->external_sym_size;
1468       esym = bfd_malloc (size * count);
1469       if (esym == NULL)
1470         goto error_return;
1471
1472       if (! _bfd_ecoff_get_accumulated_sym (handle, (bfd_byte *) esym))
1473         goto error_return;
1474
1475       count = hdr->issMax;
1476       ss = bfd_malloc (count);
1477       if (ss == NULL)
1478         goto error_return;
1479       if (! _bfd_ecoff_get_accumulated_ss (handle, (bfd_byte *) ss))
1480         goto error_return;
1481
1482       count = hdr->ipdMax;
1483       for (i = 0; i < (unsigned long) count; i++, rp++)
1484         {
1485           (*swap->swap_pdr_in) (abfd, epdr + i, &pdr);
1486           (*swap->swap_sym_in) (abfd, &esym[pdr.isym], &sym);
1487           rp->adr = sym.value;
1488           rp->regmask = pdr.regmask;
1489           rp->regoffset = pdr.regoffset;
1490           rp->fregmask = pdr.fregmask;
1491           rp->fregoffset = pdr.fregoffset;
1492           rp->frameoffset = pdr.frameoffset;
1493           rp->framereg = pdr.framereg;
1494           rp->pcreg = pdr.pcreg;
1495           rp->irpss = sindex;
1496           sv[i] = ss + sym.iss;
1497           sindex += strlen (sv[i]) + 1;
1498         }
1499     }
1500
1501   size = sizeof (struct rpdr_ext) * (count + 2) + sindex;
1502   size = BFD_ALIGN (size, 16);
1503   rtproc = bfd_alloc (abfd, size);
1504   if (rtproc == NULL)
1505     {
1506       mips_elf_hash_table (info)->procedure_count = 0;
1507       goto error_return;
1508     }
1509
1510   mips_elf_hash_table (info)->procedure_count = count + 2;
1511
1512   erp = rtproc;
1513   memset (erp, 0, sizeof (struct rpdr_ext));
1514   erp++;
1515   str = (char *) rtproc + sizeof (struct rpdr_ext) * (count + 2);
1516   strcpy (str, no_name_func);
1517   str += strlen (no_name_func) + 1;
1518   for (i = 0; i < count; i++)
1519     {
1520       ecoff_swap_rpdr_out (abfd, rpdr + i, erp + i);
1521       strcpy (str, sv[i]);
1522       str += strlen (sv[i]) + 1;
1523     }
1524   H_PUT_S32 (abfd, -1, (erp + count)->p_adr);
1525
1526   /* Set the size and contents of .rtproc section.  */
1527   s->size = size;
1528   s->contents = rtproc;
1529
1530   /* Skip this section later on (I don't think this currently
1531      matters, but someday it might).  */
1532   s->map_head.link_order = NULL;
1533
1534   if (epdr != NULL)
1535     free (epdr);
1536   if (rpdr != NULL)
1537     free (rpdr);
1538   if (esym != NULL)
1539     free (esym);
1540   if (ss != NULL)
1541     free (ss);
1542   if (sv != NULL)
1543     free (sv);
1544
1545   return TRUE;
1546
1547  error_return:
1548   if (epdr != NULL)
1549     free (epdr);
1550   if (rpdr != NULL)
1551     free (rpdr);
1552   if (esym != NULL)
1553     free (esym);
1554   if (ss != NULL)
1555     free (ss);
1556   if (sv != NULL)
1557     free (sv);
1558   return FALSE;
1559 }
1560 \f
1561 /* We're going to create a stub for H.  Create a symbol for the stub's
1562    value and size, to help make the disassembly easier to read.  */
1563
1564 static bfd_boolean
1565 mips_elf_create_stub_symbol (struct bfd_link_info *info,
1566                              struct mips_elf_link_hash_entry *h,
1567                              const char *prefix, asection *s, bfd_vma value,
1568                              bfd_vma size)
1569 {
1570   struct bfd_link_hash_entry *bh;
1571   struct elf_link_hash_entry *elfh;
1572   const char *name;
1573
1574   if (ELF_ST_IS_MICROMIPS (h->root.other))
1575     value |= 1;
1576
1577   /* Create a new symbol.  */
1578   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1579   bh = NULL;
1580   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1581                                          BSF_LOCAL, s, value, NULL,
1582                                          TRUE, FALSE, &bh))
1583     return FALSE;
1584
1585   /* Make it a local function.  */
1586   elfh = (struct elf_link_hash_entry *) bh;
1587   elfh->type = ELF_ST_INFO (STB_LOCAL, STT_FUNC);
1588   elfh->size = size;
1589   elfh->forced_local = 1;
1590   return TRUE;
1591 }
1592
1593 /* We're about to redefine H.  Create a symbol to represent H's
1594    current value and size, to help make the disassembly easier
1595    to read.  */
1596
1597 static bfd_boolean
1598 mips_elf_create_shadow_symbol (struct bfd_link_info *info,
1599                                struct mips_elf_link_hash_entry *h,
1600                                const char *prefix)
1601 {
1602   struct bfd_link_hash_entry *bh;
1603   struct elf_link_hash_entry *elfh;
1604   const char *name;
1605   asection *s;
1606   bfd_vma value;
1607
1608   /* Read the symbol's value.  */
1609   BFD_ASSERT (h->root.root.type == bfd_link_hash_defined
1610               || h->root.root.type == bfd_link_hash_defweak);
1611   s = h->root.root.u.def.section;
1612   value = h->root.root.u.def.value;
1613
1614   /* Create a new symbol.  */
1615   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1616   bh = NULL;
1617   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1618                                          BSF_LOCAL, s, value, NULL,
1619                                          TRUE, FALSE, &bh))
1620     return FALSE;
1621
1622   /* Make it local and copy the other attributes from H.  */
1623   elfh = (struct elf_link_hash_entry *) bh;
1624   elfh->type = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (h->root.type));
1625   elfh->other = h->root.other;
1626   elfh->size = h->root.size;
1627   elfh->forced_local = 1;
1628   return TRUE;
1629 }
1630
1631 /* Return TRUE if relocations in SECTION can refer directly to a MIPS16
1632    function rather than to a hard-float stub.  */
1633
1634 static bfd_boolean
1635 section_allows_mips16_refs_p (asection *section)
1636 {
1637   const char *name;
1638
1639   name = bfd_get_section_name (section->owner, section);
1640   return (FN_STUB_P (name)
1641           || CALL_STUB_P (name)
1642           || CALL_FP_STUB_P (name)
1643           || strcmp (name, ".pdr") == 0);
1644 }
1645
1646 /* [RELOCS, RELEND) are the relocations against SEC, which is a MIPS16
1647    stub section of some kind.  Return the R_SYMNDX of the target
1648    function, or 0 if we can't decide which function that is.  */
1649
1650 static unsigned long
1651 mips16_stub_symndx (const struct elf_backend_data *bed,
1652                     asection *sec ATTRIBUTE_UNUSED,
1653                     const Elf_Internal_Rela *relocs,
1654                     const Elf_Internal_Rela *relend)
1655 {
1656   int int_rels_per_ext_rel = bed->s->int_rels_per_ext_rel;
1657   const Elf_Internal_Rela *rel;
1658
1659   /* Trust the first R_MIPS_NONE relocation, if any, but not a subsequent
1660      one in a compound relocation.  */
1661   for (rel = relocs; rel < relend; rel += int_rels_per_ext_rel)
1662     if (ELF_R_TYPE (sec->owner, rel->r_info) == R_MIPS_NONE)
1663       return ELF_R_SYM (sec->owner, rel->r_info);
1664
1665   /* Otherwise trust the first relocation, whatever its kind.  This is
1666      the traditional behavior.  */
1667   if (relocs < relend)
1668     return ELF_R_SYM (sec->owner, relocs->r_info);
1669
1670   return 0;
1671 }
1672
1673 /* Check the mips16 stubs for a particular symbol, and see if we can
1674    discard them.  */
1675
1676 static void
1677 mips_elf_check_mips16_stubs (struct bfd_link_info *info,
1678                              struct mips_elf_link_hash_entry *h)
1679 {
1680   /* Dynamic symbols must use the standard call interface, in case other
1681      objects try to call them.  */
1682   if (h->fn_stub != NULL
1683       && h->root.dynindx != -1)
1684     {
1685       mips_elf_create_shadow_symbol (info, h, ".mips16.");
1686       h->need_fn_stub = TRUE;
1687     }
1688
1689   if (h->fn_stub != NULL
1690       && ! h->need_fn_stub)
1691     {
1692       /* We don't need the fn_stub; the only references to this symbol
1693          are 16 bit calls.  Clobber the size to 0 to prevent it from
1694          being included in the link.  */
1695       h->fn_stub->size = 0;
1696       h->fn_stub->flags &= ~SEC_RELOC;
1697       h->fn_stub->reloc_count = 0;
1698       h->fn_stub->flags |= SEC_EXCLUDE;
1699     }
1700
1701   if (h->call_stub != NULL
1702       && ELF_ST_IS_MIPS16 (h->root.other))
1703     {
1704       /* We don't need the call_stub; this is a 16 bit function, so
1705          calls from other 16 bit functions are OK.  Clobber the size
1706          to 0 to prevent it from being included in the link.  */
1707       h->call_stub->size = 0;
1708       h->call_stub->flags &= ~SEC_RELOC;
1709       h->call_stub->reloc_count = 0;
1710       h->call_stub->flags |= SEC_EXCLUDE;
1711     }
1712
1713   if (h->call_fp_stub != NULL
1714       && ELF_ST_IS_MIPS16 (h->root.other))
1715     {
1716       /* We don't need the call_stub; this is a 16 bit function, so
1717          calls from other 16 bit functions are OK.  Clobber the size
1718          to 0 to prevent it from being included in the link.  */
1719       h->call_fp_stub->size = 0;
1720       h->call_fp_stub->flags &= ~SEC_RELOC;
1721       h->call_fp_stub->reloc_count = 0;
1722       h->call_fp_stub->flags |= SEC_EXCLUDE;
1723     }
1724 }
1725
1726 /* Hashtable callbacks for mips_elf_la25_stubs.  */
1727
1728 static hashval_t
1729 mips_elf_la25_stub_hash (const void *entry_)
1730 {
1731   const struct mips_elf_la25_stub *entry;
1732
1733   entry = (struct mips_elf_la25_stub *) entry_;
1734   return entry->h->root.root.u.def.section->id
1735     + entry->h->root.root.u.def.value;
1736 }
1737
1738 static int
1739 mips_elf_la25_stub_eq (const void *entry1_, const void *entry2_)
1740 {
1741   const struct mips_elf_la25_stub *entry1, *entry2;
1742
1743   entry1 = (struct mips_elf_la25_stub *) entry1_;
1744   entry2 = (struct mips_elf_la25_stub *) entry2_;
1745   return ((entry1->h->root.root.u.def.section
1746            == entry2->h->root.root.u.def.section)
1747           && (entry1->h->root.root.u.def.value
1748               == entry2->h->root.root.u.def.value));
1749 }
1750
1751 /* Called by the linker to set up the la25 stub-creation code.  FN is
1752    the linker's implementation of add_stub_function.  Return true on
1753    success.  */
1754
1755 bfd_boolean
1756 _bfd_mips_elf_init_stubs (struct bfd_link_info *info,
1757                           asection *(*fn) (const char *, asection *,
1758                                            asection *))
1759 {
1760   struct mips_elf_link_hash_table *htab;
1761
1762   htab = mips_elf_hash_table (info);
1763   if (htab == NULL)
1764     return FALSE;
1765
1766   htab->add_stub_section = fn;
1767   htab->la25_stubs = htab_try_create (1, mips_elf_la25_stub_hash,
1768                                       mips_elf_la25_stub_eq, NULL);
1769   if (htab->la25_stubs == NULL)
1770     return FALSE;
1771
1772   return TRUE;
1773 }
1774
1775 /* Return true if H is a locally-defined PIC function, in the sense
1776    that it or its fn_stub might need $25 to be valid on entry.
1777    Note that MIPS16 functions set up $gp using PC-relative instructions,
1778    so they themselves never need $25 to be valid.  Only non-MIPS16
1779    entry points are of interest here.  */
1780
1781 static bfd_boolean
1782 mips_elf_local_pic_function_p (struct mips_elf_link_hash_entry *h)
1783 {
1784   return ((h->root.root.type == bfd_link_hash_defined
1785            || h->root.root.type == bfd_link_hash_defweak)
1786           && h->root.def_regular
1787           && !bfd_is_abs_section (h->root.root.u.def.section)
1788           && (!ELF_ST_IS_MIPS16 (h->root.other)
1789               || (h->fn_stub && h->need_fn_stub))
1790           && (PIC_OBJECT_P (h->root.root.u.def.section->owner)
1791               || ELF_ST_IS_MIPS_PIC (h->root.other)));
1792 }
1793
1794 /* Set *SEC to the input section that contains the target of STUB.
1795    Return the offset of the target from the start of that section.  */
1796
1797 static bfd_vma
1798 mips_elf_get_la25_target (struct mips_elf_la25_stub *stub,
1799                           asection **sec)
1800 {
1801   if (ELF_ST_IS_MIPS16 (stub->h->root.other))
1802     {
1803       BFD_ASSERT (stub->h->need_fn_stub);
1804       *sec = stub->h->fn_stub;
1805       return 0;
1806     }
1807   else
1808     {
1809       *sec = stub->h->root.root.u.def.section;
1810       return stub->h->root.root.u.def.value;
1811     }
1812 }
1813
1814 /* STUB describes an la25 stub that we have decided to implement
1815    by inserting an LUI/ADDIU pair before the target function.
1816    Create the section and redirect the function symbol to it.  */
1817
1818 static bfd_boolean
1819 mips_elf_add_la25_intro (struct mips_elf_la25_stub *stub,
1820                          struct bfd_link_info *info)
1821 {
1822   struct mips_elf_link_hash_table *htab;
1823   char *name;
1824   asection *s, *input_section;
1825   unsigned int align;
1826
1827   htab = mips_elf_hash_table (info);
1828   if (htab == NULL)
1829     return FALSE;
1830
1831   /* Create a unique name for the new section.  */
1832   name = bfd_malloc (11 + sizeof (".text.stub."));
1833   if (name == NULL)
1834     return FALSE;
1835   sprintf (name, ".text.stub.%d", (int) htab_elements (htab->la25_stubs));
1836
1837   /* Create the section.  */
1838   mips_elf_get_la25_target (stub, &input_section);
1839   s = htab->add_stub_section (name, input_section,
1840                               input_section->output_section);
1841   if (s == NULL)
1842     return FALSE;
1843
1844   /* Make sure that any padding goes before the stub.  */
1845   align = input_section->alignment_power;
1846   if (!bfd_set_section_alignment (s->owner, s, align))
1847     return FALSE;
1848   if (align > 3)
1849     s->size = (1 << align) - 8;
1850
1851   /* Create a symbol for the stub.  */
1852   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 8);
1853   stub->stub_section = s;
1854   stub->offset = s->size;
1855
1856   /* Allocate room for it.  */
1857   s->size += 8;
1858   return TRUE;
1859 }
1860
1861 /* STUB describes an la25 stub that we have decided to implement
1862    with a separate trampoline.  Allocate room for it and redirect
1863    the function symbol to it.  */
1864
1865 static bfd_boolean
1866 mips_elf_add_la25_trampoline (struct mips_elf_la25_stub *stub,
1867                               struct bfd_link_info *info)
1868 {
1869   struct mips_elf_link_hash_table *htab;
1870   asection *s;
1871
1872   htab = mips_elf_hash_table (info);
1873   if (htab == NULL)
1874     return FALSE;
1875
1876   /* Create a trampoline section, if we haven't already.  */
1877   s = htab->strampoline;
1878   if (s == NULL)
1879     {
1880       asection *input_section = stub->h->root.root.u.def.section;
1881       s = htab->add_stub_section (".text", NULL,
1882                                   input_section->output_section);
1883       if (s == NULL || !bfd_set_section_alignment (s->owner, s, 4))
1884         return FALSE;
1885       htab->strampoline = s;
1886     }
1887
1888   /* Create a symbol for the stub.  */
1889   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 16);
1890   stub->stub_section = s;
1891   stub->offset = s->size;
1892
1893   /* Allocate room for it.  */
1894   s->size += 16;
1895   return TRUE;
1896 }
1897
1898 /* H describes a symbol that needs an la25 stub.  Make sure that an
1899    appropriate stub exists and point H at it.  */
1900
1901 static bfd_boolean
1902 mips_elf_add_la25_stub (struct bfd_link_info *info,
1903                         struct mips_elf_link_hash_entry *h)
1904 {
1905   struct mips_elf_link_hash_table *htab;
1906   struct mips_elf_la25_stub search, *stub;
1907   bfd_boolean use_trampoline_p;
1908   asection *s;
1909   bfd_vma value;
1910   void **slot;
1911
1912   /* Describe the stub we want.  */
1913   search.stub_section = NULL;
1914   search.offset = 0;
1915   search.h = h;
1916
1917   /* See if we've already created an equivalent stub.  */
1918   htab = mips_elf_hash_table (info);
1919   if (htab == NULL)
1920     return FALSE;
1921
1922   slot = htab_find_slot (htab->la25_stubs, &search, INSERT);
1923   if (slot == NULL)
1924     return FALSE;
1925
1926   stub = (struct mips_elf_la25_stub *) *slot;
1927   if (stub != NULL)
1928     {
1929       /* We can reuse the existing stub.  */
1930       h->la25_stub = stub;
1931       return TRUE;
1932     }
1933
1934   /* Create a permanent copy of ENTRY and add it to the hash table.  */
1935   stub = bfd_malloc (sizeof (search));
1936   if (stub == NULL)
1937     return FALSE;
1938   *stub = search;
1939   *slot = stub;
1940
1941   /* Prefer to use LUI/ADDIU stubs if the function is at the beginning
1942      of the section and if we would need no more than 2 nops.  */
1943   value = mips_elf_get_la25_target (stub, &s);
1944   use_trampoline_p = (value != 0 || s->alignment_power > 4);
1945
1946   h->la25_stub = stub;
1947   return (use_trampoline_p
1948           ? mips_elf_add_la25_trampoline (stub, info)
1949           : mips_elf_add_la25_intro (stub, info));
1950 }
1951
1952 /* A mips_elf_link_hash_traverse callback that is called before sizing
1953    sections.  DATA points to a mips_htab_traverse_info structure.  */
1954
1955 static bfd_boolean
1956 mips_elf_check_symbols (struct mips_elf_link_hash_entry *h, void *data)
1957 {
1958   struct mips_htab_traverse_info *hti;
1959
1960   hti = (struct mips_htab_traverse_info *) data;
1961   if (!hti->info->relocatable)
1962     mips_elf_check_mips16_stubs (hti->info, h);
1963
1964   if (mips_elf_local_pic_function_p (h))
1965     {
1966       /* PR 12845: If H is in a section that has been garbage
1967          collected it will have its output section set to *ABS*.  */
1968       if (bfd_is_abs_section (h->root.root.u.def.section->output_section))
1969         return TRUE;
1970
1971       /* H is a function that might need $25 to be valid on entry.
1972          If we're creating a non-PIC relocatable object, mark H as
1973          being PIC.  If we're creating a non-relocatable object with
1974          non-PIC branches and jumps to H, make sure that H has an la25
1975          stub.  */
1976       if (hti->info->relocatable)
1977         {
1978           if (!PIC_OBJECT_P (hti->output_bfd))
1979             h->root.other = ELF_ST_SET_MIPS_PIC (h->root.other);
1980         }
1981       else if (h->has_nonpic_branches && !mips_elf_add_la25_stub (hti->info, h))
1982         {
1983           hti->error = TRUE;
1984           return FALSE;
1985         }
1986     }
1987   return TRUE;
1988 }
1989 \f
1990 /* R_MIPS16_26 is used for the mips16 jal and jalx instructions.
1991    Most mips16 instructions are 16 bits, but these instructions
1992    are 32 bits.
1993
1994    The format of these instructions is:
1995
1996    +--------------+--------------------------------+
1997    |     JALX     | X|   Imm 20:16  |   Imm 25:21  |
1998    +--------------+--------------------------------+
1999    |                Immediate  15:0                |
2000    +-----------------------------------------------+
2001
2002    JALX is the 5-bit value 00011.  X is 0 for jal, 1 for jalx.
2003    Note that the immediate value in the first word is swapped.
2004
2005    When producing a relocatable object file, R_MIPS16_26 is
2006    handled mostly like R_MIPS_26.  In particular, the addend is
2007    stored as a straight 26-bit value in a 32-bit instruction.
2008    (gas makes life simpler for itself by never adjusting a
2009    R_MIPS16_26 reloc to be against a section, so the addend is
2010    always zero).  However, the 32 bit instruction is stored as 2
2011    16-bit values, rather than a single 32-bit value.  In a
2012    big-endian file, the result is the same; in a little-endian
2013    file, the two 16-bit halves of the 32 bit value are swapped.
2014    This is so that a disassembler can recognize the jal
2015    instruction.
2016
2017    When doing a final link, R_MIPS16_26 is treated as a 32 bit
2018    instruction stored as two 16-bit values.  The addend A is the
2019    contents of the targ26 field.  The calculation is the same as
2020    R_MIPS_26.  When storing the calculated value, reorder the
2021    immediate value as shown above, and don't forget to store the
2022    value as two 16-bit values.
2023
2024    To put it in MIPS ABI terms, the relocation field is T-targ26-16,
2025    defined as
2026
2027    big-endian:
2028    +--------+----------------------+
2029    |        |                      |
2030    |        |    targ26-16         |
2031    |31    26|25                   0|
2032    +--------+----------------------+
2033
2034    little-endian:
2035    +----------+------+-------------+
2036    |          |      |             |
2037    |  sub1    |      |     sub2    |
2038    |0        9|10  15|16         31|
2039    +----------+--------------------+
2040    where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is
2041    ((sub1 << 16) | sub2)).
2042
2043    When producing a relocatable object file, the calculation is
2044    (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
2045    When producing a fully linked file, the calculation is
2046    let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
2047    ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff)
2048
2049    The table below lists the other MIPS16 instruction relocations.
2050    Each one is calculated in the same way as the non-MIPS16 relocation
2051    given on the right, but using the extended MIPS16 layout of 16-bit
2052    immediate fields:
2053
2054         R_MIPS16_GPREL          R_MIPS_GPREL16
2055         R_MIPS16_GOT16          R_MIPS_GOT16
2056         R_MIPS16_CALL16         R_MIPS_CALL16
2057         R_MIPS16_HI16           R_MIPS_HI16
2058         R_MIPS16_LO16           R_MIPS_LO16
2059
2060    A typical instruction will have a format like this:
2061
2062    +--------------+--------------------------------+
2063    |    EXTEND    |     Imm 10:5    |   Imm 15:11  |
2064    +--------------+--------------------------------+
2065    |    Major     |   rx   |   ry   |   Imm  4:0   |
2066    +--------------+--------------------------------+
2067
2068    EXTEND is the five bit value 11110.  Major is the instruction
2069    opcode.
2070
2071    All we need to do here is shuffle the bits appropriately.
2072    As above, the two 16-bit halves must be swapped on a
2073    little-endian system.  */
2074
2075 static inline bfd_boolean
2076 mips16_reloc_p (int r_type)
2077 {
2078   switch (r_type)
2079     {
2080     case R_MIPS16_26:
2081     case R_MIPS16_GPREL:
2082     case R_MIPS16_GOT16:
2083     case R_MIPS16_CALL16:
2084     case R_MIPS16_HI16:
2085     case R_MIPS16_LO16:
2086     case R_MIPS16_TLS_GD:
2087     case R_MIPS16_TLS_LDM:
2088     case R_MIPS16_TLS_DTPREL_HI16:
2089     case R_MIPS16_TLS_DTPREL_LO16:
2090     case R_MIPS16_TLS_GOTTPREL:
2091     case R_MIPS16_TLS_TPREL_HI16:
2092     case R_MIPS16_TLS_TPREL_LO16:
2093       return TRUE;
2094
2095     default:
2096       return FALSE;
2097     }
2098 }
2099
2100 /* Check if a microMIPS reloc.  */
2101
2102 static inline bfd_boolean
2103 micromips_reloc_p (unsigned int r_type)
2104 {
2105   return r_type >= R_MICROMIPS_min && r_type < R_MICROMIPS_max;
2106 }
2107
2108 /* Similar to MIPS16, the two 16-bit halves in microMIPS must be swapped
2109    on a little-endian system.  This does not apply to R_MICROMIPS_PC7_S1
2110    and R_MICROMIPS_PC10_S1 relocs that apply to 16-bit instructions.  */
2111
2112 static inline bfd_boolean
2113 micromips_reloc_shuffle_p (unsigned int r_type)
2114 {
2115   return (micromips_reloc_p (r_type)
2116           && r_type != R_MICROMIPS_PC7_S1
2117           && r_type != R_MICROMIPS_PC10_S1);
2118 }
2119
2120 static inline bfd_boolean
2121 got16_reloc_p (int r_type)
2122 {
2123   return (r_type == R_MIPS_GOT16
2124           || r_type == R_MIPS16_GOT16
2125           || r_type == R_MICROMIPS_GOT16);
2126 }
2127
2128 static inline bfd_boolean
2129 call16_reloc_p (int r_type)
2130 {
2131   return (r_type == R_MIPS_CALL16
2132           || r_type == R_MIPS16_CALL16
2133           || r_type == R_MICROMIPS_CALL16);
2134 }
2135
2136 static inline bfd_boolean
2137 got_disp_reloc_p (unsigned int r_type)
2138 {
2139   return r_type == R_MIPS_GOT_DISP || r_type == R_MICROMIPS_GOT_DISP;
2140 }
2141
2142 static inline bfd_boolean
2143 got_page_reloc_p (unsigned int r_type)
2144 {
2145   return r_type == R_MIPS_GOT_PAGE || r_type == R_MICROMIPS_GOT_PAGE;
2146 }
2147
2148 static inline bfd_boolean
2149 got_ofst_reloc_p (unsigned int r_type)
2150 {
2151   return r_type == R_MIPS_GOT_OFST || r_type == R_MICROMIPS_GOT_OFST;
2152 }
2153
2154 static inline bfd_boolean
2155 got_hi16_reloc_p (unsigned int r_type)
2156 {
2157   return r_type == R_MIPS_GOT_HI16 || r_type == R_MICROMIPS_GOT_HI16;
2158 }
2159
2160 static inline bfd_boolean
2161 got_lo16_reloc_p (unsigned int r_type)
2162 {
2163   return r_type == R_MIPS_GOT_LO16 || r_type == R_MICROMIPS_GOT_LO16;
2164 }
2165
2166 static inline bfd_boolean
2167 call_hi16_reloc_p (unsigned int r_type)
2168 {
2169   return r_type == R_MIPS_CALL_HI16 || r_type == R_MICROMIPS_CALL_HI16;
2170 }
2171
2172 static inline bfd_boolean
2173 call_lo16_reloc_p (unsigned int r_type)
2174 {
2175   return r_type == R_MIPS_CALL_LO16 || r_type == R_MICROMIPS_CALL_LO16;
2176 }
2177
2178 static inline bfd_boolean
2179 hi16_reloc_p (int r_type)
2180 {
2181   return (r_type == R_MIPS_HI16
2182           || r_type == R_MIPS16_HI16
2183           || r_type == R_MICROMIPS_HI16);
2184 }
2185
2186 static inline bfd_boolean
2187 lo16_reloc_p (int r_type)
2188 {
2189   return (r_type == R_MIPS_LO16
2190           || r_type == R_MIPS16_LO16
2191           || r_type == R_MICROMIPS_LO16);
2192 }
2193
2194 static inline bfd_boolean
2195 mips16_call_reloc_p (int r_type)
2196 {
2197   return r_type == R_MIPS16_26 || r_type == R_MIPS16_CALL16;
2198 }
2199
2200 static inline bfd_boolean
2201 jal_reloc_p (int r_type)
2202 {
2203   return (r_type == R_MIPS_26
2204           || r_type == R_MIPS16_26
2205           || r_type == R_MICROMIPS_26_S1);
2206 }
2207
2208 static inline bfd_boolean
2209 micromips_branch_reloc_p (int r_type)
2210 {
2211   return (r_type == R_MICROMIPS_26_S1
2212           || r_type == R_MICROMIPS_PC16_S1
2213           || r_type == R_MICROMIPS_PC10_S1
2214           || r_type == R_MICROMIPS_PC7_S1);
2215 }
2216
2217 static inline bfd_boolean
2218 tls_gd_reloc_p (unsigned int r_type)
2219 {
2220   return (r_type == R_MIPS_TLS_GD
2221           || r_type == R_MIPS16_TLS_GD
2222           || r_type == R_MICROMIPS_TLS_GD);
2223 }
2224
2225 static inline bfd_boolean
2226 tls_ldm_reloc_p (unsigned int r_type)
2227 {
2228   return (r_type == R_MIPS_TLS_LDM
2229           || r_type == R_MIPS16_TLS_LDM
2230           || r_type == R_MICROMIPS_TLS_LDM);
2231 }
2232
2233 static inline bfd_boolean
2234 tls_gottprel_reloc_p (unsigned int r_type)
2235 {
2236   return (r_type == R_MIPS_TLS_GOTTPREL
2237           || r_type == R_MIPS16_TLS_GOTTPREL
2238           || r_type == R_MICROMIPS_TLS_GOTTPREL);
2239 }
2240
2241 void
2242 _bfd_mips_elf_reloc_unshuffle (bfd *abfd, int r_type,
2243                                bfd_boolean jal_shuffle, bfd_byte *data)
2244 {
2245   bfd_vma first, second, val;
2246
2247   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2248     return;
2249
2250   /* Pick up the first and second halfwords of the instruction.  */
2251   first = bfd_get_16 (abfd, data);
2252   second = bfd_get_16 (abfd, data + 2);
2253   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2254     val = first << 16 | second;
2255   else if (r_type != R_MIPS16_26)
2256     val = (((first & 0xf800) << 16) | ((second & 0xffe0) << 11)
2257            | ((first & 0x1f) << 11) | (first & 0x7e0) | (second & 0x1f));
2258   else
2259     val = (((first & 0xfc00) << 16) | ((first & 0x3e0) << 11)
2260            | ((first & 0x1f) << 21) | second);
2261   bfd_put_32 (abfd, val, data);
2262 }
2263
2264 void
2265 _bfd_mips_elf_reloc_shuffle (bfd *abfd, int r_type,
2266                              bfd_boolean jal_shuffle, bfd_byte *data)
2267 {
2268   bfd_vma first, second, val;
2269
2270   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2271     return;
2272
2273   val = bfd_get_32 (abfd, data);
2274   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2275     {
2276       second = val & 0xffff;
2277       first = val >> 16;
2278     }
2279   else if (r_type != R_MIPS16_26)
2280     {
2281       second = ((val >> 11) & 0xffe0) | (val & 0x1f);
2282       first = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0);
2283     }
2284   else
2285     {
2286       second = val & 0xffff;
2287       first = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0)
2288                | ((val >> 21) & 0x1f);
2289     }
2290   bfd_put_16 (abfd, second, data + 2);
2291   bfd_put_16 (abfd, first, data);
2292 }
2293
2294 bfd_reloc_status_type
2295 _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol,
2296                                arelent *reloc_entry, asection *input_section,
2297                                bfd_boolean relocatable, void *data, bfd_vma gp)
2298 {
2299   bfd_vma relocation;
2300   bfd_signed_vma val;
2301   bfd_reloc_status_type status;
2302
2303   if (bfd_is_com_section (symbol->section))
2304     relocation = 0;
2305   else
2306     relocation = symbol->value;
2307
2308   relocation += symbol->section->output_section->vma;
2309   relocation += symbol->section->output_offset;
2310
2311   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2312     return bfd_reloc_outofrange;
2313
2314   /* Set val to the offset into the section or symbol.  */
2315   val = reloc_entry->addend;
2316
2317   _bfd_mips_elf_sign_extend (val, 16);
2318
2319   /* Adjust val for the final section location and GP value.  If we
2320      are producing relocatable output, we don't want to do this for
2321      an external symbol.  */
2322   if (! relocatable
2323       || (symbol->flags & BSF_SECTION_SYM) != 0)
2324     val += relocation - gp;
2325
2326   if (reloc_entry->howto->partial_inplace)
2327     {
2328       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2329                                        (bfd_byte *) data
2330                                        + reloc_entry->address);
2331       if (status != bfd_reloc_ok)
2332         return status;
2333     }
2334   else
2335     reloc_entry->addend = val;
2336
2337   if (relocatable)
2338     reloc_entry->address += input_section->output_offset;
2339
2340   return bfd_reloc_ok;
2341 }
2342
2343 /* Used to store a REL high-part relocation such as R_MIPS_HI16 or
2344    R_MIPS_GOT16.  REL is the relocation, INPUT_SECTION is the section
2345    that contains the relocation field and DATA points to the start of
2346    INPUT_SECTION.  */
2347
2348 struct mips_hi16
2349 {
2350   struct mips_hi16 *next;
2351   bfd_byte *data;
2352   asection *input_section;
2353   arelent rel;
2354 };
2355
2356 /* FIXME: This should not be a static variable.  */
2357
2358 static struct mips_hi16 *mips_hi16_list;
2359
2360 /* A howto special_function for REL *HI16 relocations.  We can only
2361    calculate the correct value once we've seen the partnering
2362    *LO16 relocation, so just save the information for later.
2363
2364    The ABI requires that the *LO16 immediately follow the *HI16.
2365    However, as a GNU extension, we permit an arbitrary number of
2366    *HI16s to be associated with a single *LO16.  This significantly
2367    simplies the relocation handling in gcc.  */
2368
2369 bfd_reloc_status_type
2370 _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2371                           asymbol *symbol ATTRIBUTE_UNUSED, void *data,
2372                           asection *input_section, bfd *output_bfd,
2373                           char **error_message ATTRIBUTE_UNUSED)
2374 {
2375   struct mips_hi16 *n;
2376
2377   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2378     return bfd_reloc_outofrange;
2379
2380   n = bfd_malloc (sizeof *n);
2381   if (n == NULL)
2382     return bfd_reloc_outofrange;
2383
2384   n->next = mips_hi16_list;
2385   n->data = data;
2386   n->input_section = input_section;
2387   n->rel = *reloc_entry;
2388   mips_hi16_list = n;
2389
2390   if (output_bfd != NULL)
2391     reloc_entry->address += input_section->output_offset;
2392
2393   return bfd_reloc_ok;
2394 }
2395
2396 /* A howto special_function for REL R_MIPS*_GOT16 relocations.  This is just
2397    like any other 16-bit relocation when applied to global symbols, but is
2398    treated in the same as R_MIPS_HI16 when applied to local symbols.  */
2399
2400 bfd_reloc_status_type
2401 _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2402                            void *data, asection *input_section,
2403                            bfd *output_bfd, char **error_message)
2404 {
2405   if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2406       || bfd_is_und_section (bfd_get_section (symbol))
2407       || bfd_is_com_section (bfd_get_section (symbol)))
2408     /* The relocation is against a global symbol.  */
2409     return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2410                                         input_section, output_bfd,
2411                                         error_message);
2412
2413   return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
2414                                    input_section, output_bfd, error_message);
2415 }
2416
2417 /* A howto special_function for REL *LO16 relocations.  The *LO16 itself
2418    is a straightforward 16 bit inplace relocation, but we must deal with
2419    any partnering high-part relocations as well.  */
2420
2421 bfd_reloc_status_type
2422 _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2423                           void *data, asection *input_section,
2424                           bfd *output_bfd, char **error_message)
2425 {
2426   bfd_vma vallo;
2427   bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2428
2429   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2430     return bfd_reloc_outofrange;
2431
2432   _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2433                                  location);
2434   vallo = bfd_get_32 (abfd, location);
2435   _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2436                                location);
2437
2438   while (mips_hi16_list != NULL)
2439     {
2440       bfd_reloc_status_type ret;
2441       struct mips_hi16 *hi;
2442
2443       hi = mips_hi16_list;
2444
2445       /* R_MIPS*_GOT16 relocations are something of a special case.  We
2446          want to install the addend in the same way as for a R_MIPS*_HI16
2447          relocation (with a rightshift of 16).  However, since GOT16
2448          relocations can also be used with global symbols, their howto
2449          has a rightshift of 0.  */
2450       if (hi->rel.howto->type == R_MIPS_GOT16)
2451         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE);
2452       else if (hi->rel.howto->type == R_MIPS16_GOT16)
2453         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS16_HI16, FALSE);
2454       else if (hi->rel.howto->type == R_MICROMIPS_GOT16)
2455         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MICROMIPS_HI16, FALSE);
2456
2457       /* VALLO is a signed 16-bit number.  Bias it by 0x8000 so that any
2458          carry or borrow will induce a change of +1 or -1 in the high part.  */
2459       hi->rel.addend += (vallo + 0x8000) & 0xffff;
2460
2461       ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data,
2462                                          hi->input_section, output_bfd,
2463                                          error_message);
2464       if (ret != bfd_reloc_ok)
2465         return ret;
2466
2467       mips_hi16_list = hi->next;
2468       free (hi);
2469     }
2470
2471   return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2472                                       input_section, output_bfd,
2473                                       error_message);
2474 }
2475
2476 /* A generic howto special_function.  This calculates and installs the
2477    relocation itself, thus avoiding the oft-discussed problems in
2478    bfd_perform_relocation and bfd_install_relocation.  */
2479
2480 bfd_reloc_status_type
2481 _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2482                              asymbol *symbol, void *data ATTRIBUTE_UNUSED,
2483                              asection *input_section, bfd *output_bfd,
2484                              char **error_message ATTRIBUTE_UNUSED)
2485 {
2486   bfd_signed_vma val;
2487   bfd_reloc_status_type status;
2488   bfd_boolean relocatable;
2489
2490   relocatable = (output_bfd != NULL);
2491
2492   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2493     return bfd_reloc_outofrange;
2494
2495   /* Build up the field adjustment in VAL.  */
2496   val = 0;
2497   if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)
2498     {
2499       /* Either we're calculating the final field value or we have a
2500          relocation against a section symbol.  Add in the section's
2501          offset or address.  */
2502       val += symbol->section->output_section->vma;
2503       val += symbol->section->output_offset;
2504     }
2505
2506   if (!relocatable)
2507     {
2508       /* We're calculating the final field value.  Add in the symbol's value
2509          and, if pc-relative, subtract the address of the field itself.  */
2510       val += symbol->value;
2511       if (reloc_entry->howto->pc_relative)
2512         {
2513           val -= input_section->output_section->vma;
2514           val -= input_section->output_offset;
2515           val -= reloc_entry->address;
2516         }
2517     }
2518
2519   /* VAL is now the final adjustment.  If we're keeping this relocation
2520      in the output file, and if the relocation uses a separate addend,
2521      we just need to add VAL to that addend.  Otherwise we need to add
2522      VAL to the relocation field itself.  */
2523   if (relocatable && !reloc_entry->howto->partial_inplace)
2524     reloc_entry->addend += val;
2525   else
2526     {
2527       bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2528
2529       /* Add in the separate addend, if any.  */
2530       val += reloc_entry->addend;
2531
2532       /* Add VAL to the relocation field.  */
2533       _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2534                                      location);
2535       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2536                                        location);
2537       _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2538                                    location);
2539
2540       if (status != bfd_reloc_ok)
2541         return status;
2542     }
2543
2544   if (relocatable)
2545     reloc_entry->address += input_section->output_offset;
2546
2547   return bfd_reloc_ok;
2548 }
2549 \f
2550 /* Swap an entry in a .gptab section.  Note that these routines rely
2551    on the equivalence of the two elements of the union.  */
2552
2553 static void
2554 bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex,
2555                               Elf32_gptab *in)
2556 {
2557   in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value);
2558   in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes);
2559 }
2560
2561 static void
2562 bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in,
2563                                Elf32_External_gptab *ex)
2564 {
2565   H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value);
2566   H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes);
2567 }
2568
2569 static void
2570 bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in,
2571                                 Elf32_External_compact_rel *ex)
2572 {
2573   H_PUT_32 (abfd, in->id1, ex->id1);
2574   H_PUT_32 (abfd, in->num, ex->num);
2575   H_PUT_32 (abfd, in->id2, ex->id2);
2576   H_PUT_32 (abfd, in->offset, ex->offset);
2577   H_PUT_32 (abfd, in->reserved0, ex->reserved0);
2578   H_PUT_32 (abfd, in->reserved1, ex->reserved1);
2579 }
2580
2581 static void
2582 bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in,
2583                            Elf32_External_crinfo *ex)
2584 {
2585   unsigned long l;
2586
2587   l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH)
2588        | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH)
2589        | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH)
2590        | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH));
2591   H_PUT_32 (abfd, l, ex->info);
2592   H_PUT_32 (abfd, in->konst, ex->konst);
2593   H_PUT_32 (abfd, in->vaddr, ex->vaddr);
2594 }
2595 \f
2596 /* A .reginfo section holds a single Elf32_RegInfo structure.  These
2597    routines swap this structure in and out.  They are used outside of
2598    BFD, so they are globally visible.  */
2599
2600 void
2601 bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex,
2602                                 Elf32_RegInfo *in)
2603 {
2604   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2605   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2606   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2607   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2608   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2609   in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value);
2610 }
2611
2612 void
2613 bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in,
2614                                  Elf32_External_RegInfo *ex)
2615 {
2616   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2617   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2618   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2619   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2620   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2621   H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value);
2622 }
2623
2624 /* In the 64 bit ABI, the .MIPS.options section holds register
2625    information in an Elf64_Reginfo structure.  These routines swap
2626    them in and out.  They are globally visible because they are used
2627    outside of BFD.  These routines are here so that gas can call them
2628    without worrying about whether the 64 bit ABI has been included.  */
2629
2630 void
2631 bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex,
2632                                 Elf64_Internal_RegInfo *in)
2633 {
2634   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2635   in->ri_pad = H_GET_32 (abfd, ex->ri_pad);
2636   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2637   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2638   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2639   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2640   in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value);
2641 }
2642
2643 void
2644 bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in,
2645                                  Elf64_External_RegInfo *ex)
2646 {
2647   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2648   H_PUT_32 (abfd, in->ri_pad, ex->ri_pad);
2649   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2650   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2651   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2652   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2653   H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value);
2654 }
2655
2656 /* Swap in an options header.  */
2657
2658 void
2659 bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex,
2660                               Elf_Internal_Options *in)
2661 {
2662   in->kind = H_GET_8 (abfd, ex->kind);
2663   in->size = H_GET_8 (abfd, ex->size);
2664   in->section = H_GET_16 (abfd, ex->section);
2665   in->info = H_GET_32 (abfd, ex->info);
2666 }
2667
2668 /* Swap out an options header.  */
2669
2670 void
2671 bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in,
2672                                Elf_External_Options *ex)
2673 {
2674   H_PUT_8 (abfd, in->kind, ex->kind);
2675   H_PUT_8 (abfd, in->size, ex->size);
2676   H_PUT_16 (abfd, in->section, ex->section);
2677   H_PUT_32 (abfd, in->info, ex->info);
2678 }
2679
2680 /* Swap in an abiflags structure.  */
2681
2682 void
2683 bfd_mips_elf_swap_abiflags_v0_in (bfd *abfd,
2684                                   const Elf_External_ABIFlags_v0 *ex,
2685                                   Elf_Internal_ABIFlags_v0 *in)
2686 {
2687   in->version = H_GET_16 (abfd, ex->version);
2688   in->isa_level = H_GET_8 (abfd, ex->isa_level);
2689   in->isa_rev = H_GET_8 (abfd, ex->isa_rev);
2690   in->gpr_size = H_GET_8 (abfd, ex->gpr_size);
2691   in->cpr1_size = H_GET_8 (abfd, ex->cpr1_size);
2692   in->cpr2_size = H_GET_8 (abfd, ex->cpr2_size);
2693   in->fp_abi = H_GET_8 (abfd, ex->fp_abi);
2694   in->isa_ext = H_GET_32 (abfd, ex->isa_ext);
2695   in->ases = H_GET_32 (abfd, ex->ases);
2696   in->flags1 = H_GET_32 (abfd, ex->flags1);
2697   in->flags2 = H_GET_32 (abfd, ex->flags2);
2698 }
2699
2700 /* Swap out an abiflags structure.  */
2701
2702 void
2703 bfd_mips_elf_swap_abiflags_v0_out (bfd *abfd,
2704                                    const Elf_Internal_ABIFlags_v0 *in,
2705                                    Elf_External_ABIFlags_v0 *ex)
2706 {
2707   H_PUT_16 (abfd, in->version, ex->version);
2708   H_PUT_8 (abfd, in->isa_level, ex->isa_level);
2709   H_PUT_8 (abfd, in->isa_rev, ex->isa_rev);
2710   H_PUT_8 (abfd, in->gpr_size, ex->gpr_size);
2711   H_PUT_8 (abfd, in->cpr1_size, ex->cpr1_size);
2712   H_PUT_8 (abfd, in->cpr2_size, ex->cpr2_size);
2713   H_PUT_8 (abfd, in->fp_abi, ex->fp_abi);
2714   H_PUT_32 (abfd, in->isa_ext, ex->isa_ext);
2715   H_PUT_32 (abfd, in->ases, ex->ases);
2716   H_PUT_32 (abfd, in->flags1, ex->flags1);
2717   H_PUT_32 (abfd, in->flags2, ex->flags2);
2718 }
2719 \f
2720 /* This function is called via qsort() to sort the dynamic relocation
2721    entries by increasing r_symndx value.  */
2722
2723 static int
2724 sort_dynamic_relocs (const void *arg1, const void *arg2)
2725 {
2726   Elf_Internal_Rela int_reloc1;
2727   Elf_Internal_Rela int_reloc2;
2728   int diff;
2729
2730   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
2731   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
2732
2733   diff = ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info);
2734   if (diff != 0)
2735     return diff;
2736
2737   if (int_reloc1.r_offset < int_reloc2.r_offset)
2738     return -1;
2739   if (int_reloc1.r_offset > int_reloc2.r_offset)
2740     return 1;
2741   return 0;
2742 }
2743
2744 /* Like sort_dynamic_relocs, but used for elf64 relocations.  */
2745
2746 static int
2747 sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED,
2748                         const void *arg2 ATTRIBUTE_UNUSED)
2749 {
2750 #ifdef BFD64
2751   Elf_Internal_Rela int_reloc1[3];
2752   Elf_Internal_Rela int_reloc2[3];
2753
2754   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2755     (reldyn_sorting_bfd, arg1, int_reloc1);
2756   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2757     (reldyn_sorting_bfd, arg2, int_reloc2);
2758
2759   if (ELF64_R_SYM (int_reloc1[0].r_info) < ELF64_R_SYM (int_reloc2[0].r_info))
2760     return -1;
2761   if (ELF64_R_SYM (int_reloc1[0].r_info) > ELF64_R_SYM (int_reloc2[0].r_info))
2762     return 1;
2763
2764   if (int_reloc1[0].r_offset < int_reloc2[0].r_offset)
2765     return -1;
2766   if (int_reloc1[0].r_offset > int_reloc2[0].r_offset)
2767     return 1;
2768   return 0;
2769 #else
2770   abort ();
2771 #endif
2772 }
2773
2774
2775 /* This routine is used to write out ECOFF debugging external symbol
2776    information.  It is called via mips_elf_link_hash_traverse.  The
2777    ECOFF external symbol information must match the ELF external
2778    symbol information.  Unfortunately, at this point we don't know
2779    whether a symbol is required by reloc information, so the two
2780    tables may wind up being different.  We must sort out the external
2781    symbol information before we can set the final size of the .mdebug
2782    section, and we must set the size of the .mdebug section before we
2783    can relocate any sections, and we can't know which symbols are
2784    required by relocation until we relocate the sections.
2785    Fortunately, it is relatively unlikely that any symbol will be
2786    stripped but required by a reloc.  In particular, it can not happen
2787    when generating a final executable.  */
2788
2789 static bfd_boolean
2790 mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data)
2791 {
2792   struct extsym_info *einfo = data;
2793   bfd_boolean strip;
2794   asection *sec, *output_section;
2795
2796   if (h->root.indx == -2)
2797     strip = FALSE;
2798   else if ((h->root.def_dynamic
2799             || h->root.ref_dynamic
2800             || h->root.type == bfd_link_hash_new)
2801            && !h->root.def_regular
2802            && !h->root.ref_regular)
2803     strip = TRUE;
2804   else if (einfo->info->strip == strip_all
2805            || (einfo->info->strip == strip_some
2806                && bfd_hash_lookup (einfo->info->keep_hash,
2807                                    h->root.root.root.string,
2808                                    FALSE, FALSE) == NULL))
2809     strip = TRUE;
2810   else
2811     strip = FALSE;
2812
2813   if (strip)
2814     return TRUE;
2815
2816   if (h->esym.ifd == -2)
2817     {
2818       h->esym.jmptbl = 0;
2819       h->esym.cobol_main = 0;
2820       h->esym.weakext = 0;
2821       h->esym.reserved = 0;
2822       h->esym.ifd = ifdNil;
2823       h->esym.asym.value = 0;
2824       h->esym.asym.st = stGlobal;
2825
2826       if (h->root.root.type == bfd_link_hash_undefined
2827           || h->root.root.type == bfd_link_hash_undefweak)
2828         {
2829           const char *name;
2830
2831           /* Use undefined class.  Also, set class and type for some
2832              special symbols.  */
2833           name = h->root.root.root.string;
2834           if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
2835               || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
2836             {
2837               h->esym.asym.sc = scData;
2838               h->esym.asym.st = stLabel;
2839               h->esym.asym.value = 0;
2840             }
2841           else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
2842             {
2843               h->esym.asym.sc = scAbs;
2844               h->esym.asym.st = stLabel;
2845               h->esym.asym.value =
2846                 mips_elf_hash_table (einfo->info)->procedure_count;
2847             }
2848           else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd))
2849             {
2850               h->esym.asym.sc = scAbs;
2851               h->esym.asym.st = stLabel;
2852               h->esym.asym.value = elf_gp (einfo->abfd);
2853             }
2854           else
2855             h->esym.asym.sc = scUndefined;
2856         }
2857       else if (h->root.root.type != bfd_link_hash_defined
2858           && h->root.root.type != bfd_link_hash_defweak)
2859         h->esym.asym.sc = scAbs;
2860       else
2861         {
2862           const char *name;
2863
2864           sec = h->root.root.u.def.section;
2865           output_section = sec->output_section;
2866
2867           /* When making a shared library and symbol h is the one from
2868              the another shared library, OUTPUT_SECTION may be null.  */
2869           if (output_section == NULL)
2870             h->esym.asym.sc = scUndefined;
2871           else
2872             {
2873               name = bfd_section_name (output_section->owner, output_section);
2874
2875               if (strcmp (name, ".text") == 0)
2876                 h->esym.asym.sc = scText;
2877               else if (strcmp (name, ".data") == 0)
2878                 h->esym.asym.sc = scData;
2879               else if (strcmp (name, ".sdata") == 0)
2880                 h->esym.asym.sc = scSData;
2881               else if (strcmp (name, ".rodata") == 0
2882                        || strcmp (name, ".rdata") == 0)
2883                 h->esym.asym.sc = scRData;
2884               else if (strcmp (name, ".bss") == 0)
2885                 h->esym.asym.sc = scBss;
2886               else if (strcmp (name, ".sbss") == 0)
2887                 h->esym.asym.sc = scSBss;
2888               else if (strcmp (name, ".init") == 0)
2889                 h->esym.asym.sc = scInit;
2890               else if (strcmp (name, ".fini") == 0)
2891                 h->esym.asym.sc = scFini;
2892               else
2893                 h->esym.asym.sc = scAbs;
2894             }
2895         }
2896
2897       h->esym.asym.reserved = 0;
2898       h->esym.asym.index = indexNil;
2899     }
2900
2901   if (h->root.root.type == bfd_link_hash_common)
2902     h->esym.asym.value = h->root.root.u.c.size;
2903   else if (h->root.root.type == bfd_link_hash_defined
2904            || h->root.root.type == bfd_link_hash_defweak)
2905     {
2906       if (h->esym.asym.sc == scCommon)
2907         h->esym.asym.sc = scBss;
2908       else if (h->esym.asym.sc == scSCommon)
2909         h->esym.asym.sc = scSBss;
2910
2911       sec = h->root.root.u.def.section;
2912       output_section = sec->output_section;
2913       if (output_section != NULL)
2914         h->esym.asym.value = (h->root.root.u.def.value
2915                               + sec->output_offset
2916                               + output_section->vma);
2917       else
2918         h->esym.asym.value = 0;
2919     }
2920   else
2921     {
2922       struct mips_elf_link_hash_entry *hd = h;
2923
2924       while (hd->root.root.type == bfd_link_hash_indirect)
2925         hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link;
2926
2927       if (hd->needs_lazy_stub)
2928         {
2929           BFD_ASSERT (hd->root.plt.plist != NULL);
2930           BFD_ASSERT (hd->root.plt.plist->stub_offset != MINUS_ONE);
2931           /* Set type and value for a symbol with a function stub.  */
2932           h->esym.asym.st = stProc;
2933           sec = hd->root.root.u.def.section;
2934           if (sec == NULL)
2935             h->esym.asym.value = 0;
2936           else
2937             {
2938               output_section = sec->output_section;
2939               if (output_section != NULL)
2940                 h->esym.asym.value = (hd->root.plt.plist->stub_offset
2941                                       + sec->output_offset
2942                                       + output_section->vma);
2943               else
2944                 h->esym.asym.value = 0;
2945             }
2946         }
2947     }
2948
2949   if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap,
2950                                       h->root.root.root.string,
2951                                       &h->esym))
2952     {
2953       einfo->failed = TRUE;
2954       return FALSE;
2955     }
2956
2957   return TRUE;
2958 }
2959
2960 /* A comparison routine used to sort .gptab entries.  */
2961
2962 static int
2963 gptab_compare (const void *p1, const void *p2)
2964 {
2965   const Elf32_gptab *a1 = p1;
2966   const Elf32_gptab *a2 = p2;
2967
2968   return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value;
2969 }
2970 \f
2971 /* Functions to manage the got entry hash table.  */
2972
2973 /* Use all 64 bits of a bfd_vma for the computation of a 32-bit
2974    hash number.  */
2975
2976 static INLINE hashval_t
2977 mips_elf_hash_bfd_vma (bfd_vma addr)
2978 {
2979 #ifdef BFD64
2980   return addr + (addr >> 32);
2981 #else
2982   return addr;
2983 #endif
2984 }
2985
2986 static hashval_t
2987 mips_elf_got_entry_hash (const void *entry_)
2988 {
2989   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2990
2991   return (entry->symndx
2992           + ((entry->tls_type == GOT_TLS_LDM) << 18)
2993           + (entry->tls_type == GOT_TLS_LDM ? 0
2994              : !entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address)
2995              : entry->symndx >= 0 ? (entry->abfd->id
2996                                      + mips_elf_hash_bfd_vma (entry->d.addend))
2997              : entry->d.h->root.root.root.hash));
2998 }
2999
3000 static int
3001 mips_elf_got_entry_eq (const void *entry1, const void *entry2)
3002 {
3003   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
3004   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
3005
3006   return (e1->symndx == e2->symndx
3007           && e1->tls_type == e2->tls_type
3008           && (e1->tls_type == GOT_TLS_LDM ? TRUE
3009               : !e1->abfd ? !e2->abfd && e1->d.address == e2->d.address
3010               : e1->symndx >= 0 ? (e1->abfd == e2->abfd
3011                                    && e1->d.addend == e2->d.addend)
3012               : e2->abfd && e1->d.h == e2->d.h));
3013 }
3014
3015 static hashval_t
3016 mips_got_page_ref_hash (const void *ref_)
3017 {
3018   const struct mips_got_page_ref *ref;
3019
3020   ref = (const struct mips_got_page_ref *) ref_;
3021   return ((ref->symndx >= 0
3022            ? (hashval_t) (ref->u.abfd->id + ref->symndx)
3023            : ref->u.h->root.root.root.hash)
3024           + mips_elf_hash_bfd_vma (ref->addend));
3025 }
3026
3027 static int
3028 mips_got_page_ref_eq (const void *ref1_, const void *ref2_)
3029 {
3030   const struct mips_got_page_ref *ref1, *ref2;
3031
3032   ref1 = (const struct mips_got_page_ref *) ref1_;
3033   ref2 = (const struct mips_got_page_ref *) ref2_;
3034   return (ref1->symndx == ref2->symndx
3035           && (ref1->symndx < 0
3036               ? ref1->u.h == ref2->u.h
3037               : ref1->u.abfd == ref2->u.abfd)
3038           && ref1->addend == ref2->addend);
3039 }
3040
3041 static hashval_t
3042 mips_got_page_entry_hash (const void *entry_)
3043 {
3044   const struct mips_got_page_entry *entry;
3045
3046   entry = (const struct mips_got_page_entry *) entry_;
3047   return entry->sec->id;
3048 }
3049
3050 static int
3051 mips_got_page_entry_eq (const void *entry1_, const void *entry2_)
3052 {
3053   const struct mips_got_page_entry *entry1, *entry2;
3054
3055   entry1 = (const struct mips_got_page_entry *) entry1_;
3056   entry2 = (const struct mips_got_page_entry *) entry2_;
3057   return entry1->sec == entry2->sec;
3058 }
3059 \f
3060 /* Create and return a new mips_got_info structure.  */
3061
3062 static struct mips_got_info *
3063 mips_elf_create_got_info (bfd *abfd)
3064 {
3065   struct mips_got_info *g;
3066
3067   g = bfd_zalloc (abfd, sizeof (struct mips_got_info));
3068   if (g == NULL)
3069     return NULL;
3070
3071   g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
3072                                     mips_elf_got_entry_eq, NULL);
3073   if (g->got_entries == NULL)
3074     return NULL;
3075
3076   g->got_page_refs = htab_try_create (1, mips_got_page_ref_hash,
3077                                       mips_got_page_ref_eq, NULL);
3078   if (g->got_page_refs == NULL)
3079     return NULL;
3080
3081   return g;
3082 }
3083
3084 /* Return the GOT info for input bfd ABFD, trying to create a new one if
3085    CREATE_P and if ABFD doesn't already have a GOT.  */
3086
3087 static struct mips_got_info *
3088 mips_elf_bfd_got (bfd *abfd, bfd_boolean create_p)
3089 {
3090   struct mips_elf_obj_tdata *tdata;
3091
3092   if (!is_mips_elf (abfd))
3093     return NULL;
3094
3095   tdata = mips_elf_tdata (abfd);
3096   if (!tdata->got && create_p)
3097     tdata->got = mips_elf_create_got_info (abfd);
3098   return tdata->got;
3099 }
3100
3101 /* Record that ABFD should use output GOT G.  */
3102
3103 static void
3104 mips_elf_replace_bfd_got (bfd *abfd, struct mips_got_info *g)
3105 {
3106   struct mips_elf_obj_tdata *tdata;
3107
3108   BFD_ASSERT (is_mips_elf (abfd));
3109   tdata = mips_elf_tdata (abfd);
3110   if (tdata->got)
3111     {
3112       /* The GOT structure itself and the hash table entries are
3113          allocated to a bfd, but the hash tables aren't.  */
3114       htab_delete (tdata->got->got_entries);
3115       htab_delete (tdata->got->got_page_refs);
3116       if (tdata->got->got_page_entries)
3117         htab_delete (tdata->got->got_page_entries);
3118     }
3119   tdata->got = g;
3120 }
3121
3122 /* Return the dynamic relocation section.  If it doesn't exist, try to
3123    create a new it if CREATE_P, otherwise return NULL.  Also return NULL
3124    if creation fails.  */
3125
3126 static asection *
3127 mips_elf_rel_dyn_section (struct bfd_link_info *info, bfd_boolean create_p)
3128 {
3129   const char *dname;
3130   asection *sreloc;
3131   bfd *dynobj;
3132
3133   dname = MIPS_ELF_REL_DYN_NAME (info);
3134   dynobj = elf_hash_table (info)->dynobj;
3135   sreloc = bfd_get_linker_section (dynobj, dname);
3136   if (sreloc == NULL && create_p)
3137     {
3138       sreloc = bfd_make_section_anyway_with_flags (dynobj, dname,
3139                                                    (SEC_ALLOC
3140                                                     | SEC_LOAD
3141                                                     | SEC_HAS_CONTENTS
3142                                                     | SEC_IN_MEMORY
3143                                                     | SEC_LINKER_CREATED
3144                                                     | SEC_READONLY));
3145       if (sreloc == NULL
3146           || ! bfd_set_section_alignment (dynobj, sreloc,
3147                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
3148         return NULL;
3149     }
3150   return sreloc;
3151 }
3152
3153 /* Return the GOT_TLS_* type required by relocation type R_TYPE.  */
3154
3155 static int
3156 mips_elf_reloc_tls_type (unsigned int r_type)
3157 {
3158   if (tls_gd_reloc_p (r_type))
3159     return GOT_TLS_GD;
3160
3161   if (tls_ldm_reloc_p (r_type))
3162     return GOT_TLS_LDM;
3163
3164   if (tls_gottprel_reloc_p (r_type))
3165     return GOT_TLS_IE;
3166
3167   return GOT_TLS_NONE;
3168 }
3169
3170 /* Return the number of GOT slots needed for GOT TLS type TYPE.  */
3171
3172 static int
3173 mips_tls_got_entries (unsigned int type)
3174 {
3175   switch (type)
3176     {
3177     case GOT_TLS_GD:
3178     case GOT_TLS_LDM:
3179       return 2;
3180
3181     case GOT_TLS_IE:
3182       return 1;
3183
3184     case GOT_TLS_NONE:
3185       return 0;
3186     }
3187   abort ();
3188 }
3189
3190 /* Count the number of relocations needed for a TLS GOT entry, with
3191    access types from TLS_TYPE, and symbol H (or a local symbol if H
3192    is NULL).  */
3193
3194 static int
3195 mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type,
3196                      struct elf_link_hash_entry *h)
3197 {
3198   int indx = 0;
3199   bfd_boolean need_relocs = FALSE;
3200   bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3201
3202   if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, h)
3203       && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, h)))
3204     indx = h->dynindx;
3205
3206   if ((info->shared || indx != 0)
3207       && (h == NULL
3208           || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
3209           || h->root.type != bfd_link_hash_undefweak))
3210     need_relocs = TRUE;
3211
3212   if (!need_relocs)
3213     return 0;
3214
3215   switch (tls_type)
3216     {
3217     case GOT_TLS_GD:
3218       return indx != 0 ? 2 : 1;
3219
3220     case GOT_TLS_IE:
3221       return 1;
3222
3223     case GOT_TLS_LDM:
3224       return info->shared ? 1 : 0;
3225
3226     default:
3227       return 0;
3228     }
3229 }
3230
3231 /* Add the number of GOT entries and TLS relocations required by ENTRY
3232    to G.  */
3233
3234 static void
3235 mips_elf_count_got_entry (struct bfd_link_info *info,
3236                           struct mips_got_info *g,
3237                           struct mips_got_entry *entry)
3238 {
3239   if (entry->tls_type)
3240     {
3241       g->tls_gotno += mips_tls_got_entries (entry->tls_type);
3242       g->relocs += mips_tls_got_relocs (info, entry->tls_type,
3243                                         entry->symndx < 0
3244                                         ? &entry->d.h->root : NULL);
3245     }
3246   else if (entry->symndx >= 0 || entry->d.h->global_got_area == GGA_NONE)
3247     g->local_gotno += 1;
3248   else
3249     g->global_gotno += 1;
3250 }
3251
3252 /* Output a simple dynamic relocation into SRELOC.  */
3253
3254 static void
3255 mips_elf_output_dynamic_relocation (bfd *output_bfd,
3256                                     asection *sreloc,
3257                                     unsigned long reloc_index,
3258                                     unsigned long indx,
3259                                     int r_type,
3260                                     bfd_vma offset)
3261 {
3262   Elf_Internal_Rela rel[3];
3263
3264   memset (rel, 0, sizeof (rel));
3265
3266   rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type);
3267   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
3268
3269   if (ABI_64_P (output_bfd))
3270     {
3271       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
3272         (output_bfd, &rel[0],
3273          (sreloc->contents
3274           + reloc_index * sizeof (Elf64_Mips_External_Rel)));
3275     }
3276   else
3277     bfd_elf32_swap_reloc_out
3278       (output_bfd, &rel[0],
3279        (sreloc->contents
3280         + reloc_index * sizeof (Elf32_External_Rel)));
3281 }
3282
3283 /* Initialize a set of TLS GOT entries for one symbol.  */
3284
3285 static void
3286 mips_elf_initialize_tls_slots (bfd *abfd, struct bfd_link_info *info,
3287                                struct mips_got_entry *entry,
3288                                struct mips_elf_link_hash_entry *h,
3289                                bfd_vma value)
3290 {
3291   struct mips_elf_link_hash_table *htab;
3292   int indx;
3293   asection *sreloc, *sgot;
3294   bfd_vma got_offset, got_offset2;
3295   bfd_boolean need_relocs = FALSE;
3296
3297   htab = mips_elf_hash_table (info);
3298   if (htab == NULL)
3299     return;
3300
3301   sgot = htab->sgot;
3302
3303   indx = 0;
3304   if (h != NULL)
3305     {
3306       bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3307
3308       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, &h->root)
3309           && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3310         indx = h->root.dynindx;
3311     }
3312
3313   if (entry->tls_initialized)
3314     return;
3315
3316   if ((info->shared || indx != 0)
3317       && (h == NULL
3318           || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT
3319           || h->root.type != bfd_link_hash_undefweak))
3320     need_relocs = TRUE;
3321
3322   /* MINUS_ONE means the symbol is not defined in this object.  It may not
3323      be defined at all; assume that the value doesn't matter in that
3324      case.  Otherwise complain if we would use the value.  */
3325   BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs)
3326               || h->root.root.type == bfd_link_hash_undefweak);
3327
3328   /* Emit necessary relocations.  */
3329   sreloc = mips_elf_rel_dyn_section (info, FALSE);
3330   got_offset = entry->gotidx;
3331
3332   switch (entry->tls_type)
3333     {
3334     case GOT_TLS_GD:
3335       /* General Dynamic.  */
3336       got_offset2 = got_offset + MIPS_ELF_GOT_SIZE (abfd);
3337
3338       if (need_relocs)
3339         {
3340           mips_elf_output_dynamic_relocation
3341             (abfd, sreloc, sreloc->reloc_count++, indx,
3342              ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3343              sgot->output_offset + sgot->output_section->vma + got_offset);
3344
3345           if (indx)
3346             mips_elf_output_dynamic_relocation
3347               (abfd, sreloc, sreloc->reloc_count++, indx,
3348                ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32,
3349                sgot->output_offset + sgot->output_section->vma + got_offset2);
3350           else
3351             MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3352                                sgot->contents + got_offset2);
3353         }
3354       else
3355         {
3356           MIPS_ELF_PUT_WORD (abfd, 1,
3357                              sgot->contents + got_offset);
3358           MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3359                              sgot->contents + got_offset2);
3360         }
3361       break;
3362
3363     case GOT_TLS_IE:
3364       /* Initial Exec model.  */
3365       if (need_relocs)
3366         {
3367           if (indx == 0)
3368             MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma,
3369                                sgot->contents + got_offset);
3370           else
3371             MIPS_ELF_PUT_WORD (abfd, 0,
3372                                sgot->contents + got_offset);
3373
3374           mips_elf_output_dynamic_relocation
3375             (abfd, sreloc, sreloc->reloc_count++, indx,
3376              ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32,
3377              sgot->output_offset + sgot->output_section->vma + got_offset);
3378         }
3379       else
3380         MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info),
3381                            sgot->contents + got_offset);
3382       break;
3383
3384     case GOT_TLS_LDM:
3385       /* The initial offset is zero, and the LD offsets will include the
3386          bias by DTP_OFFSET.  */
3387       MIPS_ELF_PUT_WORD (abfd, 0,
3388                          sgot->contents + got_offset
3389                          + MIPS_ELF_GOT_SIZE (abfd));
3390
3391       if (!info->shared)
3392         MIPS_ELF_PUT_WORD (abfd, 1,
3393                            sgot->contents + got_offset);
3394       else
3395         mips_elf_output_dynamic_relocation
3396           (abfd, sreloc, sreloc->reloc_count++, indx,
3397            ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3398            sgot->output_offset + sgot->output_section->vma + got_offset);
3399       break;
3400
3401     default:
3402       abort ();
3403     }
3404
3405   entry->tls_initialized = TRUE;
3406 }
3407
3408 /* Return the offset from _GLOBAL_OFFSET_TABLE_ of the .got.plt entry
3409    for global symbol H.  .got.plt comes before the GOT, so the offset
3410    will be negative.  */
3411
3412 static bfd_vma
3413 mips_elf_gotplt_index (struct bfd_link_info *info,
3414                        struct elf_link_hash_entry *h)
3415 {
3416   bfd_vma got_address, got_value;
3417   struct mips_elf_link_hash_table *htab;
3418
3419   htab = mips_elf_hash_table (info);
3420   BFD_ASSERT (htab != NULL);
3421
3422   BFD_ASSERT (h->plt.plist != NULL);
3423   BFD_ASSERT (h->plt.plist->gotplt_index != MINUS_ONE);
3424
3425   /* Calculate the address of the associated .got.plt entry.  */
3426   got_address = (htab->sgotplt->output_section->vma
3427                  + htab->sgotplt->output_offset
3428                  + (h->plt.plist->gotplt_index
3429                     * MIPS_ELF_GOT_SIZE (info->output_bfd)));
3430
3431   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
3432   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
3433                + htab->root.hgot->root.u.def.section->output_offset
3434                + htab->root.hgot->root.u.def.value);
3435
3436   return got_address - got_value;
3437 }
3438
3439 /* Return the GOT offset for address VALUE.   If there is not yet a GOT
3440    entry for this value, create one.  If R_SYMNDX refers to a TLS symbol,
3441    create a TLS GOT entry instead.  Return -1 if no satisfactory GOT
3442    offset can be found.  */
3443
3444 static bfd_vma
3445 mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3446                           bfd_vma value, unsigned long r_symndx,
3447                           struct mips_elf_link_hash_entry *h, int r_type)
3448 {
3449   struct mips_elf_link_hash_table *htab;
3450   struct mips_got_entry *entry;
3451
3452   htab = mips_elf_hash_table (info);
3453   BFD_ASSERT (htab != NULL);
3454
3455   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value,
3456                                            r_symndx, h, r_type);
3457   if (!entry)
3458     return MINUS_ONE;
3459
3460   if (entry->tls_type)
3461     mips_elf_initialize_tls_slots (abfd, info, entry, h, value);
3462   return entry->gotidx;
3463 }
3464
3465 /* Return the GOT index of global symbol H in the primary GOT.  */
3466
3467 static bfd_vma
3468 mips_elf_primary_global_got_index (bfd *obfd, struct bfd_link_info *info,
3469                                    struct elf_link_hash_entry *h)
3470 {
3471   struct mips_elf_link_hash_table *htab;
3472   long global_got_dynindx;
3473   struct mips_got_info *g;
3474   bfd_vma got_index;
3475
3476   htab = mips_elf_hash_table (info);
3477   BFD_ASSERT (htab != NULL);
3478
3479   global_got_dynindx = 0;
3480   if (htab->global_gotsym != NULL)
3481     global_got_dynindx = htab->global_gotsym->dynindx;
3482
3483   /* Once we determine the global GOT entry with the lowest dynamic
3484      symbol table index, we must put all dynamic symbols with greater
3485      indices into the primary GOT.  That makes it easy to calculate the
3486      GOT offset.  */
3487   BFD_ASSERT (h->dynindx >= global_got_dynindx);
3488   g = mips_elf_bfd_got (obfd, FALSE);
3489   got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3490                * MIPS_ELF_GOT_SIZE (obfd));
3491   BFD_ASSERT (got_index < htab->sgot->size);
3492
3493   return got_index;
3494 }
3495
3496 /* Return the GOT index for the global symbol indicated by H, which is
3497    referenced by a relocation of type R_TYPE in IBFD.  */
3498
3499 static bfd_vma
3500 mips_elf_global_got_index (bfd *obfd, struct bfd_link_info *info, bfd *ibfd,
3501                            struct elf_link_hash_entry *h, int r_type)
3502 {
3503   struct mips_elf_link_hash_table *htab;
3504   struct mips_got_info *g;
3505   struct mips_got_entry lookup, *entry;
3506   bfd_vma gotidx;
3507
3508   htab = mips_elf_hash_table (info);
3509   BFD_ASSERT (htab != NULL);
3510
3511   g = mips_elf_bfd_got (ibfd, FALSE);
3512   BFD_ASSERT (g);
3513
3514   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3515   if (!lookup.tls_type && g == mips_elf_bfd_got (obfd, FALSE))
3516     return mips_elf_primary_global_got_index (obfd, info, h);
3517
3518   lookup.abfd = ibfd;
3519   lookup.symndx = -1;
3520   lookup.d.h = (struct mips_elf_link_hash_entry *) h;
3521   entry = htab_find (g->got_entries, &lookup);
3522   BFD_ASSERT (entry);
3523
3524   gotidx = entry->gotidx;
3525   BFD_ASSERT (gotidx > 0 && gotidx < htab->sgot->size);
3526
3527   if (lookup.tls_type)
3528     {
3529       bfd_vma value = MINUS_ONE;
3530
3531       if ((h->root.type == bfd_link_hash_defined
3532            || h->root.type == bfd_link_hash_defweak)
3533           && h->root.u.def.section->output_section)
3534         value = (h->root.u.def.value
3535                  + h->root.u.def.section->output_offset
3536                  + h->root.u.def.section->output_section->vma);
3537
3538       mips_elf_initialize_tls_slots (obfd, info, entry, lookup.d.h, value);
3539     }
3540   return gotidx;
3541 }
3542
3543 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3544    entries are supposed to be placed at small offsets in the GOT, i.e.,
3545    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3546    entry could be created.  If OFFSETP is nonnull, use it to return the
3547    offset of the GOT entry from VALUE.  */
3548
3549 static bfd_vma
3550 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3551                    bfd_vma value, bfd_vma *offsetp)
3552 {
3553   bfd_vma page, got_index;
3554   struct mips_got_entry *entry;
3555
3556   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3557   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3558                                            NULL, R_MIPS_GOT_PAGE);
3559
3560   if (!entry)
3561     return MINUS_ONE;
3562
3563   got_index = entry->gotidx;
3564
3565   if (offsetp)
3566     *offsetp = value - entry->d.address;
3567
3568   return got_index;
3569 }
3570
3571 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3572    EXTERNAL is true if the relocation was originally against a global
3573    symbol that binds locally.  */
3574
3575 static bfd_vma
3576 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3577                       bfd_vma value, bfd_boolean external)
3578 {
3579   struct mips_got_entry *entry;
3580
3581   /* GOT16 relocations against local symbols are followed by a LO16
3582      relocation; those against global symbols are not.  Thus if the
3583      symbol was originally local, the GOT16 relocation should load the
3584      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3585   if (! external)
3586     value = mips_elf_high (value) << 16;
3587
3588   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3589      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3590      same in all cases.  */
3591   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3592                                            NULL, R_MIPS_GOT16);
3593   if (entry)
3594     return entry->gotidx;
3595   else
3596     return MINUS_ONE;
3597 }
3598
3599 /* Returns the offset for the entry at the INDEXth position
3600    in the GOT.  */
3601
3602 static bfd_vma
3603 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3604                                 bfd *input_bfd, bfd_vma got_index)
3605 {
3606   struct mips_elf_link_hash_table *htab;
3607   asection *sgot;
3608   bfd_vma gp;
3609
3610   htab = mips_elf_hash_table (info);
3611   BFD_ASSERT (htab != NULL);
3612
3613   sgot = htab->sgot;
3614   gp = _bfd_get_gp_value (output_bfd)
3615     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3616
3617   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3618 }
3619
3620 /* Create and return a local GOT entry for VALUE, which was calculated
3621    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3622    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3623    instead.  */
3624
3625 static struct mips_got_entry *
3626 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3627                                  bfd *ibfd, bfd_vma value,
3628                                  unsigned long r_symndx,
3629                                  struct mips_elf_link_hash_entry *h,
3630                                  int r_type)
3631 {
3632   struct mips_got_entry lookup, *entry;
3633   void **loc;
3634   struct mips_got_info *g;
3635   struct mips_elf_link_hash_table *htab;
3636   bfd_vma gotidx;
3637
3638   htab = mips_elf_hash_table (info);
3639   BFD_ASSERT (htab != NULL);
3640
3641   g = mips_elf_bfd_got (ibfd, FALSE);
3642   if (g == NULL)
3643     {
3644       g = mips_elf_bfd_got (abfd, FALSE);
3645       BFD_ASSERT (g != NULL);
3646     }
3647
3648   /* This function shouldn't be called for symbols that live in the global
3649      area of the GOT.  */
3650   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3651
3652   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3653   if (lookup.tls_type)
3654     {
3655       lookup.abfd = ibfd;
3656       if (tls_ldm_reloc_p (r_type))
3657         {
3658           lookup.symndx = 0;
3659           lookup.d.addend = 0;
3660         }
3661       else if (h == NULL)
3662         {
3663           lookup.symndx = r_symndx;
3664           lookup.d.addend = 0;
3665         }
3666       else
3667         {
3668           lookup.symndx = -1;
3669           lookup.d.h = h;
3670         }
3671
3672       entry = (struct mips_got_entry *) htab_find (g->got_entries, &lookup);
3673       BFD_ASSERT (entry);
3674
3675       gotidx = entry->gotidx;
3676       BFD_ASSERT (gotidx > 0 && gotidx < htab->sgot->size);
3677
3678       return entry;
3679     }
3680
3681   lookup.abfd = NULL;
3682   lookup.symndx = -1;
3683   lookup.d.address = value;
3684   loc = htab_find_slot (g->got_entries, &lookup, INSERT);
3685   if (!loc)
3686     return NULL;
3687
3688   entry = (struct mips_got_entry *) *loc;
3689   if (entry)
3690     return entry;
3691
3692   if (g->assigned_low_gotno > g->assigned_high_gotno)
3693     {
3694       /* We didn't allocate enough space in the GOT.  */
3695       (*_bfd_error_handler)
3696         (_("not enough GOT space for local GOT entries"));
3697       bfd_set_error (bfd_error_bad_value);
3698       return NULL;
3699     }
3700
3701   entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3702   if (!entry)
3703     return NULL;
3704
3705   if (got16_reloc_p (r_type)
3706       || call16_reloc_p (r_type)
3707       || got_page_reloc_p (r_type)
3708       || got_disp_reloc_p (r_type))
3709     lookup.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_low_gotno++;
3710   else
3711     lookup.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_high_gotno--;
3712
3713   *entry = lookup;
3714   *loc = entry;
3715
3716   MIPS_ELF_PUT_WORD (abfd, value, htab->sgot->contents + entry->gotidx);
3717
3718   /* These GOT entries need a dynamic relocation on VxWorks.  */
3719   if (htab->is_vxworks)
3720     {
3721       Elf_Internal_Rela outrel;
3722       asection *s;
3723       bfd_byte *rloc;
3724       bfd_vma got_address;
3725
3726       s = mips_elf_rel_dyn_section (info, FALSE);
3727       got_address = (htab->sgot->output_section->vma
3728                      + htab->sgot->output_offset
3729                      + entry->gotidx);
3730
3731       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3732       outrel.r_offset = got_address;
3733       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3734       outrel.r_addend = value;
3735       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3736     }
3737
3738   return entry;
3739 }
3740
3741 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3742    The number might be exact or a worst-case estimate, depending on how
3743    much information is available to elf_backend_omit_section_dynsym at
3744    the current linking stage.  */
3745
3746 static bfd_size_type
3747 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3748 {
3749   bfd_size_type count;
3750
3751   count = 0;
3752   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
3753     {
3754       asection *p;
3755       const struct elf_backend_data *bed;
3756
3757       bed = get_elf_backend_data (output_bfd);
3758       for (p = output_bfd->sections; p ; p = p->next)
3759         if ((p->flags & SEC_EXCLUDE) == 0
3760             && (p->flags & SEC_ALLOC) != 0
3761             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3762           ++count;
3763     }
3764   return count;
3765 }
3766
3767 /* Sort the dynamic symbol table so that symbols that need GOT entries
3768    appear towards the end.  */
3769
3770 static bfd_boolean
3771 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3772 {
3773   struct mips_elf_link_hash_table *htab;
3774   struct mips_elf_hash_sort_data hsd;
3775   struct mips_got_info *g;
3776
3777   if (elf_hash_table (info)->dynsymcount == 0)
3778     return TRUE;
3779
3780   htab = mips_elf_hash_table (info);
3781   BFD_ASSERT (htab != NULL);
3782
3783   g = htab->got_info;
3784   if (g == NULL)
3785     return TRUE;
3786
3787   hsd.low = NULL;
3788   hsd.max_unref_got_dynindx
3789     = hsd.min_got_dynindx
3790     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3791   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3792   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3793                                 elf_hash_table (info)),
3794                                mips_elf_sort_hash_table_f,
3795                                &hsd);
3796
3797   /* There should have been enough room in the symbol table to
3798      accommodate both the GOT and non-GOT symbols.  */
3799   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3800   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3801               == elf_hash_table (info)->dynsymcount);
3802   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3803               == g->global_gotno);
3804
3805   /* Now we know which dynamic symbol has the lowest dynamic symbol
3806      table index in the GOT.  */
3807   htab->global_gotsym = hsd.low;
3808
3809   return TRUE;
3810 }
3811
3812 /* If H needs a GOT entry, assign it the highest available dynamic
3813    index.  Otherwise, assign it the lowest available dynamic
3814    index.  */
3815
3816 static bfd_boolean
3817 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3818 {
3819   struct mips_elf_hash_sort_data *hsd = data;
3820
3821   /* Symbols without dynamic symbol table entries aren't interesting
3822      at all.  */
3823   if (h->root.dynindx == -1)
3824     return TRUE;
3825
3826   switch (h->global_got_area)
3827     {
3828     case GGA_NONE:
3829       h->root.dynindx = hsd->max_non_got_dynindx++;
3830       break;
3831
3832     case GGA_NORMAL:
3833       h->root.dynindx = --hsd->min_got_dynindx;
3834       hsd->low = (struct elf_link_hash_entry *) h;
3835       break;
3836
3837     case GGA_RELOC_ONLY:
3838       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3839         hsd->low = (struct elf_link_hash_entry *) h;
3840       h->root.dynindx = hsd->max_unref_got_dynindx++;
3841       break;
3842     }
3843
3844   return TRUE;
3845 }
3846
3847 /* Record that input bfd ABFD requires a GOT entry like *LOOKUP
3848    (which is owned by the caller and shouldn't be added to the
3849    hash table directly).  */
3850
3851 static bfd_boolean
3852 mips_elf_record_got_entry (struct bfd_link_info *info, bfd *abfd,
3853                            struct mips_got_entry *lookup)
3854 {
3855   struct mips_elf_link_hash_table *htab;
3856   struct mips_got_entry *entry;
3857   struct mips_got_info *g;
3858   void **loc, **bfd_loc;
3859
3860   /* Make sure there's a slot for this entry in the master GOT.  */
3861   htab = mips_elf_hash_table (info);
3862   g = htab->got_info;
3863   loc = htab_find_slot (g->got_entries, lookup, INSERT);
3864   if (!loc)
3865     return FALSE;
3866
3867   /* Populate the entry if it isn't already.  */
3868   entry = (struct mips_got_entry *) *loc;
3869   if (!entry)
3870     {
3871       entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3872       if (!entry)
3873         return FALSE;
3874
3875       lookup->tls_initialized = FALSE;
3876       lookup->gotidx = -1;
3877       *entry = *lookup;
3878       *loc = entry;
3879     }
3880
3881   /* Reuse the same GOT entry for the BFD's GOT.  */
3882   g = mips_elf_bfd_got (abfd, TRUE);
3883   if (!g)
3884     return FALSE;
3885
3886   bfd_loc = htab_find_slot (g->got_entries, lookup, INSERT);
3887   if (!bfd_loc)
3888     return FALSE;
3889
3890   if (!*bfd_loc)
3891     *bfd_loc = entry;
3892   return TRUE;
3893 }
3894
3895 /* ABFD has a GOT relocation of type R_TYPE against H.  Reserve a GOT
3896    entry for it.  FOR_CALL is true if the caller is only interested in
3897    using the GOT entry for calls.  */
3898
3899 static bfd_boolean
3900 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3901                                    bfd *abfd, struct bfd_link_info *info,
3902                                    bfd_boolean for_call, int r_type)
3903 {
3904   struct mips_elf_link_hash_table *htab;
3905   struct mips_elf_link_hash_entry *hmips;
3906   struct mips_got_entry entry;
3907   unsigned char tls_type;
3908
3909   htab = mips_elf_hash_table (info);
3910   BFD_ASSERT (htab != NULL);
3911
3912   hmips = (struct mips_elf_link_hash_entry *) h;
3913   if (!for_call)
3914     hmips->got_only_for_calls = FALSE;
3915
3916   /* A global symbol in the GOT must also be in the dynamic symbol
3917      table.  */
3918   if (h->dynindx == -1)
3919     {
3920       switch (ELF_ST_VISIBILITY (h->other))
3921         {
3922         case STV_INTERNAL:
3923         case STV_HIDDEN:
3924           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3925           break;
3926         }
3927       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3928         return FALSE;
3929     }
3930
3931   tls_type = mips_elf_reloc_tls_type (r_type);
3932   if (tls_type == GOT_TLS_NONE && hmips->global_got_area > GGA_NORMAL)
3933     hmips->global_got_area = GGA_NORMAL;
3934
3935   entry.abfd = abfd;
3936   entry.symndx = -1;
3937   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3938   entry.tls_type = tls_type;
3939   return mips_elf_record_got_entry (info, abfd, &entry);
3940 }
3941
3942 /* ABFD has a GOT relocation of type R_TYPE against symbol SYMNDX + ADDEND,
3943    where SYMNDX is a local symbol.  Reserve a GOT entry for it.  */
3944
3945 static bfd_boolean
3946 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
3947                                   struct bfd_link_info *info, int r_type)
3948 {
3949   struct mips_elf_link_hash_table *htab;
3950   struct mips_got_info *g;
3951   struct mips_got_entry entry;
3952
3953   htab = mips_elf_hash_table (info);
3954   BFD_ASSERT (htab != NULL);
3955
3956   g = htab->got_info;
3957   BFD_ASSERT (g != NULL);
3958
3959   entry.abfd = abfd;
3960   entry.symndx = symndx;
3961   entry.d.addend = addend;
3962   entry.tls_type = mips_elf_reloc_tls_type (r_type);
3963   return mips_elf_record_got_entry (info, abfd, &entry);
3964 }
3965
3966 /* Record that ABFD has a page relocation against SYMNDX + ADDEND.
3967    H is the symbol's hash table entry, or null if SYMNDX is local
3968    to ABFD.  */
3969
3970 static bfd_boolean
3971 mips_elf_record_got_page_ref (struct bfd_link_info *info, bfd *abfd,
3972                               long symndx, struct elf_link_hash_entry *h,
3973                               bfd_signed_vma addend)
3974 {
3975   struct mips_elf_link_hash_table *htab;
3976   struct mips_got_info *g1, *g2;
3977   struct mips_got_page_ref lookup, *entry;
3978   void **loc, **bfd_loc;
3979
3980   htab = mips_elf_hash_table (info);
3981   BFD_ASSERT (htab != NULL);
3982
3983   g1 = htab->got_info;
3984   BFD_ASSERT (g1 != NULL);
3985
3986   if (h)
3987     {
3988       lookup.symndx = -1;
3989       lookup.u.h = (struct mips_elf_link_hash_entry *) h;
3990     }
3991   else
3992     {
3993       lookup.symndx = symndx;
3994       lookup.u.abfd = abfd;
3995     }
3996   lookup.addend = addend;
3997   loc = htab_find_slot (g1->got_page_refs, &lookup, INSERT);
3998   if (loc == NULL)
3999     return FALSE;
4000
4001   entry = (struct mips_got_page_ref *) *loc;
4002   if (!entry)
4003     {
4004       entry = bfd_alloc (abfd, sizeof (*entry));
4005       if (!entry)
4006         return FALSE;
4007
4008       *entry = lookup;
4009       *loc = entry;
4010     }
4011
4012   /* Add the same entry to the BFD's GOT.  */
4013   g2 = mips_elf_bfd_got (abfd, TRUE);
4014   if (!g2)
4015     return FALSE;
4016
4017   bfd_loc = htab_find_slot (g2->got_page_refs, &lookup, INSERT);
4018   if (!bfd_loc)
4019     return FALSE;
4020
4021   if (!*bfd_loc)
4022     *bfd_loc = entry;
4023
4024   return TRUE;
4025 }
4026
4027 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
4028
4029 static void
4030 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
4031                                        unsigned int n)
4032 {
4033   asection *s;
4034   struct mips_elf_link_hash_table *htab;
4035
4036   htab = mips_elf_hash_table (info);
4037   BFD_ASSERT (htab != NULL);
4038
4039   s = mips_elf_rel_dyn_section (info, FALSE);
4040   BFD_ASSERT (s != NULL);
4041
4042   if (htab->is_vxworks)
4043     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
4044   else
4045     {
4046       if (s->size == 0)
4047         {
4048           /* Make room for a null element.  */
4049           s->size += MIPS_ELF_REL_SIZE (abfd);
4050           ++s->reloc_count;
4051         }
4052       s->size += n * MIPS_ELF_REL_SIZE (abfd);
4053     }
4054 }
4055 \f
4056 /* A htab_traverse callback for GOT entries, with DATA pointing to a
4057    mips_elf_traverse_got_arg structure.  Count the number of GOT
4058    entries and TLS relocs.  Set DATA->value to true if we need
4059    to resolve indirect or warning symbols and then recreate the GOT.  */
4060
4061 static int
4062 mips_elf_check_recreate_got (void **entryp, void *data)
4063 {
4064   struct mips_got_entry *entry;
4065   struct mips_elf_traverse_got_arg *arg;
4066
4067   entry = (struct mips_got_entry *) *entryp;
4068   arg = (struct mips_elf_traverse_got_arg *) data;
4069   if (entry->abfd != NULL && entry->symndx == -1)
4070     {
4071       struct mips_elf_link_hash_entry *h;
4072
4073       h = entry->d.h;
4074       if (h->root.root.type == bfd_link_hash_indirect
4075           || h->root.root.type == bfd_link_hash_warning)
4076         {
4077           arg->value = TRUE;
4078           return 0;
4079         }
4080     }
4081   mips_elf_count_got_entry (arg->info, arg->g, entry);
4082   return 1;
4083 }
4084
4085 /* A htab_traverse callback for GOT entries, with DATA pointing to a
4086    mips_elf_traverse_got_arg structure.  Add all entries to DATA->g,
4087    converting entries for indirect and warning symbols into entries
4088    for the target symbol.  Set DATA->g to null on error.  */
4089
4090 static int
4091 mips_elf_recreate_got (void **entryp, void *data)
4092 {
4093   struct mips_got_entry new_entry, *entry;
4094   struct mips_elf_traverse_got_arg *arg;
4095   void **slot;
4096
4097   entry = (struct mips_got_entry *) *entryp;
4098   arg = (struct mips_elf_traverse_got_arg *) data;
4099   if (entry->abfd != NULL
4100       && entry->symndx == -1
4101       && (entry->d.h->root.root.type == bfd_link_hash_indirect
4102           || entry->d.h->root.root.type == bfd_link_hash_warning))
4103     {
4104       struct mips_elf_link_hash_entry *h;
4105
4106       new_entry = *entry;
4107       entry = &new_entry;
4108       h = entry->d.h;
4109       do
4110         {
4111           BFD_ASSERT (h->global_got_area == GGA_NONE);
4112           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
4113         }
4114       while (h->root.root.type == bfd_link_hash_indirect
4115              || h->root.root.type == bfd_link_hash_warning);
4116       entry->d.h = h;
4117     }
4118   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
4119   if (slot == NULL)
4120     {
4121       arg->g = NULL;
4122       return 0;
4123     }
4124   if (*slot == NULL)
4125     {
4126       if (entry == &new_entry)
4127         {
4128           entry = bfd_alloc (entry->abfd, sizeof (*entry));
4129           if (!entry)
4130             {
4131               arg->g = NULL;
4132               return 0;
4133             }
4134           *entry = new_entry;
4135         }
4136       *slot = entry;
4137       mips_elf_count_got_entry (arg->info, arg->g, entry);
4138     }
4139   return 1;
4140 }
4141
4142 /* Return the maximum number of GOT page entries required for RANGE.  */
4143
4144 static bfd_vma
4145 mips_elf_pages_for_range (const struct mips_got_page_range *range)
4146 {
4147   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
4148 }
4149
4150 /* Record that G requires a page entry that can reach SEC + ADDEND.  */
4151
4152 static bfd_boolean
4153 mips_elf_record_got_page_entry (struct mips_elf_traverse_got_arg *arg,
4154                                 asection *sec, bfd_signed_vma addend)
4155 {
4156   struct mips_got_info *g = arg->g;
4157   struct mips_got_page_entry lookup, *entry;
4158   struct mips_got_page_range **range_ptr, *range;
4159   bfd_vma old_pages, new_pages;
4160   void **loc;
4161
4162   /* Find the mips_got_page_entry hash table entry for this section.  */
4163   lookup.sec = sec;
4164   loc = htab_find_slot (g->got_page_entries, &lookup, INSERT);
4165   if (loc == NULL)
4166     return FALSE;
4167
4168   /* Create a mips_got_page_entry if this is the first time we've
4169      seen the section.  */
4170   entry = (struct mips_got_page_entry *) *loc;
4171   if (!entry)
4172     {
4173       entry = bfd_zalloc (arg->info->output_bfd, sizeof (*entry));
4174       if (!entry)
4175         return FALSE;
4176
4177       entry->sec = sec;
4178       *loc = entry;
4179     }
4180
4181   /* Skip over ranges whose maximum extent cannot share a page entry
4182      with ADDEND.  */
4183   range_ptr = &entry->ranges;
4184   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
4185     range_ptr = &(*range_ptr)->next;
4186
4187   /* If we scanned to the end of the list, or found a range whose
4188      minimum extent cannot share a page entry with ADDEND, create
4189      a new singleton range.  */
4190   range = *range_ptr;
4191   if (!range || addend < range->min_addend - 0xffff)
4192     {
4193       range = bfd_zalloc (arg->info->output_bfd, sizeof (*range));
4194       if (!range)
4195         return FALSE;
4196
4197       range->next = *range_ptr;
4198       range->min_addend = addend;
4199       range->max_addend = addend;
4200
4201       *range_ptr = range;
4202       entry->num_pages++;
4203       g->page_gotno++;
4204       return TRUE;
4205     }
4206
4207   /* Remember how many pages the old range contributed.  */
4208   old_pages = mips_elf_pages_for_range (range);
4209
4210   /* Update the ranges.  */
4211   if (addend < range->min_addend)
4212     range->min_addend = addend;
4213   else if (addend > range->max_addend)
4214     {
4215       if (range->next && addend >= range->next->min_addend - 0xffff)
4216         {
4217           old_pages += mips_elf_pages_for_range (range->next);
4218           range->max_addend = range->next->max_addend;
4219           range->next = range->next->next;
4220         }
4221       else
4222         range->max_addend = addend;
4223     }
4224
4225   /* Record any change in the total estimate.  */
4226   new_pages = mips_elf_pages_for_range (range);
4227   if (old_pages != new_pages)
4228     {
4229       entry->num_pages += new_pages - old_pages;
4230       g->page_gotno += new_pages - old_pages;
4231     }
4232
4233   return TRUE;
4234 }
4235
4236 /* A htab_traverse callback for which *REFP points to a mips_got_page_ref
4237    and for which DATA points to a mips_elf_traverse_got_arg.  Work out
4238    whether the page reference described by *REFP needs a GOT page entry,
4239    and record that entry in DATA->g if so.  Set DATA->g to null on failure.  */
4240
4241 static bfd_boolean
4242 mips_elf_resolve_got_page_ref (void **refp, void *data)
4243 {
4244   struct mips_got_page_ref *ref;
4245   struct mips_elf_traverse_got_arg *arg;
4246   struct mips_elf_link_hash_table *htab;
4247   asection *sec;
4248   bfd_vma addend;
4249
4250   ref = (struct mips_got_page_ref *) *refp;
4251   arg = (struct mips_elf_traverse_got_arg *) data;
4252   htab = mips_elf_hash_table (arg->info);
4253
4254   if (ref->symndx < 0)
4255     {
4256       struct mips_elf_link_hash_entry *h;
4257
4258       /* Global GOT_PAGEs decay to GOT_DISP and so don't need page entries.  */
4259       h = ref->u.h;
4260       if (!SYMBOL_REFERENCES_LOCAL (arg->info, &h->root))
4261         return 1;
4262
4263       /* Ignore undefined symbols; we'll issue an error later if
4264          appropriate.  */
4265       if (!((h->root.root.type == bfd_link_hash_defined
4266              || h->root.root.type == bfd_link_hash_defweak)
4267             && h->root.root.u.def.section))
4268         return 1;
4269
4270       sec = h->root.root.u.def.section;
4271       addend = h->root.root.u.def.value + ref->addend;
4272     }
4273   else
4274     {
4275       Elf_Internal_Sym *isym;
4276
4277       /* Read in the symbol.  */
4278       isym = bfd_sym_from_r_symndx (&htab->sym_cache, ref->u.abfd,
4279                                     ref->symndx);
4280       if (isym == NULL)
4281         {
4282           arg->g = NULL;
4283           return 0;
4284         }
4285
4286       /* Get the associated input section.  */
4287       sec = bfd_section_from_elf_index (ref->u.abfd, isym->st_shndx);
4288       if (sec == NULL)
4289         {
4290           arg->g = NULL;
4291           return 0;
4292         }
4293
4294       /* If this is a mergable section, work out the section and offset
4295          of the merged data.  For section symbols, the addend specifies
4296          of the offset _of_ the first byte in the data, otherwise it
4297          specifies the offset _from_ the first byte.  */
4298       if (sec->flags & SEC_MERGE)
4299         {
4300           void *secinfo;
4301
4302           secinfo = elf_section_data (sec)->sec_info;
4303           if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
4304             addend = _bfd_merged_section_offset (ref->u.abfd, &sec, secinfo,
4305                                                  isym->st_value + ref->addend);
4306           else
4307             addend = _bfd_merged_section_offset (ref->u.abfd, &sec, secinfo,
4308                                                  isym->st_value) + ref->addend;
4309         }
4310       else
4311         addend = isym->st_value + ref->addend;
4312     }
4313   if (!mips_elf_record_got_page_entry (arg, sec, addend))
4314     {
4315       arg->g = NULL;
4316       return 0;
4317     }
4318   return 1;
4319 }
4320
4321 /* If any entries in G->got_entries are for indirect or warning symbols,
4322    replace them with entries for the target symbol.  Convert g->got_page_refs
4323    into got_page_entry structures and estimate the number of page entries
4324    that they require.  */
4325
4326 static bfd_boolean
4327 mips_elf_resolve_final_got_entries (struct bfd_link_info *info,
4328                                     struct mips_got_info *g)
4329 {
4330   struct mips_elf_traverse_got_arg tga;
4331   struct mips_got_info oldg;
4332
4333   oldg = *g;
4334
4335   tga.info = info;
4336   tga.g = g;
4337   tga.value = FALSE;
4338   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &tga);
4339   if (tga.value)
4340     {
4341       *g = oldg;
4342       g->got_entries = htab_create (htab_size (oldg.got_entries),
4343                                     mips_elf_got_entry_hash,
4344                                     mips_elf_got_entry_eq, NULL);
4345       if (!g->got_entries)
4346         return FALSE;
4347
4348       htab_traverse (oldg.got_entries, mips_elf_recreate_got, &tga);
4349       if (!tga.g)
4350         return FALSE;
4351
4352       htab_delete (oldg.got_entries);
4353     }
4354
4355   g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4356                                          mips_got_page_entry_eq, NULL);
4357   if (g->got_page_entries == NULL)
4358     return FALSE;
4359
4360   tga.info = info;
4361   tga.g = g;
4362   htab_traverse (g->got_page_refs, mips_elf_resolve_got_page_ref, &tga);
4363
4364   return TRUE;
4365 }
4366
4367 /* Return true if a GOT entry for H should live in the local rather than
4368    global GOT area.  */
4369
4370 static bfd_boolean
4371 mips_use_local_got_p (struct bfd_link_info *info,
4372                       struct mips_elf_link_hash_entry *h)
4373 {
4374   /* Symbols that aren't in the dynamic symbol table must live in the
4375      local GOT.  This includes symbols that are completely undefined
4376      and which therefore don't bind locally.  We'll report undefined
4377      symbols later if appropriate.  */
4378   if (h->root.dynindx == -1)
4379     return TRUE;
4380
4381   /* Symbols that bind locally can (and in the case of forced-local
4382      symbols, must) live in the local GOT.  */
4383   if (h->got_only_for_calls
4384       ? SYMBOL_CALLS_LOCAL (info, &h->root)
4385       : SYMBOL_REFERENCES_LOCAL (info, &h->root))
4386     return TRUE;
4387
4388   /* If this is an executable that must provide a definition of the symbol,
4389      either though PLTs or copy relocations, then that address should go in
4390      the local rather than global GOT.  */
4391   if (info->executable && h->has_static_relocs)
4392     return TRUE;
4393
4394   return FALSE;
4395 }
4396
4397 /* A mips_elf_link_hash_traverse callback for which DATA points to the
4398    link_info structure.  Decide whether the hash entry needs an entry in
4399    the global part of the primary GOT, setting global_got_area accordingly.
4400    Count the number of global symbols that are in the primary GOT only
4401    because they have relocations against them (reloc_only_gotno).  */
4402
4403 static int
4404 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
4405 {
4406   struct bfd_link_info *info;
4407   struct mips_elf_link_hash_table *htab;
4408   struct mips_got_info *g;
4409
4410   info = (struct bfd_link_info *) data;
4411   htab = mips_elf_hash_table (info);
4412   g = htab->got_info;
4413   if (h->global_got_area != GGA_NONE)
4414     {
4415       /* Make a final decision about whether the symbol belongs in the
4416          local or global GOT.  */
4417       if (mips_use_local_got_p (info, h))
4418         /* The symbol belongs in the local GOT.  We no longer need this
4419            entry if it was only used for relocations; those relocations
4420            will be against the null or section symbol instead of H.  */
4421         h->global_got_area = GGA_NONE;
4422       else if (htab->is_vxworks
4423                && h->got_only_for_calls
4424                && h->root.plt.plist->mips_offset != MINUS_ONE)
4425         /* On VxWorks, calls can refer directly to the .got.plt entry;
4426            they don't need entries in the regular GOT.  .got.plt entries
4427            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4428         h->global_got_area = GGA_NONE;
4429       else if (h->global_got_area == GGA_RELOC_ONLY)
4430         {
4431           g->reloc_only_gotno++;
4432           g->global_gotno++;
4433         }
4434     }
4435   return 1;
4436 }
4437 \f
4438 /* A htab_traverse callback for GOT entries.  Add each one to the GOT
4439    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4440
4441 static int
4442 mips_elf_add_got_entry (void **entryp, void *data)
4443 {
4444   struct mips_got_entry *entry;
4445   struct mips_elf_traverse_got_arg *arg;
4446   void **slot;
4447
4448   entry = (struct mips_got_entry *) *entryp;
4449   arg = (struct mips_elf_traverse_got_arg *) data;
4450   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
4451   if (!slot)
4452     {
4453       arg->g = NULL;
4454       return 0;
4455     }
4456   if (!*slot)
4457     {
4458       *slot = entry;
4459       mips_elf_count_got_entry (arg->info, arg->g, entry);
4460     }
4461   return 1;
4462 }
4463
4464 /* A htab_traverse callback for GOT page entries.  Add each one to the GOT
4465    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4466
4467 static int
4468 mips_elf_add_got_page_entry (void **entryp, void *data)
4469 {
4470   struct mips_got_page_entry *entry;
4471   struct mips_elf_traverse_got_arg *arg;
4472   void **slot;
4473
4474   entry = (struct mips_got_page_entry *) *entryp;
4475   arg = (struct mips_elf_traverse_got_arg *) data;
4476   slot = htab_find_slot (arg->g->got_page_entries, entry, INSERT);
4477   if (!slot)
4478     {
4479       arg->g = NULL;
4480       return 0;
4481     }
4482   if (!*slot)
4483     {
4484       *slot = entry;
4485       arg->g->page_gotno += entry->num_pages;
4486     }
4487   return 1;
4488 }
4489
4490 /* Consider merging FROM, which is ABFD's GOT, into TO.  Return -1 if
4491    this would lead to overflow, 1 if they were merged successfully,
4492    and 0 if a merge failed due to lack of memory.  (These values are chosen
4493    so that nonnegative return values can be returned by a htab_traverse
4494    callback.)  */
4495
4496 static int
4497 mips_elf_merge_got_with (bfd *abfd, struct mips_got_info *from,
4498                          struct mips_got_info *to,
4499                          struct mips_elf_got_per_bfd_arg *arg)
4500 {
4501   struct mips_elf_traverse_got_arg tga;
4502   unsigned int estimate;
4503
4504   /* Work out how many page entries we would need for the combined GOT.  */
4505   estimate = arg->max_pages;
4506   if (estimate >= from->page_gotno + to->page_gotno)
4507     estimate = from->page_gotno + to->page_gotno;
4508
4509   /* And conservatively estimate how many local and TLS entries
4510      would be needed.  */
4511   estimate += from->local_gotno + to->local_gotno;
4512   estimate += from->tls_gotno + to->tls_gotno;
4513
4514   /* If we're merging with the primary got, any TLS relocations will
4515      come after the full set of global entries.  Otherwise estimate those
4516      conservatively as well.  */
4517   if (to == arg->primary && from->tls_gotno + to->tls_gotno)
4518     estimate += arg->global_count;
4519   else
4520     estimate += from->global_gotno + to->global_gotno;
4521
4522   /* Bail out if the combined GOT might be too big.  */
4523   if (estimate > arg->max_count)
4524     return -1;
4525
4526   /* Transfer the bfd's got information from FROM to TO.  */
4527   tga.info = arg->info;
4528   tga.g = to;
4529   htab_traverse (from->got_entries, mips_elf_add_got_entry, &tga);
4530   if (!tga.g)
4531     return 0;
4532
4533   htab_traverse (from->got_page_entries, mips_elf_add_got_page_entry, &tga);
4534   if (!tga.g)
4535     return 0;
4536
4537   mips_elf_replace_bfd_got (abfd, to);
4538   return 1;
4539 }
4540
4541 /* Attempt to merge GOT G, which belongs to ABFD.  Try to use as much
4542    as possible of the primary got, since it doesn't require explicit
4543    dynamic relocations, but don't use bfds that would reference global
4544    symbols out of the addressable range.  Failing the primary got,
4545    attempt to merge with the current got, or finish the current got
4546    and then make make the new got current.  */
4547
4548 static bfd_boolean
4549 mips_elf_merge_got (bfd *abfd, struct mips_got_info *g,
4550                     struct mips_elf_got_per_bfd_arg *arg)
4551 {
4552   unsigned int estimate;
4553   int result;
4554
4555   if (!mips_elf_resolve_final_got_entries (arg->info, g))
4556     return FALSE;
4557
4558   /* Work out the number of page, local and TLS entries.  */
4559   estimate = arg->max_pages;
4560   if (estimate > g->page_gotno)
4561     estimate = g->page_gotno;
4562   estimate += g->local_gotno + g->tls_gotno;
4563
4564   /* We place TLS GOT entries after both locals and globals.  The globals
4565      for the primary GOT may overflow the normal GOT size limit, so be
4566      sure not to merge a GOT which requires TLS with the primary GOT in that
4567      case.  This doesn't affect non-primary GOTs.  */
4568   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4569
4570   if (estimate <= arg->max_count)
4571     {
4572       /* If we don't have a primary GOT, use it as
4573          a starting point for the primary GOT.  */
4574       if (!arg->primary)
4575         {
4576           arg->primary = g;
4577           return TRUE;
4578         }
4579
4580       /* Try merging with the primary GOT.  */
4581       result = mips_elf_merge_got_with (abfd, g, arg->primary, arg);
4582       if (result >= 0)
4583         return result;
4584     }
4585
4586   /* If we can merge with the last-created got, do it.  */
4587   if (arg->current)
4588     {
4589       result = mips_elf_merge_got_with (abfd, g, arg->current, arg);
4590       if (result >= 0)
4591         return result;
4592     }
4593
4594   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4595      fits; if it turns out that it doesn't, we'll get relocation
4596      overflows anyway.  */
4597   g->next = arg->current;
4598   arg->current = g;
4599
4600   return TRUE;
4601 }
4602
4603 /* ENTRYP is a hash table entry for a mips_got_entry.  Set its gotidx
4604    to GOTIDX, duplicating the entry if it has already been assigned
4605    an index in a different GOT.  */
4606
4607 static bfd_boolean
4608 mips_elf_set_gotidx (void **entryp, long gotidx)
4609 {
4610   struct mips_got_entry *entry;
4611
4612   entry = (struct mips_got_entry *) *entryp;
4613   if (entry->gotidx > 0)
4614     {
4615       struct mips_got_entry *new_entry;
4616
4617       new_entry = bfd_alloc (entry->abfd, sizeof (*entry));
4618       if (!new_entry)
4619         return FALSE;
4620
4621       *new_entry = *entry;
4622       *entryp = new_entry;
4623       entry = new_entry;
4624     }
4625   entry->gotidx = gotidx;
4626   return TRUE;
4627 }
4628
4629 /* Set the TLS GOT index for the GOT entry in ENTRYP.  DATA points to a
4630    mips_elf_traverse_got_arg in which DATA->value is the size of one
4631    GOT entry.  Set DATA->g to null on failure.  */
4632
4633 static int
4634 mips_elf_initialize_tls_index (void **entryp, void *data)
4635 {
4636   struct mips_got_entry *entry;
4637   struct mips_elf_traverse_got_arg *arg;
4638
4639   /* We're only interested in TLS symbols.  */
4640   entry = (struct mips_got_entry *) *entryp;
4641   if (entry->tls_type == GOT_TLS_NONE)
4642     return 1;
4643
4644   arg = (struct mips_elf_traverse_got_arg *) data;
4645   if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->tls_assigned_gotno))
4646     {
4647       arg->g = NULL;
4648       return 0;
4649     }
4650
4651   /* Account for the entries we've just allocated.  */
4652   arg->g->tls_assigned_gotno += mips_tls_got_entries (entry->tls_type);
4653   return 1;
4654 }
4655
4656 /* A htab_traverse callback for GOT entries, where DATA points to a
4657    mips_elf_traverse_got_arg.  Set the global_got_area of each global
4658    symbol to DATA->value.  */
4659
4660 static int
4661 mips_elf_set_global_got_area (void **entryp, void *data)
4662 {
4663   struct mips_got_entry *entry;
4664   struct mips_elf_traverse_got_arg *arg;
4665
4666   entry = (struct mips_got_entry *) *entryp;
4667   arg = (struct mips_elf_traverse_got_arg *) data;
4668   if (entry->abfd != NULL
4669       && entry->symndx == -1
4670       && entry->d.h->global_got_area != GGA_NONE)
4671     entry->d.h->global_got_area = arg->value;
4672   return 1;
4673 }
4674
4675 /* A htab_traverse callback for secondary GOT entries, where DATA points
4676    to a mips_elf_traverse_got_arg.  Assign GOT indices to global entries
4677    and record the number of relocations they require.  DATA->value is
4678    the size of one GOT entry.  Set DATA->g to null on failure.  */
4679
4680 static int
4681 mips_elf_set_global_gotidx (void **entryp, void *data)
4682 {
4683   struct mips_got_entry *entry;
4684   struct mips_elf_traverse_got_arg *arg;
4685
4686   entry = (struct mips_got_entry *) *entryp;
4687   arg = (struct mips_elf_traverse_got_arg *) data;
4688   if (entry->abfd != NULL
4689       && entry->symndx == -1
4690       && entry->d.h->global_got_area != GGA_NONE)
4691     {
4692       if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->assigned_low_gotno))
4693         {
4694           arg->g = NULL;
4695           return 0;
4696         }
4697       arg->g->assigned_low_gotno += 1;
4698
4699       if (arg->info->shared
4700           || (elf_hash_table (arg->info)->dynamic_sections_created
4701               && entry->d.h->root.def_dynamic
4702               && !entry->d.h->root.def_regular))
4703         arg->g->relocs += 1;
4704     }
4705
4706   return 1;
4707 }
4708
4709 /* A htab_traverse callback for GOT entries for which DATA is the
4710    bfd_link_info.  Forbid any global symbols from having traditional
4711    lazy-binding stubs.  */
4712
4713 static int
4714 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4715 {
4716   struct bfd_link_info *info;
4717   struct mips_elf_link_hash_table *htab;
4718   struct mips_got_entry *entry;
4719
4720   entry = (struct mips_got_entry *) *entryp;
4721   info = (struct bfd_link_info *) data;
4722   htab = mips_elf_hash_table (info);
4723   BFD_ASSERT (htab != NULL);
4724
4725   if (entry->abfd != NULL
4726       && entry->symndx == -1
4727       && entry->d.h->needs_lazy_stub)
4728     {
4729       entry->d.h->needs_lazy_stub = FALSE;
4730       htab->lazy_stub_count--;
4731     }
4732
4733   return 1;
4734 }
4735
4736 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4737    the primary GOT.  */
4738 static bfd_vma
4739 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4740 {
4741   if (!g->next)
4742     return 0;
4743
4744   g = mips_elf_bfd_got (ibfd, FALSE);
4745   if (! g)
4746     return 0;
4747
4748   BFD_ASSERT (g->next);
4749
4750   g = g->next;
4751
4752   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4753     * MIPS_ELF_GOT_SIZE (abfd);
4754 }
4755
4756 /* Turn a single GOT that is too big for 16-bit addressing into
4757    a sequence of GOTs, each one 16-bit addressable.  */
4758
4759 static bfd_boolean
4760 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4761                     asection *got, bfd_size_type pages)
4762 {
4763   struct mips_elf_link_hash_table *htab;
4764   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4765   struct mips_elf_traverse_got_arg tga;
4766   struct mips_got_info *g, *gg;
4767   unsigned int assign, needed_relocs;
4768   bfd *dynobj, *ibfd;
4769
4770   dynobj = elf_hash_table (info)->dynobj;
4771   htab = mips_elf_hash_table (info);
4772   BFD_ASSERT (htab != NULL);
4773
4774   g = htab->got_info;
4775
4776   got_per_bfd_arg.obfd = abfd;
4777   got_per_bfd_arg.info = info;
4778   got_per_bfd_arg.current = NULL;
4779   got_per_bfd_arg.primary = NULL;
4780   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4781                                 / MIPS_ELF_GOT_SIZE (abfd))
4782                                - htab->reserved_gotno);
4783   got_per_bfd_arg.max_pages = pages;
4784   /* The number of globals that will be included in the primary GOT.
4785      See the calls to mips_elf_set_global_got_area below for more
4786      information.  */
4787   got_per_bfd_arg.global_count = g->global_gotno;
4788
4789   /* Try to merge the GOTs of input bfds together, as long as they
4790      don't seem to exceed the maximum GOT size, choosing one of them
4791      to be the primary GOT.  */
4792   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
4793     {
4794       gg = mips_elf_bfd_got (ibfd, FALSE);
4795       if (gg && !mips_elf_merge_got (ibfd, gg, &got_per_bfd_arg))
4796         return FALSE;
4797     }
4798
4799   /* If we do not find any suitable primary GOT, create an empty one.  */
4800   if (got_per_bfd_arg.primary == NULL)
4801     g->next = mips_elf_create_got_info (abfd);
4802   else
4803     g->next = got_per_bfd_arg.primary;
4804   g->next->next = got_per_bfd_arg.current;
4805
4806   /* GG is now the master GOT, and G is the primary GOT.  */
4807   gg = g;
4808   g = g->next;
4809
4810   /* Map the output bfd to the primary got.  That's what we're going
4811      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4812      didn't mark in check_relocs, and we want a quick way to find it.
4813      We can't just use gg->next because we're going to reverse the
4814      list.  */
4815   mips_elf_replace_bfd_got (abfd, g);
4816
4817   /* Every symbol that is referenced in a dynamic relocation must be
4818      present in the primary GOT, so arrange for them to appear after
4819      those that are actually referenced.  */
4820   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4821   g->global_gotno = gg->global_gotno;
4822
4823   tga.info = info;
4824   tga.value = GGA_RELOC_ONLY;
4825   htab_traverse (gg->got_entries, mips_elf_set_global_got_area, &tga);
4826   tga.value = GGA_NORMAL;
4827   htab_traverse (g->got_entries, mips_elf_set_global_got_area, &tga);
4828
4829   /* Now go through the GOTs assigning them offset ranges.
4830      [assigned_low_gotno, local_gotno[ will be set to the range of local
4831      entries in each GOT.  We can then compute the end of a GOT by
4832      adding local_gotno to global_gotno.  We reverse the list and make
4833      it circular since then we'll be able to quickly compute the
4834      beginning of a GOT, by computing the end of its predecessor.  To
4835      avoid special cases for the primary GOT, while still preserving
4836      assertions that are valid for both single- and multi-got links,
4837      we arrange for the main got struct to have the right number of
4838      global entries, but set its local_gotno such that the initial
4839      offset of the primary GOT is zero.  Remember that the primary GOT
4840      will become the last item in the circular linked list, so it
4841      points back to the master GOT.  */
4842   gg->local_gotno = -g->global_gotno;
4843   gg->global_gotno = g->global_gotno;
4844   gg->tls_gotno = 0;
4845   assign = 0;
4846   gg->next = gg;
4847
4848   do
4849     {
4850       struct mips_got_info *gn;
4851
4852       assign += htab->reserved_gotno;
4853       g->assigned_low_gotno = assign;
4854       g->local_gotno += assign;
4855       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4856       g->assigned_high_gotno = g->local_gotno - 1;
4857       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4858
4859       /* Take g out of the direct list, and push it onto the reversed
4860          list that gg points to.  g->next is guaranteed to be nonnull after
4861          this operation, as required by mips_elf_initialize_tls_index. */
4862       gn = g->next;
4863       g->next = gg->next;
4864       gg->next = g;
4865
4866       /* Set up any TLS entries.  We always place the TLS entries after
4867          all non-TLS entries.  */
4868       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4869       tga.g = g;
4870       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4871       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
4872       if (!tga.g)
4873         return FALSE;
4874       BFD_ASSERT (g->tls_assigned_gotno == assign);
4875
4876       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4877       g = gn;
4878
4879       /* Forbid global symbols in every non-primary GOT from having
4880          lazy-binding stubs.  */
4881       if (g)
4882         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4883     }
4884   while (g);
4885
4886   got->size = assign * MIPS_ELF_GOT_SIZE (abfd);
4887
4888   needed_relocs = 0;
4889   for (g = gg->next; g && g->next != gg; g = g->next)
4890     {
4891       unsigned int save_assign;
4892
4893       /* Assign offsets to global GOT entries and count how many
4894          relocations they need.  */
4895       save_assign = g->assigned_low_gotno;
4896       g->assigned_low_gotno = g->local_gotno;
4897       tga.info = info;
4898       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4899       tga.g = g;
4900       htab_traverse (g->got_entries, mips_elf_set_global_gotidx, &tga);
4901       if (!tga.g)
4902         return FALSE;
4903       BFD_ASSERT (g->assigned_low_gotno == g->local_gotno + g->global_gotno);
4904       g->assigned_low_gotno = save_assign;
4905
4906       if (info->shared)
4907         {
4908           g->relocs += g->local_gotno - g->assigned_low_gotno;
4909           BFD_ASSERT (g->assigned_low_gotno == g->next->local_gotno
4910                       + g->next->global_gotno
4911                       + g->next->tls_gotno
4912                       + htab->reserved_gotno);
4913         }
4914       needed_relocs += g->relocs;
4915     }
4916   needed_relocs += g->relocs;
4917
4918   if (needed_relocs)
4919     mips_elf_allocate_dynamic_relocations (dynobj, info,
4920                                            needed_relocs);
4921
4922   return TRUE;
4923 }
4924
4925 \f
4926 /* Returns the first relocation of type r_type found, beginning with
4927    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4928
4929 static const Elf_Internal_Rela *
4930 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4931                           const Elf_Internal_Rela *relocation,
4932                           const Elf_Internal_Rela *relend)
4933 {
4934   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4935
4936   while (relocation < relend)
4937     {
4938       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4939           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4940         return relocation;
4941
4942       ++relocation;
4943     }
4944
4945   /* We didn't find it.  */
4946   return NULL;
4947 }
4948
4949 /* Return whether an input relocation is against a local symbol.  */
4950
4951 static bfd_boolean
4952 mips_elf_local_relocation_p (bfd *input_bfd,
4953                              const Elf_Internal_Rela *relocation,
4954                              asection **local_sections)
4955 {
4956   unsigned long r_symndx;
4957   Elf_Internal_Shdr *symtab_hdr;
4958   size_t extsymoff;
4959
4960   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4961   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4962   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
4963
4964   if (r_symndx < extsymoff)
4965     return TRUE;
4966   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
4967     return TRUE;
4968
4969   return FALSE;
4970 }
4971 \f
4972 /* Sign-extend VALUE, which has the indicated number of BITS.  */
4973
4974 bfd_vma
4975 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
4976 {
4977   if (value & ((bfd_vma) 1 << (bits - 1)))
4978     /* VALUE is negative.  */
4979     value |= ((bfd_vma) - 1) << bits;
4980
4981   return value;
4982 }
4983
4984 /* Return non-zero if the indicated VALUE has overflowed the maximum
4985    range expressible by a signed number with the indicated number of
4986    BITS.  */
4987
4988 static bfd_boolean
4989 mips_elf_overflow_p (bfd_vma value, int bits)
4990 {
4991   bfd_signed_vma svalue = (bfd_signed_vma) value;
4992
4993   if (svalue > (1 << (bits - 1)) - 1)
4994     /* The value is too big.  */
4995     return TRUE;
4996   else if (svalue < -(1 << (bits - 1)))
4997     /* The value is too small.  */
4998     return TRUE;
4999
5000   /* All is well.  */
5001   return FALSE;
5002 }
5003
5004 /* Calculate the %high function.  */
5005
5006 static bfd_vma
5007 mips_elf_high (bfd_vma value)
5008 {
5009   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
5010 }
5011
5012 /* Calculate the %higher function.  */
5013
5014 static bfd_vma
5015 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
5016 {
5017 #ifdef BFD64
5018   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
5019 #else
5020   abort ();
5021   return MINUS_ONE;
5022 #endif
5023 }
5024
5025 /* Calculate the %highest function.  */
5026
5027 static bfd_vma
5028 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
5029 {
5030 #ifdef BFD64
5031   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
5032 #else
5033   abort ();
5034   return MINUS_ONE;
5035 #endif
5036 }
5037 \f
5038 /* Create the .compact_rel section.  */
5039
5040 static bfd_boolean
5041 mips_elf_create_compact_rel_section
5042   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
5043 {
5044   flagword flags;
5045   register asection *s;
5046
5047   if (bfd_get_linker_section (abfd, ".compact_rel") == NULL)
5048     {
5049       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
5050                | SEC_READONLY);
5051
5052       s = bfd_make_section_anyway_with_flags (abfd, ".compact_rel", flags);
5053       if (s == NULL
5054           || ! bfd_set_section_alignment (abfd, s,
5055                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
5056         return FALSE;
5057
5058       s->size = sizeof (Elf32_External_compact_rel);
5059     }
5060
5061   return TRUE;
5062 }
5063
5064 /* Create the .got section to hold the global offset table.  */
5065
5066 static bfd_boolean
5067 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
5068 {
5069   flagword flags;
5070   register asection *s;
5071   struct elf_link_hash_entry *h;
5072   struct bfd_link_hash_entry *bh;
5073   struct mips_elf_link_hash_table *htab;
5074
5075   htab = mips_elf_hash_table (info);
5076   BFD_ASSERT (htab != NULL);
5077
5078   /* This function may be called more than once.  */
5079   if (htab->sgot)
5080     return TRUE;
5081
5082   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
5083            | SEC_LINKER_CREATED);
5084
5085   /* We have to use an alignment of 2**4 here because this is hardcoded
5086      in the function stub generation and in the linker script.  */
5087   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
5088   if (s == NULL
5089       || ! bfd_set_section_alignment (abfd, s, 4))
5090     return FALSE;
5091   htab->sgot = s;
5092
5093   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
5094      linker script because we don't want to define the symbol if we
5095      are not creating a global offset table.  */
5096   bh = NULL;
5097   if (! (_bfd_generic_link_add_one_symbol
5098          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
5099           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
5100     return FALSE;
5101
5102   h = (struct elf_link_hash_entry *) bh;
5103   h->non_elf = 0;
5104   h->def_regular = 1;
5105   h->type = STT_OBJECT;
5106   h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
5107   elf_hash_table (info)->hgot = h;
5108
5109   if (info->shared
5110       && ! bfd_elf_link_record_dynamic_symbol (info, h))
5111     return FALSE;
5112
5113   htab->got_info = mips_elf_create_got_info (abfd);
5114   mips_elf_section_data (s)->elf.this_hdr.sh_flags
5115     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
5116
5117   /* We also need a .got.plt section when generating PLTs.  */
5118   s = bfd_make_section_anyway_with_flags (abfd, ".got.plt",
5119                                           SEC_ALLOC | SEC_LOAD
5120                                           | SEC_HAS_CONTENTS
5121                                           | SEC_IN_MEMORY
5122                                           | SEC_LINKER_CREATED);
5123   if (s == NULL)
5124     return FALSE;
5125   htab->sgotplt = s;
5126
5127   return TRUE;
5128 }
5129 \f
5130 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
5131    __GOTT_INDEX__ symbols.  These symbols are only special for
5132    shared objects; they are not used in executables.  */
5133
5134 static bfd_boolean
5135 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
5136 {
5137   return (mips_elf_hash_table (info)->is_vxworks
5138           && info->shared
5139           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
5140               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
5141 }
5142
5143 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
5144    require an la25 stub.  See also mips_elf_local_pic_function_p,
5145    which determines whether the destination function ever requires a
5146    stub.  */
5147
5148 static bfd_boolean
5149 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type,
5150                                      bfd_boolean target_is_16_bit_code_p)
5151 {
5152   /* We specifically ignore branches and jumps from EF_PIC objects,
5153      where the onus is on the compiler or programmer to perform any
5154      necessary initialization of $25.  Sometimes such initialization
5155      is unnecessary; for example, -mno-shared functions do not use
5156      the incoming value of $25, and may therefore be called directly.  */
5157   if (PIC_OBJECT_P (input_bfd))
5158     return FALSE;
5159
5160   switch (r_type)
5161     {
5162     case R_MIPS_26:
5163     case R_MIPS_PC16:
5164     case R_MICROMIPS_26_S1:
5165     case R_MICROMIPS_PC7_S1:
5166     case R_MICROMIPS_PC10_S1:
5167     case R_MICROMIPS_PC16_S1:
5168     case R_MICROMIPS_PC23_S2:
5169       return TRUE;
5170
5171     case R_MIPS16_26:
5172       return !target_is_16_bit_code_p;
5173
5174     default:
5175       return FALSE;
5176     }
5177 }
5178 \f
5179 /* Calculate the value produced by the RELOCATION (which comes from
5180    the INPUT_BFD).  The ADDEND is the addend to use for this
5181    RELOCATION; RELOCATION->R_ADDEND is ignored.
5182
5183    The result of the relocation calculation is stored in VALUEP.
5184    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
5185    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5186
5187    This function returns bfd_reloc_continue if the caller need take no
5188    further action regarding this relocation, bfd_reloc_notsupported if
5189    something goes dramatically wrong, bfd_reloc_overflow if an
5190    overflow occurs, and bfd_reloc_ok to indicate success.  */
5191
5192 static bfd_reloc_status_type
5193 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
5194                                asection *input_section,
5195                                struct bfd_link_info *info,
5196                                const Elf_Internal_Rela *relocation,
5197                                bfd_vma addend, reloc_howto_type *howto,
5198                                Elf_Internal_Sym *local_syms,
5199                                asection **local_sections, bfd_vma *valuep,
5200                                const char **namep,
5201                                bfd_boolean *cross_mode_jump_p,
5202                                bfd_boolean save_addend)
5203 {
5204   /* The eventual value we will return.  */
5205   bfd_vma value;
5206   /* The address of the symbol against which the relocation is
5207      occurring.  */
5208   bfd_vma symbol = 0;
5209   /* The final GP value to be used for the relocatable, executable, or
5210      shared object file being produced.  */
5211   bfd_vma gp;
5212   /* The place (section offset or address) of the storage unit being
5213      relocated.  */
5214   bfd_vma p;
5215   /* The value of GP used to create the relocatable object.  */
5216   bfd_vma gp0;
5217   /* The offset into the global offset table at which the address of
5218      the relocation entry symbol, adjusted by the addend, resides
5219      during execution.  */
5220   bfd_vma g = MINUS_ONE;
5221   /* The section in which the symbol referenced by the relocation is
5222      located.  */
5223   asection *sec = NULL;
5224   struct mips_elf_link_hash_entry *h = NULL;
5225   /* TRUE if the symbol referred to by this relocation is a local
5226      symbol.  */
5227   bfd_boolean local_p, was_local_p;
5228   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
5229   bfd_boolean gp_disp_p = FALSE;
5230   /* TRUE if the symbol referred to by this relocation is
5231      "__gnu_local_gp".  */
5232   bfd_boolean gnu_local_gp_p = FALSE;
5233   Elf_Internal_Shdr *symtab_hdr;
5234   size_t extsymoff;
5235   unsigned long r_symndx;
5236   int r_type;
5237   /* TRUE if overflow occurred during the calculation of the
5238      relocation value.  */
5239   bfd_boolean overflowed_p;
5240   /* TRUE if this relocation refers to a MIPS16 function.  */
5241   bfd_boolean target_is_16_bit_code_p = FALSE;
5242   bfd_boolean target_is_micromips_code_p = FALSE;
5243   struct mips_elf_link_hash_table *htab;
5244   bfd *dynobj;
5245
5246   dynobj = elf_hash_table (info)->dynobj;
5247   htab = mips_elf_hash_table (info);
5248   BFD_ASSERT (htab != NULL);
5249
5250   /* Parse the relocation.  */
5251   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
5252   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5253   p = (input_section->output_section->vma
5254        + input_section->output_offset
5255        + relocation->r_offset);
5256
5257   /* Assume that there will be no overflow.  */
5258   overflowed_p = FALSE;
5259
5260   /* Figure out whether or not the symbol is local, and get the offset
5261      used in the array of hash table entries.  */
5262   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
5263   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
5264                                          local_sections);
5265   was_local_p = local_p;
5266   if (! elf_bad_symtab (input_bfd))
5267     extsymoff = symtab_hdr->sh_info;
5268   else
5269     {
5270       /* The symbol table does not follow the rule that local symbols
5271          must come before globals.  */
5272       extsymoff = 0;
5273     }
5274
5275   /* Figure out the value of the symbol.  */
5276   if (local_p)
5277     {
5278       Elf_Internal_Sym *sym;
5279
5280       sym = local_syms + r_symndx;
5281       sec = local_sections[r_symndx];
5282
5283       symbol = sec->output_section->vma + sec->output_offset;
5284       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION
5285           || (sec->flags & SEC_MERGE))
5286         symbol += sym->st_value;
5287       if ((sec->flags & SEC_MERGE)
5288           && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
5289         {
5290           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
5291           addend -= symbol;
5292           addend += sec->output_section->vma + sec->output_offset;
5293         }
5294
5295       /* MIPS16/microMIPS text labels should be treated as odd.  */
5296       if (ELF_ST_IS_COMPRESSED (sym->st_other))
5297         ++symbol;
5298
5299       /* Record the name of this symbol, for our caller.  */
5300       *namep = bfd_elf_string_from_elf_section (input_bfd,
5301                                                 symtab_hdr->sh_link,
5302                                                 sym->st_name);
5303       if (*namep == '\0')
5304         *namep = bfd_section_name (input_bfd, sec);
5305
5306       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
5307       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
5308     }
5309   else
5310     {
5311       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
5312
5313       /* For global symbols we look up the symbol in the hash-table.  */
5314       h = ((struct mips_elf_link_hash_entry *)
5315            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
5316       /* Find the real hash-table entry for this symbol.  */
5317       while (h->root.root.type == bfd_link_hash_indirect
5318              || h->root.root.type == bfd_link_hash_warning)
5319         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
5320
5321       /* Record the name of this symbol, for our caller.  */
5322       *namep = h->root.root.root.string;
5323
5324       /* See if this is the special _gp_disp symbol.  Note that such a
5325          symbol must always be a global symbol.  */
5326       if (strcmp (*namep, "_gp_disp") == 0
5327           && ! NEWABI_P (input_bfd))
5328         {
5329           /* Relocations against _gp_disp are permitted only with
5330              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
5331           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
5332             return bfd_reloc_notsupported;
5333
5334           gp_disp_p = TRUE;
5335         }
5336       /* See if this is the special _gp symbol.  Note that such a
5337          symbol must always be a global symbol.  */
5338       else if (strcmp (*namep, "__gnu_local_gp") == 0)
5339         gnu_local_gp_p = TRUE;
5340
5341
5342       /* If this symbol is defined, calculate its address.  Note that
5343          _gp_disp is a magic symbol, always implicitly defined by the
5344          linker, so it's inappropriate to check to see whether or not
5345          its defined.  */
5346       else if ((h->root.root.type == bfd_link_hash_defined
5347                 || h->root.root.type == bfd_link_hash_defweak)
5348                && h->root.root.u.def.section)
5349         {
5350           sec = h->root.root.u.def.section;
5351           if (sec->output_section)
5352             symbol = (h->root.root.u.def.value
5353                       + sec->output_section->vma
5354                       + sec->output_offset);
5355           else
5356             symbol = h->root.root.u.def.value;
5357         }
5358       else if (h->root.root.type == bfd_link_hash_undefweak)
5359         /* We allow relocations against undefined weak symbols, giving
5360            it the value zero, so that you can undefined weak functions
5361            and check to see if they exist by looking at their
5362            addresses.  */
5363         symbol = 0;
5364       else if (info->unresolved_syms_in_objects == RM_IGNORE
5365                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5366         symbol = 0;
5367       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
5368                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
5369         {
5370           /* If this is a dynamic link, we should have created a
5371              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
5372              in in _bfd_mips_elf_create_dynamic_sections.
5373              Otherwise, we should define the symbol with a value of 0.
5374              FIXME: It should probably get into the symbol table
5375              somehow as well.  */
5376           BFD_ASSERT (! info->shared);
5377           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
5378           symbol = 0;
5379         }
5380       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
5381         {
5382           /* This is an optional symbol - an Irix specific extension to the
5383              ELF spec.  Ignore it for now.
5384              XXX - FIXME - there is more to the spec for OPTIONAL symbols
5385              than simply ignoring them, but we do not handle this for now.
5386              For information see the "64-bit ELF Object File Specification"
5387              which is available from here:
5388              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
5389           symbol = 0;
5390         }
5391       else if ((*info->callbacks->undefined_symbol)
5392                (info, h->root.root.root.string, input_bfd,
5393                 input_section, relocation->r_offset,
5394                 (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
5395                  || ELF_ST_VISIBILITY (h->root.other)))
5396         {
5397           return bfd_reloc_undefined;
5398         }
5399       else
5400         {
5401           return bfd_reloc_notsupported;
5402         }
5403
5404       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
5405       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (h->root.other);
5406     }
5407
5408   /* If this is a reference to a 16-bit function with a stub, we need
5409      to redirect the relocation to the stub unless:
5410
5411      (a) the relocation is for a MIPS16 JAL;
5412
5413      (b) the relocation is for a MIPS16 PIC call, and there are no
5414          non-MIPS16 uses of the GOT slot; or
5415
5416      (c) the section allows direct references to MIPS16 functions.  */
5417   if (r_type != R_MIPS16_26
5418       && !info->relocatable
5419       && ((h != NULL
5420            && h->fn_stub != NULL
5421            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5422           || (local_p
5423               && mips_elf_tdata (input_bfd)->local_stubs != NULL
5424               && mips_elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5425       && !section_allows_mips16_refs_p (input_section))
5426     {
5427       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5428          have already noticed that we were going to need the
5429          stub.  */
5430       if (local_p)
5431         {
5432           sec = mips_elf_tdata (input_bfd)->local_stubs[r_symndx];
5433           value = 0;
5434         }
5435       else
5436         {
5437           BFD_ASSERT (h->need_fn_stub);
5438           if (h->la25_stub)
5439             {
5440               /* If a LA25 header for the stub itself exists, point to the
5441                  prepended LUI/ADDIU sequence.  */
5442               sec = h->la25_stub->stub_section;
5443               value = h->la25_stub->offset;
5444             }
5445           else
5446             {
5447               sec = h->fn_stub;
5448               value = 0;
5449             }
5450         }
5451
5452       symbol = sec->output_section->vma + sec->output_offset + value;
5453       /* The target is 16-bit, but the stub isn't.  */
5454       target_is_16_bit_code_p = FALSE;
5455     }
5456   /* If this is a MIPS16 call with a stub, that is made through the PLT or
5457      to a standard MIPS function, we need to redirect the call to the stub.
5458      Note that we specifically exclude R_MIPS16_CALL16 from this behavior;
5459      indirect calls should use an indirect stub instead.  */
5460   else if (r_type == R_MIPS16_26 && !info->relocatable
5461            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5462                || (local_p
5463                    && mips_elf_tdata (input_bfd)->local_call_stubs != NULL
5464                    && mips_elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5465            && ((h != NULL && h->use_plt_entry) || !target_is_16_bit_code_p))
5466     {
5467       if (local_p)
5468         sec = mips_elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5469       else
5470         {
5471           /* If both call_stub and call_fp_stub are defined, we can figure
5472              out which one to use by checking which one appears in the input
5473              file.  */
5474           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5475             {
5476               asection *o;
5477
5478               sec = NULL;
5479               for (o = input_bfd->sections; o != NULL; o = o->next)
5480                 {
5481                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5482                     {
5483                       sec = h->call_fp_stub;
5484                       break;
5485                     }
5486                 }
5487               if (sec == NULL)
5488                 sec = h->call_stub;
5489             }
5490           else if (h->call_stub != NULL)
5491             sec = h->call_stub;
5492           else
5493             sec = h->call_fp_stub;
5494         }
5495
5496       BFD_ASSERT (sec->size > 0);
5497       symbol = sec->output_section->vma + sec->output_offset;
5498     }
5499   /* If this is a direct call to a PIC function, redirect to the
5500      non-PIC stub.  */
5501   else if (h != NULL && h->la25_stub
5502            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type,
5503                                                    target_is_16_bit_code_p))
5504     symbol = (h->la25_stub->stub_section->output_section->vma
5505               + h->la25_stub->stub_section->output_offset
5506               + h->la25_stub->offset);
5507   /* For direct MIPS16 and microMIPS calls make sure the compressed PLT
5508      entry is used if a standard PLT entry has also been made.  In this
5509      case the symbol will have been set by mips_elf_set_plt_sym_value
5510      to point to the standard PLT entry, so redirect to the compressed
5511      one.  */
5512   else if ((r_type == R_MIPS16_26 || r_type == R_MICROMIPS_26_S1)
5513            && !info->relocatable
5514            && h != NULL
5515            && h->use_plt_entry
5516            && h->root.plt.plist->comp_offset != MINUS_ONE
5517            && h->root.plt.plist->mips_offset != MINUS_ONE)
5518     {
5519       bfd_boolean micromips_p = MICROMIPS_P (abfd);
5520
5521       sec = htab->splt;
5522       symbol = (sec->output_section->vma
5523                 + sec->output_offset
5524                 + htab->plt_header_size
5525                 + htab->plt_mips_offset
5526                 + h->root.plt.plist->comp_offset
5527                 + 1);
5528
5529       target_is_16_bit_code_p = !micromips_p;
5530       target_is_micromips_code_p = micromips_p;
5531     }
5532
5533   /* Make sure MIPS16 and microMIPS are not used together.  */
5534   if ((r_type == R_MIPS16_26 && target_is_micromips_code_p)
5535       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5536    {
5537       (*_bfd_error_handler)
5538         (_("MIPS16 and microMIPS functions cannot call each other"));
5539       return bfd_reloc_notsupported;
5540    }
5541
5542   /* Calls from 16-bit code to 32-bit code and vice versa require the
5543      mode change.  However, we can ignore calls to undefined weak symbols,
5544      which should never be executed at runtime.  This exception is important
5545      because the assembly writer may have "known" that any definition of the
5546      symbol would be 16-bit code, and that direct jumps were therefore
5547      acceptable.  */
5548   *cross_mode_jump_p = (!info->relocatable
5549                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5550                         && ((r_type == R_MIPS16_26 && !target_is_16_bit_code_p)
5551                             || (r_type == R_MICROMIPS_26_S1
5552                                 && !target_is_micromips_code_p)
5553                             || ((r_type == R_MIPS_26 || r_type == R_MIPS_JALR)
5554                                 && (target_is_16_bit_code_p
5555                                     || target_is_micromips_code_p))));
5556
5557   local_p = (h == NULL || mips_use_local_got_p (info, h));
5558
5559   gp0 = _bfd_get_gp_value (input_bfd);
5560   gp = _bfd_get_gp_value (abfd);
5561   if (htab->got_info)
5562     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5563
5564   if (gnu_local_gp_p)
5565     symbol = gp;
5566
5567   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5568      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5569      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5570   if (got_page_reloc_p (r_type) && !local_p)
5571     {
5572       r_type = (micromips_reloc_p (r_type)
5573                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5574       addend = 0;
5575     }
5576
5577   /* If we haven't already determined the GOT offset, and we're going
5578      to need it, get it now.  */
5579   switch (r_type)
5580     {
5581     case R_MIPS16_CALL16:
5582     case R_MIPS16_GOT16:
5583     case R_MIPS_CALL16:
5584     case R_MIPS_GOT16:
5585     case R_MIPS_GOT_DISP:
5586     case R_MIPS_GOT_HI16:
5587     case R_MIPS_CALL_HI16:
5588     case R_MIPS_GOT_LO16:
5589     case R_MIPS_CALL_LO16:
5590     case R_MICROMIPS_CALL16:
5591     case R_MICROMIPS_GOT16:
5592     case R_MICROMIPS_GOT_DISP:
5593     case R_MICROMIPS_GOT_HI16:
5594     case R_MICROMIPS_CALL_HI16:
5595     case R_MICROMIPS_GOT_LO16:
5596     case R_MICROMIPS_CALL_LO16:
5597     case R_MIPS_TLS_GD:
5598     case R_MIPS_TLS_GOTTPREL:
5599     case R_MIPS_TLS_LDM:
5600     case R_MIPS16_TLS_GD:
5601     case R_MIPS16_TLS_GOTTPREL:
5602     case R_MIPS16_TLS_LDM:
5603     case R_MICROMIPS_TLS_GD:
5604     case R_MICROMIPS_TLS_GOTTPREL:
5605     case R_MICROMIPS_TLS_LDM:
5606       /* Find the index into the GOT where this value is located.  */
5607       if (tls_ldm_reloc_p (r_type))
5608         {
5609           g = mips_elf_local_got_index (abfd, input_bfd, info,
5610                                         0, 0, NULL, r_type);
5611           if (g == MINUS_ONE)
5612             return bfd_reloc_outofrange;
5613         }
5614       else if (!local_p)
5615         {
5616           /* On VxWorks, CALL relocations should refer to the .got.plt
5617              entry, which is initialized to point at the PLT stub.  */
5618           if (htab->is_vxworks
5619               && (call_hi16_reloc_p (r_type)
5620                   || call_lo16_reloc_p (r_type)
5621                   || call16_reloc_p (r_type)))
5622             {
5623               BFD_ASSERT (addend == 0);
5624               BFD_ASSERT (h->root.needs_plt);
5625               g = mips_elf_gotplt_index (info, &h->root);
5626             }
5627           else
5628             {
5629               BFD_ASSERT (addend == 0);
5630               g = mips_elf_global_got_index (abfd, info, input_bfd,
5631                                              &h->root, r_type);
5632               if (!TLS_RELOC_P (r_type)
5633                   && !elf_hash_table (info)->dynamic_sections_created)
5634                 /* This is a static link.  We must initialize the GOT entry.  */
5635                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->sgot->contents + g);
5636             }
5637         }
5638       else if (!htab->is_vxworks
5639                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5640         /* The calculation below does not involve "g".  */
5641         break;
5642       else
5643         {
5644           g = mips_elf_local_got_index (abfd, input_bfd, info,
5645                                         symbol + addend, r_symndx, h, r_type);
5646           if (g == MINUS_ONE)
5647             return bfd_reloc_outofrange;
5648         }
5649
5650       /* Convert GOT indices to actual offsets.  */
5651       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5652       break;
5653     }
5654
5655   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5656      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5657   if (h != NULL && is_gott_symbol (info, &h->root))
5658     {
5659       Elf_Internal_Rela outrel;
5660       bfd_byte *loc;
5661       asection *s;
5662
5663       s = mips_elf_rel_dyn_section (info, FALSE);
5664       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5665
5666       outrel.r_offset = (input_section->output_section->vma
5667                          + input_section->output_offset
5668                          + relocation->r_offset);
5669       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5670       outrel.r_addend = addend;
5671       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5672
5673       /* If we've written this relocation for a readonly section,
5674          we need to set DF_TEXTREL again, so that we do not delete the
5675          DT_TEXTREL tag.  */
5676       if (MIPS_ELF_READONLY_SECTION (input_section))
5677         info->flags |= DF_TEXTREL;
5678
5679       *valuep = 0;
5680       return bfd_reloc_ok;
5681     }
5682
5683   /* Figure out what kind of relocation is being performed.  */
5684   switch (r_type)
5685     {
5686     case R_MIPS_NONE:
5687       return bfd_reloc_continue;
5688
5689     case R_MIPS_16:
5690       value = symbol + _bfd_mips_elf_sign_extend (addend, 16);
5691       overflowed_p = mips_elf_overflow_p (value, 16);
5692       break;
5693
5694     case R_MIPS_32:
5695     case R_MIPS_REL32:
5696     case R_MIPS_64:
5697       if ((info->shared
5698            || (htab->root.dynamic_sections_created
5699                && h != NULL
5700                && h->root.def_dynamic
5701                && !h->root.def_regular
5702                && !h->has_static_relocs))
5703           && r_symndx != STN_UNDEF
5704           && (h == NULL
5705               || h->root.root.type != bfd_link_hash_undefweak
5706               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5707           && (input_section->flags & SEC_ALLOC) != 0)
5708         {
5709           /* If we're creating a shared library, then we can't know
5710              where the symbol will end up.  So, we create a relocation
5711              record in the output, and leave the job up to the dynamic
5712              linker.  We must do the same for executable references to
5713              shared library symbols, unless we've decided to use copy
5714              relocs or PLTs instead.  */
5715           value = addend;
5716           if (!mips_elf_create_dynamic_relocation (abfd,
5717                                                    info,
5718                                                    relocation,
5719                                                    h,
5720                                                    sec,
5721                                                    symbol,
5722                                                    &value,
5723                                                    input_section))
5724             return bfd_reloc_undefined;
5725         }
5726       else
5727         {
5728           if (r_type != R_MIPS_REL32)
5729             value = symbol + addend;
5730           else
5731             value = addend;
5732         }
5733       value &= howto->dst_mask;
5734       break;
5735
5736     case R_MIPS_PC32:
5737       value = symbol + addend - p;
5738       value &= howto->dst_mask;
5739       break;
5740
5741     case R_MIPS16_26:
5742       /* The calculation for R_MIPS16_26 is just the same as for an
5743          R_MIPS_26.  It's only the storage of the relocated field into
5744          the output file that's different.  That's handled in
5745          mips_elf_perform_relocation.  So, we just fall through to the
5746          R_MIPS_26 case here.  */
5747     case R_MIPS_26:
5748     case R_MICROMIPS_26_S1:
5749       {
5750         unsigned int shift;
5751
5752         /* Make sure the target of JALX is word-aligned.  Bit 0 must be
5753            the correct ISA mode selector and bit 1 must be 0.  */
5754         if (*cross_mode_jump_p && (symbol & 3) != (r_type == R_MIPS_26))
5755           return bfd_reloc_outofrange;
5756
5757         /* Shift is 2, unusually, for microMIPS JALX.  */
5758         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5759
5760         if (was_local_p)
5761           value = addend | ((p + 4) & (0xfc000000 << shift));
5762         else
5763           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5764         value = (value + symbol) >> shift;
5765         if (!was_local_p && h->root.root.type != bfd_link_hash_undefweak)
5766           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5767         value &= howto->dst_mask;
5768       }
5769       break;
5770
5771     case R_MIPS_TLS_DTPREL_HI16:
5772     case R_MIPS16_TLS_DTPREL_HI16:
5773     case R_MICROMIPS_TLS_DTPREL_HI16:
5774       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5775                & howto->dst_mask);
5776       break;
5777
5778     case R_MIPS_TLS_DTPREL_LO16:
5779     case R_MIPS_TLS_DTPREL32:
5780     case R_MIPS_TLS_DTPREL64:
5781     case R_MIPS16_TLS_DTPREL_LO16:
5782     case R_MICROMIPS_TLS_DTPREL_LO16:
5783       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5784       break;
5785
5786     case R_MIPS_TLS_TPREL_HI16:
5787     case R_MIPS16_TLS_TPREL_HI16:
5788     case R_MICROMIPS_TLS_TPREL_HI16:
5789       value = (mips_elf_high (addend + symbol - tprel_base (info))
5790                & howto->dst_mask);
5791       break;
5792
5793     case R_MIPS_TLS_TPREL_LO16:
5794     case R_MIPS_TLS_TPREL32:
5795     case R_MIPS_TLS_TPREL64:
5796     case R_MIPS16_TLS_TPREL_LO16:
5797     case R_MICROMIPS_TLS_TPREL_LO16:
5798       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5799       break;
5800
5801     case R_MIPS_HI16:
5802     case R_MIPS16_HI16:
5803     case R_MICROMIPS_HI16:
5804       if (!gp_disp_p)
5805         {
5806           value = mips_elf_high (addend + symbol);
5807           value &= howto->dst_mask;
5808         }
5809       else
5810         {
5811           /* For MIPS16 ABI code we generate this sequence
5812                 0: li      $v0,%hi(_gp_disp)
5813                 4: addiupc $v1,%lo(_gp_disp)
5814                 8: sll     $v0,16
5815                12: addu    $v0,$v1
5816                14: move    $gp,$v0
5817              So the offsets of hi and lo relocs are the same, but the
5818              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5819              ADDIUPC clears the low two bits of the instruction address,
5820              so the base is ($t9 + 4) & ~3.  */
5821           if (r_type == R_MIPS16_HI16)
5822             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5823           /* The microMIPS .cpload sequence uses the same assembly
5824              instructions as the traditional psABI version, but the
5825              incoming $t9 has the low bit set.  */
5826           else if (r_type == R_MICROMIPS_HI16)
5827             value = mips_elf_high (addend + gp - p - 1);
5828           else
5829             value = mips_elf_high (addend + gp - p);
5830           overflowed_p = mips_elf_overflow_p (value, 16);
5831         }
5832       break;
5833
5834     case R_MIPS_LO16:
5835     case R_MIPS16_LO16:
5836     case R_MICROMIPS_LO16:
5837     case R_MICROMIPS_HI0_LO16:
5838       if (!gp_disp_p)
5839         value = (symbol + addend) & howto->dst_mask;
5840       else
5841         {
5842           /* See the comment for R_MIPS16_HI16 above for the reason
5843              for this conditional.  */
5844           if (r_type == R_MIPS16_LO16)
5845             value = addend + gp - (p & ~(bfd_vma) 0x3);
5846           else if (r_type == R_MICROMIPS_LO16
5847                    || r_type == R_MICROMIPS_HI0_LO16)
5848             value = addend + gp - p + 3;
5849           else
5850             value = addend + gp - p + 4;
5851           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5852              for overflow.  But, on, say, IRIX5, relocations against
5853              _gp_disp are normally generated from the .cpload
5854              pseudo-op.  It generates code that normally looks like
5855              this:
5856
5857                lui    $gp,%hi(_gp_disp)
5858                addiu  $gp,$gp,%lo(_gp_disp)
5859                addu   $gp,$gp,$t9
5860
5861              Here $t9 holds the address of the function being called,
5862              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5863              relocation can easily overflow in this situation, but the
5864              R_MIPS_HI16 relocation will handle the overflow.
5865              Therefore, we consider this a bug in the MIPS ABI, and do
5866              not check for overflow here.  */
5867         }
5868       break;
5869
5870     case R_MIPS_LITERAL:
5871     case R_MICROMIPS_LITERAL:
5872       /* Because we don't merge literal sections, we can handle this
5873          just like R_MIPS_GPREL16.  In the long run, we should merge
5874          shared literals, and then we will need to additional work
5875          here.  */
5876
5877       /* Fall through.  */
5878
5879     case R_MIPS16_GPREL:
5880       /* The R_MIPS16_GPREL performs the same calculation as
5881          R_MIPS_GPREL16, but stores the relocated bits in a different
5882          order.  We don't need to do anything special here; the
5883          differences are handled in mips_elf_perform_relocation.  */
5884     case R_MIPS_GPREL16:
5885     case R_MICROMIPS_GPREL7_S2:
5886     case R_MICROMIPS_GPREL16:
5887       /* Only sign-extend the addend if it was extracted from the
5888          instruction.  If the addend was separate, leave it alone,
5889          otherwise we may lose significant bits.  */
5890       if (howto->partial_inplace)
5891         addend = _bfd_mips_elf_sign_extend (addend, 16);
5892       value = symbol + addend - gp;
5893       /* If the symbol was local, any earlier relocatable links will
5894          have adjusted its addend with the gp offset, so compensate
5895          for that now.  Don't do it for symbols forced local in this
5896          link, though, since they won't have had the gp offset applied
5897          to them before.  */
5898       if (was_local_p)
5899         value += gp0;
5900       overflowed_p = mips_elf_overflow_p (value, 16);
5901       break;
5902
5903     case R_MIPS16_GOT16:
5904     case R_MIPS16_CALL16:
5905     case R_MIPS_GOT16:
5906     case R_MIPS_CALL16:
5907     case R_MICROMIPS_GOT16:
5908     case R_MICROMIPS_CALL16:
5909       /* VxWorks does not have separate local and global semantics for
5910          R_MIPS*_GOT16; every relocation evaluates to "G".  */
5911       if (!htab->is_vxworks && local_p)
5912         {
5913           value = mips_elf_got16_entry (abfd, input_bfd, info,
5914                                         symbol + addend, !was_local_p);
5915           if (value == MINUS_ONE)
5916             return bfd_reloc_outofrange;
5917           value
5918             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5919           overflowed_p = mips_elf_overflow_p (value, 16);
5920           break;
5921         }
5922
5923       /* Fall through.  */
5924
5925     case R_MIPS_TLS_GD:
5926     case R_MIPS_TLS_GOTTPREL:
5927     case R_MIPS_TLS_LDM:
5928     case R_MIPS_GOT_DISP:
5929     case R_MIPS16_TLS_GD:
5930     case R_MIPS16_TLS_GOTTPREL:
5931     case R_MIPS16_TLS_LDM:
5932     case R_MICROMIPS_TLS_GD:
5933     case R_MICROMIPS_TLS_GOTTPREL:
5934     case R_MICROMIPS_TLS_LDM:
5935     case R_MICROMIPS_GOT_DISP:
5936       value = g;
5937       overflowed_p = mips_elf_overflow_p (value, 16);
5938       break;
5939
5940     case R_MIPS_GPREL32:
5941       value = (addend + symbol + gp0 - gp);
5942       if (!save_addend)
5943         value &= howto->dst_mask;
5944       break;
5945
5946     case R_MIPS_PC16:
5947     case R_MIPS_GNU_REL16_S2:
5948       value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p;
5949       overflowed_p = mips_elf_overflow_p (value, 18);
5950       value >>= howto->rightshift;
5951       value &= howto->dst_mask;
5952       break;
5953
5954     case R_MICROMIPS_PC7_S1:
5955       value = symbol + _bfd_mips_elf_sign_extend (addend, 8) - p;
5956       overflowed_p = mips_elf_overflow_p (value, 8);
5957       value >>= howto->rightshift;
5958       value &= howto->dst_mask;
5959       break;
5960
5961     case R_MICROMIPS_PC10_S1:
5962       value = symbol + _bfd_mips_elf_sign_extend (addend, 11) - p;
5963       overflowed_p = mips_elf_overflow_p (value, 11);
5964       value >>= howto->rightshift;
5965       value &= howto->dst_mask;
5966       break;
5967
5968     case R_MICROMIPS_PC16_S1:
5969       value = symbol + _bfd_mips_elf_sign_extend (addend, 17) - p;
5970       overflowed_p = mips_elf_overflow_p (value, 17);
5971       value >>= howto->rightshift;
5972       value &= howto->dst_mask;
5973       break;
5974
5975     case R_MICROMIPS_PC23_S2:
5976       value = symbol + _bfd_mips_elf_sign_extend (addend, 25) - ((p | 3) ^ 3);
5977       overflowed_p = mips_elf_overflow_p (value, 25);
5978       value >>= howto->rightshift;
5979       value &= howto->dst_mask;
5980       break;
5981
5982     case R_MIPS_GOT_HI16:
5983     case R_MIPS_CALL_HI16:
5984     case R_MICROMIPS_GOT_HI16:
5985     case R_MICROMIPS_CALL_HI16:
5986       /* We're allowed to handle these two relocations identically.
5987          The dynamic linker is allowed to handle the CALL relocations
5988          differently by creating a lazy evaluation stub.  */
5989       value = g;
5990       value = mips_elf_high (value);
5991       value &= howto->dst_mask;
5992       break;
5993
5994     case R_MIPS_GOT_LO16:
5995     case R_MIPS_CALL_LO16:
5996     case R_MICROMIPS_GOT_LO16:
5997     case R_MICROMIPS_CALL_LO16:
5998       value = g & howto->dst_mask;
5999       break;
6000
6001     case R_MIPS_GOT_PAGE:
6002     case R_MICROMIPS_GOT_PAGE:
6003       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
6004       if (value == MINUS_ONE)
6005         return bfd_reloc_outofrange;
6006       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
6007       overflowed_p = mips_elf_overflow_p (value, 16);
6008       break;
6009
6010     case R_MIPS_GOT_OFST:
6011     case R_MICROMIPS_GOT_OFST:
6012       if (local_p)
6013         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
6014       else
6015         value = addend;
6016       overflowed_p = mips_elf_overflow_p (value, 16);
6017       break;
6018
6019     case R_MIPS_SUB:
6020     case R_MICROMIPS_SUB:
6021       value = symbol - addend;
6022       value &= howto->dst_mask;
6023       break;
6024
6025     case R_MIPS_HIGHER:
6026     case R_MICROMIPS_HIGHER:
6027       value = mips_elf_higher (addend + symbol);
6028       value &= howto->dst_mask;
6029       break;
6030
6031     case R_MIPS_HIGHEST:
6032     case R_MICROMIPS_HIGHEST:
6033       value = mips_elf_highest (addend + symbol);
6034       value &= howto->dst_mask;
6035       break;
6036
6037     case R_MIPS_SCN_DISP:
6038     case R_MICROMIPS_SCN_DISP:
6039       value = symbol + addend - sec->output_offset;
6040       value &= howto->dst_mask;
6041       break;
6042
6043     case R_MIPS_JALR:
6044     case R_MICROMIPS_JALR:
6045       /* This relocation is only a hint.  In some cases, we optimize
6046          it into a bal instruction.  But we don't try to optimize
6047          when the symbol does not resolve locally.  */
6048       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
6049         return bfd_reloc_continue;
6050       value = symbol + addend;
6051       break;
6052
6053     case R_MIPS_PJUMP:
6054     case R_MIPS_GNU_VTINHERIT:
6055     case R_MIPS_GNU_VTENTRY:
6056       /* We don't do anything with these at present.  */
6057       return bfd_reloc_continue;
6058
6059     default:
6060       /* An unrecognized relocation type.  */
6061       return bfd_reloc_notsupported;
6062     }
6063
6064   /* Store the VALUE for our caller.  */
6065   *valuep = value;
6066   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
6067 }
6068
6069 /* Obtain the field relocated by RELOCATION.  */
6070
6071 static bfd_vma
6072 mips_elf_obtain_contents (reloc_howto_type *howto,
6073                           const Elf_Internal_Rela *relocation,
6074                           bfd *input_bfd, bfd_byte *contents)
6075 {
6076   bfd_vma x;
6077   bfd_byte *location = contents + relocation->r_offset;
6078
6079   /* Obtain the bytes.  */
6080   x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location);
6081
6082   return x;
6083 }
6084
6085 /* It has been determined that the result of the RELOCATION is the
6086    VALUE.  Use HOWTO to place VALUE into the output file at the
6087    appropriate position.  The SECTION is the section to which the
6088    relocation applies.
6089    CROSS_MODE_JUMP_P is true if the relocation field
6090    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
6091
6092    Returns FALSE if anything goes wrong.  */
6093
6094 static bfd_boolean
6095 mips_elf_perform_relocation (struct bfd_link_info *info,
6096                              reloc_howto_type *howto,
6097                              const Elf_Internal_Rela *relocation,
6098                              bfd_vma value, bfd *input_bfd,
6099                              asection *input_section, bfd_byte *contents,
6100                              bfd_boolean cross_mode_jump_p)
6101 {
6102   bfd_vma x;
6103   bfd_byte *location;
6104   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
6105
6106   /* Figure out where the relocation is occurring.  */
6107   location = contents + relocation->r_offset;
6108
6109   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
6110
6111   /* Obtain the current value.  */
6112   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
6113
6114   /* Clear the field we are setting.  */
6115   x &= ~howto->dst_mask;
6116
6117   /* Set the field.  */
6118   x |= (value & howto->dst_mask);
6119
6120   /* If required, turn JAL into JALX.  */
6121   if (cross_mode_jump_p && jal_reloc_p (r_type))
6122     {
6123       bfd_boolean ok;
6124       bfd_vma opcode = x >> 26;
6125       bfd_vma jalx_opcode;
6126
6127       /* Check to see if the opcode is already JAL or JALX.  */
6128       if (r_type == R_MIPS16_26)
6129         {
6130           ok = ((opcode == 0x6) || (opcode == 0x7));
6131           jalx_opcode = 0x7;
6132         }
6133       else if (r_type == R_MICROMIPS_26_S1)
6134         {
6135           ok = ((opcode == 0x3d) || (opcode == 0x3c));
6136           jalx_opcode = 0x3c;
6137         }
6138       else
6139         {
6140           ok = ((opcode == 0x3) || (opcode == 0x1d));
6141           jalx_opcode = 0x1d;
6142         }
6143
6144       /* If the opcode is not JAL or JALX, there's a problem.  We cannot
6145          convert J or JALS to JALX.  */
6146       if (!ok)
6147         {
6148           (*_bfd_error_handler)
6149             (_("%B: %A+0x%lx: Unsupported jump between ISA modes; consider recompiling with interlinking enabled."),
6150              input_bfd,
6151              input_section,
6152              (unsigned long) relocation->r_offset);
6153           bfd_set_error (bfd_error_bad_value);
6154           return FALSE;
6155         }
6156
6157       /* Make this the JALX opcode.  */
6158       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
6159     }
6160
6161   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
6162      range.  */
6163   if (!info->relocatable
6164       && !cross_mode_jump_p
6165       && ((JAL_TO_BAL_P (input_bfd)
6166            && r_type == R_MIPS_26
6167            && (x >> 26) == 0x3)         /* jal addr */
6168           || (JALR_TO_BAL_P (input_bfd)
6169               && r_type == R_MIPS_JALR
6170               && x == 0x0320f809)       /* jalr t9 */
6171           || (JR_TO_B_P (input_bfd)
6172               && r_type == R_MIPS_JALR
6173               && x == 0x03200008)))     /* jr t9 */
6174     {
6175       bfd_vma addr;
6176       bfd_vma dest;
6177       bfd_signed_vma off;
6178
6179       addr = (input_section->output_section->vma
6180               + input_section->output_offset
6181               + relocation->r_offset
6182               + 4);
6183       if (r_type == R_MIPS_26)
6184         dest = (value << 2) | ((addr >> 28) << 28);
6185       else
6186         dest = value;
6187       off = dest - addr;
6188       if (off <= 0x1ffff && off >= -0x20000)
6189         {
6190           if (x == 0x03200008)  /* jr t9 */
6191             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
6192           else
6193             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
6194         }
6195     }
6196
6197   /* Put the value into the output.  */
6198   bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location);
6199
6200   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !info->relocatable,
6201                                location);
6202
6203   return TRUE;
6204 }
6205 \f
6206 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
6207    is the original relocation, which is now being transformed into a
6208    dynamic relocation.  The ADDENDP is adjusted if necessary; the
6209    caller should store the result in place of the original addend.  */
6210
6211 static bfd_boolean
6212 mips_elf_create_dynamic_relocation (bfd *output_bfd,
6213                                     struct bfd_link_info *info,
6214                                     const Elf_Internal_Rela *rel,
6215                                     struct mips_elf_link_hash_entry *h,
6216                                     asection *sec, bfd_vma symbol,
6217                                     bfd_vma *addendp, asection *input_section)
6218 {
6219   Elf_Internal_Rela outrel[3];
6220   asection *sreloc;
6221   bfd *dynobj;
6222   int r_type;
6223   long indx;
6224   bfd_boolean defined_p;
6225   struct mips_elf_link_hash_table *htab;
6226
6227   htab = mips_elf_hash_table (info);
6228   BFD_ASSERT (htab != NULL);
6229
6230   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
6231   dynobj = elf_hash_table (info)->dynobj;
6232   sreloc = mips_elf_rel_dyn_section (info, FALSE);
6233   BFD_ASSERT (sreloc != NULL);
6234   BFD_ASSERT (sreloc->contents != NULL);
6235   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
6236               < sreloc->size);
6237
6238   outrel[0].r_offset =
6239     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
6240   if (ABI_64_P (output_bfd))
6241     {
6242       outrel[1].r_offset =
6243         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
6244       outrel[2].r_offset =
6245         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
6246     }
6247
6248   if (outrel[0].r_offset == MINUS_ONE)
6249     /* The relocation field has been deleted.  */
6250     return TRUE;
6251
6252   if (outrel[0].r_offset == MINUS_TWO)
6253     {
6254       /* The relocation field has been converted into a relative value of
6255          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
6256          the field to be fully relocated, so add in the symbol's value.  */
6257       *addendp += symbol;
6258       return TRUE;
6259     }
6260
6261   /* We must now calculate the dynamic symbol table index to use
6262      in the relocation.  */
6263   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
6264     {
6265       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
6266       indx = h->root.dynindx;
6267       if (SGI_COMPAT (output_bfd))
6268         defined_p = h->root.def_regular;
6269       else
6270         /* ??? glibc's ld.so just adds the final GOT entry to the
6271            relocation field.  It therefore treats relocs against
6272            defined symbols in the same way as relocs against
6273            undefined symbols.  */
6274         defined_p = FALSE;
6275     }
6276   else
6277     {
6278       if (sec != NULL && bfd_is_abs_section (sec))
6279         indx = 0;
6280       else if (sec == NULL || sec->owner == NULL)
6281         {
6282           bfd_set_error (bfd_error_bad_value);
6283           return FALSE;
6284         }
6285       else
6286         {
6287           indx = elf_section_data (sec->output_section)->dynindx;
6288           if (indx == 0)
6289             {
6290               asection *osec = htab->root.text_index_section;
6291               indx = elf_section_data (osec)->dynindx;
6292             }
6293           if (indx == 0)
6294             abort ();
6295         }
6296
6297       /* Instead of generating a relocation using the section
6298          symbol, we may as well make it a fully relative
6299          relocation.  We want to avoid generating relocations to
6300          local symbols because we used to generate them
6301          incorrectly, without adding the original symbol value,
6302          which is mandated by the ABI for section symbols.  In
6303          order to give dynamic loaders and applications time to
6304          phase out the incorrect use, we refrain from emitting
6305          section-relative relocations.  It's not like they're
6306          useful, after all.  This should be a bit more efficient
6307          as well.  */
6308       /* ??? Although this behavior is compatible with glibc's ld.so,
6309          the ABI says that relocations against STN_UNDEF should have
6310          a symbol value of 0.  Irix rld honors this, so relocations
6311          against STN_UNDEF have no effect.  */
6312       if (!SGI_COMPAT (output_bfd))
6313         indx = 0;
6314       defined_p = TRUE;
6315     }
6316
6317   /* If the relocation was previously an absolute relocation and
6318      this symbol will not be referred to by the relocation, we must
6319      adjust it by the value we give it in the dynamic symbol table.
6320      Otherwise leave the job up to the dynamic linker.  */
6321   if (defined_p && r_type != R_MIPS_REL32)
6322     *addendp += symbol;
6323
6324   if (htab->is_vxworks)
6325     /* VxWorks uses non-relative relocations for this.  */
6326     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
6327   else
6328     /* The relocation is always an REL32 relocation because we don't
6329        know where the shared library will wind up at load-time.  */
6330     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
6331                                    R_MIPS_REL32);
6332
6333   /* For strict adherence to the ABI specification, we should
6334      generate a R_MIPS_64 relocation record by itself before the
6335      _REL32/_64 record as well, such that the addend is read in as
6336      a 64-bit value (REL32 is a 32-bit relocation, after all).
6337      However, since none of the existing ELF64 MIPS dynamic
6338      loaders seems to care, we don't waste space with these
6339      artificial relocations.  If this turns out to not be true,
6340      mips_elf_allocate_dynamic_relocation() should be tweaked so
6341      as to make room for a pair of dynamic relocations per
6342      invocation if ABI_64_P, and here we should generate an
6343      additional relocation record with R_MIPS_64 by itself for a
6344      NULL symbol before this relocation record.  */
6345   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
6346                                  ABI_64_P (output_bfd)
6347                                  ? R_MIPS_64
6348                                  : R_MIPS_NONE);
6349   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
6350
6351   /* Adjust the output offset of the relocation to reference the
6352      correct location in the output file.  */
6353   outrel[0].r_offset += (input_section->output_section->vma
6354                          + input_section->output_offset);
6355   outrel[1].r_offset += (input_section->output_section->vma
6356                          + input_section->output_offset);
6357   outrel[2].r_offset += (input_section->output_section->vma
6358                          + input_section->output_offset);
6359
6360   /* Put the relocation back out.  We have to use the special
6361      relocation outputter in the 64-bit case since the 64-bit
6362      relocation format is non-standard.  */
6363   if (ABI_64_P (output_bfd))
6364     {
6365       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
6366         (output_bfd, &outrel[0],
6367          (sreloc->contents
6368           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
6369     }
6370   else if (htab->is_vxworks)
6371     {
6372       /* VxWorks uses RELA rather than REL dynamic relocations.  */
6373       outrel[0].r_addend = *addendp;
6374       bfd_elf32_swap_reloca_out
6375         (output_bfd, &outrel[0],
6376          (sreloc->contents
6377           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
6378     }
6379   else
6380     bfd_elf32_swap_reloc_out
6381       (output_bfd, &outrel[0],
6382        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
6383
6384   /* We've now added another relocation.  */
6385   ++sreloc->reloc_count;
6386
6387   /* Make sure the output section is writable.  The dynamic linker
6388      will be writing to it.  */
6389   elf_section_data (input_section->output_section)->this_hdr.sh_flags
6390     |= SHF_WRITE;
6391
6392   /* On IRIX5, make an entry of compact relocation info.  */
6393   if (IRIX_COMPAT (output_bfd) == ict_irix5)
6394     {
6395       asection *scpt = bfd_get_linker_section (dynobj, ".compact_rel");
6396       bfd_byte *cr;
6397
6398       if (scpt)
6399         {
6400           Elf32_crinfo cptrel;
6401
6402           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
6403           cptrel.vaddr = (rel->r_offset
6404                           + input_section->output_section->vma
6405                           + input_section->output_offset);
6406           if (r_type == R_MIPS_REL32)
6407             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
6408           else
6409             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
6410           mips_elf_set_cr_dist2to (cptrel, 0);
6411           cptrel.konst = *addendp;
6412
6413           cr = (scpt->contents
6414                 + sizeof (Elf32_External_compact_rel));
6415           mips_elf_set_cr_relvaddr (cptrel, 0);
6416           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
6417                                      ((Elf32_External_crinfo *) cr
6418                                       + scpt->reloc_count));
6419           ++scpt->reloc_count;
6420         }
6421     }
6422
6423   /* If we've written this relocation for a readonly section,
6424      we need to set DF_TEXTREL again, so that we do not delete the
6425      DT_TEXTREL tag.  */
6426   if (MIPS_ELF_READONLY_SECTION (input_section))
6427     info->flags |= DF_TEXTREL;
6428
6429   return TRUE;
6430 }
6431 \f
6432 /* Return the MACH for a MIPS e_flags value.  */
6433
6434 unsigned long
6435 _bfd_elf_mips_mach (flagword flags)
6436 {
6437   switch (flags & EF_MIPS_MACH)
6438     {
6439     case E_MIPS_MACH_3900:
6440       return bfd_mach_mips3900;
6441
6442     case E_MIPS_MACH_4010:
6443       return bfd_mach_mips4010;
6444
6445     case E_MIPS_MACH_4100:
6446       return bfd_mach_mips4100;
6447
6448     case E_MIPS_MACH_4111:
6449       return bfd_mach_mips4111;
6450
6451     case E_MIPS_MACH_4120:
6452       return bfd_mach_mips4120;
6453
6454     case E_MIPS_MACH_4650:
6455       return bfd_mach_mips4650;
6456
6457     case E_MIPS_MACH_5400:
6458       return bfd_mach_mips5400;
6459
6460     case E_MIPS_MACH_5500:
6461       return bfd_mach_mips5500;
6462
6463     case E_MIPS_MACH_5900:
6464       return bfd_mach_mips5900;
6465
6466     case E_MIPS_MACH_9000:
6467       return bfd_mach_mips9000;
6468
6469     case E_MIPS_MACH_SB1:
6470       return bfd_mach_mips_sb1;
6471
6472     case E_MIPS_MACH_LS2E:
6473       return bfd_mach_mips_loongson_2e;
6474
6475     case E_MIPS_MACH_LS2F:
6476       return bfd_mach_mips_loongson_2f;
6477
6478     case E_MIPS_MACH_LS3A:
6479       return bfd_mach_mips_loongson_3a;
6480
6481     case E_MIPS_MACH_OCTEON2:
6482       return bfd_mach_mips_octeon2;
6483
6484     case E_MIPS_MACH_OCTEON:
6485       return bfd_mach_mips_octeon;
6486
6487     case E_MIPS_MACH_XLR:
6488       return bfd_mach_mips_xlr;
6489
6490     default:
6491       switch (flags & EF_MIPS_ARCH)
6492         {
6493         default:
6494         case E_MIPS_ARCH_1:
6495           return bfd_mach_mips3000;
6496
6497         case E_MIPS_ARCH_2:
6498           return bfd_mach_mips6000;
6499
6500         case E_MIPS_ARCH_3:
6501           return bfd_mach_mips4000;
6502
6503         case E_MIPS_ARCH_4:
6504           return bfd_mach_mips8000;
6505
6506         case E_MIPS_ARCH_5:
6507           return bfd_mach_mips5;
6508
6509         case E_MIPS_ARCH_32:
6510           return bfd_mach_mipsisa32;
6511
6512         case E_MIPS_ARCH_64:
6513           return bfd_mach_mipsisa64;
6514
6515         case E_MIPS_ARCH_32R2:
6516           return bfd_mach_mipsisa32r2;
6517
6518         case E_MIPS_ARCH_64R2:
6519           return bfd_mach_mipsisa64r2;
6520         }
6521     }
6522
6523   return 0;
6524 }
6525
6526 /* Return printable name for ABI.  */
6527
6528 static INLINE char *
6529 elf_mips_abi_name (bfd *abfd)
6530 {
6531   flagword flags;
6532
6533   flags = elf_elfheader (abfd)->e_flags;
6534   switch (flags & EF_MIPS_ABI)
6535     {
6536     case 0:
6537       if (ABI_N32_P (abfd))
6538         return "N32";
6539       else if (ABI_64_P (abfd))
6540         return "64";
6541       else
6542         return "none";
6543     case E_MIPS_ABI_O32:
6544       return "O32";
6545     case E_MIPS_ABI_O64:
6546       return "O64";
6547     case E_MIPS_ABI_EABI32:
6548       return "EABI32";
6549     case E_MIPS_ABI_EABI64:
6550       return "EABI64";
6551     default:
6552       return "unknown abi";
6553     }
6554 }
6555 \f
6556 /* MIPS ELF uses two common sections.  One is the usual one, and the
6557    other is for small objects.  All the small objects are kept
6558    together, and then referenced via the gp pointer, which yields
6559    faster assembler code.  This is what we use for the small common
6560    section.  This approach is copied from ecoff.c.  */
6561 static asection mips_elf_scom_section;
6562 static asymbol mips_elf_scom_symbol;
6563 static asymbol *mips_elf_scom_symbol_ptr;
6564
6565 /* MIPS ELF also uses an acommon section, which represents an
6566    allocated common symbol which may be overridden by a
6567    definition in a shared library.  */
6568 static asection mips_elf_acom_section;
6569 static asymbol mips_elf_acom_symbol;
6570 static asymbol *mips_elf_acom_symbol_ptr;
6571
6572 /* This is used for both the 32-bit and the 64-bit ABI.  */
6573
6574 void
6575 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6576 {
6577   elf_symbol_type *elfsym;
6578
6579   /* Handle the special MIPS section numbers that a symbol may use.  */
6580   elfsym = (elf_symbol_type *) asym;
6581   switch (elfsym->internal_elf_sym.st_shndx)
6582     {
6583     case SHN_MIPS_ACOMMON:
6584       /* This section is used in a dynamically linked executable file.
6585          It is an allocated common section.  The dynamic linker can
6586          either resolve these symbols to something in a shared
6587          library, or it can just leave them here.  For our purposes,
6588          we can consider these symbols to be in a new section.  */
6589       if (mips_elf_acom_section.name == NULL)
6590         {
6591           /* Initialize the acommon section.  */
6592           mips_elf_acom_section.name = ".acommon";
6593           mips_elf_acom_section.flags = SEC_ALLOC;
6594           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6595           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6596           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6597           mips_elf_acom_symbol.name = ".acommon";
6598           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6599           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6600           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6601         }
6602       asym->section = &mips_elf_acom_section;
6603       break;
6604
6605     case SHN_COMMON:
6606       /* Common symbols less than the GP size are automatically
6607          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6608       if (asym->value > elf_gp_size (abfd)
6609           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6610           || IRIX_COMPAT (abfd) == ict_irix6)
6611         break;
6612       /* Fall through.  */
6613     case SHN_MIPS_SCOMMON:
6614       if (mips_elf_scom_section.name == NULL)
6615         {
6616           /* Initialize the small common section.  */
6617           mips_elf_scom_section.name = ".scommon";
6618           mips_elf_scom_section.flags = SEC_IS_COMMON;
6619           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6620           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6621           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6622           mips_elf_scom_symbol.name = ".scommon";
6623           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6624           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6625           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6626         }
6627       asym->section = &mips_elf_scom_section;
6628       asym->value = elfsym->internal_elf_sym.st_size;
6629       break;
6630
6631     case SHN_MIPS_SUNDEFINED:
6632       asym->section = bfd_und_section_ptr;
6633       break;
6634
6635     case SHN_MIPS_TEXT:
6636       {
6637         asection *section = bfd_get_section_by_name (abfd, ".text");
6638
6639         if (section != NULL)
6640           {
6641             asym->section = section;
6642             /* MIPS_TEXT is a bit special, the address is not an offset
6643                to the base of the .text section.  So substract the section
6644                base address to make it an offset.  */
6645             asym->value -= section->vma;
6646           }
6647       }
6648       break;
6649
6650     case SHN_MIPS_DATA:
6651       {
6652         asection *section = bfd_get_section_by_name (abfd, ".data");
6653
6654         if (section != NULL)
6655           {
6656             asym->section = section;
6657             /* MIPS_DATA is a bit special, the address is not an offset
6658                to the base of the .data section.  So substract the section
6659                base address to make it an offset.  */
6660             asym->value -= section->vma;
6661           }
6662       }
6663       break;
6664     }
6665
6666   /* If this is an odd-valued function symbol, assume it's a MIPS16
6667      or microMIPS one.  */
6668   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6669       && (asym->value & 1) != 0)
6670     {
6671       asym->value--;
6672       if (MICROMIPS_P (abfd))
6673         elfsym->internal_elf_sym.st_other
6674           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6675       else
6676         elfsym->internal_elf_sym.st_other
6677           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6678     }
6679 }
6680 \f
6681 /* Implement elf_backend_eh_frame_address_size.  This differs from
6682    the default in the way it handles EABI64.
6683
6684    EABI64 was originally specified as an LP64 ABI, and that is what
6685    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6686    historically accepted the combination of -mabi=eabi and -mlong32,
6687    and this ILP32 variation has become semi-official over time.
6688    Both forms use elf32 and have pointer-sized FDE addresses.
6689
6690    If an EABI object was generated by GCC 4.0 or above, it will have
6691    an empty .gcc_compiled_longXX section, where XX is the size of longs
6692    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6693    have no special marking to distinguish them from LP64 objects.
6694
6695    We don't want users of the official LP64 ABI to be punished for the
6696    existence of the ILP32 variant, but at the same time, we don't want
6697    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6698    We therefore take the following approach:
6699
6700       - If ABFD contains a .gcc_compiled_longXX section, use it to
6701         determine the pointer size.
6702
6703       - Otherwise check the type of the first relocation.  Assume that
6704         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
6705
6706       - Otherwise punt.
6707
6708    The second check is enough to detect LP64 objects generated by pre-4.0
6709    compilers because, in the kind of output generated by those compilers,
6710    the first relocation will be associated with either a CIE personality
6711    routine or an FDE start address.  Furthermore, the compilers never
6712    used a special (non-pointer) encoding for this ABI.
6713
6714    Checking the relocation type should also be safe because there is no
6715    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
6716    did so.  */
6717
6718 unsigned int
6719 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
6720 {
6721   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
6722     return 8;
6723   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
6724     {
6725       bfd_boolean long32_p, long64_p;
6726
6727       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
6728       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
6729       if (long32_p && long64_p)
6730         return 0;
6731       if (long32_p)
6732         return 4;
6733       if (long64_p)
6734         return 8;
6735
6736       if (sec->reloc_count > 0
6737           && elf_section_data (sec)->relocs != NULL
6738           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
6739               == R_MIPS_64))
6740         return 8;
6741
6742       return 0;
6743     }
6744   return 4;
6745 }
6746 \f
6747 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
6748    relocations against two unnamed section symbols to resolve to the
6749    same address.  For example, if we have code like:
6750
6751         lw      $4,%got_disp(.data)($gp)
6752         lw      $25,%got_disp(.text)($gp)
6753         jalr    $25
6754
6755    then the linker will resolve both relocations to .data and the program
6756    will jump there rather than to .text.
6757
6758    We can work around this problem by giving names to local section symbols.
6759    This is also what the MIPSpro tools do.  */
6760
6761 bfd_boolean
6762 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
6763 {
6764   return SGI_COMPAT (abfd);
6765 }
6766 \f
6767 /* Work over a section just before writing it out.  This routine is
6768    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
6769    sections that need the SHF_MIPS_GPREL flag by name; there has to be
6770    a better way.  */
6771
6772 bfd_boolean
6773 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
6774 {
6775   if (hdr->sh_type == SHT_MIPS_REGINFO
6776       && hdr->sh_size > 0)
6777     {
6778       bfd_byte buf[4];
6779
6780       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
6781       BFD_ASSERT (hdr->contents == NULL);
6782
6783       if (bfd_seek (abfd,
6784                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
6785                     SEEK_SET) != 0)
6786         return FALSE;
6787       H_PUT_32 (abfd, elf_gp (abfd), buf);
6788       if (bfd_bwrite (buf, 4, abfd) != 4)
6789         return FALSE;
6790     }
6791
6792   if (hdr->sh_type == SHT_MIPS_OPTIONS
6793       && hdr->bfd_section != NULL
6794       && mips_elf_section_data (hdr->bfd_section) != NULL
6795       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
6796     {
6797       bfd_byte *contents, *l, *lend;
6798
6799       /* We stored the section contents in the tdata field in the
6800          set_section_contents routine.  We save the section contents
6801          so that we don't have to read them again.
6802          At this point we know that elf_gp is set, so we can look
6803          through the section contents to see if there is an
6804          ODK_REGINFO structure.  */
6805
6806       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
6807       l = contents;
6808       lend = contents + hdr->sh_size;
6809       while (l + sizeof (Elf_External_Options) <= lend)
6810         {
6811           Elf_Internal_Options intopt;
6812
6813           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6814                                         &intopt);
6815           if (intopt.size < sizeof (Elf_External_Options))
6816             {
6817               (*_bfd_error_handler)
6818                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6819                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6820               break;
6821             }
6822           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6823             {
6824               bfd_byte buf[8];
6825
6826               if (bfd_seek (abfd,
6827                             (hdr->sh_offset
6828                              + (l - contents)
6829                              + sizeof (Elf_External_Options)
6830                              + (sizeof (Elf64_External_RegInfo) - 8)),
6831                              SEEK_SET) != 0)
6832                 return FALSE;
6833               H_PUT_64 (abfd, elf_gp (abfd), buf);
6834               if (bfd_bwrite (buf, 8, abfd) != 8)
6835                 return FALSE;
6836             }
6837           else if (intopt.kind == ODK_REGINFO)
6838             {
6839               bfd_byte buf[4];
6840
6841               if (bfd_seek (abfd,
6842                             (hdr->sh_offset
6843                              + (l - contents)
6844                              + sizeof (Elf_External_Options)
6845                              + (sizeof (Elf32_External_RegInfo) - 4)),
6846                             SEEK_SET) != 0)
6847                 return FALSE;
6848               H_PUT_32 (abfd, elf_gp (abfd), buf);
6849               if (bfd_bwrite (buf, 4, abfd) != 4)
6850                 return FALSE;
6851             }
6852           l += intopt.size;
6853         }
6854     }
6855
6856   if (hdr->bfd_section != NULL)
6857     {
6858       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
6859
6860       /* .sbss is not handled specially here because the GNU/Linux
6861          prelinker can convert .sbss from NOBITS to PROGBITS and
6862          changing it back to NOBITS breaks the binary.  The entry in
6863          _bfd_mips_elf_special_sections will ensure the correct flags
6864          are set on .sbss if BFD creates it without reading it from an
6865          input file, and without special handling here the flags set
6866          on it in an input file will be followed.  */
6867       if (strcmp (name, ".sdata") == 0
6868           || strcmp (name, ".lit8") == 0
6869           || strcmp (name, ".lit4") == 0)
6870         {
6871           hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
6872           hdr->sh_type = SHT_PROGBITS;
6873         }
6874       else if (strcmp (name, ".srdata") == 0)
6875         {
6876           hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
6877           hdr->sh_type = SHT_PROGBITS;
6878         }
6879       else if (strcmp (name, ".compact_rel") == 0)
6880         {
6881           hdr->sh_flags = 0;
6882           hdr->sh_type = SHT_PROGBITS;
6883         }
6884       else if (strcmp (name, ".rtproc") == 0)
6885         {
6886           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
6887             {
6888               unsigned int adjust;
6889
6890               adjust = hdr->sh_size % hdr->sh_addralign;
6891               if (adjust != 0)
6892                 hdr->sh_size += hdr->sh_addralign - adjust;
6893             }
6894         }
6895     }
6896
6897   return TRUE;
6898 }
6899
6900 /* Handle a MIPS specific section when reading an object file.  This
6901    is called when elfcode.h finds a section with an unknown type.
6902    This routine supports both the 32-bit and 64-bit ELF ABI.
6903
6904    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
6905    how to.  */
6906
6907 bfd_boolean
6908 _bfd_mips_elf_section_from_shdr (bfd *abfd,
6909                                  Elf_Internal_Shdr *hdr,
6910                                  const char *name,
6911                                  int shindex)
6912 {
6913   flagword flags = 0;
6914
6915   /* There ought to be a place to keep ELF backend specific flags, but
6916      at the moment there isn't one.  We just keep track of the
6917      sections by their name, instead.  Fortunately, the ABI gives
6918      suggested names for all the MIPS specific sections, so we will
6919      probably get away with this.  */
6920   switch (hdr->sh_type)
6921     {
6922     case SHT_MIPS_LIBLIST:
6923       if (strcmp (name, ".liblist") != 0)
6924         return FALSE;
6925       break;
6926     case SHT_MIPS_MSYM:
6927       if (strcmp (name, ".msym") != 0)
6928         return FALSE;
6929       break;
6930     case SHT_MIPS_CONFLICT:
6931       if (strcmp (name, ".conflict") != 0)
6932         return FALSE;
6933       break;
6934     case SHT_MIPS_GPTAB:
6935       if (! CONST_STRNEQ (name, ".gptab."))
6936         return FALSE;
6937       break;
6938     case SHT_MIPS_UCODE:
6939       if (strcmp (name, ".ucode") != 0)
6940         return FALSE;
6941       break;
6942     case SHT_MIPS_DEBUG:
6943       if (strcmp (name, ".mdebug") != 0)
6944         return FALSE;
6945       flags = SEC_DEBUGGING;
6946       break;
6947     case SHT_MIPS_REGINFO:
6948       if (strcmp (name, ".reginfo") != 0
6949           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
6950         return FALSE;
6951       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6952       break;
6953     case SHT_MIPS_IFACE:
6954       if (strcmp (name, ".MIPS.interfaces") != 0)
6955         return FALSE;
6956       break;
6957     case SHT_MIPS_CONTENT:
6958       if (! CONST_STRNEQ (name, ".MIPS.content"))
6959         return FALSE;
6960       break;
6961     case SHT_MIPS_OPTIONS:
6962       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6963         return FALSE;
6964       break;
6965     case SHT_MIPS_ABIFLAGS:
6966       if (!MIPS_ELF_ABIFLAGS_SECTION_NAME_P (name))
6967         return FALSE;
6968       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6969       break;
6970     case SHT_MIPS_DWARF:
6971       if (! CONST_STRNEQ (name, ".debug_")
6972           && ! CONST_STRNEQ (name, ".zdebug_"))
6973         return FALSE;
6974       break;
6975     case SHT_MIPS_SYMBOL_LIB:
6976       if (strcmp (name, ".MIPS.symlib") != 0)
6977         return FALSE;
6978       break;
6979     case SHT_MIPS_EVENTS:
6980       if (! CONST_STRNEQ (name, ".MIPS.events")
6981           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
6982         return FALSE;
6983       break;
6984     default:
6985       break;
6986     }
6987
6988   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
6989     return FALSE;
6990
6991   if (flags)
6992     {
6993       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
6994                                    (bfd_get_section_flags (abfd,
6995                                                            hdr->bfd_section)
6996                                     | flags)))
6997         return FALSE;
6998     }
6999
7000   if (hdr->sh_type == SHT_MIPS_ABIFLAGS)
7001     {
7002       Elf_External_ABIFlags_v0 ext;
7003
7004       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
7005                                       &ext, 0, sizeof ext))
7006         return FALSE;
7007       bfd_mips_elf_swap_abiflags_v0_in (abfd, &ext,
7008                                         &mips_elf_tdata (abfd)->abiflags);
7009       if (mips_elf_tdata (abfd)->abiflags.version != 0)
7010         return FALSE;
7011       mips_elf_tdata (abfd)->abiflags_valid = TRUE;
7012     }
7013
7014   /* FIXME: We should record sh_info for a .gptab section.  */
7015
7016   /* For a .reginfo section, set the gp value in the tdata information
7017      from the contents of this section.  We need the gp value while
7018      processing relocs, so we just get it now.  The .reginfo section
7019      is not used in the 64-bit MIPS ELF ABI.  */
7020   if (hdr->sh_type == SHT_MIPS_REGINFO)
7021     {
7022       Elf32_External_RegInfo ext;
7023       Elf32_RegInfo s;
7024
7025       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
7026                                       &ext, 0, sizeof ext))
7027         return FALSE;
7028       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
7029       elf_gp (abfd) = s.ri_gp_value;
7030     }
7031
7032   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
7033      set the gp value based on what we find.  We may see both
7034      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
7035      they should agree.  */
7036   if (hdr->sh_type == SHT_MIPS_OPTIONS)
7037     {
7038       bfd_byte *contents, *l, *lend;
7039
7040       contents = bfd_malloc (hdr->sh_size);
7041       if (contents == NULL)
7042         return FALSE;
7043       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
7044                                       0, hdr->sh_size))
7045         {
7046           free (contents);
7047           return FALSE;
7048         }
7049       l = contents;
7050       lend = contents + hdr->sh_size;
7051       while (l + sizeof (Elf_External_Options) <= lend)
7052         {
7053           Elf_Internal_Options intopt;
7054
7055           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
7056                                         &intopt);
7057           if (intopt.size < sizeof (Elf_External_Options))
7058             {
7059               (*_bfd_error_handler)
7060                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
7061                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
7062               break;
7063             }
7064           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
7065             {
7066               Elf64_Internal_RegInfo intreg;
7067
7068               bfd_mips_elf64_swap_reginfo_in
7069                 (abfd,
7070                  ((Elf64_External_RegInfo *)
7071                   (l + sizeof (Elf_External_Options))),
7072                  &intreg);
7073               elf_gp (abfd) = intreg.ri_gp_value;
7074             }
7075           else if (intopt.kind == ODK_REGINFO)
7076             {
7077               Elf32_RegInfo intreg;
7078
7079               bfd_mips_elf32_swap_reginfo_in
7080                 (abfd,
7081                  ((Elf32_External_RegInfo *)
7082                   (l + sizeof (Elf_External_Options))),
7083                  &intreg);
7084               elf_gp (abfd) = intreg.ri_gp_value;
7085             }
7086           l += intopt.size;
7087         }
7088       free (contents);
7089     }
7090
7091   return TRUE;
7092 }
7093
7094 /* Set the correct type for a MIPS ELF section.  We do this by the
7095    section name, which is a hack, but ought to work.  This routine is
7096    used by both the 32-bit and the 64-bit ABI.  */
7097
7098 bfd_boolean
7099 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
7100 {
7101   const char *name = bfd_get_section_name (abfd, sec);
7102
7103   if (strcmp (name, ".liblist") == 0)
7104     {
7105       hdr->sh_type = SHT_MIPS_LIBLIST;
7106       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
7107       /* The sh_link field is set in final_write_processing.  */
7108     }
7109   else if (strcmp (name, ".conflict") == 0)
7110     hdr->sh_type = SHT_MIPS_CONFLICT;
7111   else if (CONST_STRNEQ (name, ".gptab."))
7112     {
7113       hdr->sh_type = SHT_MIPS_GPTAB;
7114       hdr->sh_entsize = sizeof (Elf32_External_gptab);
7115       /* The sh_info field is set in final_write_processing.  */
7116     }
7117   else if (strcmp (name, ".ucode") == 0)
7118     hdr->sh_type = SHT_MIPS_UCODE;
7119   else if (strcmp (name, ".mdebug") == 0)
7120     {
7121       hdr->sh_type = SHT_MIPS_DEBUG;
7122       /* In a shared object on IRIX 5.3, the .mdebug section has an
7123          entsize of 0.  FIXME: Does this matter?  */
7124       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
7125         hdr->sh_entsize = 0;
7126       else
7127         hdr->sh_entsize = 1;
7128     }
7129   else if (strcmp (name, ".reginfo") == 0)
7130     {
7131       hdr->sh_type = SHT_MIPS_REGINFO;
7132       /* In a shared object on IRIX 5.3, the .reginfo section has an
7133          entsize of 0x18.  FIXME: Does this matter?  */
7134       if (SGI_COMPAT (abfd))
7135         {
7136           if ((abfd->flags & DYNAMIC) != 0)
7137             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
7138           else
7139             hdr->sh_entsize = 1;
7140         }
7141       else
7142         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
7143     }
7144   else if (SGI_COMPAT (abfd)
7145            && (strcmp (name, ".hash") == 0
7146                || strcmp (name, ".dynamic") == 0
7147                || strcmp (name, ".dynstr") == 0))
7148     {
7149       if (SGI_COMPAT (abfd))
7150         hdr->sh_entsize = 0;
7151 #if 0
7152       /* This isn't how the IRIX6 linker behaves.  */
7153       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
7154 #endif
7155     }
7156   else if (strcmp (name, ".got") == 0
7157            || strcmp (name, ".srdata") == 0
7158            || strcmp (name, ".sdata") == 0
7159            || strcmp (name, ".sbss") == 0
7160            || strcmp (name, ".lit4") == 0
7161            || strcmp (name, ".lit8") == 0)
7162     hdr->sh_flags |= SHF_MIPS_GPREL;
7163   else if (strcmp (name, ".MIPS.interfaces") == 0)
7164     {
7165       hdr->sh_type = SHT_MIPS_IFACE;
7166       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7167     }
7168   else if (CONST_STRNEQ (name, ".MIPS.content"))
7169     {
7170       hdr->sh_type = SHT_MIPS_CONTENT;
7171       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7172       /* The sh_info field is set in final_write_processing.  */
7173     }
7174   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
7175     {
7176       hdr->sh_type = SHT_MIPS_OPTIONS;
7177       hdr->sh_entsize = 1;
7178       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7179     }
7180   else if (CONST_STRNEQ (name, ".MIPS.abiflags"))
7181     {
7182       hdr->sh_type = SHT_MIPS_ABIFLAGS;
7183       hdr->sh_entsize = sizeof (Elf_External_ABIFlags_v0);
7184     }
7185   else if (CONST_STRNEQ (name, ".debug_")
7186            || CONST_STRNEQ (name, ".zdebug_"))
7187     {
7188       hdr->sh_type = SHT_MIPS_DWARF;
7189
7190       /* Irix facilities such as libexc expect a single .debug_frame
7191          per executable, the system ones have NOSTRIP set and the linker
7192          doesn't merge sections with different flags so ...  */
7193       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
7194         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7195     }
7196   else if (strcmp (name, ".MIPS.symlib") == 0)
7197     {
7198       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
7199       /* The sh_link and sh_info fields are set in
7200          final_write_processing.  */
7201     }
7202   else if (CONST_STRNEQ (name, ".MIPS.events")
7203            || CONST_STRNEQ (name, ".MIPS.post_rel"))
7204     {
7205       hdr->sh_type = SHT_MIPS_EVENTS;
7206       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
7207       /* The sh_link field is set in final_write_processing.  */
7208     }
7209   else if (strcmp (name, ".msym") == 0)
7210     {
7211       hdr->sh_type = SHT_MIPS_MSYM;
7212       hdr->sh_flags |= SHF_ALLOC;
7213       hdr->sh_entsize = 8;
7214     }
7215
7216   /* The generic elf_fake_sections will set up REL_HDR using the default
7217    kind of relocations.  We used to set up a second header for the
7218    non-default kind of relocations here, but only NewABI would use
7219    these, and the IRIX ld doesn't like resulting empty RELA sections.
7220    Thus we create those header only on demand now.  */
7221
7222   return TRUE;
7223 }
7224
7225 /* Given a BFD section, try to locate the corresponding ELF section
7226    index.  This is used by both the 32-bit and the 64-bit ABI.
7227    Actually, it's not clear to me that the 64-bit ABI supports these,
7228    but for non-PIC objects we will certainly want support for at least
7229    the .scommon section.  */
7230
7231 bfd_boolean
7232 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
7233                                         asection *sec, int *retval)
7234 {
7235   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
7236     {
7237       *retval = SHN_MIPS_SCOMMON;
7238       return TRUE;
7239     }
7240   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
7241     {
7242       *retval = SHN_MIPS_ACOMMON;
7243       return TRUE;
7244     }
7245   return FALSE;
7246 }
7247 \f
7248 /* Hook called by the linker routine which adds symbols from an object
7249    file.  We must handle the special MIPS section numbers here.  */
7250
7251 bfd_boolean
7252 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
7253                                Elf_Internal_Sym *sym, const char **namep,
7254                                flagword *flagsp ATTRIBUTE_UNUSED,
7255                                asection **secp, bfd_vma *valp)
7256 {
7257   if (SGI_COMPAT (abfd)
7258       && (abfd->flags & DYNAMIC) != 0
7259       && strcmp (*namep, "_rld_new_interface") == 0)
7260     {
7261       /* Skip IRIX5 rld entry name.  */
7262       *namep = NULL;
7263       return TRUE;
7264     }
7265
7266   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
7267      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
7268      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
7269      a magic symbol resolved by the linker, we ignore this bogus definition
7270      of _gp_disp.  New ABI objects do not suffer from this problem so this
7271      is not done for them. */
7272   if (!NEWABI_P(abfd)
7273       && (sym->st_shndx == SHN_ABS)
7274       && (strcmp (*namep, "_gp_disp") == 0))
7275     {
7276       *namep = NULL;
7277       return TRUE;
7278     }
7279
7280   switch (sym->st_shndx)
7281     {
7282     case SHN_COMMON:
7283       /* Common symbols less than the GP size are automatically
7284          treated as SHN_MIPS_SCOMMON symbols.  */
7285       if (sym->st_size > elf_gp_size (abfd)
7286           || ELF_ST_TYPE (sym->st_info) == STT_TLS
7287           || IRIX_COMPAT (abfd) == ict_irix6)
7288         break;
7289       /* Fall through.  */
7290     case SHN_MIPS_SCOMMON:
7291       *secp = bfd_make_section_old_way (abfd, ".scommon");
7292       (*secp)->flags |= SEC_IS_COMMON;
7293       *valp = sym->st_size;
7294       break;
7295
7296     case SHN_MIPS_TEXT:
7297       /* This section is used in a shared object.  */
7298       if (mips_elf_tdata (abfd)->elf_text_section == NULL)
7299         {
7300           asymbol *elf_text_symbol;
7301           asection *elf_text_section;
7302           bfd_size_type amt = sizeof (asection);
7303
7304           elf_text_section = bfd_zalloc (abfd, amt);
7305           if (elf_text_section == NULL)
7306             return FALSE;
7307
7308           amt = sizeof (asymbol);
7309           elf_text_symbol = bfd_zalloc (abfd, amt);
7310           if (elf_text_symbol == NULL)
7311             return FALSE;
7312
7313           /* Initialize the section.  */
7314
7315           mips_elf_tdata (abfd)->elf_text_section = elf_text_section;
7316           mips_elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
7317
7318           elf_text_section->symbol = elf_text_symbol;
7319           elf_text_section->symbol_ptr_ptr = &mips_elf_tdata (abfd)->elf_text_symbol;
7320
7321           elf_text_section->name = ".text";
7322           elf_text_section->flags = SEC_NO_FLAGS;
7323           elf_text_section->output_section = NULL;
7324           elf_text_section->owner = abfd;
7325           elf_text_symbol->name = ".text";
7326           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7327           elf_text_symbol->section = elf_text_section;
7328         }
7329       /* This code used to do *secp = bfd_und_section_ptr if
7330          info->shared.  I don't know why, and that doesn't make sense,
7331          so I took it out.  */
7332       *secp = mips_elf_tdata (abfd)->elf_text_section;
7333       break;
7334
7335     case SHN_MIPS_ACOMMON:
7336       /* Fall through. XXX Can we treat this as allocated data?  */
7337     case SHN_MIPS_DATA:
7338       /* This section is used in a shared object.  */
7339       if (mips_elf_tdata (abfd)->elf_data_section == NULL)
7340         {
7341           asymbol *elf_data_symbol;
7342           asection *elf_data_section;
7343           bfd_size_type amt = sizeof (asection);
7344
7345           elf_data_section = bfd_zalloc (abfd, amt);
7346           if (elf_data_section == NULL)
7347             return FALSE;
7348
7349           amt = sizeof (asymbol);
7350           elf_data_symbol = bfd_zalloc (abfd, amt);
7351           if (elf_data_symbol == NULL)
7352             return FALSE;
7353
7354           /* Initialize the section.  */
7355
7356           mips_elf_tdata (abfd)->elf_data_section = elf_data_section;
7357           mips_elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
7358
7359           elf_data_section->symbol = elf_data_symbol;
7360           elf_data_section->symbol_ptr_ptr = &mips_elf_tdata (abfd)->elf_data_symbol;
7361
7362           elf_data_section->name = ".data";
7363           elf_data_section->flags = SEC_NO_FLAGS;
7364           elf_data_section->output_section = NULL;
7365           elf_data_section->owner = abfd;
7366           elf_data_symbol->name = ".data";
7367           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7368           elf_data_symbol->section = elf_data_section;
7369         }
7370       /* This code used to do *secp = bfd_und_section_ptr if
7371          info->shared.  I don't know why, and that doesn't make sense,
7372          so I took it out.  */
7373       *secp = mips_elf_tdata (abfd)->elf_data_section;
7374       break;
7375
7376     case SHN_MIPS_SUNDEFINED:
7377       *secp = bfd_und_section_ptr;
7378       break;
7379     }
7380
7381   if (SGI_COMPAT (abfd)
7382       && ! info->shared
7383       && info->output_bfd->xvec == abfd->xvec
7384       && strcmp (*namep, "__rld_obj_head") == 0)
7385     {
7386       struct elf_link_hash_entry *h;
7387       struct bfd_link_hash_entry *bh;
7388
7389       /* Mark __rld_obj_head as dynamic.  */
7390       bh = NULL;
7391       if (! (_bfd_generic_link_add_one_symbol
7392              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
7393               get_elf_backend_data (abfd)->collect, &bh)))
7394         return FALSE;
7395
7396       h = (struct elf_link_hash_entry *) bh;
7397       h->non_elf = 0;
7398       h->def_regular = 1;
7399       h->type = STT_OBJECT;
7400
7401       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7402         return FALSE;
7403
7404       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
7405       mips_elf_hash_table (info)->rld_symbol = h;
7406     }
7407
7408   /* If this is a mips16 text symbol, add 1 to the value to make it
7409      odd.  This will cause something like .word SYM to come up with
7410      the right value when it is loaded into the PC.  */
7411   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7412     ++*valp;
7413
7414   return TRUE;
7415 }
7416
7417 /* This hook function is called before the linker writes out a global
7418    symbol.  We mark symbols as small common if appropriate.  This is
7419    also where we undo the increment of the value for a mips16 symbol.  */
7420
7421 int
7422 _bfd_mips_elf_link_output_symbol_hook
7423   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
7424    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
7425    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
7426 {
7427   /* If we see a common symbol, which implies a relocatable link, then
7428      if a symbol was small common in an input file, mark it as small
7429      common in the output file.  */
7430   if (sym->st_shndx == SHN_COMMON
7431       && strcmp (input_sec->name, ".scommon") == 0)
7432     sym->st_shndx = SHN_MIPS_SCOMMON;
7433
7434   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7435     sym->st_value &= ~1;
7436
7437   return 1;
7438 }
7439 \f
7440 /* Functions for the dynamic linker.  */
7441
7442 /* Create dynamic sections when linking against a dynamic object.  */
7443
7444 bfd_boolean
7445 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
7446 {
7447   struct elf_link_hash_entry *h;
7448   struct bfd_link_hash_entry *bh;
7449   flagword flags;
7450   register asection *s;
7451   const char * const *namep;
7452   struct mips_elf_link_hash_table *htab;
7453
7454   htab = mips_elf_hash_table (info);
7455   BFD_ASSERT (htab != NULL);
7456
7457   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
7458            | SEC_LINKER_CREATED | SEC_READONLY);
7459
7460   /* The psABI requires a read-only .dynamic section, but the VxWorks
7461      EABI doesn't.  */
7462   if (!htab->is_vxworks)
7463     {
7464       s = bfd_get_linker_section (abfd, ".dynamic");
7465       if (s != NULL)
7466         {
7467           if (! bfd_set_section_flags (abfd, s, flags))
7468             return FALSE;
7469         }
7470     }
7471
7472   /* We need to create .got section.  */
7473   if (!mips_elf_create_got_section (abfd, info))
7474     return FALSE;
7475
7476   if (! mips_elf_rel_dyn_section (info, TRUE))
7477     return FALSE;
7478
7479   /* Create .stub section.  */
7480   s = bfd_make_section_anyway_with_flags (abfd,
7481                                           MIPS_ELF_STUB_SECTION_NAME (abfd),
7482                                           flags | SEC_CODE);
7483   if (s == NULL
7484       || ! bfd_set_section_alignment (abfd, s,
7485                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7486     return FALSE;
7487   htab->sstubs = s;
7488
7489   if (!mips_elf_hash_table (info)->use_rld_obj_head
7490       && !info->shared
7491       && bfd_get_linker_section (abfd, ".rld_map") == NULL)
7492     {
7493       s = bfd_make_section_anyway_with_flags (abfd, ".rld_map",
7494                                               flags &~ (flagword) SEC_READONLY);
7495       if (s == NULL
7496           || ! bfd_set_section_alignment (abfd, s,
7497                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7498         return FALSE;
7499     }
7500
7501   /* On IRIX5, we adjust add some additional symbols and change the
7502      alignments of several sections.  There is no ABI documentation
7503      indicating that this is necessary on IRIX6, nor any evidence that
7504      the linker takes such action.  */
7505   if (IRIX_COMPAT (abfd) == ict_irix5)
7506     {
7507       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7508         {
7509           bh = NULL;
7510           if (! (_bfd_generic_link_add_one_symbol
7511                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7512                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7513             return FALSE;
7514
7515           h = (struct elf_link_hash_entry *) bh;
7516           h->non_elf = 0;
7517           h->def_regular = 1;
7518           h->type = STT_SECTION;
7519
7520           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7521             return FALSE;
7522         }
7523
7524       /* We need to create a .compact_rel section.  */
7525       if (SGI_COMPAT (abfd))
7526         {
7527           if (!mips_elf_create_compact_rel_section (abfd, info))
7528             return FALSE;
7529         }
7530
7531       /* Change alignments of some sections.  */
7532       s = bfd_get_linker_section (abfd, ".hash");
7533       if (s != NULL)
7534         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7535
7536       s = bfd_get_linker_section (abfd, ".dynsym");
7537       if (s != NULL)
7538         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7539
7540       s = bfd_get_linker_section (abfd, ".dynstr");
7541       if (s != NULL)
7542         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7543
7544       /* ??? */
7545       s = bfd_get_section_by_name (abfd, ".reginfo");
7546       if (s != NULL)
7547         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7548
7549       s = bfd_get_linker_section (abfd, ".dynamic");
7550       if (s != NULL)
7551         (void) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7552     }
7553
7554   if (!info->shared)
7555     {
7556       const char *name;
7557
7558       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7559       bh = NULL;
7560       if (!(_bfd_generic_link_add_one_symbol
7561             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7562              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7563         return FALSE;
7564
7565       h = (struct elf_link_hash_entry *) bh;
7566       h->non_elf = 0;
7567       h->def_regular = 1;
7568       h->type = STT_SECTION;
7569
7570       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7571         return FALSE;
7572
7573       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7574         {
7575           /* __rld_map is a four byte word located in the .data section
7576              and is filled in by the rtld to contain a pointer to
7577              the _r_debug structure. Its symbol value will be set in
7578              _bfd_mips_elf_finish_dynamic_symbol.  */
7579           s = bfd_get_linker_section (abfd, ".rld_map");
7580           BFD_ASSERT (s != NULL);
7581
7582           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7583           bh = NULL;
7584           if (!(_bfd_generic_link_add_one_symbol
7585                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7586                  get_elf_backend_data (abfd)->collect, &bh)))
7587             return FALSE;
7588
7589           h = (struct elf_link_hash_entry *) bh;
7590           h->non_elf = 0;
7591           h->def_regular = 1;
7592           h->type = STT_OBJECT;
7593
7594           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7595             return FALSE;
7596           mips_elf_hash_table (info)->rld_symbol = h;
7597         }
7598     }
7599
7600   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7601      Also, on VxWorks, create the _PROCEDURE_LINKAGE_TABLE_ symbol.  */
7602   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7603     return FALSE;
7604
7605   /* Cache the sections created above.  */
7606   htab->splt = bfd_get_linker_section (abfd, ".plt");
7607   htab->sdynbss = bfd_get_linker_section (abfd, ".dynbss");
7608   if (htab->is_vxworks)
7609     {
7610       htab->srelbss = bfd_get_linker_section (abfd, ".rela.bss");
7611       htab->srelplt = bfd_get_linker_section (abfd, ".rela.plt");
7612     }
7613   else
7614     htab->srelplt = bfd_get_linker_section (abfd, ".rel.plt");
7615   if (!htab->sdynbss
7616       || (htab->is_vxworks && !htab->srelbss && !info->shared)
7617       || !htab->srelplt
7618       || !htab->splt)
7619     abort ();
7620
7621   /* Do the usual VxWorks handling.  */
7622   if (htab->is_vxworks
7623       && !elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7624     return FALSE;
7625
7626   return TRUE;
7627 }
7628 \f
7629 /* Return true if relocation REL against section SEC is a REL rather than
7630    RELA relocation.  RELOCS is the first relocation in the section and
7631    ABFD is the bfd that contains SEC.  */
7632
7633 static bfd_boolean
7634 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7635                            const Elf_Internal_Rela *relocs,
7636                            const Elf_Internal_Rela *rel)
7637 {
7638   Elf_Internal_Shdr *rel_hdr;
7639   const struct elf_backend_data *bed;
7640
7641   /* To determine which flavor of relocation this is, we depend on the
7642      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7643   rel_hdr = elf_section_data (sec)->rel.hdr;
7644   if (rel_hdr == NULL)
7645     return FALSE;
7646   bed = get_elf_backend_data (abfd);
7647   return ((size_t) (rel - relocs)
7648           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7649 }
7650
7651 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7652    HOWTO is the relocation's howto and CONTENTS points to the contents
7653    of the section that REL is against.  */
7654
7655 static bfd_vma
7656 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7657                           reloc_howto_type *howto, bfd_byte *contents)
7658 {
7659   bfd_byte *location;
7660   unsigned int r_type;
7661   bfd_vma addend;
7662
7663   r_type = ELF_R_TYPE (abfd, rel->r_info);
7664   location = contents + rel->r_offset;
7665
7666   /* Get the addend, which is stored in the input file.  */
7667   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7668   addend = mips_elf_obtain_contents (howto, rel, abfd, contents);
7669   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7670
7671   return addend & howto->src_mask;
7672 }
7673
7674 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7675    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7676    and update *ADDEND with the final addend.  Return true on success
7677    or false if the LO16 could not be found.  RELEND is the exclusive
7678    upper bound on the relocations for REL's section.  */
7679
7680 static bfd_boolean
7681 mips_elf_add_lo16_rel_addend (bfd *abfd,
7682                               const Elf_Internal_Rela *rel,
7683                               const Elf_Internal_Rela *relend,
7684                               bfd_byte *contents, bfd_vma *addend)
7685 {
7686   unsigned int r_type, lo16_type;
7687   const Elf_Internal_Rela *lo16_relocation;
7688   reloc_howto_type *lo16_howto;
7689   bfd_vma l;
7690
7691   r_type = ELF_R_TYPE (abfd, rel->r_info);
7692   if (mips16_reloc_p (r_type))
7693     lo16_type = R_MIPS16_LO16;
7694   else if (micromips_reloc_p (r_type))
7695     lo16_type = R_MICROMIPS_LO16;
7696   else
7697     lo16_type = R_MIPS_LO16;
7698
7699   /* The combined value is the sum of the HI16 addend, left-shifted by
7700      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7701      code does a `lui' of the HI16 value, and then an `addiu' of the
7702      LO16 value.)
7703
7704      Scan ahead to find a matching LO16 relocation.
7705
7706      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7707      be immediately following.  However, for the IRIX6 ABI, the next
7708      relocation may be a composed relocation consisting of several
7709      relocations for the same address.  In that case, the R_MIPS_LO16
7710      relocation may occur as one of these.  We permit a similar
7711      extension in general, as that is useful for GCC.
7712
7713      In some cases GCC dead code elimination removes the LO16 but keeps
7714      the corresponding HI16.  This is strictly speaking a violation of
7715      the ABI but not immediately harmful.  */
7716   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
7717   if (lo16_relocation == NULL)
7718     return FALSE;
7719
7720   /* Obtain the addend kept there.  */
7721   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
7722   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
7723
7724   l <<= lo16_howto->rightshift;
7725   l = _bfd_mips_elf_sign_extend (l, 16);
7726
7727   *addend <<= 16;
7728   *addend += l;
7729   return TRUE;
7730 }
7731
7732 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
7733    store the contents in *CONTENTS on success.  Assume that *CONTENTS
7734    already holds the contents if it is nonull on entry.  */
7735
7736 static bfd_boolean
7737 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
7738 {
7739   if (*contents)
7740     return TRUE;
7741
7742   /* Get cached copy if it exists.  */
7743   if (elf_section_data (sec)->this_hdr.contents != NULL)
7744     {
7745       *contents = elf_section_data (sec)->this_hdr.contents;
7746       return TRUE;
7747     }
7748
7749   return bfd_malloc_and_get_section (abfd, sec, contents);
7750 }
7751
7752 /* Make a new PLT record to keep internal data.  */
7753
7754 static struct plt_entry *
7755 mips_elf_make_plt_record (bfd *abfd)
7756 {
7757   struct plt_entry *entry;
7758
7759   entry = bfd_zalloc (abfd, sizeof (*entry));
7760   if (entry == NULL)
7761     return NULL;
7762
7763   entry->stub_offset = MINUS_ONE;
7764   entry->mips_offset = MINUS_ONE;
7765   entry->comp_offset = MINUS_ONE;
7766   entry->gotplt_index = MINUS_ONE;
7767   return entry;
7768 }
7769
7770 /* Look through the relocs for a section during the first phase, and
7771    allocate space in the global offset table and record the need for
7772    standard MIPS and compressed procedure linkage table entries.  */
7773
7774 bfd_boolean
7775 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
7776                             asection *sec, const Elf_Internal_Rela *relocs)
7777 {
7778   const char *name;
7779   bfd *dynobj;
7780   Elf_Internal_Shdr *symtab_hdr;
7781   struct elf_link_hash_entry **sym_hashes;
7782   size_t extsymoff;
7783   const Elf_Internal_Rela *rel;
7784   const Elf_Internal_Rela *rel_end;
7785   asection *sreloc;
7786   const struct elf_backend_data *bed;
7787   struct mips_elf_link_hash_table *htab;
7788   bfd_byte *contents;
7789   bfd_vma addend;
7790   reloc_howto_type *howto;
7791
7792   if (info->relocatable)
7793     return TRUE;
7794
7795   htab = mips_elf_hash_table (info);
7796   BFD_ASSERT (htab != NULL);
7797
7798   dynobj = elf_hash_table (info)->dynobj;
7799   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7800   sym_hashes = elf_sym_hashes (abfd);
7801   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
7802
7803   bed = get_elf_backend_data (abfd);
7804   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
7805
7806   /* Check for the mips16 stub sections.  */
7807
7808   name = bfd_get_section_name (abfd, sec);
7809   if (FN_STUB_P (name))
7810     {
7811       unsigned long r_symndx;
7812
7813       /* Look at the relocation information to figure out which symbol
7814          this is for.  */
7815
7816       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7817       if (r_symndx == 0)
7818         {
7819           (*_bfd_error_handler)
7820             (_("%B: Warning: cannot determine the target function for"
7821                " stub section `%s'"),
7822              abfd, name);
7823           bfd_set_error (bfd_error_bad_value);
7824           return FALSE;
7825         }
7826
7827       if (r_symndx < extsymoff
7828           || sym_hashes[r_symndx - extsymoff] == NULL)
7829         {
7830           asection *o;
7831
7832           /* This stub is for a local symbol.  This stub will only be
7833              needed if there is some relocation in this BFD, other
7834              than a 16 bit function call, which refers to this symbol.  */
7835           for (o = abfd->sections; o != NULL; o = o->next)
7836             {
7837               Elf_Internal_Rela *sec_relocs;
7838               const Elf_Internal_Rela *r, *rend;
7839
7840               /* We can ignore stub sections when looking for relocs.  */
7841               if ((o->flags & SEC_RELOC) == 0
7842                   || o->reloc_count == 0
7843                   || section_allows_mips16_refs_p (o))
7844                 continue;
7845
7846               sec_relocs
7847                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7848                                              info->keep_memory);
7849               if (sec_relocs == NULL)
7850                 return FALSE;
7851
7852               rend = sec_relocs + o->reloc_count;
7853               for (r = sec_relocs; r < rend; r++)
7854                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7855                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
7856                   break;
7857
7858               if (elf_section_data (o)->relocs != sec_relocs)
7859                 free (sec_relocs);
7860
7861               if (r < rend)
7862                 break;
7863             }
7864
7865           if (o == NULL)
7866             {
7867               /* There is no non-call reloc for this stub, so we do
7868                  not need it.  Since this function is called before
7869                  the linker maps input sections to output sections, we
7870                  can easily discard it by setting the SEC_EXCLUDE
7871                  flag.  */
7872               sec->flags |= SEC_EXCLUDE;
7873               return TRUE;
7874             }
7875
7876           /* Record this stub in an array of local symbol stubs for
7877              this BFD.  */
7878           if (mips_elf_tdata (abfd)->local_stubs == NULL)
7879             {
7880               unsigned long symcount;
7881               asection **n;
7882               bfd_size_type amt;
7883
7884               if (elf_bad_symtab (abfd))
7885                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7886               else
7887                 symcount = symtab_hdr->sh_info;
7888               amt = symcount * sizeof (asection *);
7889               n = bfd_zalloc (abfd, amt);
7890               if (n == NULL)
7891                 return FALSE;
7892               mips_elf_tdata (abfd)->local_stubs = n;
7893             }
7894
7895           sec->flags |= SEC_KEEP;
7896           mips_elf_tdata (abfd)->local_stubs[r_symndx] = sec;
7897
7898           /* We don't need to set mips16_stubs_seen in this case.
7899              That flag is used to see whether we need to look through
7900              the global symbol table for stubs.  We don't need to set
7901              it here, because we just have a local stub.  */
7902         }
7903       else
7904         {
7905           struct mips_elf_link_hash_entry *h;
7906
7907           h = ((struct mips_elf_link_hash_entry *)
7908                sym_hashes[r_symndx - extsymoff]);
7909
7910           while (h->root.root.type == bfd_link_hash_indirect
7911                  || h->root.root.type == bfd_link_hash_warning)
7912             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
7913
7914           /* H is the symbol this stub is for.  */
7915
7916           /* If we already have an appropriate stub for this function, we
7917              don't need another one, so we can discard this one.  Since
7918              this function is called before the linker maps input sections
7919              to output sections, we can easily discard it by setting the
7920              SEC_EXCLUDE flag.  */
7921           if (h->fn_stub != NULL)
7922             {
7923               sec->flags |= SEC_EXCLUDE;
7924               return TRUE;
7925             }
7926
7927           sec->flags |= SEC_KEEP;
7928           h->fn_stub = sec;
7929           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7930         }
7931     }
7932   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
7933     {
7934       unsigned long r_symndx;
7935       struct mips_elf_link_hash_entry *h;
7936       asection **loc;
7937
7938       /* Look at the relocation information to figure out which symbol
7939          this is for.  */
7940
7941       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7942       if (r_symndx == 0)
7943         {
7944           (*_bfd_error_handler)
7945             (_("%B: Warning: cannot determine the target function for"
7946                " stub section `%s'"),
7947              abfd, name);
7948           bfd_set_error (bfd_error_bad_value);
7949           return FALSE;
7950         }
7951
7952       if (r_symndx < extsymoff
7953           || sym_hashes[r_symndx - extsymoff] == NULL)
7954         {
7955           asection *o;
7956
7957           /* This stub is for a local symbol.  This stub will only be
7958              needed if there is some relocation (R_MIPS16_26) in this BFD
7959              that refers to this symbol.  */
7960           for (o = abfd->sections; o != NULL; o = o->next)
7961             {
7962               Elf_Internal_Rela *sec_relocs;
7963               const Elf_Internal_Rela *r, *rend;
7964
7965               /* We can ignore stub sections when looking for relocs.  */
7966               if ((o->flags & SEC_RELOC) == 0
7967                   || o->reloc_count == 0
7968                   || section_allows_mips16_refs_p (o))
7969                 continue;
7970
7971               sec_relocs
7972                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7973                                              info->keep_memory);
7974               if (sec_relocs == NULL)
7975                 return FALSE;
7976
7977               rend = sec_relocs + o->reloc_count;
7978               for (r = sec_relocs; r < rend; r++)
7979                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7980                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
7981                     break;
7982
7983               if (elf_section_data (o)->relocs != sec_relocs)
7984                 free (sec_relocs);
7985
7986               if (r < rend)
7987                 break;
7988             }
7989
7990           if (o == NULL)
7991             {
7992               /* There is no non-call reloc for this stub, so we do
7993                  not need it.  Since this function is called before
7994                  the linker maps input sections to output sections, we
7995                  can easily discard it by setting the SEC_EXCLUDE
7996                  flag.  */
7997               sec->flags |= SEC_EXCLUDE;
7998               return TRUE;
7999             }
8000
8001           /* Record this stub in an array of local symbol call_stubs for
8002              this BFD.  */
8003           if (mips_elf_tdata (abfd)->local_call_stubs == NULL)
8004             {
8005               unsigned long symcount;
8006               asection **n;
8007               bfd_size_type amt;
8008
8009               if (elf_bad_symtab (abfd))
8010                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
8011               else
8012                 symcount = symtab_hdr->sh_info;
8013               amt = symcount * sizeof (asection *);
8014               n = bfd_zalloc (abfd, amt);
8015               if (n == NULL)
8016                 return FALSE;
8017               mips_elf_tdata (abfd)->local_call_stubs = n;
8018             }
8019
8020           sec->flags |= SEC_KEEP;
8021           mips_elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
8022
8023           /* We don't need to set mips16_stubs_seen in this case.
8024              That flag is used to see whether we need to look through
8025              the global symbol table for stubs.  We don't need to set
8026              it here, because we just have a local stub.  */
8027         }
8028       else
8029         {
8030           h = ((struct mips_elf_link_hash_entry *)
8031                sym_hashes[r_symndx - extsymoff]);
8032
8033           /* H is the symbol this stub is for.  */
8034
8035           if (CALL_FP_STUB_P (name))
8036             loc = &h->call_fp_stub;
8037           else
8038             loc = &h->call_stub;
8039
8040           /* If we already have an appropriate stub for this function, we
8041              don't need another one, so we can discard this one.  Since
8042              this function is called before the linker maps input sections
8043              to output sections, we can easily discard it by setting the
8044              SEC_EXCLUDE flag.  */
8045           if (*loc != NULL)
8046             {
8047               sec->flags |= SEC_EXCLUDE;
8048               return TRUE;
8049             }
8050
8051           sec->flags |= SEC_KEEP;
8052           *loc = sec;
8053           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
8054         }
8055     }
8056
8057   sreloc = NULL;
8058   contents = NULL;
8059   for (rel = relocs; rel < rel_end; ++rel)
8060     {
8061       unsigned long r_symndx;
8062       unsigned int r_type;
8063       struct elf_link_hash_entry *h;
8064       bfd_boolean can_make_dynamic_p;
8065       bfd_boolean call_reloc_p;
8066       bfd_boolean constrain_symbol_p;
8067
8068       r_symndx = ELF_R_SYM (abfd, rel->r_info);
8069       r_type = ELF_R_TYPE (abfd, rel->r_info);
8070
8071       if (r_symndx < extsymoff)
8072         h = NULL;
8073       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
8074         {
8075           (*_bfd_error_handler)
8076             (_("%B: Malformed reloc detected for section %s"),
8077              abfd, name);
8078           bfd_set_error (bfd_error_bad_value);
8079           return FALSE;
8080         }
8081       else
8082         {
8083           h = sym_hashes[r_symndx - extsymoff];
8084           if (h != NULL)
8085             {
8086               while (h->root.type == bfd_link_hash_indirect
8087                      || h->root.type == bfd_link_hash_warning)
8088                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
8089
8090               /* PR15323, ref flags aren't set for references in the
8091                  same object.  */
8092               h->root.non_ir_ref = 1;
8093             }
8094         }
8095
8096       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
8097          relocation into a dynamic one.  */
8098       can_make_dynamic_p = FALSE;
8099
8100       /* Set CALL_RELOC_P to true if the relocation is for a call,
8101          and if pointer equality therefore doesn't matter.  */
8102       call_reloc_p = FALSE;
8103
8104       /* Set CONSTRAIN_SYMBOL_P if we need to take the relocation
8105          into account when deciding how to define the symbol.
8106          Relocations in nonallocatable sections such as .pdr and
8107          .debug* should have no effect.  */
8108       constrain_symbol_p = ((sec->flags & SEC_ALLOC) != 0);
8109
8110       switch (r_type)
8111         {
8112         case R_MIPS_CALL16:
8113         case R_MIPS_CALL_HI16:
8114         case R_MIPS_CALL_LO16:
8115         case R_MIPS16_CALL16:
8116         case R_MICROMIPS_CALL16:
8117         case R_MICROMIPS_CALL_HI16:
8118         case R_MICROMIPS_CALL_LO16:
8119           call_reloc_p = TRUE;
8120           /* Fall through.  */
8121
8122         case R_MIPS_GOT16:
8123         case R_MIPS_GOT_HI16:
8124         case R_MIPS_GOT_LO16:
8125         case R_MIPS_GOT_PAGE:
8126         case R_MIPS_GOT_OFST:
8127         case R_MIPS_GOT_DISP:
8128         case R_MIPS_TLS_GOTTPREL:
8129         case R_MIPS_TLS_GD:
8130         case R_MIPS_TLS_LDM:
8131         case R_MIPS16_GOT16:
8132         case R_MIPS16_TLS_GOTTPREL:
8133         case R_MIPS16_TLS_GD:
8134         case R_MIPS16_TLS_LDM:
8135         case R_MICROMIPS_GOT16:
8136         case R_MICROMIPS_GOT_HI16:
8137         case R_MICROMIPS_GOT_LO16:
8138         case R_MICROMIPS_GOT_PAGE:
8139         case R_MICROMIPS_GOT_OFST:
8140         case R_MICROMIPS_GOT_DISP:
8141         case R_MICROMIPS_TLS_GOTTPREL:
8142         case R_MICROMIPS_TLS_GD:
8143         case R_MICROMIPS_TLS_LDM:
8144           if (dynobj == NULL)
8145             elf_hash_table (info)->dynobj = dynobj = abfd;
8146           if (!mips_elf_create_got_section (dynobj, info))
8147             return FALSE;
8148           if (htab->is_vxworks && !info->shared)
8149             {
8150               (*_bfd_error_handler)
8151                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
8152                  abfd, (unsigned long) rel->r_offset);
8153               bfd_set_error (bfd_error_bad_value);
8154               return FALSE;
8155             }
8156           can_make_dynamic_p = TRUE;
8157           break;
8158
8159         case R_MIPS_NONE:
8160         case R_MIPS_JALR:
8161         case R_MICROMIPS_JALR:
8162           /* These relocations have empty fields and are purely there to
8163              provide link information.  The symbol value doesn't matter.  */
8164           constrain_symbol_p = FALSE;
8165           break;
8166
8167         case R_MIPS_GPREL16:
8168         case R_MIPS_GPREL32:
8169         case R_MIPS16_GPREL:
8170         case R_MICROMIPS_GPREL16:
8171           /* GP-relative relocations always resolve to a definition in a
8172              regular input file, ignoring the one-definition rule.  This is
8173              important for the GP setup sequence in NewABI code, which
8174              always resolves to a local function even if other relocations
8175              against the symbol wouldn't.  */
8176           constrain_symbol_p = FALSE;
8177           break;
8178
8179         case R_MIPS_32:
8180         case R_MIPS_REL32:
8181         case R_MIPS_64:
8182           /* In VxWorks executables, references to external symbols
8183              must be handled using copy relocs or PLT entries; it is not
8184              possible to convert this relocation into a dynamic one.
8185
8186              For executables that use PLTs and copy-relocs, we have a
8187              choice between converting the relocation into a dynamic
8188              one or using copy relocations or PLT entries.  It is
8189              usually better to do the former, unless the relocation is
8190              against a read-only section.  */
8191           if ((info->shared
8192                || (h != NULL
8193                    && !htab->is_vxworks
8194                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
8195                    && !(!info->nocopyreloc
8196                         && !PIC_OBJECT_P (abfd)
8197                         && MIPS_ELF_READONLY_SECTION (sec))))
8198               && (sec->flags & SEC_ALLOC) != 0)
8199             {
8200               can_make_dynamic_p = TRUE;
8201               if (dynobj == NULL)
8202                 elf_hash_table (info)->dynobj = dynobj = abfd;
8203             }
8204           break;
8205
8206         case R_MIPS_26:
8207         case R_MIPS_PC16:
8208         case R_MIPS16_26:
8209         case R_MICROMIPS_26_S1:
8210         case R_MICROMIPS_PC7_S1:
8211         case R_MICROMIPS_PC10_S1:
8212         case R_MICROMIPS_PC16_S1:
8213         case R_MICROMIPS_PC23_S2:
8214           call_reloc_p = TRUE;
8215           break;
8216         }
8217
8218       if (h)
8219         {
8220           if (constrain_symbol_p)
8221             {
8222               if (!can_make_dynamic_p)
8223                 ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = 1;
8224
8225               if (!call_reloc_p)
8226                 h->pointer_equality_needed = 1;
8227
8228               /* We must not create a stub for a symbol that has
8229                  relocations related to taking the function's address.
8230                  This doesn't apply to VxWorks, where CALL relocs refer
8231                  to a .got.plt entry instead of a normal .got entry.  */
8232               if (!htab->is_vxworks && (!can_make_dynamic_p || !call_reloc_p))
8233                 ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8234             }
8235
8236           /* Relocations against the special VxWorks __GOTT_BASE__ and
8237              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
8238              room for them in .rela.dyn.  */
8239           if (is_gott_symbol (info, h))
8240             {
8241               if (sreloc == NULL)
8242                 {
8243                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8244                   if (sreloc == NULL)
8245                     return FALSE;
8246                 }
8247               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8248               if (MIPS_ELF_READONLY_SECTION (sec))
8249                 /* We tell the dynamic linker that there are
8250                    relocations against the text segment.  */
8251                 info->flags |= DF_TEXTREL;
8252             }
8253         }
8254       else if (call_lo16_reloc_p (r_type)
8255                || got_lo16_reloc_p (r_type)
8256                || got_disp_reloc_p (r_type)
8257                || (got16_reloc_p (r_type) && htab->is_vxworks))
8258         {
8259           /* We may need a local GOT entry for this relocation.  We
8260              don't count R_MIPS_GOT_PAGE because we can estimate the
8261              maximum number of pages needed by looking at the size of
8262              the segment.  Similar comments apply to R_MIPS*_GOT16 and
8263              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
8264              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
8265              R_MIPS_CALL_HI16 because these are always followed by an
8266              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
8267           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8268                                                  rel->r_addend, info, r_type))
8269             return FALSE;
8270         }
8271
8272       if (h != NULL
8273           && mips_elf_relocation_needs_la25_stub (abfd, r_type,
8274                                                   ELF_ST_IS_MIPS16 (h->other)))
8275         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
8276
8277       switch (r_type)
8278         {
8279         case R_MIPS_CALL16:
8280         case R_MIPS16_CALL16:
8281         case R_MICROMIPS_CALL16:
8282           if (h == NULL)
8283             {
8284               (*_bfd_error_handler)
8285                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
8286                  abfd, (unsigned long) rel->r_offset);
8287               bfd_set_error (bfd_error_bad_value);
8288               return FALSE;
8289             }
8290           /* Fall through.  */
8291
8292         case R_MIPS_CALL_HI16:
8293         case R_MIPS_CALL_LO16:
8294         case R_MICROMIPS_CALL_HI16:
8295         case R_MICROMIPS_CALL_LO16:
8296           if (h != NULL)
8297             {
8298               /* Make sure there is room in the regular GOT to hold the
8299                  function's address.  We may eliminate it in favour of
8300                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
8301               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE,
8302                                                       r_type))
8303                 return FALSE;
8304
8305               /* We need a stub, not a plt entry for the undefined
8306                  function.  But we record it as if it needs plt.  See
8307                  _bfd_elf_adjust_dynamic_symbol.  */
8308               h->needs_plt = 1;
8309               h->type = STT_FUNC;
8310             }
8311           break;
8312
8313         case R_MIPS_GOT_PAGE:
8314         case R_MICROMIPS_GOT_PAGE:
8315         case R_MIPS16_GOT16:
8316         case R_MIPS_GOT16:
8317         case R_MIPS_GOT_HI16:
8318         case R_MIPS_GOT_LO16:
8319         case R_MICROMIPS_GOT16:
8320         case R_MICROMIPS_GOT_HI16:
8321         case R_MICROMIPS_GOT_LO16:
8322           if (!h || got_page_reloc_p (r_type))
8323             {
8324               /* This relocation needs (or may need, if h != NULL) a
8325                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
8326                  know for sure until we know whether the symbol is
8327                  preemptible.  */
8328               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
8329                 {
8330                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
8331                     return FALSE;
8332                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8333                   addend = mips_elf_read_rel_addend (abfd, rel,
8334                                                      howto, contents);
8335                   if (got16_reloc_p (r_type))
8336                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
8337                                                   contents, &addend);
8338                   else
8339                     addend <<= howto->rightshift;
8340                 }
8341               else
8342                 addend = rel->r_addend;
8343               if (!mips_elf_record_got_page_ref (info, abfd, r_symndx,
8344                                                  h, addend))
8345                 return FALSE;
8346
8347               if (h)
8348                 {
8349                   struct mips_elf_link_hash_entry *hmips =
8350                     (struct mips_elf_link_hash_entry *) h;
8351
8352                   /* This symbol is definitely not overridable.  */
8353                   if (hmips->root.def_regular
8354                       && ! (info->shared && ! info->symbolic
8355                             && ! hmips->root.forced_local))
8356                     h = NULL;
8357                 }
8358             }
8359           /* If this is a global, overridable symbol, GOT_PAGE will
8360              decay to GOT_DISP, so we'll need a GOT entry for it.  */
8361           /* Fall through.  */
8362
8363         case R_MIPS_GOT_DISP:
8364         case R_MICROMIPS_GOT_DISP:
8365           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8366                                                        FALSE, r_type))
8367             return FALSE;
8368           break;
8369
8370         case R_MIPS_TLS_GOTTPREL:
8371         case R_MIPS16_TLS_GOTTPREL:
8372         case R_MICROMIPS_TLS_GOTTPREL:
8373           if (info->shared)
8374             info->flags |= DF_STATIC_TLS;
8375           /* Fall through */
8376
8377         case R_MIPS_TLS_LDM:
8378         case R_MIPS16_TLS_LDM:
8379         case R_MICROMIPS_TLS_LDM:
8380           if (tls_ldm_reloc_p (r_type))
8381             {
8382               r_symndx = STN_UNDEF;
8383               h = NULL;
8384             }
8385           /* Fall through */
8386
8387         case R_MIPS_TLS_GD:
8388         case R_MIPS16_TLS_GD:
8389         case R_MICROMIPS_TLS_GD:
8390           /* This symbol requires a global offset table entry, or two
8391              for TLS GD relocations.  */
8392           if (h != NULL)
8393             {
8394               if (!mips_elf_record_global_got_symbol (h, abfd, info,
8395                                                       FALSE, r_type))
8396                 return FALSE;
8397             }
8398           else
8399             {
8400               if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8401                                                      rel->r_addend,
8402                                                      info, r_type))
8403                 return FALSE;
8404             }
8405           break;
8406
8407         case R_MIPS_32:
8408         case R_MIPS_REL32:
8409         case R_MIPS_64:
8410           /* In VxWorks executables, references to external symbols
8411              are handled using copy relocs or PLT stubs, so there's
8412              no need to add a .rela.dyn entry for this relocation.  */
8413           if (can_make_dynamic_p)
8414             {
8415               if (sreloc == NULL)
8416                 {
8417                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8418                   if (sreloc == NULL)
8419                     return FALSE;
8420                 }
8421               if (info->shared && h == NULL)
8422                 {
8423                   /* When creating a shared object, we must copy these
8424                      reloc types into the output file as R_MIPS_REL32
8425                      relocs.  Make room for this reloc in .rel(a).dyn.  */
8426                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8427                   if (MIPS_ELF_READONLY_SECTION (sec))
8428                     /* We tell the dynamic linker that there are
8429                        relocations against the text segment.  */
8430                     info->flags |= DF_TEXTREL;
8431                 }
8432               else
8433                 {
8434                   struct mips_elf_link_hash_entry *hmips;
8435
8436                   /* For a shared object, we must copy this relocation
8437                      unless the symbol turns out to be undefined and
8438                      weak with non-default visibility, in which case
8439                      it will be left as zero.
8440
8441                      We could elide R_MIPS_REL32 for locally binding symbols
8442                      in shared libraries, but do not yet do so.
8443
8444                      For an executable, we only need to copy this
8445                      reloc if the symbol is defined in a dynamic
8446                      object.  */
8447                   hmips = (struct mips_elf_link_hash_entry *) h;
8448                   ++hmips->possibly_dynamic_relocs;
8449                   if (MIPS_ELF_READONLY_SECTION (sec))
8450                     /* We need it to tell the dynamic linker if there
8451                        are relocations against the text segment.  */
8452                     hmips->readonly_reloc = TRUE;
8453                 }
8454             }
8455
8456           if (SGI_COMPAT (abfd))
8457             mips_elf_hash_table (info)->compact_rel_size +=
8458               sizeof (Elf32_External_crinfo);
8459           break;
8460
8461         case R_MIPS_26:
8462         case R_MIPS_GPREL16:
8463         case R_MIPS_LITERAL:
8464         case R_MIPS_GPREL32:
8465         case R_MICROMIPS_26_S1:
8466         case R_MICROMIPS_GPREL16:
8467         case R_MICROMIPS_LITERAL:
8468         case R_MICROMIPS_GPREL7_S2:
8469           if (SGI_COMPAT (abfd))
8470             mips_elf_hash_table (info)->compact_rel_size +=
8471               sizeof (Elf32_External_crinfo);
8472           break;
8473
8474           /* This relocation describes the C++ object vtable hierarchy.
8475              Reconstruct it for later use during GC.  */
8476         case R_MIPS_GNU_VTINHERIT:
8477           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
8478             return FALSE;
8479           break;
8480
8481           /* This relocation describes which C++ vtable entries are actually
8482              used.  Record for later use during GC.  */
8483         case R_MIPS_GNU_VTENTRY:
8484           BFD_ASSERT (h != NULL);
8485           if (h != NULL
8486               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
8487             return FALSE;
8488           break;
8489
8490         default:
8491           break;
8492         }
8493
8494       /* Record the need for a PLT entry.  At this point we don't know
8495          yet if we are going to create a PLT in the first place, but
8496          we only record whether the relocation requires a standard MIPS
8497          or a compressed code entry anyway.  If we don't make a PLT after
8498          all, then we'll just ignore these arrangements.  Likewise if
8499          a PLT entry is not created because the symbol is satisfied
8500          locally.  */
8501       if (h != NULL
8502           && jal_reloc_p (r_type)
8503           && !SYMBOL_CALLS_LOCAL (info, h))
8504         {
8505           if (h->plt.plist == NULL)
8506             h->plt.plist = mips_elf_make_plt_record (abfd);
8507           if (h->plt.plist == NULL)
8508             return FALSE;
8509
8510           if (r_type == R_MIPS_26)
8511             h->plt.plist->need_mips = TRUE;
8512           else
8513             h->plt.plist->need_comp = TRUE;
8514         }
8515
8516       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8517          if there is one.  We only need to handle global symbols here;
8518          we decide whether to keep or delete stubs for local symbols
8519          when processing the stub's relocations.  */
8520       if (h != NULL
8521           && !mips16_call_reloc_p (r_type)
8522           && !section_allows_mips16_refs_p (sec))
8523         {
8524           struct mips_elf_link_hash_entry *mh;
8525
8526           mh = (struct mips_elf_link_hash_entry *) h;
8527           mh->need_fn_stub = TRUE;
8528         }
8529
8530       /* Refuse some position-dependent relocations when creating a
8531          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8532          not PIC, but we can create dynamic relocations and the result
8533          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8534          combined with R_MIPS_GOT16.  */
8535       if (info->shared)
8536         {
8537           switch (r_type)
8538             {
8539             case R_MIPS16_HI16:
8540             case R_MIPS_HI16:
8541             case R_MIPS_HIGHER:
8542             case R_MIPS_HIGHEST:
8543             case R_MICROMIPS_HI16:
8544             case R_MICROMIPS_HIGHER:
8545             case R_MICROMIPS_HIGHEST:
8546               /* Don't refuse a high part relocation if it's against
8547                  no symbol (e.g. part of a compound relocation).  */
8548               if (r_symndx == STN_UNDEF)
8549                 break;
8550
8551               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8552                  and has a special meaning.  */
8553               if (!NEWABI_P (abfd) && h != NULL
8554                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8555                 break;
8556
8557               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8558               if (is_gott_symbol (info, h))
8559                 break;
8560
8561               /* FALLTHROUGH */
8562
8563             case R_MIPS16_26:
8564             case R_MIPS_26:
8565             case R_MICROMIPS_26_S1:
8566               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8567               (*_bfd_error_handler)
8568                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8569                  abfd, howto->name,
8570                  (h) ? h->root.root.string : "a local symbol");
8571               bfd_set_error (bfd_error_bad_value);
8572               return FALSE;
8573             default:
8574               break;
8575             }
8576         }
8577     }
8578
8579   return TRUE;
8580 }
8581 \f
8582 bfd_boolean
8583 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8584                          struct bfd_link_info *link_info,
8585                          bfd_boolean *again)
8586 {
8587   Elf_Internal_Rela *internal_relocs;
8588   Elf_Internal_Rela *irel, *irelend;
8589   Elf_Internal_Shdr *symtab_hdr;
8590   bfd_byte *contents = NULL;
8591   size_t extsymoff;
8592   bfd_boolean changed_contents = FALSE;
8593   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8594   Elf_Internal_Sym *isymbuf = NULL;
8595
8596   /* We are not currently changing any sizes, so only one pass.  */
8597   *again = FALSE;
8598
8599   if (link_info->relocatable)
8600     return TRUE;
8601
8602   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8603                                                link_info->keep_memory);
8604   if (internal_relocs == NULL)
8605     return TRUE;
8606
8607   irelend = internal_relocs + sec->reloc_count
8608     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8609   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8610   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8611
8612   for (irel = internal_relocs; irel < irelend; irel++)
8613     {
8614       bfd_vma symval;
8615       bfd_signed_vma sym_offset;
8616       unsigned int r_type;
8617       unsigned long r_symndx;
8618       asection *sym_sec;
8619       unsigned long instruction;
8620
8621       /* Turn jalr into bgezal, and jr into beq, if they're marked
8622          with a JALR relocation, that indicate where they jump to.
8623          This saves some pipeline bubbles.  */
8624       r_type = ELF_R_TYPE (abfd, irel->r_info);
8625       if (r_type != R_MIPS_JALR)
8626         continue;
8627
8628       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8629       /* Compute the address of the jump target.  */
8630       if (r_symndx >= extsymoff)
8631         {
8632           struct mips_elf_link_hash_entry *h
8633             = ((struct mips_elf_link_hash_entry *)
8634                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8635
8636           while (h->root.root.type == bfd_link_hash_indirect
8637                  || h->root.root.type == bfd_link_hash_warning)
8638             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8639
8640           /* If a symbol is undefined, or if it may be overridden,
8641              skip it.  */
8642           if (! ((h->root.root.type == bfd_link_hash_defined
8643                   || h->root.root.type == bfd_link_hash_defweak)
8644                  && h->root.root.u.def.section)
8645               || (link_info->shared && ! link_info->symbolic
8646                   && !h->root.forced_local))
8647             continue;
8648
8649           sym_sec = h->root.root.u.def.section;
8650           if (sym_sec->output_section)
8651             symval = (h->root.root.u.def.value
8652                       + sym_sec->output_section->vma
8653                       + sym_sec->output_offset);
8654           else
8655             symval = h->root.root.u.def.value;
8656         }
8657       else
8658         {
8659           Elf_Internal_Sym *isym;
8660
8661           /* Read this BFD's symbols if we haven't done so already.  */
8662           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8663             {
8664               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8665               if (isymbuf == NULL)
8666                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8667                                                 symtab_hdr->sh_info, 0,
8668                                                 NULL, NULL, NULL);
8669               if (isymbuf == NULL)
8670                 goto relax_return;
8671             }
8672
8673           isym = isymbuf + r_symndx;
8674           if (isym->st_shndx == SHN_UNDEF)
8675             continue;
8676           else if (isym->st_shndx == SHN_ABS)
8677             sym_sec = bfd_abs_section_ptr;
8678           else if (isym->st_shndx == SHN_COMMON)
8679             sym_sec = bfd_com_section_ptr;
8680           else
8681             sym_sec
8682               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8683           symval = isym->st_value
8684             + sym_sec->output_section->vma
8685             + sym_sec->output_offset;
8686         }
8687
8688       /* Compute branch offset, from delay slot of the jump to the
8689          branch target.  */
8690       sym_offset = (symval + irel->r_addend)
8691         - (sec_start + irel->r_offset + 4);
8692
8693       /* Branch offset must be properly aligned.  */
8694       if ((sym_offset & 3) != 0)
8695         continue;
8696
8697       sym_offset >>= 2;
8698
8699       /* Check that it's in range.  */
8700       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
8701         continue;
8702
8703       /* Get the section contents if we haven't done so already.  */
8704       if (!mips_elf_get_section_contents (abfd, sec, &contents))
8705         goto relax_return;
8706
8707       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
8708
8709       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
8710       if ((instruction & 0xfc1fffff) == 0x0000f809)
8711         instruction = 0x04110000;
8712       /* If it was jr <reg>, turn it into b <target>.  */
8713       else if ((instruction & 0xfc1fffff) == 0x00000008)
8714         instruction = 0x10000000;
8715       else
8716         continue;
8717
8718       instruction |= (sym_offset & 0xffff);
8719       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
8720       changed_contents = TRUE;
8721     }
8722
8723   if (contents != NULL
8724       && elf_section_data (sec)->this_hdr.contents != contents)
8725     {
8726       if (!changed_contents && !link_info->keep_memory)
8727         free (contents);
8728       else
8729         {
8730           /* Cache the section contents for elf_link_input_bfd.  */
8731           elf_section_data (sec)->this_hdr.contents = contents;
8732         }
8733     }
8734   return TRUE;
8735
8736  relax_return:
8737   if (contents != NULL
8738       && elf_section_data (sec)->this_hdr.contents != contents)
8739     free (contents);
8740   return FALSE;
8741 }
8742 \f
8743 /* Allocate space for global sym dynamic relocs.  */
8744
8745 static bfd_boolean
8746 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
8747 {
8748   struct bfd_link_info *info = inf;
8749   bfd *dynobj;
8750   struct mips_elf_link_hash_entry *hmips;
8751   struct mips_elf_link_hash_table *htab;
8752
8753   htab = mips_elf_hash_table (info);
8754   BFD_ASSERT (htab != NULL);
8755
8756   dynobj = elf_hash_table (info)->dynobj;
8757   hmips = (struct mips_elf_link_hash_entry *) h;
8758
8759   /* VxWorks executables are handled elsewhere; we only need to
8760      allocate relocations in shared objects.  */
8761   if (htab->is_vxworks && !info->shared)
8762     return TRUE;
8763
8764   /* Ignore indirect symbols.  All relocations against such symbols
8765      will be redirected to the target symbol.  */
8766   if (h->root.type == bfd_link_hash_indirect)
8767     return TRUE;
8768
8769   /* If this symbol is defined in a dynamic object, or we are creating
8770      a shared library, we will need to copy any R_MIPS_32 or
8771      R_MIPS_REL32 relocs against it into the output file.  */
8772   if (! info->relocatable
8773       && hmips->possibly_dynamic_relocs != 0
8774       && (h->root.type == bfd_link_hash_defweak
8775           || (!h->def_regular && !ELF_COMMON_DEF_P (h))
8776           || info->shared))
8777     {
8778       bfd_boolean do_copy = TRUE;
8779
8780       if (h->root.type == bfd_link_hash_undefweak)
8781         {
8782           /* Do not copy relocations for undefined weak symbols with
8783              non-default visibility.  */
8784           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
8785             do_copy = FALSE;
8786
8787           /* Make sure undefined weak symbols are output as a dynamic
8788              symbol in PIEs.  */
8789           else if (h->dynindx == -1 && !h->forced_local)
8790             {
8791               if (! bfd_elf_link_record_dynamic_symbol (info, h))
8792                 return FALSE;
8793             }
8794         }
8795
8796       if (do_copy)
8797         {
8798           /* Even though we don't directly need a GOT entry for this symbol,
8799              the SVR4 psABI requires it to have a dynamic symbol table
8800              index greater that DT_MIPS_GOTSYM if there are dynamic
8801              relocations against it.
8802
8803              VxWorks does not enforce the same mapping between the GOT
8804              and the symbol table, so the same requirement does not
8805              apply there.  */
8806           if (!htab->is_vxworks)
8807             {
8808               if (hmips->global_got_area > GGA_RELOC_ONLY)
8809                 hmips->global_got_area = GGA_RELOC_ONLY;
8810               hmips->got_only_for_calls = FALSE;
8811             }
8812
8813           mips_elf_allocate_dynamic_relocations
8814             (dynobj, info, hmips->possibly_dynamic_relocs);
8815           if (hmips->readonly_reloc)
8816             /* We tell the dynamic linker that there are relocations
8817                against the text segment.  */
8818             info->flags |= DF_TEXTREL;
8819         }
8820     }
8821
8822   return TRUE;
8823 }
8824
8825 /* Adjust a symbol defined by a dynamic object and referenced by a
8826    regular object.  The current definition is in some section of the
8827    dynamic object, but we're not including those sections.  We have to
8828    change the definition to something the rest of the link can
8829    understand.  */
8830
8831 bfd_boolean
8832 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
8833                                      struct elf_link_hash_entry *h)
8834 {
8835   bfd *dynobj;
8836   struct mips_elf_link_hash_entry *hmips;
8837   struct mips_elf_link_hash_table *htab;
8838
8839   htab = mips_elf_hash_table (info);
8840   BFD_ASSERT (htab != NULL);
8841
8842   dynobj = elf_hash_table (info)->dynobj;
8843   hmips = (struct mips_elf_link_hash_entry *) h;
8844
8845   /* Make sure we know what is going on here.  */
8846   BFD_ASSERT (dynobj != NULL
8847               && (h->needs_plt
8848                   || h->u.weakdef != NULL
8849                   || (h->def_dynamic
8850                       && h->ref_regular
8851                       && !h->def_regular)));
8852
8853   hmips = (struct mips_elf_link_hash_entry *) h;
8854
8855   /* If there are call relocations against an externally-defined symbol,
8856      see whether we can create a MIPS lazy-binding stub for it.  We can
8857      only do this if all references to the function are through call
8858      relocations, and in that case, the traditional lazy-binding stubs
8859      are much more efficient than PLT entries.
8860
8861      Traditional stubs are only available on SVR4 psABI-based systems;
8862      VxWorks always uses PLTs instead.  */
8863   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
8864     {
8865       if (! elf_hash_table (info)->dynamic_sections_created)
8866         return TRUE;
8867
8868       /* If this symbol is not defined in a regular file, then set
8869          the symbol to the stub location.  This is required to make
8870          function pointers compare as equal between the normal
8871          executable and the shared library.  */
8872       if (!h->def_regular)
8873         {
8874           hmips->needs_lazy_stub = TRUE;
8875           htab->lazy_stub_count++;
8876           return TRUE;
8877         }
8878     }
8879   /* As above, VxWorks requires PLT entries for externally-defined
8880      functions that are only accessed through call relocations.
8881
8882      Both VxWorks and non-VxWorks targets also need PLT entries if there
8883      are static-only relocations against an externally-defined function.
8884      This can technically occur for shared libraries if there are
8885      branches to the symbol, although it is unlikely that this will be
8886      used in practice due to the short ranges involved.  It can occur
8887      for any relative or absolute relocation in executables; in that
8888      case, the PLT entry becomes the function's canonical address.  */
8889   else if (((h->needs_plt && !hmips->no_fn_stub)
8890             || (h->type == STT_FUNC && hmips->has_static_relocs))
8891            && htab->use_plts_and_copy_relocs
8892            && !SYMBOL_CALLS_LOCAL (info, h)
8893            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
8894                 && h->root.type == bfd_link_hash_undefweak))
8895     {
8896       bfd_boolean micromips_p = MICROMIPS_P (info->output_bfd);
8897       bfd_boolean newabi_p = NEWABI_P (info->output_bfd);
8898
8899       /* If this is the first symbol to need a PLT entry, then make some
8900          basic setup.  Also work out PLT entry sizes.  We'll need them
8901          for PLT offset calculations.  */
8902       if (htab->plt_mips_offset + htab->plt_comp_offset == 0)
8903         {
8904           BFD_ASSERT (htab->sgotplt->size == 0);
8905           BFD_ASSERT (htab->plt_got_index == 0);
8906
8907           /* If we're using the PLT additions to the psABI, each PLT
8908              entry is 16 bytes and the PLT0 entry is 32 bytes.
8909              Encourage better cache usage by aligning.  We do this
8910              lazily to avoid pessimizing traditional objects.  */
8911           if (!htab->is_vxworks
8912               && !bfd_set_section_alignment (dynobj, htab->splt, 5))
8913             return FALSE;
8914
8915           /* Make sure that .got.plt is word-aligned.  We do this lazily
8916              for the same reason as above.  */
8917           if (!bfd_set_section_alignment (dynobj, htab->sgotplt,
8918                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
8919             return FALSE;
8920
8921           /* On non-VxWorks targets, the first two entries in .got.plt
8922              are reserved.  */
8923           if (!htab->is_vxworks)
8924             htab->plt_got_index
8925               += (get_elf_backend_data (dynobj)->got_header_size
8926                   / MIPS_ELF_GOT_SIZE (dynobj));
8927
8928           /* On VxWorks, also allocate room for the header's
8929              .rela.plt.unloaded entries.  */
8930           if (htab->is_vxworks && !info->shared)
8931             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
8932
8933           /* Now work out the sizes of individual PLT entries.  */
8934           if (htab->is_vxworks && info->shared)
8935             htab->plt_mips_entry_size
8936               = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
8937           else if (htab->is_vxworks)
8938             htab->plt_mips_entry_size
8939               = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
8940           else if (newabi_p)
8941             htab->plt_mips_entry_size
8942               = 4 * ARRAY_SIZE (mips_exec_plt_entry);
8943           else if (!micromips_p)
8944             {
8945               htab->plt_mips_entry_size
8946                 = 4 * ARRAY_SIZE (mips_exec_plt_entry);
8947               htab->plt_comp_entry_size
8948                 = 2 * ARRAY_SIZE (mips16_o32_exec_plt_entry);
8949             }
8950           else if (htab->insn32)
8951             {
8952               htab->plt_mips_entry_size
8953                 = 4 * ARRAY_SIZE (mips_exec_plt_entry);
8954               htab->plt_comp_entry_size
8955                 = 2 * ARRAY_SIZE (micromips_insn32_o32_exec_plt_entry);
8956             }
8957           else
8958             {
8959               htab->plt_mips_entry_size
8960                 = 4 * ARRAY_SIZE (mips_exec_plt_entry);
8961               htab->plt_comp_entry_size
8962                 = 2 * ARRAY_SIZE (micromips_o32_exec_plt_entry);
8963             }
8964         }
8965
8966       if (h->plt.plist == NULL)
8967         h->plt.plist = mips_elf_make_plt_record (dynobj);
8968       if (h->plt.plist == NULL)
8969         return FALSE;
8970
8971       /* There are no defined MIPS16 or microMIPS PLT entries for VxWorks,
8972          n32 or n64, so always use a standard entry there.
8973
8974          If the symbol has a MIPS16 call stub and gets a PLT entry, then
8975          all MIPS16 calls will go via that stub, and there is no benefit
8976          to having a MIPS16 entry.  And in the case of call_stub a
8977          standard entry actually has to be used as the stub ends with a J
8978          instruction.  */
8979       if (newabi_p
8980           || htab->is_vxworks
8981           || hmips->call_stub
8982           || hmips->call_fp_stub)
8983         {
8984           h->plt.plist->need_mips = TRUE;
8985           h->plt.plist->need_comp = FALSE;
8986         }
8987
8988       /* Otherwise, if there are no direct calls to the function, we
8989          have a free choice of whether to use standard or compressed
8990          entries.  Prefer microMIPS entries if the object is known to
8991          contain microMIPS code, so that it becomes possible to create
8992          pure microMIPS binaries.  Prefer standard entries otherwise,
8993          because MIPS16 ones are no smaller and are usually slower.  */
8994       if (!h->plt.plist->need_mips && !h->plt.plist->need_comp)
8995         {
8996           if (micromips_p)
8997             h->plt.plist->need_comp = TRUE;
8998           else
8999             h->plt.plist->need_mips = TRUE;
9000         }
9001
9002       if (h->plt.plist->need_mips)
9003         {
9004           h->plt.plist->mips_offset = htab->plt_mips_offset;
9005           htab->plt_mips_offset += htab->plt_mips_entry_size;
9006         }
9007       if (h->plt.plist->need_comp)
9008         {
9009           h->plt.plist->comp_offset = htab->plt_comp_offset;
9010           htab->plt_comp_offset += htab->plt_comp_entry_size;
9011         }
9012
9013       /* Reserve the corresponding .got.plt entry now too.  */
9014       h->plt.plist->gotplt_index = htab->plt_got_index++;
9015
9016       /* If the output file has no definition of the symbol, set the
9017          symbol's value to the address of the stub.  */
9018       if (!info->shared && !h->def_regular)
9019         hmips->use_plt_entry = TRUE;
9020
9021       /* Make room for the R_MIPS_JUMP_SLOT relocation.  */
9022       htab->srelplt->size += (htab->is_vxworks
9023                               ? MIPS_ELF_RELA_SIZE (dynobj)
9024                               : MIPS_ELF_REL_SIZE (dynobj));
9025
9026       /* Make room for the .rela.plt.unloaded relocations.  */
9027       if (htab->is_vxworks && !info->shared)
9028         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
9029
9030       /* All relocations against this symbol that could have been made
9031          dynamic will now refer to the PLT entry instead.  */
9032       hmips->possibly_dynamic_relocs = 0;
9033
9034       return TRUE;
9035     }
9036
9037   /* If this is a weak symbol, and there is a real definition, the
9038      processor independent code will have arranged for us to see the
9039      real definition first, and we can just use the same value.  */
9040   if (h->u.weakdef != NULL)
9041     {
9042       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
9043                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
9044       h->root.u.def.section = h->u.weakdef->root.u.def.section;
9045       h->root.u.def.value = h->u.weakdef->root.u.def.value;
9046       return TRUE;
9047     }
9048
9049   /* Otherwise, there is nothing further to do for symbols defined
9050      in regular objects.  */
9051   if (h->def_regular)
9052     return TRUE;
9053
9054   /* There's also nothing more to do if we'll convert all relocations
9055      against this symbol into dynamic relocations.  */
9056   if (!hmips->has_static_relocs)
9057     return TRUE;
9058
9059   /* We're now relying on copy relocations.  Complain if we have
9060      some that we can't convert.  */
9061   if (!htab->use_plts_and_copy_relocs || info->shared)
9062     {
9063       (*_bfd_error_handler) (_("non-dynamic relocations refer to "
9064                                "dynamic symbol %s"),
9065                              h->root.root.string);
9066       bfd_set_error (bfd_error_bad_value);
9067       return FALSE;
9068     }
9069
9070   /* We must allocate the symbol in our .dynbss section, which will
9071      become part of the .bss section of the executable.  There will be
9072      an entry for this symbol in the .dynsym section.  The dynamic
9073      object will contain position independent code, so all references
9074      from the dynamic object to this symbol will go through the global
9075      offset table.  The dynamic linker will use the .dynsym entry to
9076      determine the address it must put in the global offset table, so
9077      both the dynamic object and the regular object will refer to the
9078      same memory location for the variable.  */
9079
9080   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
9081     {
9082       if (htab->is_vxworks)
9083         htab->srelbss->size += sizeof (Elf32_External_Rela);
9084       else
9085         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
9086       h->needs_copy = 1;
9087     }
9088
9089   /* All relocations against this symbol that could have been made
9090      dynamic will now refer to the local copy instead.  */
9091   hmips->possibly_dynamic_relocs = 0;
9092
9093   return _bfd_elf_adjust_dynamic_copy (h, htab->sdynbss);
9094 }
9095 \f
9096 /* This function is called after all the input files have been read,
9097    and the input sections have been assigned to output sections.  We
9098    check for any mips16 stub sections that we can discard.  */
9099
9100 bfd_boolean
9101 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
9102                                     struct bfd_link_info *info)
9103 {
9104   asection *sect;
9105   struct mips_elf_link_hash_table *htab;
9106   struct mips_htab_traverse_info hti;
9107
9108   htab = mips_elf_hash_table (info);
9109   BFD_ASSERT (htab != NULL);
9110
9111   /* The .reginfo section has a fixed size.  */
9112   sect = bfd_get_section_by_name (output_bfd, ".reginfo");
9113   if (sect != NULL)
9114     bfd_set_section_size (output_bfd, sect, sizeof (Elf32_External_RegInfo));
9115
9116   /* The .MIPS.abiflags section has a fixed size.  */
9117   sect = bfd_get_section_by_name (output_bfd, ".MIPS.abiflags");
9118   if (sect != NULL)
9119     bfd_set_section_size (output_bfd, sect, sizeof (Elf_External_ABIFlags_v0));
9120
9121   hti.info = info;
9122   hti.output_bfd = output_bfd;
9123   hti.error = FALSE;
9124   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
9125                                mips_elf_check_symbols, &hti);
9126   if (hti.error)
9127     return FALSE;
9128
9129   return TRUE;
9130 }
9131
9132 /* If the link uses a GOT, lay it out and work out its size.  */
9133
9134 static bfd_boolean
9135 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
9136 {
9137   bfd *dynobj;
9138   asection *s;
9139   struct mips_got_info *g;
9140   bfd_size_type loadable_size = 0;
9141   bfd_size_type page_gotno;
9142   bfd *ibfd;
9143   struct mips_elf_traverse_got_arg tga;
9144   struct mips_elf_link_hash_table *htab;
9145
9146   htab = mips_elf_hash_table (info);
9147   BFD_ASSERT (htab != NULL);
9148
9149   s = htab->sgot;
9150   if (s == NULL)
9151     return TRUE;
9152
9153   dynobj = elf_hash_table (info)->dynobj;
9154   g = htab->got_info;
9155
9156   /* Allocate room for the reserved entries.  VxWorks always reserves
9157      3 entries; other objects only reserve 2 entries.  */
9158   BFD_ASSERT (g->assigned_low_gotno == 0);
9159   if (htab->is_vxworks)
9160     htab->reserved_gotno = 3;
9161   else
9162     htab->reserved_gotno = 2;
9163   g->local_gotno += htab->reserved_gotno;
9164   g->assigned_low_gotno = htab->reserved_gotno;
9165
9166   /* Decide which symbols need to go in the global part of the GOT and
9167      count the number of reloc-only GOT symbols.  */
9168   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
9169
9170   if (!mips_elf_resolve_final_got_entries (info, g))
9171     return FALSE;
9172
9173   /* Calculate the total loadable size of the output.  That
9174      will give us the maximum number of GOT_PAGE entries
9175      required.  */
9176   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
9177     {
9178       asection *subsection;
9179
9180       for (subsection = ibfd->sections;
9181            subsection;
9182            subsection = subsection->next)
9183         {
9184           if ((subsection->flags & SEC_ALLOC) == 0)
9185             continue;
9186           loadable_size += ((subsection->size + 0xf)
9187                             &~ (bfd_size_type) 0xf);
9188         }
9189     }
9190
9191   if (htab->is_vxworks)
9192     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
9193        relocations against local symbols evaluate to "G", and the EABI does
9194        not include R_MIPS_GOT_PAGE.  */
9195     page_gotno = 0;
9196   else
9197     /* Assume there are two loadable segments consisting of contiguous
9198        sections.  Is 5 enough?  */
9199     page_gotno = (loadable_size >> 16) + 5;
9200
9201   /* Choose the smaller of the two page estimates; both are intended to be
9202      conservative.  */
9203   if (page_gotno > g->page_gotno)
9204     page_gotno = g->page_gotno;
9205
9206   g->local_gotno += page_gotno;
9207   g->assigned_high_gotno = g->local_gotno - 1;
9208
9209   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
9210   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
9211   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
9212
9213   /* VxWorks does not support multiple GOTs.  It initializes $gp to
9214      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
9215      dynamic loader.  */
9216   if (!htab->is_vxworks && s->size > MIPS_ELF_GOT_MAX_SIZE (info))
9217     {
9218       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
9219         return FALSE;
9220     }
9221   else
9222     {
9223       /* Record that all bfds use G.  This also has the effect of freeing
9224          the per-bfd GOTs, which we no longer need.  */
9225       for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
9226         if (mips_elf_bfd_got (ibfd, FALSE))
9227           mips_elf_replace_bfd_got (ibfd, g);
9228       mips_elf_replace_bfd_got (output_bfd, g);
9229
9230       /* Set up TLS entries.  */
9231       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
9232       tga.info = info;
9233       tga.g = g;
9234       tga.value = MIPS_ELF_GOT_SIZE (output_bfd);
9235       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
9236       if (!tga.g)
9237         return FALSE;
9238       BFD_ASSERT (g->tls_assigned_gotno
9239                   == g->global_gotno + g->local_gotno + g->tls_gotno);
9240
9241       /* Each VxWorks GOT entry needs an explicit relocation.  */
9242       if (htab->is_vxworks && info->shared)
9243         g->relocs += g->global_gotno + g->local_gotno - htab->reserved_gotno;
9244
9245       /* Allocate room for the TLS relocations.  */
9246       if (g->relocs)
9247         mips_elf_allocate_dynamic_relocations (dynobj, info, g->relocs);
9248     }
9249
9250   return TRUE;
9251 }
9252
9253 /* Estimate the size of the .MIPS.stubs section.  */
9254
9255 static void
9256 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
9257 {
9258   struct mips_elf_link_hash_table *htab;
9259   bfd_size_type dynsymcount;
9260
9261   htab = mips_elf_hash_table (info);
9262   BFD_ASSERT (htab != NULL);
9263
9264   if (htab->lazy_stub_count == 0)
9265     return;
9266
9267   /* IRIX rld assumes that a function stub isn't at the end of the .text
9268      section, so add a dummy entry to the end.  */
9269   htab->lazy_stub_count++;
9270
9271   /* Get a worst-case estimate of the number of dynamic symbols needed.
9272      At this point, dynsymcount does not account for section symbols
9273      and count_section_dynsyms may overestimate the number that will
9274      be needed.  */
9275   dynsymcount = (elf_hash_table (info)->dynsymcount
9276                  + count_section_dynsyms (output_bfd, info));
9277
9278   /* Determine the size of one stub entry.  There's no disadvantage
9279      from using microMIPS code here, so for the sake of pure-microMIPS
9280      binaries we prefer it whenever there's any microMIPS code in
9281      output produced at all.  This has a benefit of stubs being
9282      shorter by 4 bytes each too, unless in the insn32 mode.  */
9283   if (!MICROMIPS_P (output_bfd))
9284     htab->function_stub_size = (dynsymcount > 0x10000
9285                                 ? MIPS_FUNCTION_STUB_BIG_SIZE
9286                                 : MIPS_FUNCTION_STUB_NORMAL_SIZE);
9287   else if (htab->insn32)
9288     htab->function_stub_size = (dynsymcount > 0x10000
9289                                 ? MICROMIPS_INSN32_FUNCTION_STUB_BIG_SIZE
9290                                 : MICROMIPS_INSN32_FUNCTION_STUB_NORMAL_SIZE);
9291   else
9292     htab->function_stub_size = (dynsymcount > 0x10000
9293                                 ? MICROMIPS_FUNCTION_STUB_BIG_SIZE
9294                                 : MICROMIPS_FUNCTION_STUB_NORMAL_SIZE);
9295
9296   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
9297 }
9298
9299 /* A mips_elf_link_hash_traverse callback for which DATA points to a
9300    mips_htab_traverse_info.  If H needs a traditional MIPS lazy-binding
9301    stub, allocate an entry in the stubs section.  */
9302
9303 static bfd_boolean
9304 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void *data)
9305 {
9306   struct mips_htab_traverse_info *hti = data;
9307   struct mips_elf_link_hash_table *htab;
9308   struct bfd_link_info *info;
9309   bfd *output_bfd;
9310
9311   info = hti->info;
9312   output_bfd = hti->output_bfd;
9313   htab = mips_elf_hash_table (info);
9314   BFD_ASSERT (htab != NULL);
9315
9316   if (h->needs_lazy_stub)
9317     {
9318       bfd_boolean micromips_p = MICROMIPS_P (output_bfd);
9319       unsigned int other = micromips_p ? STO_MICROMIPS : 0;
9320       bfd_vma isa_bit = micromips_p;
9321
9322       BFD_ASSERT (htab->root.dynobj != NULL);
9323       if (h->root.plt.plist == NULL)
9324         h->root.plt.plist = mips_elf_make_plt_record (htab->sstubs->owner);
9325       if (h->root.plt.plist == NULL)
9326         {
9327           hti->error = TRUE;
9328           return FALSE;
9329         }
9330       h->root.root.u.def.section = htab->sstubs;
9331       h->root.root.u.def.value = htab->sstubs->size + isa_bit;
9332       h->root.plt.plist->stub_offset = htab->sstubs->size;
9333       h->root.other = other;
9334       htab->sstubs->size += htab->function_stub_size;
9335     }
9336   return TRUE;
9337 }
9338
9339 /* Allocate offsets in the stubs section to each symbol that needs one.
9340    Set the final size of the .MIPS.stub section.  */
9341
9342 static bfd_boolean
9343 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
9344 {
9345   bfd *output_bfd = info->output_bfd;
9346   bfd_boolean micromips_p = MICROMIPS_P (output_bfd);
9347   unsigned int other = micromips_p ? STO_MICROMIPS : 0;
9348   bfd_vma isa_bit = micromips_p;
9349   struct mips_elf_link_hash_table *htab;
9350   struct mips_htab_traverse_info hti;
9351   struct elf_link_hash_entry *h;
9352   bfd *dynobj;
9353
9354   htab = mips_elf_hash_table (info);
9355   BFD_ASSERT (htab != NULL);
9356
9357   if (htab->lazy_stub_count == 0)
9358     return TRUE;
9359
9360   htab->sstubs->size = 0;
9361   hti.info = info;
9362   hti.output_bfd = output_bfd;
9363   hti.error = FALSE;
9364   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, &hti);
9365   if (hti.error)
9366     return FALSE;
9367   htab->sstubs->size += htab->function_stub_size;
9368   BFD_ASSERT (htab->sstubs->size
9369               == htab->lazy_stub_count * htab->function_stub_size);
9370
9371   dynobj = elf_hash_table (info)->dynobj;
9372   BFD_ASSERT (dynobj != NULL);
9373   h = _bfd_elf_define_linkage_sym (dynobj, info, htab->sstubs, "_MIPS_STUBS_");
9374   if (h == NULL)
9375     return FALSE;
9376   h->root.u.def.value = isa_bit;
9377   h->other = other;
9378   h->type = STT_FUNC;
9379
9380   return TRUE;
9381 }
9382
9383 /* A mips_elf_link_hash_traverse callback for which DATA points to a
9384    bfd_link_info.  If H uses the address of a PLT entry as the value
9385    of the symbol, then set the entry in the symbol table now.  Prefer
9386    a standard MIPS PLT entry.  */
9387
9388 static bfd_boolean
9389 mips_elf_set_plt_sym_value (struct mips_elf_link_hash_entry *h, void *data)
9390 {
9391   struct bfd_link_info *info = data;
9392   bfd_boolean micromips_p = MICROMIPS_P (info->output_bfd);
9393   struct mips_elf_link_hash_table *htab;
9394   unsigned int other;
9395   bfd_vma isa_bit;
9396   bfd_vma val;
9397
9398   htab = mips_elf_hash_table (info);
9399   BFD_ASSERT (htab != NULL);
9400
9401   if (h->use_plt_entry)
9402     {
9403       BFD_ASSERT (h->root.plt.plist != NULL);
9404       BFD_ASSERT (h->root.plt.plist->mips_offset != MINUS_ONE
9405                   || h->root.plt.plist->comp_offset != MINUS_ONE);
9406
9407       val = htab->plt_header_size;
9408       if (h->root.plt.plist->mips_offset != MINUS_ONE)
9409         {
9410           isa_bit = 0;
9411           val += h->root.plt.plist->mips_offset;
9412           other = 0;
9413         }
9414       else
9415         {
9416           isa_bit = 1;
9417           val += htab->plt_mips_offset + h->root.plt.plist->comp_offset;
9418           other = micromips_p ? STO_MICROMIPS : STO_MIPS16;
9419         }
9420       val += isa_bit;
9421       /* For VxWorks, point at the PLT load stub rather than the lazy
9422          resolution stub; this stub will become the canonical function
9423          address.  */
9424       if (htab->is_vxworks)
9425         val += 8;
9426
9427       h->root.root.u.def.section = htab->splt;
9428       h->root.root.u.def.value = val;
9429       h->root.other = other;
9430     }
9431
9432   return TRUE;
9433 }
9434
9435 /* Set the sizes of the dynamic sections.  */
9436
9437 bfd_boolean
9438 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
9439                                      struct bfd_link_info *info)
9440 {
9441   bfd *dynobj;
9442   asection *s, *sreldyn;
9443   bfd_boolean reltext;
9444   struct mips_elf_link_hash_table *htab;
9445
9446   htab = mips_elf_hash_table (info);
9447   BFD_ASSERT (htab != NULL);
9448   dynobj = elf_hash_table (info)->dynobj;
9449   BFD_ASSERT (dynobj != NULL);
9450
9451   if (elf_hash_table (info)->dynamic_sections_created)
9452     {
9453       /* Set the contents of the .interp section to the interpreter.  */
9454       if (info->executable)
9455         {
9456           s = bfd_get_linker_section (dynobj, ".interp");
9457           BFD_ASSERT (s != NULL);
9458           s->size
9459             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
9460           s->contents
9461             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
9462         }
9463
9464       /* Figure out the size of the PLT header if we know that we
9465          are using it.  For the sake of cache alignment always use
9466          a standard header whenever any standard entries are present
9467          even if microMIPS entries are present as well.  This also
9468          lets the microMIPS header rely on the value of $v0 only set
9469          by microMIPS entries, for a small size reduction.
9470
9471          Set symbol table entry values for symbols that use the
9472          address of their PLT entry now that we can calculate it.
9473
9474          Also create the _PROCEDURE_LINKAGE_TABLE_ symbol if we
9475          haven't already in _bfd_elf_create_dynamic_sections.  */
9476       if (htab->splt && htab->plt_mips_offset + htab->plt_comp_offset != 0)
9477         {
9478           bfd_boolean micromips_p = (MICROMIPS_P (output_bfd)
9479                                      && !htab->plt_mips_offset);
9480           unsigned int other = micromips_p ? STO_MICROMIPS : 0;
9481           bfd_vma isa_bit = micromips_p;
9482           struct elf_link_hash_entry *h;
9483           bfd_vma size;
9484
9485           BFD_ASSERT (htab->use_plts_and_copy_relocs);
9486           BFD_ASSERT (htab->sgotplt->size == 0);
9487           BFD_ASSERT (htab->splt->size == 0);
9488
9489           if (htab->is_vxworks && info->shared)
9490             size = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
9491           else if (htab->is_vxworks)
9492             size = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
9493           else if (ABI_64_P (output_bfd))
9494             size = 4 * ARRAY_SIZE (mips_n64_exec_plt0_entry);
9495           else if (ABI_N32_P (output_bfd))
9496             size = 4 * ARRAY_SIZE (mips_n32_exec_plt0_entry);
9497           else if (!micromips_p)
9498             size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
9499           else if (htab->insn32)
9500             size = 2 * ARRAY_SIZE (micromips_insn32_o32_exec_plt0_entry);
9501           else
9502             size = 2 * ARRAY_SIZE (micromips_o32_exec_plt0_entry);
9503
9504           htab->plt_header_is_comp = micromips_p;
9505           htab->plt_header_size = size;
9506           htab->splt->size = (size
9507                               + htab->plt_mips_offset
9508                               + htab->plt_comp_offset);
9509           htab->sgotplt->size = (htab->plt_got_index
9510                                  * MIPS_ELF_GOT_SIZE (dynobj));
9511
9512           mips_elf_link_hash_traverse (htab, mips_elf_set_plt_sym_value, info);
9513
9514           if (htab->root.hplt == NULL)
9515             {
9516               h = _bfd_elf_define_linkage_sym (dynobj, info, htab->splt,
9517                                                "_PROCEDURE_LINKAGE_TABLE_");
9518               htab->root.hplt = h;
9519               if (h == NULL)
9520                 return FALSE;
9521             }
9522
9523           h = htab->root.hplt;
9524           h->root.u.def.value = isa_bit;
9525           h->other = other;
9526           h->type = STT_FUNC;
9527         }
9528     }
9529
9530   /* Allocate space for global sym dynamic relocs.  */
9531   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, info);
9532
9533   mips_elf_estimate_stub_size (output_bfd, info);
9534
9535   if (!mips_elf_lay_out_got (output_bfd, info))
9536     return FALSE;
9537
9538   mips_elf_lay_out_lazy_stubs (info);
9539
9540   /* The check_relocs and adjust_dynamic_symbol entry points have
9541      determined the sizes of the various dynamic sections.  Allocate
9542      memory for them.  */
9543   reltext = FALSE;
9544   for (s = dynobj->sections; s != NULL; s = s->next)
9545     {
9546       const char *name;
9547
9548       /* It's OK to base decisions on the section name, because none
9549          of the dynobj section names depend upon the input files.  */
9550       name = bfd_get_section_name (dynobj, s);
9551
9552       if ((s->flags & SEC_LINKER_CREATED) == 0)
9553         continue;
9554
9555       if (CONST_STRNEQ (name, ".rel"))
9556         {
9557           if (s->size != 0)
9558             {
9559               const char *outname;
9560               asection *target;
9561
9562               /* If this relocation section applies to a read only
9563                  section, then we probably need a DT_TEXTREL entry.
9564                  If the relocation section is .rel(a).dyn, we always
9565                  assert a DT_TEXTREL entry rather than testing whether
9566                  there exists a relocation to a read only section or
9567                  not.  */
9568               outname = bfd_get_section_name (output_bfd,
9569                                               s->output_section);
9570               target = bfd_get_section_by_name (output_bfd, outname + 4);
9571               if ((target != NULL
9572                    && (target->flags & SEC_READONLY) != 0
9573                    && (target->flags & SEC_ALLOC) != 0)
9574                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
9575                 reltext = TRUE;
9576
9577               /* We use the reloc_count field as a counter if we need
9578                  to copy relocs into the output file.  */
9579               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
9580                 s->reloc_count = 0;
9581
9582               /* If combreloc is enabled, elf_link_sort_relocs() will
9583                  sort relocations, but in a different way than we do,
9584                  and before we're done creating relocations.  Also, it
9585                  will move them around between input sections'
9586                  relocation's contents, so our sorting would be
9587                  broken, so don't let it run.  */
9588               info->combreloc = 0;
9589             }
9590         }
9591       else if (! info->shared
9592                && ! mips_elf_hash_table (info)->use_rld_obj_head
9593                && CONST_STRNEQ (name, ".rld_map"))
9594         {
9595           /* We add a room for __rld_map.  It will be filled in by the
9596              rtld to contain a pointer to the _r_debug structure.  */
9597           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
9598         }
9599       else if (SGI_COMPAT (output_bfd)
9600                && CONST_STRNEQ (name, ".compact_rel"))
9601         s->size += mips_elf_hash_table (info)->compact_rel_size;
9602       else if (s == htab->splt)
9603         {
9604           /* If the last PLT entry has a branch delay slot, allocate
9605              room for an extra nop to fill the delay slot.  This is
9606              for CPUs without load interlocking.  */
9607           if (! LOAD_INTERLOCKS_P (output_bfd)
9608               && ! htab->is_vxworks && s->size > 0)
9609             s->size += 4;
9610         }
9611       else if (! CONST_STRNEQ (name, ".init")
9612                && s != htab->sgot
9613                && s != htab->sgotplt
9614                && s != htab->sstubs
9615                && s != htab->sdynbss)
9616         {
9617           /* It's not one of our sections, so don't allocate space.  */
9618           continue;
9619         }
9620
9621       if (s->size == 0)
9622         {
9623           s->flags |= SEC_EXCLUDE;
9624           continue;
9625         }
9626
9627       if ((s->flags & SEC_HAS_CONTENTS) == 0)
9628         continue;
9629
9630       /* Allocate memory for the section contents.  */
9631       s->contents = bfd_zalloc (dynobj, s->size);
9632       if (s->contents == NULL)
9633         {
9634           bfd_set_error (bfd_error_no_memory);
9635           return FALSE;
9636         }
9637     }
9638
9639   if (elf_hash_table (info)->dynamic_sections_created)
9640     {
9641       /* Add some entries to the .dynamic section.  We fill in the
9642          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
9643          must add the entries now so that we get the correct size for
9644          the .dynamic section.  */
9645
9646       /* SGI object has the equivalence of DT_DEBUG in the
9647          DT_MIPS_RLD_MAP entry.  This must come first because glibc
9648          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and some tools
9649          may only look at the first one they see.  */
9650       if (!info->shared
9651           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
9652         return FALSE;
9653
9654       /* The DT_DEBUG entry may be filled in by the dynamic linker and
9655          used by the debugger.  */
9656       if (info->executable
9657           && !SGI_COMPAT (output_bfd)
9658           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
9659         return FALSE;
9660
9661       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
9662         info->flags |= DF_TEXTREL;
9663
9664       if ((info->flags & DF_TEXTREL) != 0)
9665         {
9666           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
9667             return FALSE;
9668
9669           /* Clear the DF_TEXTREL flag.  It will be set again if we
9670              write out an actual text relocation; we may not, because
9671              at this point we do not know whether e.g. any .eh_frame
9672              absolute relocations have been converted to PC-relative.  */
9673           info->flags &= ~DF_TEXTREL;
9674         }
9675
9676       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
9677         return FALSE;
9678
9679       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
9680       if (htab->is_vxworks)
9681         {
9682           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
9683              use any of the DT_MIPS_* tags.  */
9684           if (sreldyn && sreldyn->size > 0)
9685             {
9686               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
9687                 return FALSE;
9688
9689               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
9690                 return FALSE;
9691
9692               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
9693                 return FALSE;
9694             }
9695         }
9696       else
9697         {
9698           if (sreldyn && sreldyn->size > 0)
9699             {
9700               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
9701                 return FALSE;
9702
9703               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
9704                 return FALSE;
9705
9706               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
9707                 return FALSE;
9708             }
9709
9710           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
9711             return FALSE;
9712
9713           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
9714             return FALSE;
9715
9716           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
9717             return FALSE;
9718
9719           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
9720             return FALSE;
9721
9722           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
9723             return FALSE;
9724
9725           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
9726             return FALSE;
9727
9728           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
9729             return FALSE;
9730
9731           if (IRIX_COMPAT (dynobj) == ict_irix5
9732               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
9733             return FALSE;
9734
9735           if (IRIX_COMPAT (dynobj) == ict_irix6
9736               && (bfd_get_section_by_name
9737                   (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
9738               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
9739             return FALSE;
9740         }
9741       if (htab->splt->size > 0)
9742         {
9743           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
9744             return FALSE;
9745
9746           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
9747             return FALSE;
9748
9749           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
9750             return FALSE;
9751
9752           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
9753             return FALSE;
9754         }
9755       if (htab->is_vxworks
9756           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
9757         return FALSE;
9758     }
9759
9760   return TRUE;
9761 }
9762 \f
9763 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
9764    Adjust its R_ADDEND field so that it is correct for the output file.
9765    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
9766    and sections respectively; both use symbol indexes.  */
9767
9768 static void
9769 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
9770                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
9771                         asection **local_sections, Elf_Internal_Rela *rel)
9772 {
9773   unsigned int r_type, r_symndx;
9774   Elf_Internal_Sym *sym;
9775   asection *sec;
9776
9777   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9778     {
9779       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9780       if (gprel16_reloc_p (r_type)
9781           || r_type == R_MIPS_GPREL32
9782           || literal_reloc_p (r_type))
9783         {
9784           rel->r_addend += _bfd_get_gp_value (input_bfd);
9785           rel->r_addend -= _bfd_get_gp_value (output_bfd);
9786         }
9787
9788       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
9789       sym = local_syms + r_symndx;
9790
9791       /* Adjust REL's addend to account for section merging.  */
9792       if (!info->relocatable)
9793         {
9794           sec = local_sections[r_symndx];
9795           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
9796         }
9797
9798       /* This would normally be done by the rela_normal code in elflink.c.  */
9799       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
9800         rel->r_addend += local_sections[r_symndx]->output_offset;
9801     }
9802 }
9803
9804 /* Handle relocations against symbols from removed linkonce sections,
9805    or sections discarded by a linker script.  We use this wrapper around
9806    RELOC_AGAINST_DISCARDED_SECTION to handle triplets of compound relocs
9807    on 64-bit ELF targets.  In this case for any relocation handled, which
9808    always be the first in a triplet, the remaining two have to be processed
9809    together with the first, even if they are R_MIPS_NONE.  It is the symbol
9810    index referred by the first reloc that applies to all the three and the
9811    remaining two never refer to an object symbol.  And it is the final
9812    relocation (the last non-null one) that determines the output field of
9813    the whole relocation so retrieve the corresponding howto structure for
9814    the relocatable field to be cleared by RELOC_AGAINST_DISCARDED_SECTION.
9815
9816    Note that RELOC_AGAINST_DISCARDED_SECTION is a macro that uses "continue"
9817    and therefore requires to be pasted in a loop.  It also defines a block
9818    and does not protect any of its arguments, hence the extra brackets.  */
9819
9820 static void
9821 mips_reloc_against_discarded_section (bfd *output_bfd,
9822                                       struct bfd_link_info *info,
9823                                       bfd *input_bfd, asection *input_section,
9824                                       Elf_Internal_Rela **rel,
9825                                       const Elf_Internal_Rela **relend,
9826                                       bfd_boolean rel_reloc,
9827                                       reloc_howto_type *howto,
9828                                       bfd_byte *contents)
9829 {
9830   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
9831   int count = bed->s->int_rels_per_ext_rel;
9832   unsigned int r_type;
9833   int i;
9834
9835   for (i = count - 1; i > 0; i--)
9836     {
9837       r_type = ELF_R_TYPE (output_bfd, (*rel)[i].r_info);
9838       if (r_type != R_MIPS_NONE)
9839         {
9840           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9841           break;
9842         }
9843     }
9844   do
9845     {
9846        RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
9847                                         (*rel), count, (*relend),
9848                                         howto, i, contents);
9849     }
9850   while (0);
9851 }
9852
9853 /* Relocate a MIPS ELF section.  */
9854
9855 bfd_boolean
9856 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
9857                                 bfd *input_bfd, asection *input_section,
9858                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
9859                                 Elf_Internal_Sym *local_syms,
9860                                 asection **local_sections)
9861 {
9862   Elf_Internal_Rela *rel;
9863   const Elf_Internal_Rela *relend;
9864   bfd_vma addend = 0;
9865   bfd_boolean use_saved_addend_p = FALSE;
9866   const struct elf_backend_data *bed;
9867
9868   bed = get_elf_backend_data (output_bfd);
9869   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
9870   for (rel = relocs; rel < relend; ++rel)
9871     {
9872       const char *name;
9873       bfd_vma value = 0;
9874       reloc_howto_type *howto;
9875       bfd_boolean cross_mode_jump_p = FALSE;
9876       /* TRUE if the relocation is a RELA relocation, rather than a
9877          REL relocation.  */
9878       bfd_boolean rela_relocation_p = TRUE;
9879       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9880       const char *msg;
9881       unsigned long r_symndx;
9882       asection *sec;
9883       Elf_Internal_Shdr *symtab_hdr;
9884       struct elf_link_hash_entry *h;
9885       bfd_boolean rel_reloc;
9886
9887       rel_reloc = (NEWABI_P (input_bfd)
9888                    && mips_elf_rel_relocation_p (input_bfd, input_section,
9889                                                  relocs, rel));
9890       /* Find the relocation howto for this relocation.  */
9891       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9892
9893       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
9894       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9895       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9896         {
9897           sec = local_sections[r_symndx];
9898           h = NULL;
9899         }
9900       else
9901         {
9902           unsigned long extsymoff;
9903
9904           extsymoff = 0;
9905           if (!elf_bad_symtab (input_bfd))
9906             extsymoff = symtab_hdr->sh_info;
9907           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
9908           while (h->root.type == bfd_link_hash_indirect
9909                  || h->root.type == bfd_link_hash_warning)
9910             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9911
9912           sec = NULL;
9913           if (h->root.type == bfd_link_hash_defined
9914               || h->root.type == bfd_link_hash_defweak)
9915             sec = h->root.u.def.section;
9916         }
9917
9918       if (sec != NULL && discarded_section (sec))
9919         {
9920           mips_reloc_against_discarded_section (output_bfd, info, input_bfd,
9921                                                 input_section, &rel, &relend,
9922                                                 rel_reloc, howto, contents);
9923           continue;
9924         }
9925
9926       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
9927         {
9928           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
9929              64-bit code, but make sure all their addresses are in the
9930              lowermost or uppermost 32-bit section of the 64-bit address
9931              space.  Thus, when they use an R_MIPS_64 they mean what is
9932              usually meant by R_MIPS_32, with the exception that the
9933              stored value is sign-extended to 64 bits.  */
9934           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
9935
9936           /* On big-endian systems, we need to lie about the position
9937              of the reloc.  */
9938           if (bfd_big_endian (input_bfd))
9939             rel->r_offset += 4;
9940         }
9941
9942       if (!use_saved_addend_p)
9943         {
9944           /* If these relocations were originally of the REL variety,
9945              we must pull the addend out of the field that will be
9946              relocated.  Otherwise, we simply use the contents of the
9947              RELA relocation.  */
9948           if (mips_elf_rel_relocation_p (input_bfd, input_section,
9949                                          relocs, rel))
9950             {
9951               rela_relocation_p = FALSE;
9952               addend = mips_elf_read_rel_addend (input_bfd, rel,
9953                                                  howto, contents);
9954               if (hi16_reloc_p (r_type)
9955                   || (got16_reloc_p (r_type)
9956                       && mips_elf_local_relocation_p (input_bfd, rel,
9957                                                       local_sections)))
9958                 {
9959                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
9960                                                      contents, &addend))
9961                     {
9962                       if (h)
9963                         name = h->root.root.string;
9964                       else
9965                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9966                                                  local_syms + r_symndx,
9967                                                  sec);
9968                       (*_bfd_error_handler)
9969                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
9970                          input_bfd, input_section, name, howto->name,
9971                          rel->r_offset);
9972                     }
9973                 }
9974               else
9975                 addend <<= howto->rightshift;
9976             }
9977           else
9978             addend = rel->r_addend;
9979           mips_elf_adjust_addend (output_bfd, info, input_bfd,
9980                                   local_syms, local_sections, rel);
9981         }
9982
9983       if (info->relocatable)
9984         {
9985           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
9986               && bfd_big_endian (input_bfd))
9987             rel->r_offset -= 4;
9988
9989           if (!rela_relocation_p && rel->r_addend)
9990             {
9991               addend += rel->r_addend;
9992               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
9993                 addend = mips_elf_high (addend);
9994               else if (r_type == R_MIPS_HIGHER)
9995                 addend = mips_elf_higher (addend);
9996               else if (r_type == R_MIPS_HIGHEST)
9997                 addend = mips_elf_highest (addend);
9998               else
9999                 addend >>= howto->rightshift;
10000
10001               /* We use the source mask, rather than the destination
10002                  mask because the place to which we are writing will be
10003                  source of the addend in the final link.  */
10004               addend &= howto->src_mask;
10005
10006               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
10007                 /* See the comment above about using R_MIPS_64 in the 32-bit
10008                    ABI.  Here, we need to update the addend.  It would be
10009                    possible to get away with just using the R_MIPS_32 reloc
10010                    but for endianness.  */
10011                 {
10012                   bfd_vma sign_bits;
10013                   bfd_vma low_bits;
10014                   bfd_vma high_bits;
10015
10016                   if (addend & ((bfd_vma) 1 << 31))
10017 #ifdef BFD64
10018                     sign_bits = ((bfd_vma) 1 << 32) - 1;
10019 #else
10020                     sign_bits = -1;
10021 #endif
10022                   else
10023                     sign_bits = 0;
10024
10025                   /* If we don't know that we have a 64-bit type,
10026                      do two separate stores.  */
10027                   if (bfd_big_endian (input_bfd))
10028                     {
10029                       /* Store the sign-bits (which are most significant)
10030                          first.  */
10031                       low_bits = sign_bits;
10032                       high_bits = addend;
10033                     }
10034                   else
10035                     {
10036                       low_bits = addend;
10037                       high_bits = sign_bits;
10038                     }
10039                   bfd_put_32 (input_bfd, low_bits,
10040                               contents + rel->r_offset);
10041                   bfd_put_32 (input_bfd, high_bits,
10042                               contents + rel->r_offset + 4);
10043                   continue;
10044                 }
10045
10046               if (! mips_elf_perform_relocation (info, howto, rel, addend,
10047                                                  input_bfd, input_section,
10048                                                  contents, FALSE))
10049                 return FALSE;
10050             }
10051
10052           /* Go on to the next relocation.  */
10053           continue;
10054         }
10055
10056       /* In the N32 and 64-bit ABIs there may be multiple consecutive
10057          relocations for the same offset.  In that case we are
10058          supposed to treat the output of each relocation as the addend
10059          for the next.  */
10060       if (rel + 1 < relend
10061           && rel->r_offset == rel[1].r_offset
10062           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
10063         use_saved_addend_p = TRUE;
10064       else
10065         use_saved_addend_p = FALSE;
10066
10067       /* Figure out what value we are supposed to relocate.  */
10068       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
10069                                              input_section, info, rel,
10070                                              addend, howto, local_syms,
10071                                              local_sections, &value,
10072                                              &name, &cross_mode_jump_p,
10073                                              use_saved_addend_p))
10074         {
10075         case bfd_reloc_continue:
10076           /* There's nothing to do.  */
10077           continue;
10078
10079         case bfd_reloc_undefined:
10080           /* mips_elf_calculate_relocation already called the
10081              undefined_symbol callback.  There's no real point in
10082              trying to perform the relocation at this point, so we
10083              just skip ahead to the next relocation.  */
10084           continue;
10085
10086         case bfd_reloc_notsupported:
10087           msg = _("internal error: unsupported relocation error");
10088           info->callbacks->warning
10089             (info, msg, name, input_bfd, input_section, rel->r_offset);
10090           return FALSE;
10091
10092         case bfd_reloc_overflow:
10093           if (use_saved_addend_p)
10094             /* Ignore overflow until we reach the last relocation for
10095                a given location.  */
10096             ;
10097           else
10098             {
10099               struct mips_elf_link_hash_table *htab;
10100
10101               htab = mips_elf_hash_table (info);
10102               BFD_ASSERT (htab != NULL);
10103               BFD_ASSERT (name != NULL);
10104               if (!htab->small_data_overflow_reported
10105                   && (gprel16_reloc_p (howto->type)
10106                       || literal_reloc_p (howto->type)))
10107                 {
10108                   msg = _("small-data section exceeds 64KB;"
10109                           " lower small-data size limit (see option -G)");
10110
10111                   htab->small_data_overflow_reported = TRUE;
10112                   (*info->callbacks->einfo) ("%P: %s\n", msg);
10113                 }
10114               if (! ((*info->callbacks->reloc_overflow)
10115                      (info, NULL, name, howto->name, (bfd_vma) 0,
10116                       input_bfd, input_section, rel->r_offset)))
10117                 return FALSE;
10118             }
10119           break;
10120
10121         case bfd_reloc_ok:
10122           break;
10123
10124         case bfd_reloc_outofrange:
10125           if (jal_reloc_p (howto->type))
10126             {
10127               msg = _("JALX to a non-word-aligned address");
10128               info->callbacks->warning
10129                 (info, msg, name, input_bfd, input_section, rel->r_offset);
10130               return FALSE;
10131             }
10132           /* Fall through.  */
10133
10134         default:
10135           abort ();
10136           break;
10137         }
10138
10139       /* If we've got another relocation for the address, keep going
10140          until we reach the last one.  */
10141       if (use_saved_addend_p)
10142         {
10143           addend = value;
10144           continue;
10145         }
10146
10147       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
10148         /* See the comment above about using R_MIPS_64 in the 32-bit
10149            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
10150            that calculated the right value.  Now, however, we
10151            sign-extend the 32-bit result to 64-bits, and store it as a
10152            64-bit value.  We are especially generous here in that we
10153            go to extreme lengths to support this usage on systems with
10154            only a 32-bit VMA.  */
10155         {
10156           bfd_vma sign_bits;
10157           bfd_vma low_bits;
10158           bfd_vma high_bits;
10159
10160           if (value & ((bfd_vma) 1 << 31))
10161 #ifdef BFD64
10162             sign_bits = ((bfd_vma) 1 << 32) - 1;
10163 #else
10164             sign_bits = -1;
10165 #endif
10166           else
10167             sign_bits = 0;
10168
10169           /* If we don't know that we have a 64-bit type,
10170              do two separate stores.  */
10171           if (bfd_big_endian (input_bfd))
10172             {
10173               /* Undo what we did above.  */
10174               rel->r_offset -= 4;
10175               /* Store the sign-bits (which are most significant)
10176                  first.  */
10177               low_bits = sign_bits;
10178               high_bits = value;
10179             }
10180           else
10181             {
10182               low_bits = value;
10183               high_bits = sign_bits;
10184             }
10185           bfd_put_32 (input_bfd, low_bits,
10186                       contents + rel->r_offset);
10187           bfd_put_32 (input_bfd, high_bits,
10188                       contents + rel->r_offset + 4);
10189           continue;
10190         }
10191
10192       /* Actually perform the relocation.  */
10193       if (! mips_elf_perform_relocation (info, howto, rel, value,
10194                                          input_bfd, input_section,
10195                                          contents, cross_mode_jump_p))
10196         return FALSE;
10197     }
10198
10199   return TRUE;
10200 }
10201 \f
10202 /* A function that iterates over each entry in la25_stubs and fills
10203    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
10204
10205 static int
10206 mips_elf_create_la25_stub (void **slot, void *data)
10207 {
10208   struct mips_htab_traverse_info *hti;
10209   struct mips_elf_link_hash_table *htab;
10210   struct mips_elf_la25_stub *stub;
10211   asection *s;
10212   bfd_byte *loc;
10213   bfd_vma offset, target, target_high, target_low;
10214
10215   stub = (struct mips_elf_la25_stub *) *slot;
10216   hti = (struct mips_htab_traverse_info *) data;
10217   htab = mips_elf_hash_table (hti->info);
10218   BFD_ASSERT (htab != NULL);
10219
10220   /* Create the section contents, if we haven't already.  */
10221   s = stub->stub_section;
10222   loc = s->contents;
10223   if (loc == NULL)
10224     {
10225       loc = bfd_malloc (s->size);
10226       if (loc == NULL)
10227         {
10228           hti->error = TRUE;
10229           return FALSE;
10230         }
10231       s->contents = loc;
10232     }
10233
10234   /* Work out where in the section this stub should go.  */
10235   offset = stub->offset;
10236
10237   /* Work out the target address.  */
10238   target = mips_elf_get_la25_target (stub, &s);
10239   target += s->output_section->vma + s->output_offset;
10240
10241   target_high = ((target + 0x8000) >> 16) & 0xffff;
10242   target_low = (target & 0xffff);
10243
10244   if (stub->stub_section != htab->strampoline)
10245     {
10246       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
10247          of the section and write the two instructions at the end.  */
10248       memset (loc, 0, offset);
10249       loc += offset;
10250       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
10251         {
10252           bfd_put_micromips_32 (hti->output_bfd,
10253                                 LA25_LUI_MICROMIPS (target_high),
10254                                 loc);
10255           bfd_put_micromips_32 (hti->output_bfd,
10256                                 LA25_ADDIU_MICROMIPS (target_low),
10257                                 loc + 4);
10258         }
10259       else
10260         {
10261           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
10262           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
10263         }
10264     }
10265   else
10266     {
10267       /* This is trampoline.  */
10268       loc += offset;
10269       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
10270         {
10271           bfd_put_micromips_32 (hti->output_bfd,
10272                                 LA25_LUI_MICROMIPS (target_high), loc);
10273           bfd_put_micromips_32 (hti->output_bfd,
10274                                 LA25_J_MICROMIPS (target), loc + 4);
10275           bfd_put_micromips_32 (hti->output_bfd,
10276                                 LA25_ADDIU_MICROMIPS (target_low), loc + 8);
10277           bfd_put_32 (hti->output_bfd, 0, loc + 12);
10278         }
10279       else
10280         {
10281           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
10282           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
10283           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
10284           bfd_put_32 (hti->output_bfd, 0, loc + 12);
10285         }
10286     }
10287   return TRUE;
10288 }
10289
10290 /* If NAME is one of the special IRIX6 symbols defined by the linker,
10291    adjust it appropriately now.  */
10292
10293 static void
10294 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
10295                                       const char *name, Elf_Internal_Sym *sym)
10296 {
10297   /* The linker script takes care of providing names and values for
10298      these, but we must place them into the right sections.  */
10299   static const char* const text_section_symbols[] = {
10300     "_ftext",
10301     "_etext",
10302     "__dso_displacement",
10303     "__elf_header",
10304     "__program_header_table",
10305     NULL
10306   };
10307
10308   static const char* const data_section_symbols[] = {
10309     "_fdata",
10310     "_edata",
10311     "_end",
10312     "_fbss",
10313     NULL
10314   };
10315
10316   const char* const *p;
10317   int i;
10318
10319   for (i = 0; i < 2; ++i)
10320     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
10321          *p;
10322          ++p)
10323       if (strcmp (*p, name) == 0)
10324         {
10325           /* All of these symbols are given type STT_SECTION by the
10326              IRIX6 linker.  */
10327           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10328           sym->st_other = STO_PROTECTED;
10329
10330           /* The IRIX linker puts these symbols in special sections.  */
10331           if (i == 0)
10332             sym->st_shndx = SHN_MIPS_TEXT;
10333           else
10334             sym->st_shndx = SHN_MIPS_DATA;
10335
10336           break;
10337         }
10338 }
10339
10340 /* Finish up dynamic symbol handling.  We set the contents of various
10341    dynamic sections here.  */
10342
10343 bfd_boolean
10344 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
10345                                      struct bfd_link_info *info,
10346                                      struct elf_link_hash_entry *h,
10347                                      Elf_Internal_Sym *sym)
10348 {
10349   bfd *dynobj;
10350   asection *sgot;
10351   struct mips_got_info *g, *gg;
10352   const char *name;
10353   int idx;
10354   struct mips_elf_link_hash_table *htab;
10355   struct mips_elf_link_hash_entry *hmips;
10356
10357   htab = mips_elf_hash_table (info);
10358   BFD_ASSERT (htab != NULL);
10359   dynobj = elf_hash_table (info)->dynobj;
10360   hmips = (struct mips_elf_link_hash_entry *) h;
10361
10362   BFD_ASSERT (!htab->is_vxworks);
10363
10364   if (h->plt.plist != NULL
10365       && (h->plt.plist->mips_offset != MINUS_ONE
10366           || h->plt.plist->comp_offset != MINUS_ONE))
10367     {
10368       /* We've decided to create a PLT entry for this symbol.  */
10369       bfd_byte *loc;
10370       bfd_vma header_address, got_address;
10371       bfd_vma got_address_high, got_address_low, load;
10372       bfd_vma got_index;
10373       bfd_vma isa_bit;
10374
10375       got_index = h->plt.plist->gotplt_index;
10376
10377       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10378       BFD_ASSERT (h->dynindx != -1);
10379       BFD_ASSERT (htab->splt != NULL);
10380       BFD_ASSERT (got_index != MINUS_ONE);
10381       BFD_ASSERT (!h->def_regular);
10382
10383       /* Calculate the address of the PLT header.  */
10384       isa_bit = htab->plt_header_is_comp;
10385       header_address = (htab->splt->output_section->vma
10386                         + htab->splt->output_offset + isa_bit);
10387
10388       /* Calculate the address of the .got.plt entry.  */
10389       got_address = (htab->sgotplt->output_section->vma
10390                      + htab->sgotplt->output_offset
10391                      + got_index * MIPS_ELF_GOT_SIZE (dynobj));
10392
10393       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10394       got_address_low = got_address & 0xffff;
10395
10396       /* Initially point the .got.plt entry at the PLT header.  */
10397       loc = (htab->sgotplt->contents + got_index * MIPS_ELF_GOT_SIZE (dynobj));
10398       if (ABI_64_P (output_bfd))
10399         bfd_put_64 (output_bfd, header_address, loc);
10400       else
10401         bfd_put_32 (output_bfd, header_address, loc);
10402
10403       /* Now handle the PLT itself.  First the standard entry (the order
10404          does not matter, we just have to pick one).  */
10405       if (h->plt.plist->mips_offset != MINUS_ONE)
10406         {
10407           const bfd_vma *plt_entry;
10408           bfd_vma plt_offset;
10409
10410           plt_offset = htab->plt_header_size + h->plt.plist->mips_offset;
10411
10412           BFD_ASSERT (plt_offset <= htab->splt->size);
10413
10414           /* Find out where the .plt entry should go.  */
10415           loc = htab->splt->contents + plt_offset;
10416
10417           /* Pick the load opcode.  */
10418           load = MIPS_ELF_LOAD_WORD (output_bfd);
10419
10420           /* Fill in the PLT entry itself.  */
10421           plt_entry = mips_exec_plt_entry;
10422           bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
10423           bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load,
10424                       loc + 4);
10425
10426           if (! LOAD_INTERLOCKS_P (output_bfd))
10427             {
10428               bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
10429               bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10430             }
10431           else
10432             {
10433               bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
10434               bfd_put_32 (output_bfd, plt_entry[2] | got_address_low,
10435                           loc + 12);
10436             }
10437         }
10438
10439       /* Now the compressed entry.  They come after any standard ones.  */
10440       if (h->plt.plist->comp_offset != MINUS_ONE)
10441         {
10442           bfd_vma plt_offset;
10443
10444           plt_offset = (htab->plt_header_size + htab->plt_mips_offset
10445                         + h->plt.plist->comp_offset);
10446
10447           BFD_ASSERT (plt_offset <= htab->splt->size);
10448
10449           /* Find out where the .plt entry should go.  */
10450           loc = htab->splt->contents + plt_offset;
10451
10452           /* Fill in the PLT entry itself.  */
10453           if (!MICROMIPS_P (output_bfd))
10454             {
10455               const bfd_vma *plt_entry = mips16_o32_exec_plt_entry;
10456
10457               bfd_put_16 (output_bfd, plt_entry[0], loc);
10458               bfd_put_16 (output_bfd, plt_entry[1], loc + 2);
10459               bfd_put_16 (output_bfd, plt_entry[2], loc + 4);
10460               bfd_put_16 (output_bfd, plt_entry[3], loc + 6);
10461               bfd_put_16 (output_bfd, plt_entry[4], loc + 8);
10462               bfd_put_16 (output_bfd, plt_entry[5], loc + 10);
10463               bfd_put_32 (output_bfd, got_address, loc + 12);
10464             }
10465           else if (htab->insn32)
10466             {
10467               const bfd_vma *plt_entry = micromips_insn32_o32_exec_plt_entry;
10468
10469               bfd_put_16 (output_bfd, plt_entry[0], loc);
10470               bfd_put_16 (output_bfd, got_address_high, loc + 2);
10471               bfd_put_16 (output_bfd, plt_entry[2], loc + 4);
10472               bfd_put_16 (output_bfd, got_address_low, loc + 6);
10473               bfd_put_16 (output_bfd, plt_entry[4], loc + 8);
10474               bfd_put_16 (output_bfd, plt_entry[5], loc + 10);
10475               bfd_put_16 (output_bfd, plt_entry[6], loc + 12);
10476               bfd_put_16 (output_bfd, got_address_low, loc + 14);
10477             }
10478           else
10479             {
10480               const bfd_vma *plt_entry = micromips_o32_exec_plt_entry;
10481               bfd_signed_vma gotpc_offset;
10482               bfd_vma loc_address;
10483
10484               BFD_ASSERT (got_address % 4 == 0);
10485
10486               loc_address = (htab->splt->output_section->vma
10487                              + htab->splt->output_offset + plt_offset);
10488               gotpc_offset = got_address - ((loc_address | 3) ^ 3);
10489
10490               /* ADDIUPC has a span of +/-16MB, check we're in range.  */
10491               if (gotpc_offset + 0x1000000 >= 0x2000000)
10492                 {
10493                   (*_bfd_error_handler)
10494                     (_("%B: `%A' offset of %ld from `%A' "
10495                        "beyond the range of ADDIUPC"),
10496                      output_bfd,
10497                      htab->sgotplt->output_section,
10498                      htab->splt->output_section,
10499                      (long) gotpc_offset);
10500                   bfd_set_error (bfd_error_no_error);
10501                   return FALSE;
10502                 }
10503               bfd_put_16 (output_bfd,
10504                           plt_entry[0] | ((gotpc_offset >> 18) & 0x7f), loc);
10505               bfd_put_16 (output_bfd, (gotpc_offset >> 2) & 0xffff, loc + 2);
10506               bfd_put_16 (output_bfd, plt_entry[2], loc + 4);
10507               bfd_put_16 (output_bfd, plt_entry[3], loc + 6);
10508               bfd_put_16 (output_bfd, plt_entry[4], loc + 8);
10509               bfd_put_16 (output_bfd, plt_entry[5], loc + 10);
10510             }
10511         }
10512
10513       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10514       mips_elf_output_dynamic_relocation (output_bfd, htab->srelplt,
10515                                           got_index - 2, h->dynindx,
10516                                           R_MIPS_JUMP_SLOT, got_address);
10517
10518       /* We distinguish between PLT entries and lazy-binding stubs by
10519          giving the former an st_other value of STO_MIPS_PLT.  Set the
10520          flag and leave the value if there are any relocations in the
10521          binary where pointer equality matters.  */
10522       sym->st_shndx = SHN_UNDEF;
10523       if (h->pointer_equality_needed)
10524         sym->st_other = ELF_ST_SET_MIPS_PLT (sym->st_other);
10525       else
10526         {
10527           sym->st_value = 0;
10528           sym->st_other = 0;
10529         }
10530     }
10531
10532   if (h->plt.plist != NULL && h->plt.plist->stub_offset != MINUS_ONE)
10533     {
10534       /* We've decided to create a lazy-binding stub.  */
10535       bfd_boolean micromips_p = MICROMIPS_P (output_bfd);
10536       unsigned int other = micromips_p ? STO_MICROMIPS : 0;
10537       bfd_vma stub_size = htab->function_stub_size;
10538       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
10539       bfd_vma isa_bit = micromips_p;
10540       bfd_vma stub_big_size;
10541
10542       if (!micromips_p)
10543         stub_big_size = MIPS_FUNCTION_STUB_BIG_SIZE;
10544       else if (htab->insn32)
10545         stub_big_size = MICROMIPS_INSN32_FUNCTION_STUB_BIG_SIZE;
10546       else
10547         stub_big_size = MICROMIPS_FUNCTION_STUB_BIG_SIZE;
10548
10549       /* This symbol has a stub.  Set it up.  */
10550
10551       BFD_ASSERT (h->dynindx != -1);
10552
10553       BFD_ASSERT (stub_size == stub_big_size || h->dynindx <= 0xffff);
10554
10555       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
10556          sign extension at runtime in the stub, resulting in a negative
10557          index value.  */
10558       if (h->dynindx & ~0x7fffffff)
10559         return FALSE;
10560
10561       /* Fill the stub.  */
10562       if (micromips_p)
10563         {
10564           idx = 0;
10565           bfd_put_micromips_32 (output_bfd, STUB_LW_MICROMIPS (output_bfd),
10566                                 stub + idx);
10567           idx += 4;
10568           if (htab->insn32)
10569             {
10570               bfd_put_micromips_32 (output_bfd,
10571                                     STUB_MOVE32_MICROMIPS (output_bfd),
10572                                     stub + idx);
10573               idx += 4;
10574             }
10575           else
10576             {
10577               bfd_put_16 (output_bfd, STUB_MOVE_MICROMIPS, stub + idx);
10578               idx += 2;
10579             }
10580           if (stub_size == stub_big_size)
10581             {
10582               long dynindx_hi = (h->dynindx >> 16) & 0x7fff;
10583
10584               bfd_put_micromips_32 (output_bfd,
10585                                     STUB_LUI_MICROMIPS (dynindx_hi),
10586                                     stub + idx);
10587               idx += 4;
10588             }
10589           if (htab->insn32)
10590             {
10591               bfd_put_micromips_32 (output_bfd, STUB_JALR32_MICROMIPS,
10592                                     stub + idx);
10593               idx += 4;
10594             }
10595           else
10596             {
10597               bfd_put_16 (output_bfd, STUB_JALR_MICROMIPS, stub + idx);
10598               idx += 2;
10599             }
10600
10601           /* If a large stub is not required and sign extension is not a
10602              problem, then use legacy code in the stub.  */
10603           if (stub_size == stub_big_size)
10604             bfd_put_micromips_32 (output_bfd,
10605                                   STUB_ORI_MICROMIPS (h->dynindx & 0xffff),
10606                                   stub + idx);
10607           else if (h->dynindx & ~0x7fff)
10608             bfd_put_micromips_32 (output_bfd,
10609                                   STUB_LI16U_MICROMIPS (h->dynindx & 0xffff),
10610                                   stub + idx);
10611           else
10612             bfd_put_micromips_32 (output_bfd,
10613                                   STUB_LI16S_MICROMIPS (output_bfd,
10614                                                         h->dynindx),
10615                                   stub + idx);
10616         }
10617       else
10618         {
10619           idx = 0;
10620           bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
10621           idx += 4;
10622           bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + idx);
10623           idx += 4;
10624           if (stub_size == stub_big_size)
10625             {
10626               bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
10627                           stub + idx);
10628               idx += 4;
10629             }
10630           bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
10631           idx += 4;
10632
10633           /* If a large stub is not required and sign extension is not a
10634              problem, then use legacy code in the stub.  */
10635           if (stub_size == stub_big_size)
10636             bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff),
10637                         stub + idx);
10638           else if (h->dynindx & ~0x7fff)
10639             bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff),
10640                         stub + idx);
10641           else
10642             bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
10643                         stub + idx);
10644         }
10645
10646       BFD_ASSERT (h->plt.plist->stub_offset <= htab->sstubs->size);
10647       memcpy (htab->sstubs->contents + h->plt.plist->stub_offset,
10648               stub, stub_size);
10649
10650       /* Mark the symbol as undefined.  stub_offset != -1 occurs
10651          only for the referenced symbol.  */
10652       sym->st_shndx = SHN_UNDEF;
10653
10654       /* The run-time linker uses the st_value field of the symbol
10655          to reset the global offset table entry for this external
10656          to its stub address when unlinking a shared object.  */
10657       sym->st_value = (htab->sstubs->output_section->vma
10658                        + htab->sstubs->output_offset
10659                        + h->plt.plist->stub_offset
10660                        + isa_bit);
10661       sym->st_other = other;
10662     }
10663
10664   /* If we have a MIPS16 function with a stub, the dynamic symbol must
10665      refer to the stub, since only the stub uses the standard calling
10666      conventions.  */
10667   if (h->dynindx != -1 && hmips->fn_stub != NULL)
10668     {
10669       BFD_ASSERT (hmips->need_fn_stub);
10670       sym->st_value = (hmips->fn_stub->output_section->vma
10671                        + hmips->fn_stub->output_offset);
10672       sym->st_size = hmips->fn_stub->size;
10673       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
10674     }
10675
10676   BFD_ASSERT (h->dynindx != -1
10677               || h->forced_local);
10678
10679   sgot = htab->sgot;
10680   g = htab->got_info;
10681   BFD_ASSERT (g != NULL);
10682
10683   /* Run through the global symbol table, creating GOT entries for all
10684      the symbols that need them.  */
10685   if (hmips->global_got_area != GGA_NONE)
10686     {
10687       bfd_vma offset;
10688       bfd_vma value;
10689
10690       value = sym->st_value;
10691       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
10692       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
10693     }
10694
10695   if (hmips->global_got_area != GGA_NONE && g->next)
10696     {
10697       struct mips_got_entry e, *p;
10698       bfd_vma entry;
10699       bfd_vma offset;
10700
10701       gg = g;
10702
10703       e.abfd = output_bfd;
10704       e.symndx = -1;
10705       e.d.h = hmips;
10706       e.tls_type = GOT_TLS_NONE;
10707
10708       for (g = g->next; g->next != gg; g = g->next)
10709         {
10710           if (g->got_entries
10711               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
10712                                                            &e)))
10713             {
10714               offset = p->gotidx;
10715               BFD_ASSERT (offset > 0 && offset < htab->sgot->size);
10716               if (info->shared
10717                   || (elf_hash_table (info)->dynamic_sections_created
10718                       && p->d.h != NULL
10719                       && p->d.h->root.def_dynamic
10720                       && !p->d.h->root.def_regular))
10721                 {
10722                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
10723                      the various compatibility problems, it's easier to mock
10724                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
10725                      mips_elf_create_dynamic_relocation to calculate the
10726                      appropriate addend.  */
10727                   Elf_Internal_Rela rel[3];
10728
10729                   memset (rel, 0, sizeof (rel));
10730                   if (ABI_64_P (output_bfd))
10731                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
10732                   else
10733                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
10734                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
10735
10736                   entry = 0;
10737                   if (! (mips_elf_create_dynamic_relocation
10738                          (output_bfd, info, rel,
10739                           e.d.h, NULL, sym->st_value, &entry, sgot)))
10740                     return FALSE;
10741                 }
10742               else
10743                 entry = sym->st_value;
10744               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
10745             }
10746         }
10747     }
10748
10749   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
10750   name = h->root.root.string;
10751   if (h == elf_hash_table (info)->hdynamic
10752       || h == elf_hash_table (info)->hgot)
10753     sym->st_shndx = SHN_ABS;
10754   else if (strcmp (name, "_DYNAMIC_LINK") == 0
10755            || strcmp (name, "_DYNAMIC_LINKING") == 0)
10756     {
10757       sym->st_shndx = SHN_ABS;
10758       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10759       sym->st_value = 1;
10760     }
10761   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
10762     {
10763       sym->st_shndx = SHN_ABS;
10764       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10765       sym->st_value = elf_gp (output_bfd);
10766     }
10767   else if (SGI_COMPAT (output_bfd))
10768     {
10769       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
10770           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
10771         {
10772           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10773           sym->st_other = STO_PROTECTED;
10774           sym->st_value = 0;
10775           sym->st_shndx = SHN_MIPS_DATA;
10776         }
10777       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
10778         {
10779           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10780           sym->st_other = STO_PROTECTED;
10781           sym->st_value = mips_elf_hash_table (info)->procedure_count;
10782           sym->st_shndx = SHN_ABS;
10783         }
10784       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
10785         {
10786           if (h->type == STT_FUNC)
10787             sym->st_shndx = SHN_MIPS_TEXT;
10788           else if (h->type == STT_OBJECT)
10789             sym->st_shndx = SHN_MIPS_DATA;
10790         }
10791     }
10792
10793   /* Emit a copy reloc, if needed.  */
10794   if (h->needs_copy)
10795     {
10796       asection *s;
10797       bfd_vma symval;
10798
10799       BFD_ASSERT (h->dynindx != -1);
10800       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10801
10802       s = mips_elf_rel_dyn_section (info, FALSE);
10803       symval = (h->root.u.def.section->output_section->vma
10804                 + h->root.u.def.section->output_offset
10805                 + h->root.u.def.value);
10806       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
10807                                           h->dynindx, R_MIPS_COPY, symval);
10808     }
10809
10810   /* Handle the IRIX6-specific symbols.  */
10811   if (IRIX_COMPAT (output_bfd) == ict_irix6)
10812     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
10813
10814   /* Keep dynamic compressed symbols odd.  This allows the dynamic linker
10815      to treat compressed symbols like any other.  */
10816   if (ELF_ST_IS_MIPS16 (sym->st_other))
10817     {
10818       BFD_ASSERT (sym->st_value & 1);
10819       sym->st_other -= STO_MIPS16;
10820     }
10821   else if (ELF_ST_IS_MICROMIPS (sym->st_other))
10822     {
10823       BFD_ASSERT (sym->st_value & 1);
10824       sym->st_other -= STO_MICROMIPS;
10825     }
10826
10827   return TRUE;
10828 }
10829
10830 /* Likewise, for VxWorks.  */
10831
10832 bfd_boolean
10833 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
10834                                          struct bfd_link_info *info,
10835                                          struct elf_link_hash_entry *h,
10836                                          Elf_Internal_Sym *sym)
10837 {
10838   bfd *dynobj;
10839   asection *sgot;
10840   struct mips_got_info *g;
10841   struct mips_elf_link_hash_table *htab;
10842   struct mips_elf_link_hash_entry *hmips;
10843
10844   htab = mips_elf_hash_table (info);
10845   BFD_ASSERT (htab != NULL);
10846   dynobj = elf_hash_table (info)->dynobj;
10847   hmips = (struct mips_elf_link_hash_entry *) h;
10848
10849   if (h->plt.plist != NULL && h->plt.plist->mips_offset != MINUS_ONE)
10850     {
10851       bfd_byte *loc;
10852       bfd_vma plt_address, got_address, got_offset, branch_offset;
10853       Elf_Internal_Rela rel;
10854       static const bfd_vma *plt_entry;
10855       bfd_vma gotplt_index;
10856       bfd_vma plt_offset;
10857
10858       plt_offset = htab->plt_header_size + h->plt.plist->mips_offset;
10859       gotplt_index = h->plt.plist->gotplt_index;
10860
10861       BFD_ASSERT (h->dynindx != -1);
10862       BFD_ASSERT (htab->splt != NULL);
10863       BFD_ASSERT (gotplt_index != MINUS_ONE);
10864       BFD_ASSERT (plt_offset <= htab->splt->size);
10865
10866       /* Calculate the address of the .plt entry.  */
10867       plt_address = (htab->splt->output_section->vma
10868                      + htab->splt->output_offset
10869                      + plt_offset);
10870
10871       /* Calculate the address of the .got.plt entry.  */
10872       got_address = (htab->sgotplt->output_section->vma
10873                      + htab->sgotplt->output_offset
10874                      + gotplt_index * MIPS_ELF_GOT_SIZE (output_bfd));
10875
10876       /* Calculate the offset of the .got.plt entry from
10877          _GLOBAL_OFFSET_TABLE_.  */
10878       got_offset = mips_elf_gotplt_index (info, h);
10879
10880       /* Calculate the offset for the branch at the start of the PLT
10881          entry.  The branch jumps to the beginning of .plt.  */
10882       branch_offset = -(plt_offset / 4 + 1) & 0xffff;
10883
10884       /* Fill in the initial value of the .got.plt entry.  */
10885       bfd_put_32 (output_bfd, plt_address,
10886                   (htab->sgotplt->contents
10887                    + gotplt_index * MIPS_ELF_GOT_SIZE (output_bfd)));
10888
10889       /* Find out where the .plt entry should go.  */
10890       loc = htab->splt->contents + plt_offset;
10891
10892       if (info->shared)
10893         {
10894           plt_entry = mips_vxworks_shared_plt_entry;
10895           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10896           bfd_put_32 (output_bfd, plt_entry[1] | gotplt_index, loc + 4);
10897         }
10898       else
10899         {
10900           bfd_vma got_address_high, got_address_low;
10901
10902           plt_entry = mips_vxworks_exec_plt_entry;
10903           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10904           got_address_low = got_address & 0xffff;
10905
10906           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10907           bfd_put_32 (output_bfd, plt_entry[1] | gotplt_index, loc + 4);
10908           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
10909           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
10910           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10911           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10912           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10913           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10914
10915           loc = (htab->srelplt2->contents
10916                  + (gotplt_index * 3 + 2) * sizeof (Elf32_External_Rela));
10917
10918           /* Emit a relocation for the .got.plt entry.  */
10919           rel.r_offset = got_address;
10920           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10921           rel.r_addend = plt_offset;
10922           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10923
10924           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
10925           loc += sizeof (Elf32_External_Rela);
10926           rel.r_offset = plt_address + 8;
10927           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10928           rel.r_addend = got_offset;
10929           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10930
10931           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
10932           loc += sizeof (Elf32_External_Rela);
10933           rel.r_offset += 4;
10934           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10935           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10936         }
10937
10938       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10939       loc = (htab->srelplt->contents
10940              + gotplt_index * sizeof (Elf32_External_Rela));
10941       rel.r_offset = got_address;
10942       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
10943       rel.r_addend = 0;
10944       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10945
10946       if (!h->def_regular)
10947         sym->st_shndx = SHN_UNDEF;
10948     }
10949
10950   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
10951
10952   sgot = htab->sgot;
10953   g = htab->got_info;
10954   BFD_ASSERT (g != NULL);
10955
10956   /* See if this symbol has an entry in the GOT.  */
10957   if (hmips->global_got_area != GGA_NONE)
10958     {
10959       bfd_vma offset;
10960       Elf_Internal_Rela outrel;
10961       bfd_byte *loc;
10962       asection *s;
10963
10964       /* Install the symbol value in the GOT.   */
10965       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
10966       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
10967
10968       /* Add a dynamic relocation for it.  */
10969       s = mips_elf_rel_dyn_section (info, FALSE);
10970       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
10971       outrel.r_offset = (sgot->output_section->vma
10972                          + sgot->output_offset
10973                          + offset);
10974       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
10975       outrel.r_addend = 0;
10976       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
10977     }
10978
10979   /* Emit a copy reloc, if needed.  */
10980   if (h->needs_copy)
10981     {
10982       Elf_Internal_Rela rel;
10983
10984       BFD_ASSERT (h->dynindx != -1);
10985
10986       rel.r_offset = (h->root.u.def.section->output_section->vma
10987                       + h->root.u.def.section->output_offset
10988                       + h->root.u.def.value);
10989       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
10990       rel.r_addend = 0;
10991       bfd_elf32_swap_reloca_out (output_bfd, &rel,
10992                                  htab->srelbss->contents
10993                                  + (htab->srelbss->reloc_count
10994                                     * sizeof (Elf32_External_Rela)));
10995       ++htab->srelbss->reloc_count;
10996     }
10997
10998   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
10999   if (ELF_ST_IS_COMPRESSED (sym->st_other))
11000     sym->st_value &= ~1;
11001
11002   return TRUE;
11003 }
11004
11005 /* Write out a plt0 entry to the beginning of .plt.  */
11006
11007 static bfd_boolean
11008 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
11009 {
11010   bfd_byte *loc;
11011   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
11012   static const bfd_vma *plt_entry;
11013   struct mips_elf_link_hash_table *htab;
11014
11015   htab = mips_elf_hash_table (info);
11016   BFD_ASSERT (htab != NULL);
11017
11018   if (ABI_64_P (output_bfd))
11019     plt_entry = mips_n64_exec_plt0_entry;
11020   else if (ABI_N32_P (output_bfd))
11021     plt_entry = mips_n32_exec_plt0_entry;
11022   else if (!htab->plt_header_is_comp)
11023     plt_entry = mips_o32_exec_plt0_entry;
11024   else if (htab->insn32)
11025     plt_entry = micromips_insn32_o32_exec_plt0_entry;
11026   else
11027     plt_entry = micromips_o32_exec_plt0_entry;
11028
11029   /* Calculate the value of .got.plt.  */
11030   gotplt_value = (htab->sgotplt->output_section->vma
11031                   + htab->sgotplt->output_offset);
11032   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
11033   gotplt_value_low = gotplt_value & 0xffff;
11034
11035   /* The PLT sequence is not safe for N64 if .got.plt's address can
11036      not be loaded in two instructions.  */
11037   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
11038               || ~(gotplt_value | 0x7fffffff) == 0);
11039
11040   /* Install the PLT header.  */
11041   loc = htab->splt->contents;
11042   if (plt_entry == micromips_o32_exec_plt0_entry)
11043     {
11044       bfd_vma gotpc_offset;
11045       bfd_vma loc_address;
11046       size_t i;
11047
11048       BFD_ASSERT (gotplt_value % 4 == 0);
11049
11050       loc_address = (htab->splt->output_section->vma
11051                      + htab->splt->output_offset);
11052       gotpc_offset = gotplt_value - ((loc_address | 3) ^ 3);
11053
11054       /* ADDIUPC has a span of +/-16MB, check we're in range.  */
11055       if (gotpc_offset + 0x1000000 >= 0x2000000)
11056         {
11057           (*_bfd_error_handler)
11058             (_("%B: `%A' offset of %ld from `%A' beyond the range of ADDIUPC"),
11059              output_bfd,
11060              htab->sgotplt->output_section,
11061              htab->splt->output_section,
11062              (long) gotpc_offset);
11063           bfd_set_error (bfd_error_no_error);
11064           return FALSE;
11065         }
11066       bfd_put_16 (output_bfd,
11067                   plt_entry[0] | ((gotpc_offset >> 18) & 0x7f), loc);
11068       bfd_put_16 (output_bfd, (gotpc_offset >> 2) & 0xffff, loc + 2);
11069       for (i = 2; i < ARRAY_SIZE (micromips_o32_exec_plt0_entry); i++)
11070         bfd_put_16 (output_bfd, plt_entry[i], loc + (i * 2));
11071     }
11072   else if (plt_entry == micromips_insn32_o32_exec_plt0_entry)
11073     {
11074       size_t i;
11075
11076       bfd_put_16 (output_bfd, plt_entry[0], loc);
11077       bfd_put_16 (output_bfd, gotplt_value_high, loc + 2);
11078       bfd_put_16 (output_bfd, plt_entry[2], loc + 4);
11079       bfd_put_16 (output_bfd, gotplt_value_low, loc + 6);
11080       bfd_put_16 (output_bfd, plt_entry[4], loc + 8);
11081       bfd_put_16 (output_bfd, gotplt_value_low, loc + 10);
11082       for (i = 6; i < ARRAY_SIZE (micromips_insn32_o32_exec_plt0_entry); i++)
11083         bfd_put_16 (output_bfd, plt_entry[i], loc + (i * 2));
11084     }
11085   else
11086     {
11087       bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
11088       bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
11089       bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
11090       bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
11091       bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
11092       bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
11093       bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
11094       bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
11095     }
11096
11097   return TRUE;
11098 }
11099
11100 /* Install the PLT header for a VxWorks executable and finalize the
11101    contents of .rela.plt.unloaded.  */
11102
11103 static void
11104 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
11105 {
11106   Elf_Internal_Rela rela;
11107   bfd_byte *loc;
11108   bfd_vma got_value, got_value_high, got_value_low, plt_address;
11109   static const bfd_vma *plt_entry;
11110   struct mips_elf_link_hash_table *htab;
11111
11112   htab = mips_elf_hash_table (info);
11113   BFD_ASSERT (htab != NULL);
11114
11115   plt_entry = mips_vxworks_exec_plt0_entry;
11116
11117   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
11118   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
11119                + htab->root.hgot->root.u.def.section->output_offset
11120                + htab->root.hgot->root.u.def.value);
11121
11122   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
11123   got_value_low = got_value & 0xffff;
11124
11125   /* Calculate the address of the PLT header.  */
11126   plt_address = htab->splt->output_section->vma + htab->splt->output_offset;
11127
11128   /* Install the PLT header.  */
11129   loc = htab->splt->contents;
11130   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
11131   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
11132   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
11133   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
11134   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
11135   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
11136
11137   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
11138   loc = htab->srelplt2->contents;
11139   rela.r_offset = plt_address;
11140   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
11141   rela.r_addend = 0;
11142   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
11143   loc += sizeof (Elf32_External_Rela);
11144
11145   /* Output the relocation for the following addiu of
11146      %lo(_GLOBAL_OFFSET_TABLE_).  */
11147   rela.r_offset += 4;
11148   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
11149   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
11150   loc += sizeof (Elf32_External_Rela);
11151
11152   /* Fix up the remaining relocations.  They may have the wrong
11153      symbol index for _G_O_T_ or _P_L_T_ depending on the order
11154      in which symbols were output.  */
11155   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
11156     {
11157       Elf_Internal_Rela rel;
11158
11159       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
11160       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
11161       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
11162       loc += sizeof (Elf32_External_Rela);
11163
11164       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
11165       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
11166       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
11167       loc += sizeof (Elf32_External_Rela);
11168
11169       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
11170       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
11171       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
11172       loc += sizeof (Elf32_External_Rela);
11173     }
11174 }
11175
11176 /* Install the PLT header for a VxWorks shared library.  */
11177
11178 static void
11179 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
11180 {
11181   unsigned int i;
11182   struct mips_elf_link_hash_table *htab;
11183
11184   htab = mips_elf_hash_table (info);
11185   BFD_ASSERT (htab != NULL);
11186
11187   /* We just need to copy the entry byte-by-byte.  */
11188   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
11189     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
11190                 htab->splt->contents + i * 4);
11191 }
11192
11193 /* Finish up the dynamic sections.  */
11194
11195 bfd_boolean
11196 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
11197                                        struct bfd_link_info *info)
11198 {
11199   bfd *dynobj;
11200   asection *sdyn;
11201   asection *sgot;
11202   struct mips_got_info *gg, *g;
11203   struct mips_elf_link_hash_table *htab;
11204
11205   htab = mips_elf_hash_table (info);
11206   BFD_ASSERT (htab != NULL);
11207
11208   dynobj = elf_hash_table (info)->dynobj;
11209
11210   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
11211
11212   sgot = htab->sgot;
11213   gg = htab->got_info;
11214
11215   if (elf_hash_table (info)->dynamic_sections_created)
11216     {
11217       bfd_byte *b;
11218       int dyn_to_skip = 0, dyn_skipped = 0;
11219
11220       BFD_ASSERT (sdyn != NULL);
11221       BFD_ASSERT (gg != NULL);
11222
11223       g = mips_elf_bfd_got (output_bfd, FALSE);
11224       BFD_ASSERT (g != NULL);
11225
11226       for (b = sdyn->contents;
11227            b < sdyn->contents + sdyn->size;
11228            b += MIPS_ELF_DYN_SIZE (dynobj))
11229         {
11230           Elf_Internal_Dyn dyn;
11231           const char *name;
11232           size_t elemsize;
11233           asection *s;
11234           bfd_boolean swap_out_p;
11235
11236           /* Read in the current dynamic entry.  */
11237           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
11238
11239           /* Assume that we're going to modify it and write it out.  */
11240           swap_out_p = TRUE;
11241
11242           switch (dyn.d_tag)
11243             {
11244             case DT_RELENT:
11245               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
11246               break;
11247
11248             case DT_RELAENT:
11249               BFD_ASSERT (htab->is_vxworks);
11250               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
11251               break;
11252
11253             case DT_STRSZ:
11254               /* Rewrite DT_STRSZ.  */
11255               dyn.d_un.d_val =
11256                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
11257               break;
11258
11259             case DT_PLTGOT:
11260               s = htab->sgot;
11261               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
11262               break;
11263
11264             case DT_MIPS_PLTGOT:
11265               s = htab->sgotplt;
11266               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
11267               break;
11268
11269             case DT_MIPS_RLD_VERSION:
11270               dyn.d_un.d_val = 1; /* XXX */
11271               break;
11272
11273             case DT_MIPS_FLAGS:
11274               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
11275               break;
11276
11277             case DT_MIPS_TIME_STAMP:
11278               {
11279                 time_t t;
11280                 time (&t);
11281                 dyn.d_un.d_val = t;
11282               }
11283               break;
11284
11285             case DT_MIPS_ICHECKSUM:
11286               /* XXX FIXME: */
11287               swap_out_p = FALSE;
11288               break;
11289
11290             case DT_MIPS_IVERSION:
11291               /* XXX FIXME: */
11292               swap_out_p = FALSE;
11293               break;
11294
11295             case DT_MIPS_BASE_ADDRESS:
11296               s = output_bfd->sections;
11297               BFD_ASSERT (s != NULL);
11298               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
11299               break;
11300
11301             case DT_MIPS_LOCAL_GOTNO:
11302               dyn.d_un.d_val = g->local_gotno;
11303               break;
11304
11305             case DT_MIPS_UNREFEXTNO:
11306               /* The index into the dynamic symbol table which is the
11307                  entry of the first external symbol that is not
11308                  referenced within the same object.  */
11309               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
11310               break;
11311
11312             case DT_MIPS_GOTSYM:
11313               if (htab->global_gotsym)
11314                 {
11315                   dyn.d_un.d_val = htab->global_gotsym->dynindx;
11316                   break;
11317                 }
11318               /* In case if we don't have global got symbols we default
11319                  to setting DT_MIPS_GOTSYM to the same value as
11320                  DT_MIPS_SYMTABNO, so we just fall through.  */
11321
11322             case DT_MIPS_SYMTABNO:
11323               name = ".dynsym";
11324               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
11325               s = bfd_get_section_by_name (output_bfd, name);
11326               BFD_ASSERT (s != NULL);
11327
11328               dyn.d_un.d_val = s->size / elemsize;
11329               break;
11330
11331             case DT_MIPS_HIPAGENO:
11332               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
11333               break;
11334
11335             case DT_MIPS_RLD_MAP:
11336               {
11337                 struct elf_link_hash_entry *h;
11338                 h = mips_elf_hash_table (info)->rld_symbol;
11339                 if (!h)
11340                   {
11341                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
11342                     swap_out_p = FALSE;
11343                     break;
11344                   }
11345                 s = h->root.u.def.section;
11346                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
11347                                   + h->root.u.def.value);
11348               }
11349               break;
11350
11351             case DT_MIPS_OPTIONS:
11352               s = (bfd_get_section_by_name
11353                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
11354               dyn.d_un.d_ptr = s->vma;
11355               break;
11356
11357             case DT_RELASZ:
11358               BFD_ASSERT (htab->is_vxworks);
11359               /* The count does not include the JUMP_SLOT relocations.  */
11360               if (htab->srelplt)
11361                 dyn.d_un.d_val -= htab->srelplt->size;
11362               break;
11363
11364             case DT_PLTREL:
11365               BFD_ASSERT (htab->use_plts_and_copy_relocs);
11366               if (htab->is_vxworks)
11367                 dyn.d_un.d_val = DT_RELA;
11368               else
11369                 dyn.d_un.d_val = DT_REL;
11370               break;
11371
11372             case DT_PLTRELSZ:
11373               BFD_ASSERT (htab->use_plts_and_copy_relocs);
11374               dyn.d_un.d_val = htab->srelplt->size;
11375               break;
11376
11377             case DT_JMPREL:
11378               BFD_ASSERT (htab->use_plts_and_copy_relocs);
11379               dyn.d_un.d_ptr = (htab->srelplt->output_section->vma
11380                                 + htab->srelplt->output_offset);
11381               break;
11382
11383             case DT_TEXTREL:
11384               /* If we didn't need any text relocations after all, delete
11385                  the dynamic tag.  */
11386               if (!(info->flags & DF_TEXTREL))
11387                 {
11388                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
11389                   swap_out_p = FALSE;
11390                 }
11391               break;
11392
11393             case DT_FLAGS:
11394               /* If we didn't need any text relocations after all, clear
11395                  DF_TEXTREL from DT_FLAGS.  */
11396               if (!(info->flags & DF_TEXTREL))
11397                 dyn.d_un.d_val &= ~DF_TEXTREL;
11398               else
11399                 swap_out_p = FALSE;
11400               break;
11401
11402             default:
11403               swap_out_p = FALSE;
11404               if (htab->is_vxworks
11405                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
11406                 swap_out_p = TRUE;
11407               break;
11408             }
11409
11410           if (swap_out_p || dyn_skipped)
11411             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
11412               (dynobj, &dyn, b - dyn_skipped);
11413
11414           if (dyn_to_skip)
11415             {
11416               dyn_skipped += dyn_to_skip;
11417               dyn_to_skip = 0;
11418             }
11419         }
11420
11421       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
11422       if (dyn_skipped > 0)
11423         memset (b - dyn_skipped, 0, dyn_skipped);
11424     }
11425
11426   if (sgot != NULL && sgot->size > 0
11427       && !bfd_is_abs_section (sgot->output_section))
11428     {
11429       if (htab->is_vxworks)
11430         {
11431           /* The first entry of the global offset table points to the
11432              ".dynamic" section.  The second is initialized by the
11433              loader and contains the shared library identifier.
11434              The third is also initialized by the loader and points
11435              to the lazy resolution stub.  */
11436           MIPS_ELF_PUT_WORD (output_bfd,
11437                              sdyn->output_offset + sdyn->output_section->vma,
11438                              sgot->contents);
11439           MIPS_ELF_PUT_WORD (output_bfd, 0,
11440                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
11441           MIPS_ELF_PUT_WORD (output_bfd, 0,
11442                              sgot->contents
11443                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
11444         }
11445       else
11446         {
11447           /* The first entry of the global offset table will be filled at
11448              runtime. The second entry will be used by some runtime loaders.
11449              This isn't the case of IRIX rld.  */
11450           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
11451           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
11452                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
11453         }
11454
11455       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
11456          = MIPS_ELF_GOT_SIZE (output_bfd);
11457     }
11458
11459   /* Generate dynamic relocations for the non-primary gots.  */
11460   if (gg != NULL && gg->next)
11461     {
11462       Elf_Internal_Rela rel[3];
11463       bfd_vma addend = 0;
11464
11465       memset (rel, 0, sizeof (rel));
11466       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
11467
11468       for (g = gg->next; g->next != gg; g = g->next)
11469         {
11470           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
11471             + g->next->tls_gotno;
11472
11473           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
11474                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
11475           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
11476                              sgot->contents
11477                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
11478
11479           if (! info->shared)
11480             continue;
11481
11482           for (; got_index < g->local_gotno; got_index++)
11483             {
11484               if (got_index >= g->assigned_low_gotno
11485                   && got_index <= g->assigned_high_gotno)
11486                 continue;
11487
11488               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
11489                 = got_index * MIPS_ELF_GOT_SIZE (output_bfd);
11490               if (!(mips_elf_create_dynamic_relocation
11491                     (output_bfd, info, rel, NULL,
11492                      bfd_abs_section_ptr,
11493                      0, &addend, sgot)))
11494                 return FALSE;
11495               BFD_ASSERT (addend == 0);
11496             }
11497         }
11498     }
11499
11500   /* The generation of dynamic relocations for the non-primary gots
11501      adds more dynamic relocations.  We cannot count them until
11502      here.  */
11503
11504   if (elf_hash_table (info)->dynamic_sections_created)
11505     {
11506       bfd_byte *b;
11507       bfd_boolean swap_out_p;
11508
11509       BFD_ASSERT (sdyn != NULL);
11510
11511       for (b = sdyn->contents;
11512            b < sdyn->contents + sdyn->size;
11513            b += MIPS_ELF_DYN_SIZE (dynobj))
11514         {
11515           Elf_Internal_Dyn dyn;
11516           asection *s;
11517
11518           /* Read in the current dynamic entry.  */
11519           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
11520
11521           /* Assume that we're going to modify it and write it out.  */
11522           swap_out_p = TRUE;
11523
11524           switch (dyn.d_tag)
11525             {
11526             case DT_RELSZ:
11527               /* Reduce DT_RELSZ to account for any relocations we
11528                  decided not to make.  This is for the n64 irix rld,
11529                  which doesn't seem to apply any relocations if there
11530                  are trailing null entries.  */
11531               s = mips_elf_rel_dyn_section (info, FALSE);
11532               dyn.d_un.d_val = (s->reloc_count
11533                                 * (ABI_64_P (output_bfd)
11534                                    ? sizeof (Elf64_Mips_External_Rel)
11535                                    : sizeof (Elf32_External_Rel)));
11536               /* Adjust the section size too.  Tools like the prelinker
11537                  can reasonably expect the values to the same.  */
11538               elf_section_data (s->output_section)->this_hdr.sh_size
11539                 = dyn.d_un.d_val;
11540               break;
11541
11542             default:
11543               swap_out_p = FALSE;
11544               break;
11545             }
11546
11547           if (swap_out_p)
11548             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
11549               (dynobj, &dyn, b);
11550         }
11551     }
11552
11553   {
11554     asection *s;
11555     Elf32_compact_rel cpt;
11556
11557     if (SGI_COMPAT (output_bfd))
11558       {
11559         /* Write .compact_rel section out.  */
11560         s = bfd_get_linker_section (dynobj, ".compact_rel");
11561         if (s != NULL)
11562           {
11563             cpt.id1 = 1;
11564             cpt.num = s->reloc_count;
11565             cpt.id2 = 2;
11566             cpt.offset = (s->output_section->filepos
11567                           + sizeof (Elf32_External_compact_rel));
11568             cpt.reserved0 = 0;
11569             cpt.reserved1 = 0;
11570             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
11571                                             ((Elf32_External_compact_rel *)
11572                                              s->contents));
11573
11574             /* Clean up a dummy stub function entry in .text.  */
11575             if (htab->sstubs != NULL)
11576               {
11577                 file_ptr dummy_offset;
11578
11579                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
11580                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
11581                 memset (htab->sstubs->contents + dummy_offset, 0,
11582                         htab->function_stub_size);
11583               }
11584           }
11585       }
11586
11587     /* The psABI says that the dynamic relocations must be sorted in
11588        increasing order of r_symndx.  The VxWorks EABI doesn't require
11589        this, and because the code below handles REL rather than RELA
11590        relocations, using it for VxWorks would be outright harmful.  */
11591     if (!htab->is_vxworks)
11592       {
11593         s = mips_elf_rel_dyn_section (info, FALSE);
11594         if (s != NULL
11595             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
11596           {
11597             reldyn_sorting_bfd = output_bfd;
11598
11599             if (ABI_64_P (output_bfd))
11600               qsort ((Elf64_External_Rel *) s->contents + 1,
11601                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
11602                      sort_dynamic_relocs_64);
11603             else
11604               qsort ((Elf32_External_Rel *) s->contents + 1,
11605                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
11606                      sort_dynamic_relocs);
11607           }
11608       }
11609   }
11610
11611   if (htab->splt && htab->splt->size > 0)
11612     {
11613       if (htab->is_vxworks)
11614         {
11615           if (info->shared)
11616             mips_vxworks_finish_shared_plt (output_bfd, info);
11617           else
11618             mips_vxworks_finish_exec_plt (output_bfd, info);
11619         }
11620       else
11621         {
11622           BFD_ASSERT (!info->shared);
11623           if (!mips_finish_exec_plt (output_bfd, info))
11624             return FALSE;
11625         }
11626     }
11627   return TRUE;
11628 }
11629
11630
11631 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
11632
11633 static void
11634 mips_set_isa_flags (bfd *abfd)
11635 {
11636   flagword val;
11637
11638   switch (bfd_get_mach (abfd))
11639     {
11640     default:
11641     case bfd_mach_mips3000:
11642       val = E_MIPS_ARCH_1;
11643       break;
11644
11645     case bfd_mach_mips3900:
11646       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
11647       break;
11648
11649     case bfd_mach_mips6000:
11650       val = E_MIPS_ARCH_2;
11651       break;
11652
11653     case bfd_mach_mips4000:
11654     case bfd_mach_mips4300:
11655     case bfd_mach_mips4400:
11656     case bfd_mach_mips4600:
11657       val = E_MIPS_ARCH_3;
11658       break;
11659
11660     case bfd_mach_mips4010:
11661       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
11662       break;
11663
11664     case bfd_mach_mips4100:
11665       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
11666       break;
11667
11668     case bfd_mach_mips4111:
11669       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
11670       break;
11671
11672     case bfd_mach_mips4120:
11673       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
11674       break;
11675
11676     case bfd_mach_mips4650:
11677       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
11678       break;
11679
11680     case bfd_mach_mips5400:
11681       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
11682       break;
11683
11684     case bfd_mach_mips5500:
11685       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
11686       break;
11687
11688     case bfd_mach_mips5900:
11689       val = E_MIPS_ARCH_3 | E_MIPS_MACH_5900;
11690       break;
11691
11692     case bfd_mach_mips9000:
11693       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
11694       break;
11695
11696     case bfd_mach_mips5000:
11697     case bfd_mach_mips7000:
11698     case bfd_mach_mips8000:
11699     case bfd_mach_mips10000:
11700     case bfd_mach_mips12000:
11701     case bfd_mach_mips14000:
11702     case bfd_mach_mips16000:
11703       val = E_MIPS_ARCH_4;
11704       break;
11705
11706     case bfd_mach_mips5:
11707       val = E_MIPS_ARCH_5;
11708       break;
11709
11710     case bfd_mach_mips_loongson_2e:
11711       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
11712       break;
11713
11714     case bfd_mach_mips_loongson_2f:
11715       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
11716       break;
11717
11718     case bfd_mach_mips_sb1:
11719       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
11720       break;
11721
11722     case bfd_mach_mips_loongson_3a:
11723       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_LS3A;
11724       break;
11725
11726     case bfd_mach_mips_octeon:
11727     case bfd_mach_mips_octeonp:
11728       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
11729       break;
11730
11731     case bfd_mach_mips_xlr:
11732       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
11733       break;
11734
11735     case bfd_mach_mips_octeon2:
11736       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
11737       break;
11738
11739     case bfd_mach_mipsisa32:
11740       val = E_MIPS_ARCH_32;
11741       break;
11742
11743     case bfd_mach_mipsisa64:
11744       val = E_MIPS_ARCH_64;
11745       break;
11746
11747     case bfd_mach_mipsisa32r2:
11748     case bfd_mach_mipsisa32r3:
11749     case bfd_mach_mipsisa32r5:
11750       val = E_MIPS_ARCH_32R2;
11751       break;
11752
11753     case bfd_mach_mipsisa64r2:
11754     case bfd_mach_mipsisa64r3:
11755     case bfd_mach_mipsisa64r5:
11756       val = E_MIPS_ARCH_64R2;
11757       break;
11758     }
11759   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
11760   elf_elfheader (abfd)->e_flags |= val;
11761
11762 }
11763
11764
11765 /* The final processing done just before writing out a MIPS ELF object
11766    file.  This gets the MIPS architecture right based on the machine
11767    number.  This is used by both the 32-bit and the 64-bit ABI.  */
11768
11769 void
11770 _bfd_mips_elf_final_write_processing (bfd *abfd,
11771                                       bfd_boolean linker ATTRIBUTE_UNUSED)
11772 {
11773   unsigned int i;
11774   Elf_Internal_Shdr **hdrpp;
11775   const char *name;
11776   asection *sec;
11777
11778   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
11779      is nonzero.  This is for compatibility with old objects, which used
11780      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
11781   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
11782     mips_set_isa_flags (abfd);
11783
11784   /* Set the sh_info field for .gptab sections and other appropriate
11785      info for each special section.  */
11786   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
11787        i < elf_numsections (abfd);
11788        i++, hdrpp++)
11789     {
11790       switch ((*hdrpp)->sh_type)
11791         {
11792         case SHT_MIPS_MSYM:
11793         case SHT_MIPS_LIBLIST:
11794           sec = bfd_get_section_by_name (abfd, ".dynstr");
11795           if (sec != NULL)
11796             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11797           break;
11798
11799         case SHT_MIPS_GPTAB:
11800           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11801           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11802           BFD_ASSERT (name != NULL
11803                       && CONST_STRNEQ (name, ".gptab."));
11804           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
11805           BFD_ASSERT (sec != NULL);
11806           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11807           break;
11808
11809         case SHT_MIPS_CONTENT:
11810           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11811           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11812           BFD_ASSERT (name != NULL
11813                       && CONST_STRNEQ (name, ".MIPS.content"));
11814           sec = bfd_get_section_by_name (abfd,
11815                                          name + sizeof ".MIPS.content" - 1);
11816           BFD_ASSERT (sec != NULL);
11817           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11818           break;
11819
11820         case SHT_MIPS_SYMBOL_LIB:
11821           sec = bfd_get_section_by_name (abfd, ".dynsym");
11822           if (sec != NULL)
11823             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11824           sec = bfd_get_section_by_name (abfd, ".liblist");
11825           if (sec != NULL)
11826             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11827           break;
11828
11829         case SHT_MIPS_EVENTS:
11830           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11831           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11832           BFD_ASSERT (name != NULL);
11833           if (CONST_STRNEQ (name, ".MIPS.events"))
11834             sec = bfd_get_section_by_name (abfd,
11835                                            name + sizeof ".MIPS.events" - 1);
11836           else
11837             {
11838               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
11839               sec = bfd_get_section_by_name (abfd,
11840                                              (name
11841                                               + sizeof ".MIPS.post_rel" - 1));
11842             }
11843           BFD_ASSERT (sec != NULL);
11844           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11845           break;
11846
11847         }
11848     }
11849 }
11850 \f
11851 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
11852    segments.  */
11853
11854 int
11855 _bfd_mips_elf_additional_program_headers (bfd *abfd,
11856                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
11857 {
11858   asection *s;
11859   int ret = 0;
11860
11861   /* See if we need a PT_MIPS_REGINFO segment.  */
11862   s = bfd_get_section_by_name (abfd, ".reginfo");
11863   if (s && (s->flags & SEC_LOAD))
11864     ++ret;
11865
11866   /* See if we need a PT_MIPS_ABIFLAGS segment.  */
11867   if (bfd_get_section_by_name (abfd, ".MIPS.abiflags"))
11868     ++ret;
11869
11870   /* See if we need a PT_MIPS_OPTIONS segment.  */
11871   if (IRIX_COMPAT (abfd) == ict_irix6
11872       && bfd_get_section_by_name (abfd,
11873                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
11874     ++ret;
11875
11876   /* See if we need a PT_MIPS_RTPROC segment.  */
11877   if (IRIX_COMPAT (abfd) == ict_irix5
11878       && bfd_get_section_by_name (abfd, ".dynamic")
11879       && bfd_get_section_by_name (abfd, ".mdebug"))
11880     ++ret;
11881
11882   /* Allocate a PT_NULL header in dynamic objects.  See
11883      _bfd_mips_elf_modify_segment_map for details.  */
11884   if (!SGI_COMPAT (abfd)
11885       && bfd_get_section_by_name (abfd, ".dynamic"))
11886     ++ret;
11887
11888   return ret;
11889 }
11890
11891 /* Modify the segment map for an IRIX5 executable.  */
11892
11893 bfd_boolean
11894 _bfd_mips_elf_modify_segment_map (bfd *abfd,
11895                                   struct bfd_link_info *info)
11896 {
11897   asection *s;
11898   struct elf_segment_map *m, **pm;
11899   bfd_size_type amt;
11900
11901   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
11902      segment.  */
11903   s = bfd_get_section_by_name (abfd, ".reginfo");
11904   if (s != NULL && (s->flags & SEC_LOAD) != 0)
11905     {
11906       for (m = elf_seg_map (abfd); m != NULL; m = m->next)
11907         if (m->p_type == PT_MIPS_REGINFO)
11908           break;
11909       if (m == NULL)
11910         {
11911           amt = sizeof *m;
11912           m = bfd_zalloc (abfd, amt);
11913           if (m == NULL)
11914             return FALSE;
11915
11916           m->p_type = PT_MIPS_REGINFO;
11917           m->count = 1;
11918           m->sections[0] = s;
11919
11920           /* We want to put it after the PHDR and INTERP segments.  */
11921           pm = &elf_seg_map (abfd);
11922           while (*pm != NULL
11923                  && ((*pm)->p_type == PT_PHDR
11924                      || (*pm)->p_type == PT_INTERP))
11925             pm = &(*pm)->next;
11926
11927           m->next = *pm;
11928           *pm = m;
11929         }
11930     }
11931
11932   /* If there is a .MIPS.abiflags section, we need a PT_MIPS_ABIFLAGS
11933      segment.  */
11934   s = bfd_get_section_by_name (abfd, ".MIPS.abiflags");
11935   if (s != NULL && (s->flags & SEC_LOAD) != 0)
11936     {
11937       for (m = elf_seg_map (abfd); m != NULL; m = m->next)
11938         if (m->p_type == PT_MIPS_ABIFLAGS)
11939           break;
11940       if (m == NULL)
11941         {
11942           amt = sizeof *m;
11943           m = bfd_zalloc (abfd, amt);
11944           if (m == NULL)
11945             return FALSE;
11946
11947           m->p_type = PT_MIPS_ABIFLAGS;
11948           m->count = 1;
11949           m->sections[0] = s;
11950
11951           /* We want to put it after the PHDR and INTERP segments.  */
11952           pm = &elf_seg_map (abfd);
11953           while (*pm != NULL
11954                  && ((*pm)->p_type == PT_PHDR
11955                      || (*pm)->p_type == PT_INTERP))
11956             pm = &(*pm)->next;
11957
11958           m->next = *pm;
11959           *pm = m;
11960         }
11961     }
11962
11963   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
11964      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
11965      PT_MIPS_OPTIONS segment immediately following the program header
11966      table.  */
11967   if (NEWABI_P (abfd)
11968       /* On non-IRIX6 new abi, we'll have already created a segment
11969          for this section, so don't create another.  I'm not sure this
11970          is not also the case for IRIX 6, but I can't test it right
11971          now.  */
11972       && IRIX_COMPAT (abfd) == ict_irix6)
11973     {
11974       for (s = abfd->sections; s; s = s->next)
11975         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
11976           break;
11977
11978       if (s)
11979         {
11980           struct elf_segment_map *options_segment;
11981
11982           pm = &elf_seg_map (abfd);
11983           while (*pm != NULL
11984                  && ((*pm)->p_type == PT_PHDR
11985                      || (*pm)->p_type == PT_INTERP))
11986             pm = &(*pm)->next;
11987
11988           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
11989             {
11990               amt = sizeof (struct elf_segment_map);
11991               options_segment = bfd_zalloc (abfd, amt);
11992               options_segment->next = *pm;
11993               options_segment->p_type = PT_MIPS_OPTIONS;
11994               options_segment->p_flags = PF_R;
11995               options_segment->p_flags_valid = TRUE;
11996               options_segment->count = 1;
11997               options_segment->sections[0] = s;
11998               *pm = options_segment;
11999             }
12000         }
12001     }
12002   else
12003     {
12004       if (IRIX_COMPAT (abfd) == ict_irix5)
12005         {
12006           /* If there are .dynamic and .mdebug sections, we make a room
12007              for the RTPROC header.  FIXME: Rewrite without section names.  */
12008           if (bfd_get_section_by_name (abfd, ".interp") == NULL
12009               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
12010               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
12011             {
12012               for (m = elf_seg_map (abfd); m != NULL; m = m->next)
12013                 if (m->p_type == PT_MIPS_RTPROC)
12014                   break;
12015               if (m == NULL)
12016                 {
12017                   amt = sizeof *m;
12018                   m = bfd_zalloc (abfd, amt);
12019                   if (m == NULL)
12020                     return FALSE;
12021
12022                   m->p_type = PT_MIPS_RTPROC;
12023
12024                   s = bfd_get_section_by_name (abfd, ".rtproc");
12025                   if (s == NULL)
12026                     {
12027                       m->count = 0;
12028                       m->p_flags = 0;
12029                       m->p_flags_valid = 1;
12030                     }
12031                   else
12032                     {
12033                       m->count = 1;
12034                       m->sections[0] = s;
12035                     }
12036
12037                   /* We want to put it after the DYNAMIC segment.  */
12038                   pm = &elf_seg_map (abfd);
12039                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
12040                     pm = &(*pm)->next;
12041                   if (*pm != NULL)
12042                     pm = &(*pm)->next;
12043
12044                   m->next = *pm;
12045                   *pm = m;
12046                 }
12047             }
12048         }
12049       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
12050          .dynstr, .dynsym, and .hash sections, and everything in
12051          between.  */
12052       for (pm = &elf_seg_map (abfd); *pm != NULL;
12053            pm = &(*pm)->next)
12054         if ((*pm)->p_type == PT_DYNAMIC)
12055           break;
12056       m = *pm;
12057       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
12058          glibc's dynamic linker has traditionally derived the number of
12059          tags from the p_filesz field, and sometimes allocates stack
12060          arrays of that size.  An overly-big PT_DYNAMIC segment can
12061          be actively harmful in such cases.  Making PT_DYNAMIC contain
12062          other sections can also make life hard for the prelinker,
12063          which might move one of the other sections to a different
12064          PT_LOAD segment.  */
12065       if (SGI_COMPAT (abfd)
12066           && m != NULL
12067           && m->count == 1
12068           && strcmp (m->sections[0]->name, ".dynamic") == 0)
12069         {
12070           static const char *sec_names[] =
12071           {
12072             ".dynamic", ".dynstr", ".dynsym", ".hash"
12073           };
12074           bfd_vma low, high;
12075           unsigned int i, c;
12076           struct elf_segment_map *n;
12077
12078           low = ~(bfd_vma) 0;
12079           high = 0;
12080           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
12081             {
12082               s = bfd_get_section_by_name (abfd, sec_names[i]);
12083               if (s != NULL && (s->flags & SEC_LOAD) != 0)
12084                 {
12085                   bfd_size_type sz;
12086
12087                   if (low > s->vma)
12088                     low = s->vma;
12089                   sz = s->size;
12090                   if (high < s->vma + sz)
12091                     high = s->vma + sz;
12092                 }
12093             }
12094
12095           c = 0;
12096           for (s = abfd->sections; s != NULL; s = s->next)
12097             if ((s->flags & SEC_LOAD) != 0
12098                 && s->vma >= low
12099                 && s->vma + s->size <= high)
12100               ++c;
12101
12102           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
12103           n = bfd_zalloc (abfd, amt);
12104           if (n == NULL)
12105             return FALSE;
12106           *n = *m;
12107           n->count = c;
12108
12109           i = 0;
12110           for (s = abfd->sections; s != NULL; s = s->next)
12111             {
12112               if ((s->flags & SEC_LOAD) != 0
12113                   && s->vma >= low
12114                   && s->vma + s->size <= high)
12115                 {
12116                   n->sections[i] = s;
12117                   ++i;
12118                 }
12119             }
12120
12121           *pm = n;
12122         }
12123     }
12124
12125   /* Allocate a spare program header in dynamic objects so that tools
12126      like the prelinker can add an extra PT_LOAD entry.
12127
12128      If the prelinker needs to make room for a new PT_LOAD entry, its
12129      standard procedure is to move the first (read-only) sections into
12130      the new (writable) segment.  However, the MIPS ABI requires
12131      .dynamic to be in a read-only segment, and the section will often
12132      start within sizeof (ElfNN_Phdr) bytes of the last program header.
12133
12134      Although the prelinker could in principle move .dynamic to a
12135      writable segment, it seems better to allocate a spare program
12136      header instead, and avoid the need to move any sections.
12137      There is a long tradition of allocating spare dynamic tags,
12138      so allocating a spare program header seems like a natural
12139      extension.
12140
12141      If INFO is NULL, we may be copying an already prelinked binary
12142      with objcopy or strip, so do not add this header.  */
12143   if (info != NULL
12144       && !SGI_COMPAT (abfd)
12145       && bfd_get_section_by_name (abfd, ".dynamic"))
12146     {
12147       for (pm = &elf_seg_map (abfd); *pm != NULL; pm = &(*pm)->next)
12148         if ((*pm)->p_type == PT_NULL)
12149           break;
12150       if (*pm == NULL)
12151         {
12152           m = bfd_zalloc (abfd, sizeof (*m));
12153           if (m == NULL)
12154             return FALSE;
12155
12156           m->p_type = PT_NULL;
12157           *pm = m;
12158         }
12159     }
12160
12161   return TRUE;
12162 }
12163 \f
12164 /* Return the section that should be marked against GC for a given
12165    relocation.  */
12166
12167 asection *
12168 _bfd_mips_elf_gc_mark_hook (asection *sec,
12169                             struct bfd_link_info *info,
12170                             Elf_Internal_Rela *rel,
12171                             struct elf_link_hash_entry *h,
12172                             Elf_Internal_Sym *sym)
12173 {
12174   /* ??? Do mips16 stub sections need to be handled special?  */
12175
12176   if (h != NULL)
12177     switch (ELF_R_TYPE (sec->owner, rel->r_info))
12178       {
12179       case R_MIPS_GNU_VTINHERIT:
12180       case R_MIPS_GNU_VTENTRY:
12181         return NULL;
12182       }
12183
12184   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
12185 }
12186
12187 /* Update the got entry reference counts for the section being removed.  */
12188
12189 bfd_boolean
12190 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
12191                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
12192                              asection *sec ATTRIBUTE_UNUSED,
12193                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
12194 {
12195 #if 0
12196   Elf_Internal_Shdr *symtab_hdr;
12197   struct elf_link_hash_entry **sym_hashes;
12198   bfd_signed_vma *local_got_refcounts;
12199   const Elf_Internal_Rela *rel, *relend;
12200   unsigned long r_symndx;
12201   struct elf_link_hash_entry *h;
12202
12203   if (info->relocatable)
12204     return TRUE;
12205
12206   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12207   sym_hashes = elf_sym_hashes (abfd);
12208   local_got_refcounts = elf_local_got_refcounts (abfd);
12209
12210   relend = relocs + sec->reloc_count;
12211   for (rel = relocs; rel < relend; rel++)
12212     switch (ELF_R_TYPE (abfd, rel->r_info))
12213       {
12214       case R_MIPS16_GOT16:
12215       case R_MIPS16_CALL16:
12216       case R_MIPS_GOT16:
12217       case R_MIPS_CALL16:
12218       case R_MIPS_CALL_HI16:
12219       case R_MIPS_CALL_LO16:
12220       case R_MIPS_GOT_HI16:
12221       case R_MIPS_GOT_LO16:
12222       case R_MIPS_GOT_DISP:
12223       case R_MIPS_GOT_PAGE:
12224       case R_MIPS_GOT_OFST:
12225       case R_MICROMIPS_GOT16:
12226       case R_MICROMIPS_CALL16:
12227       case R_MICROMIPS_CALL_HI16:
12228       case R_MICROMIPS_CALL_LO16:
12229       case R_MICROMIPS_GOT_HI16:
12230       case R_MICROMIPS_GOT_LO16:
12231       case R_MICROMIPS_GOT_DISP:
12232       case R_MICROMIPS_GOT_PAGE:
12233       case R_MICROMIPS_GOT_OFST:
12234         /* ??? It would seem that the existing MIPS code does no sort
12235            of reference counting or whatnot on its GOT and PLT entries,
12236            so it is not possible to garbage collect them at this time.  */
12237         break;
12238
12239       default:
12240         break;
12241       }
12242 #endif
12243
12244   return TRUE;
12245 }
12246
12247 /* Prevent .MIPS.abiflags from being discarded with --gc-sections.  */
12248
12249 bfd_boolean
12250 _bfd_mips_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12251                                       elf_gc_mark_hook_fn gc_mark_hook)
12252 {
12253   bfd *sub;
12254
12255   _bfd_elf_gc_mark_extra_sections (info, gc_mark_hook);
12256
12257   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12258     {
12259       asection *o;
12260
12261       if (! is_mips_elf (sub))
12262         continue;
12263
12264       for (o = sub->sections; o != NULL; o = o->next)
12265         if (!o->gc_mark
12266             && MIPS_ELF_ABIFLAGS_SECTION_NAME_P
12267                  (bfd_get_section_name (sub, o)))
12268           {
12269             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
12270               return FALSE;
12271           }
12272     }
12273
12274   return TRUE;
12275 }
12276 \f
12277 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
12278    hiding the old indirect symbol.  Process additional relocation
12279    information.  Also called for weakdefs, in which case we just let
12280    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
12281
12282 void
12283 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
12284                                     struct elf_link_hash_entry *dir,
12285                                     struct elf_link_hash_entry *ind)
12286 {
12287   struct mips_elf_link_hash_entry *dirmips, *indmips;
12288
12289   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
12290
12291   dirmips = (struct mips_elf_link_hash_entry *) dir;
12292   indmips = (struct mips_elf_link_hash_entry *) ind;
12293   /* Any absolute non-dynamic relocations against an indirect or weak
12294      definition will be against the target symbol.  */
12295   if (indmips->has_static_relocs)
12296     dirmips->has_static_relocs = TRUE;
12297
12298   if (ind->root.type != bfd_link_hash_indirect)
12299     return;
12300
12301   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
12302   if (indmips->readonly_reloc)
12303     dirmips->readonly_reloc = TRUE;
12304   if (indmips->no_fn_stub)
12305     dirmips->no_fn_stub = TRUE;
12306   if (indmips->fn_stub)
12307     {
12308       dirmips->fn_stub = indmips->fn_stub;
12309       indmips->fn_stub = NULL;
12310     }
12311   if (indmips->need_fn_stub)
12312     {
12313       dirmips->need_fn_stub = TRUE;
12314       indmips->need_fn_stub = FALSE;
12315     }
12316   if (indmips->call_stub)
12317     {
12318       dirmips->call_stub = indmips->call_stub;
12319       indmips->call_stub = NULL;
12320     }
12321   if (indmips->call_fp_stub)
12322     {
12323       dirmips->call_fp_stub = indmips->call_fp_stub;
12324       indmips->call_fp_stub = NULL;
12325     }
12326   if (indmips->global_got_area < dirmips->global_got_area)
12327     dirmips->global_got_area = indmips->global_got_area;
12328   if (indmips->global_got_area < GGA_NONE)
12329     indmips->global_got_area = GGA_NONE;
12330   if (indmips->has_nonpic_branches)
12331     dirmips->has_nonpic_branches = TRUE;
12332 }
12333 \f
12334 #define PDR_SIZE 32
12335
12336 bfd_boolean
12337 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
12338                             struct bfd_link_info *info)
12339 {
12340   asection *o;
12341   bfd_boolean ret = FALSE;
12342   unsigned char *tdata;
12343   size_t i, skip;
12344
12345   o = bfd_get_section_by_name (abfd, ".pdr");
12346   if (! o)
12347     return FALSE;
12348   if (o->size == 0)
12349     return FALSE;
12350   if (o->size % PDR_SIZE != 0)
12351     return FALSE;
12352   if (o->output_section != NULL
12353       && bfd_is_abs_section (o->output_section))
12354     return FALSE;
12355
12356   tdata = bfd_zmalloc (o->size / PDR_SIZE);
12357   if (! tdata)
12358     return FALSE;
12359
12360   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
12361                                             info->keep_memory);
12362   if (!cookie->rels)
12363     {
12364       free (tdata);
12365       return FALSE;
12366     }
12367
12368   cookie->rel = cookie->rels;
12369   cookie->relend = cookie->rels + o->reloc_count;
12370
12371   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
12372     {
12373       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
12374         {
12375           tdata[i] = 1;
12376           skip ++;
12377         }
12378     }
12379
12380   if (skip != 0)
12381     {
12382       mips_elf_section_data (o)->u.tdata = tdata;
12383       if (o->rawsize == 0)
12384         o->rawsize = o->size;
12385       o->size -= skip * PDR_SIZE;
12386       ret = TRUE;
12387     }
12388   else
12389     free (tdata);
12390
12391   if (! info->keep_memory)
12392     free (cookie->rels);
12393
12394   return ret;
12395 }
12396
12397 bfd_boolean
12398 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
12399 {
12400   if (strcmp (sec->name, ".pdr") == 0)
12401     return TRUE;
12402   return FALSE;
12403 }
12404
12405 bfd_boolean
12406 _bfd_mips_elf_write_section (bfd *output_bfd,
12407                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
12408                              asection *sec, bfd_byte *contents)
12409 {
12410   bfd_byte *to, *from, *end;
12411   int i;
12412
12413   if (strcmp (sec->name, ".pdr") != 0)
12414     return FALSE;
12415
12416   if (mips_elf_section_data (sec)->u.tdata == NULL)
12417     return FALSE;
12418
12419   to = contents;
12420   end = contents + sec->size;
12421   for (from = contents, i = 0;
12422        from < end;
12423        from += PDR_SIZE, i++)
12424     {
12425       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
12426         continue;
12427       if (to != from)
12428         memcpy (to, from, PDR_SIZE);
12429       to += PDR_SIZE;
12430     }
12431   bfd_set_section_contents (output_bfd, sec->output_section, contents,
12432                             sec->output_offset, sec->size);
12433   return TRUE;
12434 }
12435 \f
12436 /* microMIPS code retains local labels for linker relaxation.  Omit them
12437    from output by default for clarity.  */
12438
12439 bfd_boolean
12440 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
12441 {
12442   return _bfd_elf_is_local_label_name (abfd, sym->name);
12443 }
12444
12445 /* MIPS ELF uses a special find_nearest_line routine in order the
12446    handle the ECOFF debugging information.  */
12447
12448 struct mips_elf_find_line
12449 {
12450   struct ecoff_debug_info d;
12451   struct ecoff_find_line i;
12452 };
12453
12454 bfd_boolean
12455 _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section,
12456                                  asymbol **symbols, bfd_vma offset,
12457                                  const char **filename_ptr,
12458                                  const char **functionname_ptr,
12459                                  unsigned int *line_ptr)
12460 {
12461   asection *msec;
12462
12463   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
12464                                      filename_ptr, functionname_ptr,
12465                                      line_ptr))
12466     return TRUE;
12467
12468   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
12469                                      section, symbols, offset,
12470                                      filename_ptr, functionname_ptr,
12471                                      line_ptr, NULL, ABI_64_P (abfd) ? 8 : 0,
12472                                      &elf_tdata (abfd)->dwarf2_find_line_info))
12473     return TRUE;
12474
12475   msec = bfd_get_section_by_name (abfd, ".mdebug");
12476   if (msec != NULL)
12477     {
12478       flagword origflags;
12479       struct mips_elf_find_line *fi;
12480       const struct ecoff_debug_swap * const swap =
12481         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
12482
12483       /* If we are called during a link, mips_elf_final_link may have
12484          cleared the SEC_HAS_CONTENTS field.  We force it back on here
12485          if appropriate (which it normally will be).  */
12486       origflags = msec->flags;
12487       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
12488         msec->flags |= SEC_HAS_CONTENTS;
12489
12490       fi = mips_elf_tdata (abfd)->find_line_info;
12491       if (fi == NULL)
12492         {
12493           bfd_size_type external_fdr_size;
12494           char *fraw_src;
12495           char *fraw_end;
12496           struct fdr *fdr_ptr;
12497           bfd_size_type amt = sizeof (struct mips_elf_find_line);
12498
12499           fi = bfd_zalloc (abfd, amt);
12500           if (fi == NULL)
12501             {
12502               msec->flags = origflags;
12503               return FALSE;
12504             }
12505
12506           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
12507             {
12508               msec->flags = origflags;
12509               return FALSE;
12510             }
12511
12512           /* Swap in the FDR information.  */
12513           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
12514           fi->d.fdr = bfd_alloc (abfd, amt);
12515           if (fi->d.fdr == NULL)
12516             {
12517               msec->flags = origflags;
12518               return FALSE;
12519             }
12520           external_fdr_size = swap->external_fdr_size;
12521           fdr_ptr = fi->d.fdr;
12522           fraw_src = (char *) fi->d.external_fdr;
12523           fraw_end = (fraw_src
12524                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
12525           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
12526             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
12527
12528           mips_elf_tdata (abfd)->find_line_info = fi;
12529
12530           /* Note that we don't bother to ever free this information.
12531              find_nearest_line is either called all the time, as in
12532              objdump -l, so the information should be saved, or it is
12533              rarely called, as in ld error messages, so the memory
12534              wasted is unimportant.  Still, it would probably be a
12535              good idea for free_cached_info to throw it away.  */
12536         }
12537
12538       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
12539                                   &fi->i, filename_ptr, functionname_ptr,
12540                                   line_ptr))
12541         {
12542           msec->flags = origflags;
12543           return TRUE;
12544         }
12545
12546       msec->flags = origflags;
12547     }
12548
12549   /* Fall back on the generic ELF find_nearest_line routine.  */
12550
12551   return _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
12552                                      filename_ptr, functionname_ptr,
12553                                      line_ptr);
12554 }
12555
12556 bfd_boolean
12557 _bfd_mips_elf_find_inliner_info (bfd *abfd,
12558                                  const char **filename_ptr,
12559                                  const char **functionname_ptr,
12560                                  unsigned int *line_ptr)
12561 {
12562   bfd_boolean found;
12563   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
12564                                          functionname_ptr, line_ptr,
12565                                          & elf_tdata (abfd)->dwarf2_find_line_info);
12566   return found;
12567 }
12568
12569 \f
12570 /* When are writing out the .options or .MIPS.options section,
12571    remember the bytes we are writing out, so that we can install the
12572    GP value in the section_processing routine.  */
12573
12574 bfd_boolean
12575 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
12576                                     const void *location,
12577                                     file_ptr offset, bfd_size_type count)
12578 {
12579   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
12580     {
12581       bfd_byte *c;
12582
12583       if (elf_section_data (section) == NULL)
12584         {
12585           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
12586           section->used_by_bfd = bfd_zalloc (abfd, amt);
12587           if (elf_section_data (section) == NULL)
12588             return FALSE;
12589         }
12590       c = mips_elf_section_data (section)->u.tdata;
12591       if (c == NULL)
12592         {
12593           c = bfd_zalloc (abfd, section->size);
12594           if (c == NULL)
12595             return FALSE;
12596           mips_elf_section_data (section)->u.tdata = c;
12597         }
12598
12599       memcpy (c + offset, location, count);
12600     }
12601
12602   return _bfd_elf_set_section_contents (abfd, section, location, offset,
12603                                         count);
12604 }
12605
12606 /* This is almost identical to bfd_generic_get_... except that some
12607    MIPS relocations need to be handled specially.  Sigh.  */
12608
12609 bfd_byte *
12610 _bfd_elf_mips_get_relocated_section_contents
12611   (bfd *abfd,
12612    struct bfd_link_info *link_info,
12613    struct bfd_link_order *link_order,
12614    bfd_byte *data,
12615    bfd_boolean relocatable,
12616    asymbol **symbols)
12617 {
12618   /* Get enough memory to hold the stuff */
12619   bfd *input_bfd = link_order->u.indirect.section->owner;
12620   asection *input_section = link_order->u.indirect.section;
12621   bfd_size_type sz;
12622
12623   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
12624   arelent **reloc_vector = NULL;
12625   long reloc_count;
12626
12627   if (reloc_size < 0)
12628     goto error_return;
12629
12630   reloc_vector = bfd_malloc (reloc_size);
12631   if (reloc_vector == NULL && reloc_size != 0)
12632     goto error_return;
12633
12634   /* read in the section */
12635   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
12636   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
12637     goto error_return;
12638
12639   reloc_count = bfd_canonicalize_reloc (input_bfd,
12640                                         input_section,
12641                                         reloc_vector,
12642                                         symbols);
12643   if (reloc_count < 0)
12644     goto error_return;
12645
12646   if (reloc_count > 0)
12647     {
12648       arelent **parent;
12649       /* for mips */
12650       int gp_found;
12651       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
12652
12653       {
12654         struct bfd_hash_entry *h;
12655         struct bfd_link_hash_entry *lh;
12656         /* Skip all this stuff if we aren't mixing formats.  */
12657         if (abfd && input_bfd
12658             && abfd->xvec == input_bfd->xvec)
12659           lh = 0;
12660         else
12661           {
12662             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
12663             lh = (struct bfd_link_hash_entry *) h;
12664           }
12665       lookup:
12666         if (lh)
12667           {
12668             switch (lh->type)
12669               {
12670               case bfd_link_hash_undefined:
12671               case bfd_link_hash_undefweak:
12672               case bfd_link_hash_common:
12673                 gp_found = 0;
12674                 break;
12675               case bfd_link_hash_defined:
12676               case bfd_link_hash_defweak:
12677                 gp_found = 1;
12678                 gp = lh->u.def.value;
12679                 break;
12680               case bfd_link_hash_indirect:
12681               case bfd_link_hash_warning:
12682                 lh = lh->u.i.link;
12683                 /* @@FIXME  ignoring warning for now */
12684                 goto lookup;
12685               case bfd_link_hash_new:
12686               default:
12687                 abort ();
12688               }
12689           }
12690         else
12691           gp_found = 0;
12692       }
12693       /* end mips */
12694       for (parent = reloc_vector; *parent != NULL; parent++)
12695         {
12696           char *error_message = NULL;
12697           bfd_reloc_status_type r;
12698
12699           /* Specific to MIPS: Deal with relocation types that require
12700              knowing the gp of the output bfd.  */
12701           asymbol *sym = *(*parent)->sym_ptr_ptr;
12702
12703           /* If we've managed to find the gp and have a special
12704              function for the relocation then go ahead, else default
12705              to the generic handling.  */
12706           if (gp_found
12707               && (*parent)->howto->special_function
12708               == _bfd_mips_elf32_gprel16_reloc)
12709             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
12710                                                input_section, relocatable,
12711                                                data, gp);
12712           else
12713             r = bfd_perform_relocation (input_bfd, *parent, data,
12714                                         input_section,
12715                                         relocatable ? abfd : NULL,
12716                                         &error_message);
12717
12718           if (relocatable)
12719             {
12720               asection *os = input_section->output_section;
12721
12722               /* A partial link, so keep the relocs */
12723               os->orelocation[os->reloc_count] = *parent;
12724               os->reloc_count++;
12725             }
12726
12727           if (r != bfd_reloc_ok)
12728             {
12729               switch (r)
12730                 {
12731                 case bfd_reloc_undefined:
12732                   if (!((*link_info->callbacks->undefined_symbol)
12733                         (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
12734                          input_bfd, input_section, (*parent)->address, TRUE)))
12735                     goto error_return;
12736                   break;
12737                 case bfd_reloc_dangerous:
12738                   BFD_ASSERT (error_message != NULL);
12739                   if (!((*link_info->callbacks->reloc_dangerous)
12740                         (link_info, error_message, input_bfd, input_section,
12741                          (*parent)->address)))
12742                     goto error_return;
12743                   break;
12744                 case bfd_reloc_overflow:
12745                   if (!((*link_info->callbacks->reloc_overflow)
12746                         (link_info, NULL,
12747                          bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
12748                          (*parent)->howto->name, (*parent)->addend,
12749                          input_bfd, input_section, (*parent)->address)))
12750                     goto error_return;
12751                   break;
12752                 case bfd_reloc_outofrange:
12753                 default:
12754                   abort ();
12755                   break;
12756                 }
12757
12758             }
12759         }
12760     }
12761   if (reloc_vector != NULL)
12762     free (reloc_vector);
12763   return data;
12764
12765 error_return:
12766   if (reloc_vector != NULL)
12767     free (reloc_vector);
12768   return NULL;
12769 }
12770 \f
12771 static bfd_boolean
12772 mips_elf_relax_delete_bytes (bfd *abfd,
12773                              asection *sec, bfd_vma addr, int count)
12774 {
12775   Elf_Internal_Shdr *symtab_hdr;
12776   unsigned int sec_shndx;
12777   bfd_byte *contents;
12778   Elf_Internal_Rela *irel, *irelend;
12779   Elf_Internal_Sym *isym;
12780   Elf_Internal_Sym *isymend;
12781   struct elf_link_hash_entry **sym_hashes;
12782   struct elf_link_hash_entry **end_hashes;
12783   struct elf_link_hash_entry **start_hashes;
12784   unsigned int symcount;
12785
12786   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
12787   contents = elf_section_data (sec)->this_hdr.contents;
12788
12789   irel = elf_section_data (sec)->relocs;
12790   irelend = irel + sec->reloc_count;
12791
12792   /* Actually delete the bytes.  */
12793   memmove (contents + addr, contents + addr + count,
12794            (size_t) (sec->size - addr - count));
12795   sec->size -= count;
12796
12797   /* Adjust all the relocs.  */
12798   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
12799     {
12800       /* Get the new reloc address.  */
12801       if (irel->r_offset > addr)
12802         irel->r_offset -= count;
12803     }
12804
12805   BFD_ASSERT (addr % 2 == 0);
12806   BFD_ASSERT (count % 2 == 0);
12807
12808   /* Adjust the local symbols defined in this section.  */
12809   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12810   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
12811   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
12812     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
12813       isym->st_value -= count;
12814
12815   /* Now adjust the global symbols defined in this section.  */
12816   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
12817               - symtab_hdr->sh_info);
12818   sym_hashes = start_hashes = elf_sym_hashes (abfd);
12819   end_hashes = sym_hashes + symcount;
12820
12821   for (; sym_hashes < end_hashes; sym_hashes++)
12822     {
12823       struct elf_link_hash_entry *sym_hash = *sym_hashes;
12824
12825       if ((sym_hash->root.type == bfd_link_hash_defined
12826            || sym_hash->root.type == bfd_link_hash_defweak)
12827           && sym_hash->root.u.def.section == sec)
12828         {
12829           bfd_vma value = sym_hash->root.u.def.value;
12830
12831           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
12832             value &= MINUS_TWO;
12833           if (value > addr)
12834             sym_hash->root.u.def.value -= count;
12835         }
12836     }
12837
12838   return TRUE;
12839 }
12840
12841
12842 /* Opcodes needed for microMIPS relaxation as found in
12843    opcodes/micromips-opc.c.  */
12844
12845 struct opcode_descriptor {
12846   unsigned long match;
12847   unsigned long mask;
12848 };
12849
12850 /* The $ra register aka $31.  */
12851
12852 #define RA 31
12853
12854 /* 32-bit instruction format register fields.  */
12855
12856 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
12857 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
12858
12859 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
12860
12861 #define OP16_VALID_REG(r) \
12862   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
12863
12864
12865 /* 32-bit and 16-bit branches.  */
12866
12867 static const struct opcode_descriptor b_insns_32[] = {
12868   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
12869   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
12870   { 0, 0 }  /* End marker for find_match().  */
12871 };
12872
12873 static const struct opcode_descriptor bc_insn_32 =
12874   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
12875
12876 static const struct opcode_descriptor bz_insn_32 =
12877   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
12878
12879 static const struct opcode_descriptor bzal_insn_32 =
12880   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
12881
12882 static const struct opcode_descriptor beq_insn_32 =
12883   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
12884
12885 static const struct opcode_descriptor b_insn_16 =
12886   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
12887
12888 static const struct opcode_descriptor bz_insn_16 =
12889   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
12890
12891
12892 /* 32-bit and 16-bit branch EQ and NE zero.  */
12893
12894 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
12895    eq and second the ne.  This convention is used when replacing a
12896    32-bit BEQ/BNE with the 16-bit version.  */
12897
12898 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
12899
12900 static const struct opcode_descriptor bz_rs_insns_32[] = {
12901   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
12902   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
12903   { 0, 0 }  /* End marker for find_match().  */
12904 };
12905
12906 static const struct opcode_descriptor bz_rt_insns_32[] = {
12907   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
12908   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
12909   { 0, 0 }  /* End marker for find_match().  */
12910 };
12911
12912 static const struct opcode_descriptor bzc_insns_32[] = {
12913   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
12914   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
12915   { 0, 0 }  /* End marker for find_match().  */
12916 };
12917
12918 static const struct opcode_descriptor bz_insns_16[] = {
12919   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
12920   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
12921   { 0, 0 }  /* End marker for find_match().  */
12922 };
12923
12924 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
12925
12926 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0x17) + 2)
12927 #define BZ16_REG_FIELD(r) \
12928   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 7)
12929
12930
12931 /* 32-bit instructions with a delay slot.  */
12932
12933 static const struct opcode_descriptor jal_insn_32_bd16 =
12934   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
12935
12936 static const struct opcode_descriptor jal_insn_32_bd32 =
12937   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
12938
12939 static const struct opcode_descriptor jal_x_insn_32_bd32 =
12940   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
12941
12942 static const struct opcode_descriptor j_insn_32 =
12943   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
12944
12945 static const struct opcode_descriptor jalr_insn_32 =
12946   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
12947
12948 /* This table can be compacted, because no opcode replacement is made.  */
12949
12950 static const struct opcode_descriptor ds_insns_32_bd16[] = {
12951   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
12952
12953   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
12954   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
12955
12956   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
12957   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
12958   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
12959   { 0, 0 }  /* End marker for find_match().  */
12960 };
12961
12962 /* This table can be compacted, because no opcode replacement is made.  */
12963
12964 static const struct opcode_descriptor ds_insns_32_bd32[] = {
12965   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
12966
12967   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
12968   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
12969   { 0, 0 }  /* End marker for find_match().  */
12970 };
12971
12972
12973 /* 16-bit instructions with a delay slot.  */
12974
12975 static const struct opcode_descriptor jalr_insn_16_bd16 =
12976   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
12977
12978 static const struct opcode_descriptor jalr_insn_16_bd32 =
12979   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
12980
12981 static const struct opcode_descriptor jr_insn_16 =
12982   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
12983
12984 #define JR16_REG(opcode) ((opcode) & 0x1f)
12985
12986 /* This table can be compacted, because no opcode replacement is made.  */
12987
12988 static const struct opcode_descriptor ds_insns_16_bd16[] = {
12989   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
12990
12991   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
12992   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
12993   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
12994   { 0, 0 }  /* End marker for find_match().  */
12995 };
12996
12997
12998 /* LUI instruction.  */
12999
13000 static const struct opcode_descriptor lui_insn =
13001  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
13002
13003
13004 /* ADDIU instruction.  */
13005
13006 static const struct opcode_descriptor addiu_insn =
13007   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
13008
13009 static const struct opcode_descriptor addiupc_insn =
13010   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
13011
13012 #define ADDIUPC_REG_FIELD(r) \
13013   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
13014
13015
13016 /* Relaxable instructions in a JAL delay slot: MOVE.  */
13017
13018 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
13019    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
13020 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
13021 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
13022
13023 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
13024 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
13025
13026 static const struct opcode_descriptor move_insns_32[] = {
13027   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
13028   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
13029   { 0, 0 }  /* End marker for find_match().  */
13030 };
13031
13032 static const struct opcode_descriptor move_insn_16 =
13033   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
13034
13035
13036 /* NOP instructions.  */
13037
13038 static const struct opcode_descriptor nop_insn_32 =
13039   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
13040
13041 static const struct opcode_descriptor nop_insn_16 =
13042   { /* "nop",   "",             */ 0x0c00,     0xffff };
13043
13044
13045 /* Instruction match support.  */
13046
13047 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
13048
13049 static int
13050 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
13051 {
13052   unsigned long indx;
13053
13054   for (indx = 0; insn[indx].mask != 0; indx++)
13055     if (MATCH (opcode, insn[indx]))
13056       return indx;
13057
13058   return -1;
13059 }
13060
13061
13062 /* Branch and delay slot decoding support.  */
13063
13064 /* If PTR points to what *might* be a 16-bit branch or jump, then
13065    return the minimum length of its delay slot, otherwise return 0.
13066    Non-zero results are not definitive as we might be checking against
13067    the second half of another instruction.  */
13068
13069 static int
13070 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
13071 {
13072   unsigned long opcode;
13073   int bdsize;
13074
13075   opcode = bfd_get_16 (abfd, ptr);
13076   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
13077     /* 16-bit branch/jump with a 32-bit delay slot.  */
13078     bdsize = 4;
13079   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
13080            || find_match (opcode, ds_insns_16_bd16) >= 0)
13081     /* 16-bit branch/jump with a 16-bit delay slot.  */
13082     bdsize = 2;
13083   else
13084     /* No delay slot.  */
13085     bdsize = 0;
13086
13087   return bdsize;
13088 }
13089
13090 /* If PTR points to what *might* be a 32-bit branch or jump, then
13091    return the minimum length of its delay slot, otherwise return 0.
13092    Non-zero results are not definitive as we might be checking against
13093    the second half of another instruction.  */
13094
13095 static int
13096 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
13097 {
13098   unsigned long opcode;
13099   int bdsize;
13100
13101   opcode = bfd_get_micromips_32 (abfd, ptr);
13102   if (find_match (opcode, ds_insns_32_bd32) >= 0)
13103     /* 32-bit branch/jump with a 32-bit delay slot.  */
13104     bdsize = 4;
13105   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
13106     /* 32-bit branch/jump with a 16-bit delay slot.  */
13107     bdsize = 2;
13108   else
13109     /* No delay slot.  */
13110     bdsize = 0;
13111
13112   return bdsize;
13113 }
13114
13115 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
13116    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
13117
13118 static bfd_boolean
13119 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
13120 {
13121   unsigned long opcode;
13122
13123   opcode = bfd_get_16 (abfd, ptr);
13124   if (MATCH (opcode, b_insn_16)
13125                                                 /* B16  */
13126       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
13127                                                 /* JR16  */
13128       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
13129                                                 /* BEQZ16, BNEZ16  */
13130       || (MATCH (opcode, jalr_insn_16_bd32)
13131                                                 /* JALR16  */
13132           && reg != JR16_REG (opcode) && reg != RA))
13133     return TRUE;
13134
13135   return FALSE;
13136 }
13137
13138 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
13139    then return TRUE, otherwise FALSE.  */
13140
13141 static bfd_boolean
13142 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
13143 {
13144   unsigned long opcode;
13145
13146   opcode = bfd_get_micromips_32 (abfd, ptr);
13147   if (MATCH (opcode, j_insn_32)
13148                                                 /* J  */
13149       || MATCH (opcode, bc_insn_32)
13150                                                 /* BC1F, BC1T, BC2F, BC2T  */
13151       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
13152                                                 /* JAL, JALX  */
13153       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
13154                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
13155       || (MATCH (opcode, bzal_insn_32)
13156                                                 /* BGEZAL, BLTZAL  */
13157           && reg != OP32_SREG (opcode) && reg != RA)
13158       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
13159                                                 /* JALR, JALR.HB, BEQ, BNE  */
13160           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
13161     return TRUE;
13162
13163   return FALSE;
13164 }
13165
13166 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
13167    IRELEND) at OFFSET indicate that there must be a compact branch there,
13168    then return TRUE, otherwise FALSE.  */
13169
13170 static bfd_boolean
13171 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
13172                      const Elf_Internal_Rela *internal_relocs,
13173                      const Elf_Internal_Rela *irelend)
13174 {
13175   const Elf_Internal_Rela *irel;
13176   unsigned long opcode;
13177
13178   opcode = bfd_get_micromips_32 (abfd, ptr);
13179   if (find_match (opcode, bzc_insns_32) < 0)
13180     return FALSE;
13181
13182   for (irel = internal_relocs; irel < irelend; irel++)
13183     if (irel->r_offset == offset
13184         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
13185       return TRUE;
13186
13187   return FALSE;
13188 }
13189
13190 /* Bitsize checking.  */
13191 #define IS_BITSIZE(val, N)                                              \
13192   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
13193     - (1ULL << ((N) - 1))) == (val))
13194
13195 \f
13196 bfd_boolean
13197 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
13198                              struct bfd_link_info *link_info,
13199                              bfd_boolean *again)
13200 {
13201   bfd_boolean insn32 = mips_elf_hash_table (link_info)->insn32;
13202   Elf_Internal_Shdr *symtab_hdr;
13203   Elf_Internal_Rela *internal_relocs;
13204   Elf_Internal_Rela *irel, *irelend;
13205   bfd_byte *contents = NULL;
13206   Elf_Internal_Sym *isymbuf = NULL;
13207
13208   /* Assume nothing changes.  */
13209   *again = FALSE;
13210
13211   /* We don't have to do anything for a relocatable link, if
13212      this section does not have relocs, or if this is not a
13213      code section.  */
13214
13215   if (link_info->relocatable
13216       || (sec->flags & SEC_RELOC) == 0
13217       || sec->reloc_count == 0
13218       || (sec->flags & SEC_CODE) == 0)
13219     return TRUE;
13220
13221   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
13222
13223   /* Get a copy of the native relocations.  */
13224   internal_relocs = (_bfd_elf_link_read_relocs
13225                      (abfd, sec, NULL, (Elf_Internal_Rela *) NULL,
13226                       link_info->keep_memory));
13227   if (internal_relocs == NULL)
13228     goto error_return;
13229
13230   /* Walk through them looking for relaxing opportunities.  */
13231   irelend = internal_relocs + sec->reloc_count;
13232   for (irel = internal_relocs; irel < irelend; irel++)
13233     {
13234       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
13235       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
13236       bfd_boolean target_is_micromips_code_p;
13237       unsigned long opcode;
13238       bfd_vma symval;
13239       bfd_vma pcrval;
13240       bfd_byte *ptr;
13241       int fndopc;
13242
13243       /* The number of bytes to delete for relaxation and from where
13244          to delete these bytes starting at irel->r_offset.  */
13245       int delcnt = 0;
13246       int deloff = 0;
13247
13248       /* If this isn't something that can be relaxed, then ignore
13249          this reloc.  */
13250       if (r_type != R_MICROMIPS_HI16
13251           && r_type != R_MICROMIPS_PC16_S1
13252           && r_type != R_MICROMIPS_26_S1)
13253         continue;
13254
13255       /* Get the section contents if we haven't done so already.  */
13256       if (contents == NULL)
13257         {
13258           /* Get cached copy if it exists.  */
13259           if (elf_section_data (sec)->this_hdr.contents != NULL)
13260             contents = elf_section_data (sec)->this_hdr.contents;
13261           /* Go get them off disk.  */
13262           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
13263             goto error_return;
13264         }
13265       ptr = contents + irel->r_offset;
13266
13267       /* Read this BFD's local symbols if we haven't done so already.  */
13268       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
13269         {
13270           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
13271           if (isymbuf == NULL)
13272             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
13273                                             symtab_hdr->sh_info, 0,
13274                                             NULL, NULL, NULL);
13275           if (isymbuf == NULL)
13276             goto error_return;
13277         }
13278
13279       /* Get the value of the symbol referred to by the reloc.  */
13280       if (r_symndx < symtab_hdr->sh_info)
13281         {
13282           /* A local symbol.  */
13283           Elf_Internal_Sym *isym;
13284           asection *sym_sec;
13285
13286           isym = isymbuf + r_symndx;
13287           if (isym->st_shndx == SHN_UNDEF)
13288             sym_sec = bfd_und_section_ptr;
13289           else if (isym->st_shndx == SHN_ABS)
13290             sym_sec = bfd_abs_section_ptr;
13291           else if (isym->st_shndx == SHN_COMMON)
13292             sym_sec = bfd_com_section_ptr;
13293           else
13294             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
13295           symval = (isym->st_value
13296                     + sym_sec->output_section->vma
13297                     + sym_sec->output_offset);
13298           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
13299         }
13300       else
13301         {
13302           unsigned long indx;
13303           struct elf_link_hash_entry *h;
13304
13305           /* An external symbol.  */
13306           indx = r_symndx - symtab_hdr->sh_info;
13307           h = elf_sym_hashes (abfd)[indx];
13308           BFD_ASSERT (h != NULL);
13309
13310           if (h->root.type != bfd_link_hash_defined
13311               && h->root.type != bfd_link_hash_defweak)
13312             /* This appears to be a reference to an undefined
13313                symbol.  Just ignore it -- it will be caught by the
13314                regular reloc processing.  */
13315             continue;
13316
13317           symval = (h->root.u.def.value
13318                     + h->root.u.def.section->output_section->vma
13319                     + h->root.u.def.section->output_offset);
13320           target_is_micromips_code_p = (!h->needs_plt
13321                                         && ELF_ST_IS_MICROMIPS (h->other));
13322         }
13323
13324
13325       /* For simplicity of coding, we are going to modify the
13326          section contents, the section relocs, and the BFD symbol
13327          table.  We must tell the rest of the code not to free up this
13328          information.  It would be possible to instead create a table
13329          of changes which have to be made, as is done in coff-mips.c;
13330          that would be more work, but would require less memory when
13331          the linker is run.  */
13332
13333       /* Only 32-bit instructions relaxed.  */
13334       if (irel->r_offset + 4 > sec->size)
13335         continue;
13336
13337       opcode = bfd_get_micromips_32 (abfd, ptr);
13338
13339       /* This is the pc-relative distance from the instruction the
13340          relocation is applied to, to the symbol referred.  */
13341       pcrval = (symval
13342                 - (sec->output_section->vma + sec->output_offset)
13343                 - irel->r_offset);
13344
13345       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
13346          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
13347          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
13348
13349            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
13350
13351          where pcrval has first to be adjusted to apply against the LO16
13352          location (we make the adjustment later on, when we have figured
13353          out the offset).  */
13354       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
13355         {
13356           bfd_boolean bzc = FALSE;
13357           unsigned long nextopc;
13358           unsigned long reg;
13359           bfd_vma offset;
13360
13361           /* Give up if the previous reloc was a HI16 against this symbol
13362              too.  */
13363           if (irel > internal_relocs
13364               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
13365               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
13366             continue;
13367
13368           /* Or if the next reloc is not a LO16 against this symbol.  */
13369           if (irel + 1 >= irelend
13370               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
13371               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
13372             continue;
13373
13374           /* Or if the second next reloc is a LO16 against this symbol too.  */
13375           if (irel + 2 >= irelend
13376               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
13377               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
13378             continue;
13379
13380           /* See if the LUI instruction *might* be in a branch delay slot.
13381              We check whether what looks like a 16-bit branch or jump is
13382              actually an immediate argument to a compact branch, and let
13383              it through if so.  */
13384           if (irel->r_offset >= 2
13385               && check_br16_dslot (abfd, ptr - 2)
13386               && !(irel->r_offset >= 4
13387                    && (bzc = check_relocated_bzc (abfd,
13388                                                   ptr - 4, irel->r_offset - 4,
13389                                                   internal_relocs, irelend))))
13390             continue;
13391           if (irel->r_offset >= 4
13392               && !bzc
13393               && check_br32_dslot (abfd, ptr - 4))
13394             continue;
13395
13396           reg = OP32_SREG (opcode);
13397
13398           /* We only relax adjacent instructions or ones separated with
13399              a branch or jump that has a delay slot.  The branch or jump
13400              must not fiddle with the register used to hold the address.
13401              Subtract 4 for the LUI itself.  */
13402           offset = irel[1].r_offset - irel[0].r_offset;
13403           switch (offset - 4)
13404             {
13405             case 0:
13406               break;
13407             case 2:
13408               if (check_br16 (abfd, ptr + 4, reg))
13409                 break;
13410               continue;
13411             case 4:
13412               if (check_br32 (abfd, ptr + 4, reg))
13413                 break;
13414               continue;
13415             default:
13416               continue;
13417             }
13418
13419           nextopc = bfd_get_micromips_32 (abfd, contents + irel[1].r_offset);
13420
13421           /* Give up unless the same register is used with both
13422              relocations.  */
13423           if (OP32_SREG (nextopc) != reg)
13424             continue;
13425
13426           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
13427              and rounding up to take masking of the two LSBs into account.  */
13428           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
13429
13430           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
13431           if (IS_BITSIZE (symval, 16))
13432             {
13433               /* Fix the relocation's type.  */
13434               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
13435
13436               /* Instructions using R_MICROMIPS_LO16 have the base or
13437                  source register in bits 20:16.  This register becomes $0
13438                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
13439               nextopc &= ~0x001f0000;
13440               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
13441                           contents + irel[1].r_offset);
13442             }
13443
13444           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
13445              We add 4 to take LUI deletion into account while checking
13446              the PC-relative distance.  */
13447           else if (symval % 4 == 0
13448                    && IS_BITSIZE (pcrval + 4, 25)
13449                    && MATCH (nextopc, addiu_insn)
13450                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
13451                    && OP16_VALID_REG (OP32_TREG (nextopc)))
13452             {
13453               /* Fix the relocation's type.  */
13454               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
13455
13456               /* Replace ADDIU with the ADDIUPC version.  */
13457               nextopc = (addiupc_insn.match
13458                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
13459
13460               bfd_put_micromips_32 (abfd, nextopc,
13461                                     contents + irel[1].r_offset);
13462             }
13463
13464           /* Can't do anything, give up, sigh...  */
13465           else
13466             continue;
13467
13468           /* Fix the relocation's type.  */
13469           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
13470
13471           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
13472           delcnt = 4;
13473           deloff = 0;
13474         }
13475
13476       /* Compact branch relaxation -- due to the multitude of macros
13477          employed by the compiler/assembler, compact branches are not
13478          always generated.  Obviously, this can/will be fixed elsewhere,
13479          but there is no drawback in double checking it here.  */
13480       else if (r_type == R_MICROMIPS_PC16_S1
13481                && irel->r_offset + 5 < sec->size
13482                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
13483                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
13484                && ((!insn32
13485                     && (delcnt = MATCH (bfd_get_16 (abfd, ptr + 4),
13486                                         nop_insn_16) ? 2 : 0))
13487                    || (irel->r_offset + 7 < sec->size
13488                        && (delcnt = MATCH (bfd_get_micromips_32 (abfd,
13489                                                                  ptr + 4),
13490                                            nop_insn_32) ? 4 : 0))))
13491         {
13492           unsigned long reg;
13493
13494           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
13495
13496           /* Replace BEQZ/BNEZ with the compact version.  */
13497           opcode = (bzc_insns_32[fndopc].match
13498                     | BZC32_REG_FIELD (reg)
13499                     | (opcode & 0xffff));               /* Addend value.  */
13500
13501           bfd_put_micromips_32 (abfd, opcode, ptr);
13502
13503           /* Delete the delay slot NOP: two or four bytes from
13504              irel->offset + 4; delcnt has already been set above.  */
13505           deloff = 4;
13506         }
13507
13508       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
13509          to check the distance from the next instruction, so subtract 2.  */
13510       else if (!insn32
13511                && r_type == R_MICROMIPS_PC16_S1
13512                && IS_BITSIZE (pcrval - 2, 11)
13513                && find_match (opcode, b_insns_32) >= 0)
13514         {
13515           /* Fix the relocation's type.  */
13516           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
13517
13518           /* Replace the 32-bit opcode with a 16-bit opcode.  */
13519           bfd_put_16 (abfd,
13520                       (b_insn_16.match
13521                        | (opcode & 0x3ff)),             /* Addend value.  */
13522                       ptr);
13523
13524           /* Delete 2 bytes from irel->r_offset + 2.  */
13525           delcnt = 2;
13526           deloff = 2;
13527         }
13528
13529       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
13530          to check the distance from the next instruction, so subtract 2.  */
13531       else if (!insn32
13532                && r_type == R_MICROMIPS_PC16_S1
13533                && IS_BITSIZE (pcrval - 2, 8)
13534                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
13535                     && OP16_VALID_REG (OP32_SREG (opcode)))
13536                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
13537                        && OP16_VALID_REG (OP32_TREG (opcode)))))
13538         {
13539           unsigned long reg;
13540
13541           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
13542
13543           /* Fix the relocation's type.  */
13544           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
13545
13546           /* Replace the 32-bit opcode with a 16-bit opcode.  */
13547           bfd_put_16 (abfd,
13548                       (bz_insns_16[fndopc].match
13549                        | BZ16_REG_FIELD (reg)
13550                        | (opcode & 0x7f)),              /* Addend value.  */
13551                       ptr);
13552
13553           /* Delete 2 bytes from irel->r_offset + 2.  */
13554           delcnt = 2;
13555           deloff = 2;
13556         }
13557
13558       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
13559       else if (!insn32
13560                && r_type == R_MICROMIPS_26_S1
13561                && target_is_micromips_code_p
13562                && irel->r_offset + 7 < sec->size
13563                && MATCH (opcode, jal_insn_32_bd32))
13564         {
13565           unsigned long n32opc;
13566           bfd_boolean relaxed = FALSE;
13567
13568           n32opc = bfd_get_micromips_32 (abfd, ptr + 4);
13569
13570           if (MATCH (n32opc, nop_insn_32))
13571             {
13572               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
13573               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
13574
13575               relaxed = TRUE;
13576             }
13577           else if (find_match (n32opc, move_insns_32) >= 0)
13578             {
13579               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
13580               bfd_put_16 (abfd,
13581                           (move_insn_16.match
13582                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
13583                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
13584                           ptr + 4);
13585
13586               relaxed = TRUE;
13587             }
13588           /* Other 32-bit instructions relaxable to 16-bit
13589              instructions will be handled here later.  */
13590
13591           if (relaxed)
13592             {
13593               /* JAL with 32-bit delay slot that is changed to a JALS
13594                  with 16-bit delay slot.  */
13595               bfd_put_micromips_32 (abfd, jal_insn_32_bd16.match, ptr);
13596
13597               /* Delete 2 bytes from irel->r_offset + 6.  */
13598               delcnt = 2;
13599               deloff = 6;
13600             }
13601         }
13602
13603       if (delcnt != 0)
13604         {
13605           /* Note that we've changed the relocs, section contents, etc.  */
13606           elf_section_data (sec)->relocs = internal_relocs;
13607           elf_section_data (sec)->this_hdr.contents = contents;
13608           symtab_hdr->contents = (unsigned char *) isymbuf;
13609
13610           /* Delete bytes depending on the delcnt and deloff.  */
13611           if (!mips_elf_relax_delete_bytes (abfd, sec,
13612                                             irel->r_offset + deloff, delcnt))
13613             goto error_return;
13614
13615           /* That will change things, so we should relax again.
13616              Note that this is not required, and it may be slow.  */
13617           *again = TRUE;
13618         }
13619     }
13620
13621   if (isymbuf != NULL
13622       && symtab_hdr->contents != (unsigned char *) isymbuf)
13623     {
13624       if (! link_info->keep_memory)
13625         free (isymbuf);
13626       else
13627         {
13628           /* Cache the symbols for elf_link_input_bfd.  */
13629           symtab_hdr->contents = (unsigned char *) isymbuf;
13630         }
13631     }
13632
13633   if (contents != NULL
13634       && elf_section_data (sec)->this_hdr.contents != contents)
13635     {
13636       if (! link_info->keep_memory)
13637         free (contents);
13638       else
13639         {
13640           /* Cache the section contents for elf_link_input_bfd.  */
13641           elf_section_data (sec)->this_hdr.contents = contents;
13642         }
13643     }
13644
13645   if (internal_relocs != NULL
13646       && elf_section_data (sec)->relocs != internal_relocs)
13647     free (internal_relocs);
13648
13649   return TRUE;
13650
13651  error_return:
13652   if (isymbuf != NULL
13653       && symtab_hdr->contents != (unsigned char *) isymbuf)
13654     free (isymbuf);
13655   if (contents != NULL
13656       && elf_section_data (sec)->this_hdr.contents != contents)
13657     free (contents);
13658   if (internal_relocs != NULL
13659       && elf_section_data (sec)->relocs != internal_relocs)
13660     free (internal_relocs);
13661
13662   return FALSE;
13663 }
13664 \f
13665 /* Create a MIPS ELF linker hash table.  */
13666
13667 struct bfd_link_hash_table *
13668 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
13669 {
13670   struct mips_elf_link_hash_table *ret;
13671   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
13672
13673   ret = bfd_zmalloc (amt);
13674   if (ret == NULL)
13675     return NULL;
13676
13677   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
13678                                       mips_elf_link_hash_newfunc,
13679                                       sizeof (struct mips_elf_link_hash_entry),
13680                                       MIPS_ELF_DATA))
13681     {
13682       free (ret);
13683       return NULL;
13684     }
13685   ret->root.init_plt_refcount.plist = NULL;
13686   ret->root.init_plt_offset.plist = NULL;
13687
13688   return &ret->root.root;
13689 }
13690
13691 /* Likewise, but indicate that the target is VxWorks.  */
13692
13693 struct bfd_link_hash_table *
13694 _bfd_mips_vxworks_link_hash_table_create (bfd *abfd)
13695 {
13696   struct bfd_link_hash_table *ret;
13697
13698   ret = _bfd_mips_elf_link_hash_table_create (abfd);
13699   if (ret)
13700     {
13701       struct mips_elf_link_hash_table *htab;
13702
13703       htab = (struct mips_elf_link_hash_table *) ret;
13704       htab->use_plts_and_copy_relocs = TRUE;
13705       htab->is_vxworks = TRUE;
13706     }
13707   return ret;
13708 }
13709
13710 /* A function that the linker calls if we are allowed to use PLTs
13711    and copy relocs.  */
13712
13713 void
13714 _bfd_mips_elf_use_plts_and_copy_relocs (struct bfd_link_info *info)
13715 {
13716   mips_elf_hash_table (info)->use_plts_and_copy_relocs = TRUE;
13717 }
13718
13719 /* A function that the linker calls to select between all or only
13720    32-bit microMIPS instructions.  */
13721
13722 void
13723 _bfd_mips_elf_insn32 (struct bfd_link_info *info, bfd_boolean on)
13724 {
13725   mips_elf_hash_table (info)->insn32 = on;
13726 }
13727 \f
13728 /* Return the .MIPS.abiflags value representing each ISA Extension.  */
13729
13730 unsigned int
13731 bfd_mips_isa_ext (bfd *abfd)
13732 {
13733   switch (bfd_get_mach (abfd))
13734     {
13735     case bfd_mach_mips3900:
13736       return AFL_EXT_3900;
13737     case bfd_mach_mips4010:
13738       return AFL_EXT_4010;
13739     case bfd_mach_mips4100:
13740       return AFL_EXT_4100;
13741     case bfd_mach_mips4111:
13742       return AFL_EXT_4111;
13743     case bfd_mach_mips4120:
13744       return AFL_EXT_4120;
13745     case bfd_mach_mips4650:
13746       return AFL_EXT_4650;
13747     case bfd_mach_mips5400:
13748       return AFL_EXT_5400;
13749     case bfd_mach_mips5500:
13750       return AFL_EXT_5500;
13751     case bfd_mach_mips5900:
13752       return AFL_EXT_5900;
13753     case bfd_mach_mips10000:
13754       return AFL_EXT_10000;
13755     case bfd_mach_mips_loongson_2e:
13756       return AFL_EXT_LOONGSON_2E;
13757     case bfd_mach_mips_loongson_2f:
13758       return AFL_EXT_LOONGSON_2F;
13759     case bfd_mach_mips_loongson_3a:
13760       return AFL_EXT_LOONGSON_3A;
13761     case bfd_mach_mips_sb1:
13762       return AFL_EXT_SB1;
13763     case bfd_mach_mips_octeon:
13764       return AFL_EXT_OCTEON;
13765     case bfd_mach_mips_octeonp:
13766       return AFL_EXT_OCTEONP;
13767     case bfd_mach_mips_octeon2:
13768       return AFL_EXT_OCTEON2;
13769     case bfd_mach_mips_xlr:
13770       return AFL_EXT_XLR;
13771     }
13772   return 0;
13773 }
13774
13775 /* Update the isa_level, isa_rev, isa_ext fields of abiflags.  */
13776
13777 static void
13778 update_mips_abiflags_isa (bfd *abfd, Elf_Internal_ABIFlags_v0 *abiflags)
13779 {
13780   switch (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH)
13781     {
13782     case E_MIPS_ARCH_1:
13783       abiflags->isa_level = 1;
13784       abiflags->isa_rev = 0;
13785       break;
13786     case E_MIPS_ARCH_2:
13787       abiflags->isa_level = 2;
13788       abiflags->isa_rev = 0;
13789       break;
13790     case E_MIPS_ARCH_3:
13791       abiflags->isa_level = 3;
13792       abiflags->isa_rev = 0;
13793       break;
13794     case E_MIPS_ARCH_4:
13795       abiflags->isa_level = 4;
13796       abiflags->isa_rev = 0;
13797       break;
13798     case E_MIPS_ARCH_5:
13799       abiflags->isa_level = 5;
13800       abiflags->isa_rev = 0;
13801       break;
13802     case E_MIPS_ARCH_32:
13803       abiflags->isa_level = 32;
13804       abiflags->isa_rev = 1;
13805       break;
13806     case E_MIPS_ARCH_32R2:
13807       abiflags->isa_level = 32;
13808       /* Handle MIPS32r3 and MIPS32r5 which do not have a header flag.  */
13809       if (abiflags->isa_rev < 2)
13810         abiflags->isa_rev = 2;
13811       break;
13812     case E_MIPS_ARCH_64:
13813       abiflags->isa_level = 64;
13814       abiflags->isa_rev = 1;
13815       break;
13816     case E_MIPS_ARCH_64R2:
13817       /* Handle MIPS64r3 and MIPS64r5 which do not have a header flag.  */
13818       abiflags->isa_level = 64;
13819       if (abiflags->isa_rev < 2)
13820         abiflags->isa_rev = 2;
13821       break;
13822     default:
13823       (*_bfd_error_handler)
13824         (_("%B: Unknown architecture %s"),
13825          abfd, bfd_printable_name (abfd));
13826     }
13827
13828   abiflags->isa_ext = bfd_mips_isa_ext (abfd);
13829 }
13830
13831 /* Return true if the given ELF header flags describe a 32-bit binary.  */
13832
13833 static bfd_boolean
13834 mips_32bit_flags_p (flagword flags)
13835 {
13836   return ((flags & EF_MIPS_32BITMODE) != 0
13837           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
13838           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
13839           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
13840           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
13841           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
13842           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2);
13843 }
13844
13845 /* Infer the content of the ABI flags based on the elf header.  */
13846
13847 static void
13848 infer_mips_abiflags (bfd *abfd, Elf_Internal_ABIFlags_v0* abiflags)
13849 {
13850   obj_attribute *in_attr;
13851
13852   memset (abiflags, 0, sizeof (Elf_Internal_ABIFlags_v0));
13853   update_mips_abiflags_isa (abfd, abiflags);
13854
13855   if (mips_32bit_flags_p (elf_elfheader (abfd)->e_flags))
13856     abiflags->gpr_size = AFL_REG_32;
13857   else
13858     abiflags->gpr_size = AFL_REG_64;
13859
13860   abiflags->cpr1_size = AFL_REG_NONE;
13861
13862   in_attr = elf_known_obj_attributes (abfd)[OBJ_ATTR_GNU];
13863   abiflags->fp_abi = in_attr[Tag_GNU_MIPS_ABI_FP].i;
13864
13865   if (abiflags->fp_abi == Val_GNU_MIPS_ABI_FP_SINGLE
13866       || abiflags->fp_abi == Val_GNU_MIPS_ABI_FP_XX
13867       || (abiflags->fp_abi == Val_GNU_MIPS_ABI_FP_DOUBLE
13868           && abiflags->gpr_size == AFL_REG_32))
13869     abiflags->cpr1_size = AFL_REG_32;
13870   else if (abiflags->fp_abi == Val_GNU_MIPS_ABI_FP_DOUBLE
13871            || abiflags->fp_abi == Val_GNU_MIPS_ABI_FP_64
13872            || abiflags->fp_abi == Val_GNU_MIPS_ABI_FP_64A)
13873     abiflags->cpr1_size = AFL_REG_64;
13874
13875   abiflags->cpr2_size = AFL_REG_NONE;
13876
13877   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
13878     abiflags->ases |= AFL_ASE_MDMX;
13879   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
13880     abiflags->ases |= AFL_ASE_MIPS16;
13881   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
13882     abiflags->ases |= AFL_ASE_MICROMIPS;
13883
13884   if (abiflags->fp_abi != Val_GNU_MIPS_ABI_FP_ANY
13885       && abiflags->fp_abi != Val_GNU_MIPS_ABI_FP_SOFT
13886       && abiflags->fp_abi != Val_GNU_MIPS_ABI_FP_64A
13887       && abiflags->isa_level >= 32
13888       && abiflags->isa_ext != AFL_EXT_LOONGSON_3A)
13889     abiflags->flags1 |= AFL_FLAGS1_ODDSPREG;
13890 }
13891
13892 /* We need to use a special link routine to handle the .reginfo and
13893    the .mdebug sections.  We need to merge all instances of these
13894    sections together, not write them all out sequentially.  */
13895
13896 bfd_boolean
13897 _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info)
13898 {
13899   asection *o;
13900   struct bfd_link_order *p;
13901   asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec;
13902   asection *rtproc_sec, *abiflags_sec;
13903   Elf32_RegInfo reginfo;
13904   struct ecoff_debug_info debug;
13905   struct mips_htab_traverse_info hti;
13906   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13907   const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap;
13908   HDRR *symhdr = &debug.symbolic_header;
13909   void *mdebug_handle = NULL;
13910   asection *s;
13911   EXTR esym;
13912   unsigned int i;
13913   bfd_size_type amt;
13914   struct mips_elf_link_hash_table *htab;
13915
13916   static const char * const secname[] =
13917   {
13918     ".text", ".init", ".fini", ".data",
13919     ".rodata", ".sdata", ".sbss", ".bss"
13920   };
13921   static const int sc[] =
13922   {
13923     scText, scInit, scFini, scData,
13924     scRData, scSData, scSBss, scBss
13925   };
13926
13927   /* Sort the dynamic symbols so that those with GOT entries come after
13928      those without.  */
13929   htab = mips_elf_hash_table (info);
13930   BFD_ASSERT (htab != NULL);
13931
13932   if (!mips_elf_sort_hash_table (abfd, info))
13933     return FALSE;
13934
13935   /* Create any scheduled LA25 stubs.  */
13936   hti.info = info;
13937   hti.output_bfd = abfd;
13938   hti.error = FALSE;
13939   htab_traverse (htab->la25_stubs, mips_elf_create_la25_stub, &hti);
13940   if (hti.error)
13941     return FALSE;
13942
13943   /* Get a value for the GP register.  */
13944   if (elf_gp (abfd) == 0)
13945     {
13946       struct bfd_link_hash_entry *h;
13947
13948       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
13949       if (h != NULL && h->type == bfd_link_hash_defined)
13950         elf_gp (abfd) = (h->u.def.value
13951                          + h->u.def.section->output_section->vma
13952                          + h->u.def.section->output_offset);
13953       else if (htab->is_vxworks
13954                && (h = bfd_link_hash_lookup (info->hash,
13955                                              "_GLOBAL_OFFSET_TABLE_",
13956                                              FALSE, FALSE, TRUE))
13957                && h->type == bfd_link_hash_defined)
13958         elf_gp (abfd) = (h->u.def.section->output_section->vma
13959                          + h->u.def.section->output_offset
13960                          + h->u.def.value);
13961       else if (info->relocatable)
13962         {
13963           bfd_vma lo = MINUS_ONE;
13964
13965           /* Find the GP-relative section with the lowest offset.  */
13966           for (o = abfd->sections; o != NULL; o = o->next)
13967             if (o->vma < lo
13968                 && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL))
13969               lo = o->vma;
13970
13971           /* And calculate GP relative to that.  */
13972           elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (info);
13973         }
13974       else
13975         {
13976           /* If the relocate_section function needs to do a reloc
13977              involving the GP value, it should make a reloc_dangerous
13978              callback to warn that GP is not defined.  */
13979         }
13980     }
13981
13982   /* Go through the sections and collect the .reginfo and .mdebug
13983      information.  */
13984   abiflags_sec = NULL;
13985   reginfo_sec = NULL;
13986   mdebug_sec = NULL;
13987   gptab_data_sec = NULL;
13988   gptab_bss_sec = NULL;
13989   for (o = abfd->sections; o != NULL; o = o->next)
13990     {
13991       if (strcmp (o->name, ".MIPS.abiflags") == 0)
13992         {
13993           /* We have found the .MIPS.abiflags section in the output file.
13994              Look through all the link_orders comprising it and remove them.
13995              The data is merged in _bfd_mips_elf_merge_private_bfd_data.  */
13996           for (p = o->map_head.link_order; p != NULL; p = p->next)
13997             {
13998               asection *input_section;
13999
14000               if (p->type != bfd_indirect_link_order)
14001                 {
14002                   if (p->type == bfd_data_link_order)
14003                     continue;
14004                   abort ();
14005                 }
14006
14007               input_section = p->u.indirect.section;
14008
14009               /* Hack: reset the SEC_HAS_CONTENTS flag so that
14010                  elf_link_input_bfd ignores this section.  */
14011               input_section->flags &= ~SEC_HAS_CONTENTS;
14012             }
14013
14014           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
14015           BFD_ASSERT(o->size == sizeof (Elf_External_ABIFlags_v0));
14016
14017           /* Skip this section later on (I don't think this currently
14018              matters, but someday it might).  */
14019           o->map_head.link_order = NULL;
14020
14021           abiflags_sec = o;
14022         }
14023
14024       if (strcmp (o->name, ".reginfo") == 0)
14025         {
14026           memset (&reginfo, 0, sizeof reginfo);
14027
14028           /* We have found the .reginfo section in the output file.
14029              Look through all the link_orders comprising it and merge
14030              the information together.  */
14031           for (p = o->map_head.link_order; p != NULL; p = p->next)
14032             {
14033               asection *input_section;
14034               bfd *input_bfd;
14035               Elf32_External_RegInfo ext;
14036               Elf32_RegInfo sub;
14037
14038               if (p->type != bfd_indirect_link_order)
14039                 {
14040                   if (p->type == bfd_data_link_order)
14041                     continue;
14042                   abort ();
14043                 }
14044
14045               input_section = p->u.indirect.section;
14046               input_bfd = input_section->owner;
14047
14048               if (! bfd_get_section_contents (input_bfd, input_section,
14049                                               &ext, 0, sizeof ext))
14050                 return FALSE;
14051
14052               bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub);
14053
14054               reginfo.ri_gprmask |= sub.ri_gprmask;
14055               reginfo.ri_cprmask[0] |= sub.ri_cprmask[0];
14056               reginfo.ri_cprmask[1] |= sub.ri_cprmask[1];
14057               reginfo.ri_cprmask[2] |= sub.ri_cprmask[2];
14058               reginfo.ri_cprmask[3] |= sub.ri_cprmask[3];
14059
14060               /* ri_gp_value is set by the function
14061                  mips_elf32_section_processing when the section is
14062                  finally written out.  */
14063
14064               /* Hack: reset the SEC_HAS_CONTENTS flag so that
14065                  elf_link_input_bfd ignores this section.  */
14066               input_section->flags &= ~SEC_HAS_CONTENTS;
14067             }
14068
14069           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
14070           BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo));
14071
14072           /* Skip this section later on (I don't think this currently
14073              matters, but someday it might).  */
14074           o->map_head.link_order = NULL;
14075
14076           reginfo_sec = o;
14077         }
14078
14079       if (strcmp (o->name, ".mdebug") == 0)
14080         {
14081           struct extsym_info einfo;
14082           bfd_vma last;
14083
14084           /* We have found the .mdebug section in the output file.
14085              Look through all the link_orders comprising it and merge
14086              the information together.  */
14087           symhdr->magic = swap->sym_magic;
14088           /* FIXME: What should the version stamp be?  */
14089           symhdr->vstamp = 0;
14090           symhdr->ilineMax = 0;
14091           symhdr->cbLine = 0;
14092           symhdr->idnMax = 0;
14093           symhdr->ipdMax = 0;
14094           symhdr->isymMax = 0;
14095           symhdr->ioptMax = 0;
14096           symhdr->iauxMax = 0;
14097           symhdr->issMax = 0;
14098           symhdr->issExtMax = 0;
14099           symhdr->ifdMax = 0;
14100           symhdr->crfd = 0;
14101           symhdr->iextMax = 0;
14102
14103           /* We accumulate the debugging information itself in the
14104              debug_info structure.  */
14105           debug.line = NULL;
14106           debug.external_dnr = NULL;
14107           debug.external_pdr = NULL;
14108           debug.external_sym = NULL;
14109           debug.external_opt = NULL;
14110           debug.external_aux = NULL;
14111           debug.ss = NULL;
14112           debug.ssext = debug.ssext_end = NULL;
14113           debug.external_fdr = NULL;
14114           debug.external_rfd = NULL;
14115           debug.external_ext = debug.external_ext_end = NULL;
14116
14117           mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info);
14118           if (mdebug_handle == NULL)
14119             return FALSE;
14120
14121           esym.jmptbl = 0;
14122           esym.cobol_main = 0;
14123           esym.weakext = 0;
14124           esym.reserved = 0;
14125           esym.ifd = ifdNil;
14126           esym.asym.iss = issNil;
14127           esym.asym.st = stLocal;
14128           esym.asym.reserved = 0;
14129           esym.asym.index = indexNil;
14130           last = 0;
14131           for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++)
14132             {
14133               esym.asym.sc = sc[i];
14134               s = bfd_get_section_by_name (abfd, secname[i]);
14135               if (s != NULL)
14136                 {
14137                   esym.asym.value = s->vma;
14138                   last = s->vma + s->size;
14139                 }
14140               else
14141                 esym.asym.value = last;
14142               if (!bfd_ecoff_debug_one_external (abfd, &debug, swap,
14143                                                  secname[i], &esym))
14144                 return FALSE;
14145             }
14146
14147           for (p = o->map_head.link_order; p != NULL; p = p->next)
14148             {
14149               asection *input_section;
14150               bfd *input_bfd;
14151               const struct ecoff_debug_swap *input_swap;
14152               struct ecoff_debug_info input_debug;
14153               char *eraw_src;
14154               char *eraw_end;
14155
14156               if (p->type != bfd_indirect_link_order)
14157                 {
14158                   if (p->type == bfd_data_link_order)
14159                     continue;
14160                   abort ();
14161                 }
14162
14163               input_section = p->u.indirect.section;
14164               input_bfd = input_section->owner;
14165
14166               if (!is_mips_elf (input_bfd))
14167                 {
14168                   /* I don't know what a non MIPS ELF bfd would be
14169                      doing with a .mdebug section, but I don't really
14170                      want to deal with it.  */
14171                   continue;
14172                 }
14173
14174               input_swap = (get_elf_backend_data (input_bfd)
14175                             ->elf_backend_ecoff_debug_swap);
14176
14177               BFD_ASSERT (p->size == input_section->size);
14178
14179               /* The ECOFF linking code expects that we have already
14180                  read in the debugging information and set up an
14181                  ecoff_debug_info structure, so we do that now.  */
14182               if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section,
14183                                                    &input_debug))
14184                 return FALSE;
14185
14186               if (! (bfd_ecoff_debug_accumulate
14187                      (mdebug_handle, abfd, &debug, swap, input_bfd,
14188                       &input_debug, input_swap, info)))
14189                 return FALSE;
14190
14191               /* Loop through the external symbols.  For each one with
14192                  interesting information, try to find the symbol in
14193                  the linker global hash table and save the information
14194                  for the output external symbols.  */
14195               eraw_src = input_debug.external_ext;
14196               eraw_end = (eraw_src
14197                           + (input_debug.symbolic_header.iextMax
14198                              * input_swap->external_ext_size));
14199               for (;
14200                    eraw_src < eraw_end;
14201                    eraw_src += input_swap->external_ext_size)
14202                 {
14203                   EXTR ext;
14204                   const char *name;
14205                   struct mips_elf_link_hash_entry *h;
14206
14207                   (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext);
14208                   if (ext.asym.sc == scNil
14209                       || ext.asym.sc == scUndefined
14210                       || ext.asym.sc == scSUndefined)
14211                     continue;
14212
14213                   name = input_debug.ssext + ext.asym.iss;
14214                   h = mips_elf_link_hash_lookup (mips_elf_hash_table (info),
14215                                                  name, FALSE, FALSE, TRUE);
14216                   if (h == NULL || h->esym.ifd != -2)
14217                     continue;
14218
14219                   if (ext.ifd != -1)
14220                     {
14221                       BFD_ASSERT (ext.ifd
14222                                   < input_debug.symbolic_header.ifdMax);
14223                       ext.ifd = input_debug.ifdmap[ext.ifd];
14224                     }
14225
14226                   h->esym = ext;
14227                 }
14228
14229               /* Free up the information we just read.  */
14230               free (input_debug.line);
14231               free (input_debug.external_dnr);
14232               free (input_debug.external_pdr);
14233               free (input_debug.external_sym);
14234               free (input_debug.external_opt);
14235               free (input_debug.external_aux);
14236               free (input_debug.ss);
14237               free (input_debug.ssext);
14238               free (input_debug.external_fdr);
14239               free (input_debug.external_rfd);
14240               free (input_debug.external_ext);
14241
14242               /* Hack: reset the SEC_HAS_CONTENTS flag so that
14243                  elf_link_input_bfd ignores this section.  */
14244               input_section->flags &= ~SEC_HAS_CONTENTS;
14245             }
14246
14247           if (SGI_COMPAT (abfd) && info->shared)
14248             {
14249               /* Create .rtproc section.  */
14250               rtproc_sec = bfd_get_linker_section (abfd, ".rtproc");
14251               if (rtproc_sec == NULL)
14252                 {
14253                   flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
14254                                     | SEC_LINKER_CREATED | SEC_READONLY);
14255
14256                   rtproc_sec = bfd_make_section_anyway_with_flags (abfd,
14257                                                                    ".rtproc",
14258                                                                    flags);
14259                   if (rtproc_sec == NULL
14260                       || ! bfd_set_section_alignment (abfd, rtproc_sec, 4))
14261                     return FALSE;
14262                 }
14263
14264               if (! mips_elf_create_procedure_table (mdebug_handle, abfd,
14265                                                      info, rtproc_sec,
14266                                                      &debug))
14267                 return FALSE;
14268             }
14269
14270           /* Build the external symbol information.  */
14271           einfo.abfd = abfd;
14272           einfo.info = info;
14273           einfo.debug = &debug;
14274           einfo.swap = swap;
14275           einfo.failed = FALSE;
14276           mips_elf_link_hash_traverse (mips_elf_hash_table (info),
14277                                        mips_elf_output_extsym, &einfo);
14278           if (einfo.failed)
14279             return FALSE;
14280
14281           /* Set the size of the .mdebug section.  */
14282           o->size = bfd_ecoff_debug_size (abfd, &debug, swap);
14283
14284           /* Skip this section later on (I don't think this currently
14285              matters, but someday it might).  */
14286           o->map_head.link_order = NULL;
14287
14288           mdebug_sec = o;
14289         }
14290
14291       if (CONST_STRNEQ (o->name, ".gptab."))
14292         {
14293           const char *subname;
14294           unsigned int c;
14295           Elf32_gptab *tab;
14296           Elf32_External_gptab *ext_tab;
14297           unsigned int j;
14298
14299           /* The .gptab.sdata and .gptab.sbss sections hold
14300              information describing how the small data area would
14301              change depending upon the -G switch.  These sections
14302              not used in executables files.  */
14303           if (! info->relocatable)
14304             {
14305               for (p = o->map_head.link_order; p != NULL; p = p->next)
14306                 {
14307                   asection *input_section;
14308
14309                   if (p->type != bfd_indirect_link_order)
14310                     {
14311                       if (p->type == bfd_data_link_order)
14312                         continue;
14313                       abort ();
14314                     }
14315
14316                   input_section = p->u.indirect.section;
14317
14318                   /* Hack: reset the SEC_HAS_CONTENTS flag so that
14319                      elf_link_input_bfd ignores this section.  */
14320                   input_section->flags &= ~SEC_HAS_CONTENTS;
14321                 }
14322
14323               /* Skip this section later on (I don't think this
14324                  currently matters, but someday it might).  */
14325               o->map_head.link_order = NULL;
14326
14327               /* Really remove the section.  */
14328               bfd_section_list_remove (abfd, o);
14329               --abfd->section_count;
14330
14331               continue;
14332             }
14333
14334           /* There is one gptab for initialized data, and one for
14335              uninitialized data.  */
14336           if (strcmp (o->name, ".gptab.sdata") == 0)
14337             gptab_data_sec = o;
14338           else if (strcmp (o->name, ".gptab.sbss") == 0)
14339             gptab_bss_sec = o;
14340           else
14341             {
14342               (*_bfd_error_handler)
14343                 (_("%s: illegal section name `%s'"),
14344                  bfd_get_filename (abfd), o->name);
14345               bfd_set_error (bfd_error_nonrepresentable_section);
14346               return FALSE;
14347             }
14348
14349           /* The linker script always combines .gptab.data and
14350              .gptab.sdata into .gptab.sdata, and likewise for
14351              .gptab.bss and .gptab.sbss.  It is possible that there is
14352              no .sdata or .sbss section in the output file, in which
14353              case we must change the name of the output section.  */
14354           subname = o->name + sizeof ".gptab" - 1;
14355           if (bfd_get_section_by_name (abfd, subname) == NULL)
14356             {
14357               if (o == gptab_data_sec)
14358                 o->name = ".gptab.data";
14359               else
14360                 o->name = ".gptab.bss";
14361               subname = o->name + sizeof ".gptab" - 1;
14362               BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL);
14363             }
14364
14365           /* Set up the first entry.  */
14366           c = 1;
14367           amt = c * sizeof (Elf32_gptab);
14368           tab = bfd_malloc (amt);
14369           if (tab == NULL)
14370             return FALSE;
14371           tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd);
14372           tab[0].gt_header.gt_unused = 0;
14373
14374           /* Combine the input sections.  */
14375           for (p = o->map_head.link_order; p != NULL; p = p->next)
14376             {
14377               asection *input_section;
14378               bfd *input_bfd;
14379               bfd_size_type size;
14380               unsigned long last;
14381               bfd_size_type gpentry;
14382
14383               if (p->type != bfd_indirect_link_order)
14384                 {
14385                   if (p->type == bfd_data_link_order)
14386                     continue;
14387                   abort ();
14388                 }
14389
14390               input_section = p->u.indirect.section;
14391               input_bfd = input_section->owner;
14392
14393               /* Combine the gptab entries for this input section one
14394                  by one.  We know that the input gptab entries are
14395                  sorted by ascending -G value.  */
14396               size = input_section->size;
14397               last = 0;
14398               for (gpentry = sizeof (Elf32_External_gptab);
14399                    gpentry < size;
14400                    gpentry += sizeof (Elf32_External_gptab))
14401                 {
14402                   Elf32_External_gptab ext_gptab;
14403                   Elf32_gptab int_gptab;
14404                   unsigned long val;
14405                   unsigned long add;
14406                   bfd_boolean exact;
14407                   unsigned int look;
14408
14409                   if (! (bfd_get_section_contents
14410                          (input_bfd, input_section, &ext_gptab, gpentry,
14411                           sizeof (Elf32_External_gptab))))
14412                     {
14413                       free (tab);
14414                       return FALSE;
14415                     }
14416
14417                   bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab,
14418                                                 &int_gptab);
14419                   val = int_gptab.gt_entry.gt_g_value;
14420                   add = int_gptab.gt_entry.gt_bytes - last;
14421
14422                   exact = FALSE;
14423                   for (look = 1; look < c; look++)
14424                     {
14425                       if (tab[look].gt_entry.gt_g_value >= val)
14426                         tab[look].gt_entry.gt_bytes += add;
14427
14428                       if (tab[look].gt_entry.gt_g_value == val)
14429                         exact = TRUE;
14430                     }
14431
14432                   if (! exact)
14433                     {
14434                       Elf32_gptab *new_tab;
14435                       unsigned int max;
14436
14437                       /* We need a new table entry.  */
14438                       amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab);
14439                       new_tab = bfd_realloc (tab, amt);
14440                       if (new_tab == NULL)
14441                         {
14442                           free (tab);
14443                           return FALSE;
14444                         }
14445                       tab = new_tab;
14446                       tab[c].gt_entry.gt_g_value = val;
14447                       tab[c].gt_entry.gt_bytes = add;
14448
14449                       /* Merge in the size for the next smallest -G
14450                          value, since that will be implied by this new
14451                          value.  */
14452                       max = 0;
14453                       for (look = 1; look < c; look++)
14454                         {
14455                           if (tab[look].gt_entry.gt_g_value < val
14456                               && (max == 0
14457                                   || (tab[look].gt_entry.gt_g_value
14458                                       > tab[max].gt_entry.gt_g_value)))
14459                             max = look;
14460                         }
14461                       if (max != 0)
14462                         tab[c].gt_entry.gt_bytes +=
14463                           tab[max].gt_entry.gt_bytes;
14464
14465                       ++c;
14466                     }
14467
14468                   last = int_gptab.gt_entry.gt_bytes;
14469                 }
14470
14471               /* Hack: reset the SEC_HAS_CONTENTS flag so that
14472                  elf_link_input_bfd ignores this section.  */
14473               input_section->flags &= ~SEC_HAS_CONTENTS;
14474             }
14475
14476           /* The table must be sorted by -G value.  */
14477           if (c > 2)
14478             qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare);
14479
14480           /* Swap out the table.  */
14481           amt = (bfd_size_type) c * sizeof (Elf32_External_gptab);
14482           ext_tab = bfd_alloc (abfd, amt);
14483           if (ext_tab == NULL)
14484             {
14485               free (tab);
14486               return FALSE;
14487             }
14488
14489           for (j = 0; j < c; j++)
14490             bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j);
14491           free (tab);
14492
14493           o->size = c * sizeof (Elf32_External_gptab);
14494           o->contents = (bfd_byte *) ext_tab;
14495
14496           /* Skip this section later on (I don't think this currently
14497              matters, but someday it might).  */
14498           o->map_head.link_order = NULL;
14499         }
14500     }
14501
14502   /* Invoke the regular ELF backend linker to do all the work.  */
14503   if (!bfd_elf_final_link (abfd, info))
14504     return FALSE;
14505
14506   /* Now write out the computed sections.  */
14507
14508   if (abiflags_sec != NULL)
14509     {
14510       Elf_External_ABIFlags_v0 ext;
14511       Elf_Internal_ABIFlags_v0 *abiflags;
14512
14513       abiflags = &mips_elf_tdata (abfd)->abiflags;
14514
14515       /* Set up the abiflags if no valid input sections were found.  */
14516       if (!mips_elf_tdata (abfd)->abiflags_valid)
14517         {
14518           infer_mips_abiflags (abfd, abiflags);
14519           mips_elf_tdata (abfd)->abiflags_valid = TRUE;
14520         }
14521       bfd_mips_elf_swap_abiflags_v0_out (abfd, abiflags, &ext);
14522       if (! bfd_set_section_contents (abfd, abiflags_sec, &ext, 0, sizeof ext))
14523         return FALSE;
14524     }
14525
14526   if (reginfo_sec != NULL)
14527     {
14528       Elf32_External_RegInfo ext;
14529
14530       bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext);
14531       if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext))
14532         return FALSE;
14533     }
14534
14535   if (mdebug_sec != NULL)
14536     {
14537       BFD_ASSERT (abfd->output_has_begun);
14538       if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug,
14539                                                swap, info,
14540                                                mdebug_sec->filepos))
14541         return FALSE;
14542
14543       bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info);
14544     }
14545
14546   if (gptab_data_sec != NULL)
14547     {
14548       if (! bfd_set_section_contents (abfd, gptab_data_sec,
14549                                       gptab_data_sec->contents,
14550                                       0, gptab_data_sec->size))
14551         return FALSE;
14552     }
14553
14554   if (gptab_bss_sec != NULL)
14555     {
14556       if (! bfd_set_section_contents (abfd, gptab_bss_sec,
14557                                       gptab_bss_sec->contents,
14558                                       0, gptab_bss_sec->size))
14559         return FALSE;
14560     }
14561
14562   if (SGI_COMPAT (abfd))
14563     {
14564       rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
14565       if (rtproc_sec != NULL)
14566         {
14567           if (! bfd_set_section_contents (abfd, rtproc_sec,
14568                                           rtproc_sec->contents,
14569                                           0, rtproc_sec->size))
14570             return FALSE;
14571         }
14572     }
14573
14574   return TRUE;
14575 }
14576 \f
14577 /* Structure for saying that BFD machine EXTENSION extends BASE.  */
14578
14579 struct mips_mach_extension
14580 {
14581   unsigned long extension, base;
14582 };
14583
14584
14585 /* An array describing how BFD machines relate to one another.  The entries
14586    are ordered topologically with MIPS I extensions listed last.  */
14587
14588 static const struct mips_mach_extension mips_mach_extensions[] =
14589 {
14590   /* MIPS64r2 extensions.  */
14591   { bfd_mach_mips_octeon2, bfd_mach_mips_octeonp },
14592   { bfd_mach_mips_octeonp, bfd_mach_mips_octeon },
14593   { bfd_mach_mips_octeon, bfd_mach_mipsisa64r2 },
14594   { bfd_mach_mips_loongson_3a, bfd_mach_mipsisa64r2 },
14595
14596   /* MIPS64 extensions.  */
14597   { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 },
14598   { bfd_mach_mips_sb1, bfd_mach_mipsisa64 },
14599   { bfd_mach_mips_xlr, bfd_mach_mipsisa64 },
14600
14601   /* MIPS V extensions.  */
14602   { bfd_mach_mipsisa64, bfd_mach_mips5 },
14603
14604   /* R10000 extensions.  */
14605   { bfd_mach_mips12000, bfd_mach_mips10000 },
14606   { bfd_mach_mips14000, bfd_mach_mips10000 },
14607   { bfd_mach_mips16000, bfd_mach_mips10000 },
14608
14609   /* R5000 extensions.  Note: the vr5500 ISA is an extension of the core
14610      vr5400 ISA, but doesn't include the multimedia stuff.  It seems
14611      better to allow vr5400 and vr5500 code to be merged anyway, since
14612      many libraries will just use the core ISA.  Perhaps we could add
14613      some sort of ASE flag if this ever proves a problem.  */
14614   { bfd_mach_mips5500, bfd_mach_mips5400 },
14615   { bfd_mach_mips5400, bfd_mach_mips5000 },
14616
14617   /* MIPS IV extensions.  */
14618   { bfd_mach_mips5, bfd_mach_mips8000 },
14619   { bfd_mach_mips10000, bfd_mach_mips8000 },
14620   { bfd_mach_mips5000, bfd_mach_mips8000 },
14621   { bfd_mach_mips7000, bfd_mach_mips8000 },
14622   { bfd_mach_mips9000, bfd_mach_mips8000 },
14623
14624   /* VR4100 extensions.  */
14625   { bfd_mach_mips4120, bfd_mach_mips4100 },
14626   { bfd_mach_mips4111, bfd_mach_mips4100 },
14627
14628   /* MIPS III extensions.  */
14629   { bfd_mach_mips_loongson_2e, bfd_mach_mips4000 },
14630   { bfd_mach_mips_loongson_2f, bfd_mach_mips4000 },
14631   { bfd_mach_mips8000, bfd_mach_mips4000 },
14632   { bfd_mach_mips4650, bfd_mach_mips4000 },
14633   { bfd_mach_mips4600, bfd_mach_mips4000 },
14634   { bfd_mach_mips4400, bfd_mach_mips4000 },
14635   { bfd_mach_mips4300, bfd_mach_mips4000 },
14636   { bfd_mach_mips4100, bfd_mach_mips4000 },
14637   { bfd_mach_mips4010, bfd_mach_mips4000 },
14638   { bfd_mach_mips5900, bfd_mach_mips4000 },
14639
14640   /* MIPS32 extensions.  */
14641   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
14642
14643   /* MIPS II extensions.  */
14644   { bfd_mach_mips4000, bfd_mach_mips6000 },
14645   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
14646
14647   /* MIPS I extensions.  */
14648   { bfd_mach_mips6000, bfd_mach_mips3000 },
14649   { bfd_mach_mips3900, bfd_mach_mips3000 }
14650 };
14651
14652
14653 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
14654
14655 static bfd_boolean
14656 mips_mach_extends_p (unsigned long base, unsigned long extension)
14657 {
14658   size_t i;
14659
14660   if (extension == base)
14661     return TRUE;
14662
14663   if (base == bfd_mach_mipsisa32
14664       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
14665     return TRUE;
14666
14667   if (base == bfd_mach_mipsisa32r2
14668       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
14669     return TRUE;
14670
14671   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
14672     if (extension == mips_mach_extensions[i].extension)
14673       {
14674         extension = mips_mach_extensions[i].base;
14675         if (extension == base)
14676           return TRUE;
14677       }
14678
14679   return FALSE;
14680 }
14681
14682
14683 /* Merge object attributes from IBFD into OBFD.  Raise an error if
14684    there are conflicting attributes.  */
14685 static bfd_boolean
14686 mips_elf_merge_obj_attributes (bfd *ibfd, bfd *obfd)
14687 {
14688   obj_attribute *in_attr;
14689   obj_attribute *out_attr;
14690   bfd *abi_fp_bfd;
14691   bfd *abi_msa_bfd;
14692
14693   abi_fp_bfd = mips_elf_tdata (obfd)->abi_fp_bfd;
14694   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
14695   if (!abi_fp_bfd && in_attr[Tag_GNU_MIPS_ABI_FP].i != Val_GNU_MIPS_ABI_FP_ANY)
14696     mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
14697
14698   abi_msa_bfd = mips_elf_tdata (obfd)->abi_msa_bfd;
14699   if (!abi_msa_bfd
14700       && in_attr[Tag_GNU_MIPS_ABI_MSA].i != Val_GNU_MIPS_ABI_MSA_ANY)
14701     mips_elf_tdata (obfd)->abi_msa_bfd = ibfd;
14702
14703   if (!elf_known_obj_attributes_proc (obfd)[0].i)
14704     {
14705       /* This is the first object.  Copy the attributes.  */
14706       _bfd_elf_copy_obj_attributes (ibfd, obfd);
14707
14708       /* Use the Tag_null value to indicate the attributes have been
14709          initialized.  */
14710       elf_known_obj_attributes_proc (obfd)[0].i = 1;
14711
14712       return TRUE;
14713     }
14714
14715   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
14716      non-conflicting ones.  */
14717   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
14718   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
14719     {
14720       int out_fp, in_fp;
14721
14722       out_fp = out_attr[Tag_GNU_MIPS_ABI_FP].i;
14723       in_fp = in_attr[Tag_GNU_MIPS_ABI_FP].i;
14724       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
14725       if (out_fp == Val_GNU_MIPS_ABI_FP_ANY)
14726         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_fp;
14727       else if (out_fp == Val_GNU_MIPS_ABI_FP_XX
14728                && (in_fp == Val_GNU_MIPS_ABI_FP_DOUBLE
14729                    || in_fp == Val_GNU_MIPS_ABI_FP_64
14730                    || in_fp == Val_GNU_MIPS_ABI_FP_64A))
14731         {
14732           mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
14733           out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
14734         }
14735       else if (in_fp == Val_GNU_MIPS_ABI_FP_XX
14736                && (out_fp == Val_GNU_MIPS_ABI_FP_DOUBLE
14737                    || out_fp == Val_GNU_MIPS_ABI_FP_64
14738                    || out_fp == Val_GNU_MIPS_ABI_FP_64A))
14739         /* Keep the current setting.  */;
14740       else if (out_fp == Val_GNU_MIPS_ABI_FP_64A
14741                && in_fp == Val_GNU_MIPS_ABI_FP_64)
14742         {
14743           mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
14744           out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
14745         }
14746       else if (in_fp == Val_GNU_MIPS_ABI_FP_64A
14747                && out_fp == Val_GNU_MIPS_ABI_FP_64)
14748         /* Keep the current setting.  */;
14749       else if (in_fp != Val_GNU_MIPS_ABI_FP_ANY)
14750         {
14751           const char *out_string, *in_string;
14752
14753           out_string = _bfd_mips_fp_abi_string (out_fp);
14754           in_string = _bfd_mips_fp_abi_string (in_fp);
14755           /* First warn about cases involving unrecognised ABIs.  */
14756           if (!out_string && !in_string)
14757             _bfd_error_handler
14758               (_("Warning: %B uses unknown floating point ABI %d "
14759                  "(set by %B), %B uses unknown floating point ABI %d"),
14760                obfd, abi_fp_bfd, ibfd, out_fp, in_fp);
14761           else if (!out_string)
14762             _bfd_error_handler
14763               (_("Warning: %B uses unknown floating point ABI %d "
14764                  "(set by %B), %B uses %s"),
14765                obfd, abi_fp_bfd, ibfd, out_fp, in_string);
14766           else if (!in_string)
14767             _bfd_error_handler
14768               (_("Warning: %B uses %s (set by %B), "
14769                  "%B uses unknown floating point ABI %d"),
14770                obfd, abi_fp_bfd, ibfd, out_string, in_fp);
14771           else
14772             {
14773               /* If one of the bfds is soft-float, the other must be
14774                  hard-float.  The exact choice of hard-float ABI isn't
14775                  really relevant to the error message.  */
14776               if (in_fp == Val_GNU_MIPS_ABI_FP_SOFT)
14777                 out_string = "-mhard-float";
14778               else if (out_fp == Val_GNU_MIPS_ABI_FP_SOFT)
14779                 in_string = "-mhard-float";
14780               _bfd_error_handler
14781                 (_("Warning: %B uses %s (set by %B), %B uses %s"),
14782                  obfd, abi_fp_bfd, ibfd, out_string, in_string);
14783             }
14784         }
14785     }
14786
14787   /* Check for conflicting Tag_GNU_MIPS_ABI_MSA attributes and merge
14788      non-conflicting ones.  */
14789   if (in_attr[Tag_GNU_MIPS_ABI_MSA].i != out_attr[Tag_GNU_MIPS_ABI_MSA].i)
14790     {
14791       out_attr[Tag_GNU_MIPS_ABI_MSA].type = 1;
14792       if (out_attr[Tag_GNU_MIPS_ABI_MSA].i == Val_GNU_MIPS_ABI_MSA_ANY)
14793         out_attr[Tag_GNU_MIPS_ABI_MSA].i = in_attr[Tag_GNU_MIPS_ABI_MSA].i;
14794       else if (in_attr[Tag_GNU_MIPS_ABI_MSA].i != Val_GNU_MIPS_ABI_MSA_ANY)
14795         switch (out_attr[Tag_GNU_MIPS_ABI_MSA].i)
14796           {
14797           case Val_GNU_MIPS_ABI_MSA_128:
14798             _bfd_error_handler
14799               (_("Warning: %B uses %s (set by %B), "
14800                  "%B uses unknown MSA ABI %d"),
14801                obfd, abi_msa_bfd, ibfd,
14802                "-mmsa", in_attr[Tag_GNU_MIPS_ABI_MSA].i);
14803             break;
14804
14805           default:
14806             switch (in_attr[Tag_GNU_MIPS_ABI_MSA].i)
14807               {
14808               case Val_GNU_MIPS_ABI_MSA_128:
14809                 _bfd_error_handler
14810                   (_("Warning: %B uses unknown MSA ABI %d "
14811                      "(set by %B), %B uses %s"),
14812                      obfd, abi_msa_bfd, ibfd,
14813                      out_attr[Tag_GNU_MIPS_ABI_MSA].i, "-mmsa");
14814                   break;
14815
14816               default:
14817                 _bfd_error_handler
14818                   (_("Warning: %B uses unknown MSA ABI %d "
14819                      "(set by %B), %B uses unknown MSA ABI %d"),
14820                    obfd, abi_msa_bfd, ibfd,
14821                    out_attr[Tag_GNU_MIPS_ABI_MSA].i,
14822                    in_attr[Tag_GNU_MIPS_ABI_MSA].i);
14823                 break;
14824               }
14825           }
14826     }
14827
14828   /* Merge Tag_compatibility attributes and any common GNU ones.  */
14829   _bfd_elf_merge_object_attributes (ibfd, obfd);
14830
14831   return TRUE;
14832 }
14833
14834 /* Merge backend specific data from an object file to the output
14835    object file when linking.  */
14836
14837 bfd_boolean
14838 _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
14839 {
14840   flagword old_flags;
14841   flagword new_flags;
14842   bfd_boolean ok;
14843   bfd_boolean null_input_bfd = TRUE;
14844   asection *sec;
14845   obj_attribute *out_attr;
14846
14847   /* Check if we have the same endianness.  */
14848   if (! _bfd_generic_verify_endian_match (ibfd, obfd))
14849     {
14850       (*_bfd_error_handler)
14851         (_("%B: endianness incompatible with that of the selected emulation"),
14852          ibfd);
14853       return FALSE;
14854     }
14855
14856   if (!is_mips_elf (ibfd) || !is_mips_elf (obfd))
14857     return TRUE;
14858
14859   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
14860     {
14861       (*_bfd_error_handler)
14862         (_("%B: ABI is incompatible with that of the selected emulation"),
14863          ibfd);
14864       return FALSE;
14865     }
14866
14867   /* Set up the FP ABI attribute from the abiflags if it is not already
14868      set.  */
14869   if (mips_elf_tdata (ibfd)->abiflags_valid)
14870     {
14871       obj_attribute *in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
14872       if (in_attr[Tag_GNU_MIPS_ABI_FP].i == Val_GNU_MIPS_ABI_FP_ANY)
14873         in_attr[Tag_GNU_MIPS_ABI_FP].i =
14874           mips_elf_tdata (ibfd)->abiflags.fp_abi;
14875     }
14876
14877   if (!mips_elf_merge_obj_attributes (ibfd, obfd))
14878     return FALSE;
14879
14880   /* Check to see if the input BFD actually contains any sections.
14881      If not, its flags may not have been initialised either, but it cannot
14882      actually cause any incompatibility.  */
14883   for (sec = ibfd->sections; sec != NULL; sec = sec->next)
14884     {
14885       /* Ignore synthetic sections and empty .text, .data and .bss sections
14886          which are automatically generated by gas.  Also ignore fake
14887          (s)common sections, since merely defining a common symbol does
14888          not affect compatibility.  */
14889       if ((sec->flags & SEC_IS_COMMON) == 0
14890           && strcmp (sec->name, ".reginfo")
14891           && strcmp (sec->name, ".mdebug")
14892           && (sec->size != 0
14893               || (strcmp (sec->name, ".text")
14894                   && strcmp (sec->name, ".data")
14895                   && strcmp (sec->name, ".bss"))))
14896         {
14897           null_input_bfd = FALSE;
14898           break;
14899         }
14900     }
14901   if (null_input_bfd)
14902     return TRUE;
14903
14904   /* Populate abiflags using existing information.  */
14905   if (!mips_elf_tdata (ibfd)->abiflags_valid)
14906     {
14907       infer_mips_abiflags (ibfd, &mips_elf_tdata (ibfd)->abiflags);
14908       mips_elf_tdata (ibfd)->abiflags_valid = TRUE;
14909     }
14910   else
14911     {
14912       Elf_Internal_ABIFlags_v0 abiflags;
14913       Elf_Internal_ABIFlags_v0 in_abiflags;
14914       infer_mips_abiflags (ibfd, &abiflags);
14915       in_abiflags = mips_elf_tdata (ibfd)->abiflags;
14916
14917       /* It is not possible to infer the correct ISA revision
14918          for R3 or R5 so drop down to R2 for the checks.  */
14919       if (in_abiflags.isa_rev == 3 || in_abiflags.isa_rev == 5)
14920         in_abiflags.isa_rev = 2;
14921
14922       if (in_abiflags.isa_level != abiflags.isa_level
14923           || in_abiflags.isa_rev != abiflags.isa_rev
14924           || in_abiflags.isa_ext != abiflags.isa_ext)
14925         (*_bfd_error_handler)
14926           (_("%B: warning: Inconsistent ISA between e_flags and "
14927              ".MIPS.abiflags"), ibfd);
14928       if (abiflags.fp_abi != Val_GNU_MIPS_ABI_FP_ANY
14929           && in_abiflags.fp_abi != abiflags.fp_abi)
14930         (*_bfd_error_handler)
14931           (_("%B: warning: Inconsistent FP ABI between e_flags and "
14932              ".MIPS.abiflags"), ibfd);
14933       if ((in_abiflags.ases & abiflags.ases) != abiflags.ases)
14934         (*_bfd_error_handler)
14935           (_("%B: warning: Inconsistent ASEs between e_flags and "
14936              ".MIPS.abiflags"), ibfd);
14937       if (in_abiflags.isa_ext != abiflags.isa_ext)
14938         (*_bfd_error_handler)
14939           (_("%B: warning: Inconsistent ISA extensions between e_flags and "
14940              ".MIPS.abiflags"), ibfd);
14941       if (in_abiflags.flags2 != 0)
14942         (*_bfd_error_handler)
14943           (_("%B: warning: Unexpected flag in the flags2 field of "
14944              ".MIPS.abiflags (0x%lx)"), ibfd,
14945            (unsigned long) in_abiflags.flags2);
14946     }
14947
14948   if (!mips_elf_tdata (obfd)->abiflags_valid)
14949     {
14950       /* Copy input abiflags if output abiflags are not already valid.  */
14951       mips_elf_tdata (obfd)->abiflags = mips_elf_tdata (ibfd)->abiflags;
14952       mips_elf_tdata (obfd)->abiflags_valid = TRUE;
14953     }
14954
14955   if (! elf_flags_init (obfd))
14956     {
14957       elf_flags_init (obfd) = TRUE;
14958       elf_elfheader (obfd)->e_flags = elf_elfheader (ibfd)->e_flags;
14959       elf_elfheader (obfd)->e_ident[EI_CLASS]
14960         = elf_elfheader (ibfd)->e_ident[EI_CLASS];
14961
14962       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
14963           && (bfd_get_arch_info (obfd)->the_default
14964               || mips_mach_extends_p (bfd_get_mach (obfd),
14965                                       bfd_get_mach (ibfd))))
14966         {
14967           if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
14968                                    bfd_get_mach (ibfd)))
14969             return FALSE;
14970
14971           /* Update the ABI flags isa_level, isa_rev and isa_ext fields.  */
14972           update_mips_abiflags_isa (obfd, &mips_elf_tdata (obfd)->abiflags);
14973         }
14974
14975       return TRUE;
14976     }
14977
14978   /* Update the output abiflags fp_abi using the computed fp_abi.  */
14979   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
14980   mips_elf_tdata (obfd)->abiflags.fp_abi = out_attr[Tag_GNU_MIPS_ABI_FP].i;
14981
14982 #define max(a,b) ((a) > (b) ? (a) : (b))
14983   /* Merge abiflags.  */
14984   mips_elf_tdata (obfd)->abiflags.isa_rev
14985     = max (mips_elf_tdata (obfd)->abiflags.isa_rev,
14986            mips_elf_tdata (ibfd)->abiflags.isa_rev);
14987   mips_elf_tdata (obfd)->abiflags.gpr_size
14988     = max (mips_elf_tdata (obfd)->abiflags.gpr_size,
14989            mips_elf_tdata (ibfd)->abiflags.gpr_size);
14990   mips_elf_tdata (obfd)->abiflags.cpr1_size
14991     = max (mips_elf_tdata (obfd)->abiflags.cpr1_size,
14992            mips_elf_tdata (ibfd)->abiflags.cpr1_size);
14993   mips_elf_tdata (obfd)->abiflags.cpr2_size
14994     = max (mips_elf_tdata (obfd)->abiflags.cpr2_size,
14995            mips_elf_tdata (ibfd)->abiflags.cpr2_size);
14996 #undef max
14997   mips_elf_tdata (obfd)->abiflags.ases
14998     |= mips_elf_tdata (ibfd)->abiflags.ases;
14999   mips_elf_tdata (obfd)->abiflags.flags1
15000     |= mips_elf_tdata (ibfd)->abiflags.flags1;
15001
15002   new_flags = elf_elfheader (ibfd)->e_flags;
15003   elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER;
15004   old_flags = elf_elfheader (obfd)->e_flags;
15005
15006   /* Check flag compatibility.  */
15007
15008   new_flags &= ~EF_MIPS_NOREORDER;
15009   old_flags &= ~EF_MIPS_NOREORDER;
15010
15011   /* Some IRIX 6 BSD-compatibility objects have this bit set.  It
15012      doesn't seem to matter.  */
15013   new_flags &= ~EF_MIPS_XGOT;
15014   old_flags &= ~EF_MIPS_XGOT;
15015
15016   /* MIPSpro generates ucode info in n64 objects.  Again, we should
15017      just be able to ignore this.  */
15018   new_flags &= ~EF_MIPS_UCODE;
15019   old_flags &= ~EF_MIPS_UCODE;
15020
15021   /* DSOs should only be linked with CPIC code.  */
15022   if ((ibfd->flags & DYNAMIC) != 0)
15023     new_flags |= EF_MIPS_PIC | EF_MIPS_CPIC;
15024
15025   if (new_flags == old_flags)
15026     return TRUE;
15027
15028   ok = TRUE;
15029
15030   if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)
15031       != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0))
15032     {
15033       (*_bfd_error_handler)
15034         (_("%B: warning: linking abicalls files with non-abicalls files"),
15035          ibfd);
15036       ok = TRUE;
15037     }
15038
15039   if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC))
15040     elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC;
15041   if (! (new_flags & EF_MIPS_PIC))
15042     elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC;
15043
15044   new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
15045   old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
15046
15047   /* Compare the ISAs.  */
15048   if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags))
15049     {
15050       (*_bfd_error_handler)
15051         (_("%B: linking 32-bit code with 64-bit code"),
15052          ibfd);
15053       ok = FALSE;
15054     }
15055   else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd)))
15056     {
15057       /* OBFD's ISA isn't the same as, or an extension of, IBFD's.  */
15058       if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd)))
15059         {
15060           /* Copy the architecture info from IBFD to OBFD.  Also copy
15061              the 32-bit flag (if set) so that we continue to recognise
15062              OBFD as a 32-bit binary.  */
15063           bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd));
15064           elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
15065           elf_elfheader (obfd)->e_flags
15066             |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
15067
15068           /* Update the ABI flags isa_level, isa_rev, isa_ext fields.  */
15069           update_mips_abiflags_isa (obfd, &mips_elf_tdata (obfd)->abiflags);
15070
15071           /* Copy across the ABI flags if OBFD doesn't use them
15072              and if that was what caused us to treat IBFD as 32-bit.  */
15073           if ((old_flags & EF_MIPS_ABI) == 0
15074               && mips_32bit_flags_p (new_flags)
15075               && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI))
15076             elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI;
15077         }
15078       else
15079         {
15080           /* The ISAs aren't compatible.  */
15081           (*_bfd_error_handler)
15082             (_("%B: linking %s module with previous %s modules"),
15083              ibfd,
15084              bfd_printable_name (ibfd),
15085              bfd_printable_name (obfd));
15086           ok = FALSE;
15087         }
15088     }
15089
15090   new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
15091   old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
15092
15093   /* Compare ABIs.  The 64-bit ABI does not use EF_MIPS_ABI.  But, it
15094      does set EI_CLASS differently from any 32-bit ABI.  */
15095   if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI)
15096       || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
15097           != elf_elfheader (obfd)->e_ident[EI_CLASS]))
15098     {
15099       /* Only error if both are set (to different values).  */
15100       if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI))
15101           || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
15102               != elf_elfheader (obfd)->e_ident[EI_CLASS]))
15103         {
15104           (*_bfd_error_handler)
15105             (_("%B: ABI mismatch: linking %s module with previous %s modules"),
15106              ibfd,
15107              elf_mips_abi_name (ibfd),
15108              elf_mips_abi_name (obfd));
15109           ok = FALSE;
15110         }
15111       new_flags &= ~EF_MIPS_ABI;
15112       old_flags &= ~EF_MIPS_ABI;
15113     }
15114
15115   /* Compare ASEs.  Forbid linking MIPS16 and microMIPS ASE modules together
15116      and allow arbitrary mixing of the remaining ASEs (retain the union).  */
15117   if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE))
15118     {
15119       int old_micro = old_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
15120       int new_micro = new_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
15121       int old_m16 = old_flags & EF_MIPS_ARCH_ASE_M16;
15122       int new_m16 = new_flags & EF_MIPS_ARCH_ASE_M16;
15123       int micro_mis = old_m16 && new_micro;
15124       int m16_mis = old_micro && new_m16;
15125
15126       if (m16_mis || micro_mis)
15127         {
15128           (*_bfd_error_handler)
15129             (_("%B: ASE mismatch: linking %s module with previous %s modules"),
15130              ibfd,
15131              m16_mis ? "MIPS16" : "microMIPS",
15132              m16_mis ? "microMIPS" : "MIPS16");
15133           ok = FALSE;
15134         }
15135
15136       elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE;
15137
15138       new_flags &= ~ EF_MIPS_ARCH_ASE;
15139       old_flags &= ~ EF_MIPS_ARCH_ASE;
15140     }
15141
15142   /* Compare NaN encodings.  */
15143   if ((new_flags & EF_MIPS_NAN2008) != (old_flags & EF_MIPS_NAN2008))
15144     {
15145       _bfd_error_handler (_("%B: linking %s module with previous %s modules"),
15146                           ibfd,
15147                           (new_flags & EF_MIPS_NAN2008
15148                            ? "-mnan=2008" : "-mnan=legacy"),
15149                           (old_flags & EF_MIPS_NAN2008
15150                            ? "-mnan=2008" : "-mnan=legacy"));
15151       ok = FALSE;
15152       new_flags &= ~EF_MIPS_NAN2008;
15153       old_flags &= ~EF_MIPS_NAN2008;
15154     }
15155
15156   /* Compare FP64 state.  */
15157   if ((new_flags & EF_MIPS_FP64) != (old_flags & EF_MIPS_FP64))
15158     {
15159       _bfd_error_handler (_("%B: linking %s module with previous %s modules"),
15160                           ibfd,
15161                           (new_flags & EF_MIPS_FP64
15162                            ? "-mfp64" : "-mfp32"),
15163                           (old_flags & EF_MIPS_FP64
15164                            ? "-mfp64" : "-mfp32"));
15165       ok = FALSE;
15166       new_flags &= ~EF_MIPS_FP64;
15167       old_flags &= ~EF_MIPS_FP64;
15168     }
15169
15170   /* Warn about any other mismatches */
15171   if (new_flags != old_flags)
15172     {
15173       (*_bfd_error_handler)
15174         (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"),
15175          ibfd, (unsigned long) new_flags,
15176          (unsigned long) old_flags);
15177       ok = FALSE;
15178     }
15179
15180   if (! ok)
15181     {
15182       bfd_set_error (bfd_error_bad_value);
15183       return FALSE;
15184     }
15185
15186   return TRUE;
15187 }
15188
15189 /* Function to keep MIPS specific file flags like as EF_MIPS_PIC.  */
15190
15191 bfd_boolean
15192 _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags)
15193 {
15194   BFD_ASSERT (!elf_flags_init (abfd)
15195               || elf_elfheader (abfd)->e_flags == flags);
15196
15197   elf_elfheader (abfd)->e_flags = flags;
15198   elf_flags_init (abfd) = TRUE;
15199   return TRUE;
15200 }
15201
15202 char *
15203 _bfd_mips_elf_get_target_dtag (bfd_vma dtag)
15204 {
15205   switch (dtag)
15206     {
15207     default: return "";
15208     case DT_MIPS_RLD_VERSION:
15209       return "MIPS_RLD_VERSION";
15210     case DT_MIPS_TIME_STAMP:
15211       return "MIPS_TIME_STAMP";
15212     case DT_MIPS_ICHECKSUM:
15213       return "MIPS_ICHECKSUM";
15214     case DT_MIPS_IVERSION:
15215       return "MIPS_IVERSION";
15216     case DT_MIPS_FLAGS:
15217       return "MIPS_FLAGS";
15218     case DT_MIPS_BASE_ADDRESS:
15219       return "MIPS_BASE_ADDRESS";
15220     case DT_MIPS_MSYM:
15221       return "MIPS_MSYM";
15222     case DT_MIPS_CONFLICT:
15223       return "MIPS_CONFLICT";
15224     case DT_MIPS_LIBLIST:
15225       return "MIPS_LIBLIST";
15226     case DT_MIPS_LOCAL_GOTNO:
15227       return "MIPS_LOCAL_GOTNO";
15228     case DT_MIPS_CONFLICTNO:
15229       return "MIPS_CONFLICTNO";
15230     case DT_MIPS_LIBLISTNO:
15231       return "MIPS_LIBLISTNO";
15232     case DT_MIPS_SYMTABNO:
15233       return "MIPS_SYMTABNO";
15234     case DT_MIPS_UNREFEXTNO:
15235       return "MIPS_UNREFEXTNO";
15236     case DT_MIPS_GOTSYM:
15237       return "MIPS_GOTSYM";
15238     case DT_MIPS_HIPAGENO:
15239       return "MIPS_HIPAGENO";
15240     case DT_MIPS_RLD_MAP:
15241       return "MIPS_RLD_MAP";
15242     case DT_MIPS_DELTA_CLASS:
15243       return "MIPS_DELTA_CLASS";
15244     case DT_MIPS_DELTA_CLASS_NO:
15245       return "MIPS_DELTA_CLASS_NO";
15246     case DT_MIPS_DELTA_INSTANCE:
15247       return "MIPS_DELTA_INSTANCE";
15248     case DT_MIPS_DELTA_INSTANCE_NO:
15249       return "MIPS_DELTA_INSTANCE_NO";
15250     case DT_MIPS_DELTA_RELOC:
15251       return "MIPS_DELTA_RELOC";
15252     case DT_MIPS_DELTA_RELOC_NO:
15253       return "MIPS_DELTA_RELOC_NO";
15254     case DT_MIPS_DELTA_SYM:
15255       return "MIPS_DELTA_SYM";
15256     case DT_MIPS_DELTA_SYM_NO:
15257       return "MIPS_DELTA_SYM_NO";
15258     case DT_MIPS_DELTA_CLASSSYM:
15259       return "MIPS_DELTA_CLASSSYM";
15260     case DT_MIPS_DELTA_CLASSSYM_NO:
15261       return "MIPS_DELTA_CLASSSYM_NO";
15262     case DT_MIPS_CXX_FLAGS:
15263       return "MIPS_CXX_FLAGS";
15264     case DT_MIPS_PIXIE_INIT:
15265       return "MIPS_PIXIE_INIT";
15266     case DT_MIPS_SYMBOL_LIB:
15267       return "MIPS_SYMBOL_LIB";
15268     case DT_MIPS_LOCALPAGE_GOTIDX:
15269       return "MIPS_LOCALPAGE_GOTIDX";
15270     case DT_MIPS_LOCAL_GOTIDX:
15271       return "MIPS_LOCAL_GOTIDX";
15272     case DT_MIPS_HIDDEN_GOTIDX:
15273       return "MIPS_HIDDEN_GOTIDX";
15274     case DT_MIPS_PROTECTED_GOTIDX:
15275       return "MIPS_PROTECTED_GOT_IDX";
15276     case DT_MIPS_OPTIONS:
15277       return "MIPS_OPTIONS";
15278     case DT_MIPS_INTERFACE:
15279       return "MIPS_INTERFACE";
15280     case DT_MIPS_DYNSTR_ALIGN:
15281       return "DT_MIPS_DYNSTR_ALIGN";
15282     case DT_MIPS_INTERFACE_SIZE:
15283       return "DT_MIPS_INTERFACE_SIZE";
15284     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
15285       return "DT_MIPS_RLD_TEXT_RESOLVE_ADDR";
15286     case DT_MIPS_PERF_SUFFIX:
15287       return "DT_MIPS_PERF_SUFFIX";
15288     case DT_MIPS_COMPACT_SIZE:
15289       return "DT_MIPS_COMPACT_SIZE";
15290     case DT_MIPS_GP_VALUE:
15291       return "DT_MIPS_GP_VALUE";
15292     case DT_MIPS_AUX_DYNAMIC:
15293       return "DT_MIPS_AUX_DYNAMIC";
15294     case DT_MIPS_PLTGOT:
15295       return "DT_MIPS_PLTGOT";
15296     case DT_MIPS_RWPLT:
15297       return "DT_MIPS_RWPLT";
15298     }
15299 }
15300
15301 /* Return the meaning of Tag_GNU_MIPS_ABI_FP value FP, or null if
15302    not known.  */
15303
15304 const char *
15305 _bfd_mips_fp_abi_string (int fp)
15306 {
15307   switch (fp)
15308     {
15309       /* These strings aren't translated because they're simply
15310          option lists.  */
15311     case Val_GNU_MIPS_ABI_FP_DOUBLE:
15312       return "-mdouble-float";
15313
15314     case Val_GNU_MIPS_ABI_FP_SINGLE:
15315       return "-msingle-float";
15316
15317     case Val_GNU_MIPS_ABI_FP_SOFT:
15318       return "-msoft-float";
15319
15320     case Val_GNU_MIPS_ABI_FP_OLD_64:
15321       return _("-mips32r2 -mfp64 (12 callee-saved)");
15322
15323     case Val_GNU_MIPS_ABI_FP_XX:
15324       return "-mfpxx";
15325
15326     case Val_GNU_MIPS_ABI_FP_64:
15327       return "-mgp32 -mfp64";
15328
15329     case Val_GNU_MIPS_ABI_FP_64A:
15330       return "-mgp32 -mfp64 -mno-odd-spreg";
15331
15332     default:
15333       return 0;
15334     }
15335 }
15336
15337 static void
15338 print_mips_ases (FILE *file, unsigned int mask)
15339 {
15340   if (mask & AFL_ASE_DSP)
15341     fputs ("\n\tDSP ASE", file);
15342   if (mask & AFL_ASE_DSPR2)
15343     fputs ("\n\tDSP R2 ASE", file);
15344   if (mask & AFL_ASE_EVA)
15345     fputs ("\n\tEnhanced VA Scheme", file);
15346   if (mask & AFL_ASE_MCU)
15347     fputs ("\n\tMCU (MicroController) ASE", file);
15348   if (mask & AFL_ASE_MDMX)
15349     fputs ("\n\tMDMX ASE", file);
15350   if (mask & AFL_ASE_MIPS3D)
15351     fputs ("\n\tMIPS-3D ASE", file);
15352   if (mask & AFL_ASE_MT)
15353     fputs ("\n\tMT ASE", file);
15354   if (mask & AFL_ASE_SMARTMIPS)
15355     fputs ("\n\tSmartMIPS ASE", file);
15356   if (mask & AFL_ASE_VIRT)
15357     fputs ("\n\tVZ ASE", file);
15358   if (mask & AFL_ASE_MSA)
15359     fputs ("\n\tMSA ASE", file);
15360   if (mask & AFL_ASE_MIPS16)
15361     fputs ("\n\tMIPS16 ASE", file);
15362   if (mask & AFL_ASE_MICROMIPS)
15363     fputs ("\n\tMICROMIPS ASE", file);
15364   if (mask & AFL_ASE_XPA)
15365     fputs ("\n\tXPA ASE", file);
15366   if (mask == 0)
15367     fprintf (file, "\n\t%s", _("None"));
15368 }
15369
15370 static void
15371 print_mips_isa_ext (FILE *file, unsigned int isa_ext)
15372 {
15373   switch (isa_ext)
15374     {
15375     case 0:
15376       fputs (_("None"), file);
15377       break;
15378     case AFL_EXT_XLR:
15379       fputs ("RMI XLR", file);
15380       break;
15381     case AFL_EXT_OCTEON2:
15382       fputs ("Cavium Networks Octeon2", file);
15383       break;
15384     case AFL_EXT_OCTEONP:
15385       fputs ("Cavium Networks OcteonP", file);
15386       break;
15387     case AFL_EXT_LOONGSON_3A:
15388       fputs ("Loongson 3A", file);
15389       break;
15390     case AFL_EXT_OCTEON:
15391       fputs ("Cavium Networks Octeon", file);
15392       break;
15393     case AFL_EXT_5900:
15394       fputs ("Toshiba R5900", file);
15395       break;
15396     case AFL_EXT_4650:
15397       fputs ("MIPS R4650", file);
15398       break;
15399     case AFL_EXT_4010:
15400       fputs ("LSI R4010", file);
15401       break;
15402     case AFL_EXT_4100:
15403       fputs ("NEC VR4100", file);
15404       break;
15405     case AFL_EXT_3900:
15406       fputs ("Toshiba R3900", file);
15407       break;
15408     case AFL_EXT_10000:
15409       fputs ("MIPS R10000", file);
15410       break;
15411     case AFL_EXT_SB1:
15412       fputs ("Broadcom SB-1", file);
15413       break;
15414     case AFL_EXT_4111:
15415       fputs ("NEC VR4111/VR4181", file);
15416       break;
15417     case AFL_EXT_4120:
15418       fputs ("NEC VR4120", file);
15419       break;
15420     case AFL_EXT_5400:
15421       fputs ("NEC VR5400", file);
15422       break;
15423     case AFL_EXT_5500:
15424       fputs ("NEC VR5500", file);
15425       break;
15426     case AFL_EXT_LOONGSON_2E:
15427       fputs ("ST Microelectronics Loongson 2E", file);
15428       break;
15429     case AFL_EXT_LOONGSON_2F:
15430       fputs ("ST Microelectronics Loongson 2F", file);
15431       break;
15432     default:
15433       fputs (_("Unknown"), file);
15434       break;
15435     }
15436 }
15437
15438 static void
15439 print_mips_fp_abi_value (FILE *file, int val)
15440 {
15441   switch (val)
15442     {
15443     case Val_GNU_MIPS_ABI_FP_ANY:
15444       fprintf (file, _("Hard or soft float\n"));
15445       break;
15446     case Val_GNU_MIPS_ABI_FP_DOUBLE:
15447       fprintf (file, _("Hard float (double precision)\n"));
15448       break;
15449     case Val_GNU_MIPS_ABI_FP_SINGLE:
15450       fprintf (file, _("Hard float (single precision)\n"));
15451       break;
15452     case Val_GNU_MIPS_ABI_FP_SOFT:
15453       fprintf (file, _("Soft float\n"));
15454       break;
15455     case Val_GNU_MIPS_ABI_FP_OLD_64:
15456       fprintf (file, _("Hard float (MIPS32r2 64-bit FPU 12 callee-saved)\n"));
15457       break;
15458     case Val_GNU_MIPS_ABI_FP_XX:
15459       fprintf (file, _("Hard float (32-bit CPU, Any FPU)\n"));
15460       break;
15461     case Val_GNU_MIPS_ABI_FP_64:
15462       fprintf (file, _("Hard float (32-bit CPU, 64-bit FPU)\n"));
15463       break;
15464     case Val_GNU_MIPS_ABI_FP_64A:
15465       fprintf (file, _("Hard float compat (32-bit CPU, 64-bit FPU)\n"));
15466       break;
15467     default:
15468       fprintf (file, "??? (%d)\n", val);
15469       break;
15470     }
15471 }
15472
15473 static int
15474 get_mips_reg_size (int reg_size)
15475 {
15476   return (reg_size == AFL_REG_NONE) ? 0
15477          : (reg_size == AFL_REG_32) ? 32
15478          : (reg_size == AFL_REG_64) ? 64
15479          : (reg_size == AFL_REG_128) ? 128
15480          : -1;
15481 }
15482
15483 bfd_boolean
15484 _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr)
15485 {
15486   FILE *file = ptr;
15487
15488   BFD_ASSERT (abfd != NULL && ptr != NULL);
15489
15490   /* Print normal ELF private data.  */
15491   _bfd_elf_print_private_bfd_data (abfd, ptr);
15492
15493   /* xgettext:c-format */
15494   fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
15495
15496   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
15497     fprintf (file, _(" [abi=O32]"));
15498   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64)
15499     fprintf (file, _(" [abi=O64]"));
15500   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32)
15501     fprintf (file, _(" [abi=EABI32]"));
15502   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
15503     fprintf (file, _(" [abi=EABI64]"));
15504   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI))
15505     fprintf (file, _(" [abi unknown]"));
15506   else if (ABI_N32_P (abfd))
15507     fprintf (file, _(" [abi=N32]"));
15508   else if (ABI_64_P (abfd))
15509     fprintf (file, _(" [abi=64]"));
15510   else
15511     fprintf (file, _(" [no abi set]"));
15512
15513   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1)
15514     fprintf (file, " [mips1]");
15515   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2)
15516     fprintf (file, " [mips2]");
15517   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3)
15518     fprintf (file, " [mips3]");
15519   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4)
15520     fprintf (file, " [mips4]");
15521   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5)
15522     fprintf (file, " [mips5]");
15523   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32)
15524     fprintf (file, " [mips32]");
15525   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64)
15526     fprintf (file, " [mips64]");
15527   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2)
15528     fprintf (file, " [mips32r2]");
15529   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2)
15530     fprintf (file, " [mips64r2]");
15531   else
15532     fprintf (file, _(" [unknown ISA]"));
15533
15534   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
15535     fprintf (file, " [mdmx]");
15536
15537   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
15538     fprintf (file, " [mips16]");
15539
15540   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
15541     fprintf (file, " [micromips]");
15542
15543   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NAN2008)
15544     fprintf (file, " [nan2008]");
15545
15546   if (elf_elfheader (abfd)->e_flags & EF_MIPS_FP64)
15547     fprintf (file, " [old fp64]");
15548
15549   if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE)
15550     fprintf (file, " [32bitmode]");
15551   else
15552     fprintf (file, _(" [not 32bitmode]"));
15553
15554   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NOREORDER)
15555     fprintf (file, " [noreorder]");
15556
15557   if (elf_elfheader (abfd)->e_flags & EF_MIPS_PIC)
15558     fprintf (file, " [PIC]");
15559
15560   if (elf_elfheader (abfd)->e_flags & EF_MIPS_CPIC)
15561     fprintf (file, " [CPIC]");
15562
15563   if (elf_elfheader (abfd)->e_flags & EF_MIPS_XGOT)
15564     fprintf (file, " [XGOT]");
15565
15566   if (elf_elfheader (abfd)->e_flags & EF_MIPS_UCODE)
15567     fprintf (file, " [UCODE]");
15568
15569   fputc ('\n', file);
15570
15571   if (mips_elf_tdata (abfd)->abiflags_valid)
15572     {
15573       Elf_Internal_ABIFlags_v0 *abiflags = &mips_elf_tdata (abfd)->abiflags;
15574       fprintf (file, "\nMIPS ABI Flags Version: %d\n", abiflags->version);
15575       fprintf (file, "\nISA: MIPS%d", abiflags->isa_level);
15576       if (abiflags->isa_rev > 1)
15577         fprintf (file, "r%d", abiflags->isa_rev);
15578       fprintf (file, "\nGPR size: %d",
15579                get_mips_reg_size (abiflags->gpr_size));
15580       fprintf (file, "\nCPR1 size: %d",
15581                get_mips_reg_size (abiflags->cpr1_size));
15582       fprintf (file, "\nCPR2 size: %d",
15583                get_mips_reg_size (abiflags->cpr2_size));
15584       fputs ("\nFP ABI: ", file);
15585       print_mips_fp_abi_value (file, abiflags->fp_abi);
15586       fputs ("ISA Extension: ", file);
15587       print_mips_isa_ext (file, abiflags->isa_ext);
15588       fputs ("\nASEs:", file);
15589       print_mips_ases (file, abiflags->ases);
15590       fprintf (file, "\nFLAGS 1: %8.8lx", abiflags->flags1);
15591       fprintf (file, "\nFLAGS 2: %8.8lx", abiflags->flags2);
15592       fputc ('\n', file);
15593     }
15594
15595   return TRUE;
15596 }
15597
15598 const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] =
15599 {
15600   { STRING_COMMA_LEN (".lit4"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
15601   { STRING_COMMA_LEN (".lit8"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
15602   { STRING_COMMA_LEN (".mdebug"), 0, SHT_MIPS_DEBUG, 0 },
15603   { STRING_COMMA_LEN (".sbss"),  -2, SHT_NOBITS,     SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
15604   { STRING_COMMA_LEN (".sdata"), -2, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
15605   { STRING_COMMA_LEN (".ucode"),  0, SHT_MIPS_UCODE, 0 },
15606   { NULL,                     0,  0, 0,              0 }
15607 };
15608
15609 /* Merge non visibility st_other attributes.  Ensure that the
15610    STO_OPTIONAL flag is copied into h->other, even if this is not a
15611    definiton of the symbol.  */
15612 void
15613 _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
15614                                       const Elf_Internal_Sym *isym,
15615                                       bfd_boolean definition,
15616                                       bfd_boolean dynamic ATTRIBUTE_UNUSED)
15617 {
15618   if ((isym->st_other & ~ELF_ST_VISIBILITY (-1)) != 0)
15619     {
15620       unsigned char other;
15621
15622       other = (definition ? isym->st_other : h->other);
15623       other &= ~ELF_ST_VISIBILITY (-1);
15624       h->other = other | ELF_ST_VISIBILITY (h->other);
15625     }
15626
15627   if (!definition
15628       && ELF_MIPS_IS_OPTIONAL (isym->st_other))
15629     h->other |= STO_OPTIONAL;
15630 }
15631
15632 /* Decide whether an undefined symbol is special and can be ignored.
15633    This is the case for OPTIONAL symbols on IRIX.  */
15634 bfd_boolean
15635 _bfd_mips_elf_ignore_undef_symbol (struct elf_link_hash_entry *h)
15636 {
15637   return ELF_MIPS_IS_OPTIONAL (h->other) ? TRUE : FALSE;
15638 }
15639
15640 bfd_boolean
15641 _bfd_mips_elf_common_definition (Elf_Internal_Sym *sym)
15642 {
15643   return (sym->st_shndx == SHN_COMMON
15644           || sym->st_shndx == SHN_MIPS_ACOMMON
15645           || sym->st_shndx == SHN_MIPS_SCOMMON);
15646 }
15647
15648 /* Return address for Ith PLT stub in section PLT, for relocation REL
15649    or (bfd_vma) -1 if it should not be included.  */
15650
15651 bfd_vma
15652 _bfd_mips_elf_plt_sym_val (bfd_vma i, const asection *plt,
15653                            const arelent *rel ATTRIBUTE_UNUSED)
15654 {
15655   return (plt->vma
15656           + 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry)
15657           + i * 4 * ARRAY_SIZE (mips_exec_plt_entry));
15658 }
15659
15660 /* Build a table of synthetic symbols to represent the PLT.  As with MIPS16
15661    and microMIPS PLT slots we may have a many-to-one mapping between .plt
15662    and .got.plt and also the slots may be of a different size each we walk
15663    the PLT manually fetching instructions and matching them against known
15664    patterns.  To make things easier standard MIPS slots, if any, always come
15665    first.  As we don't create proper ELF symbols we use the UDATA.I member
15666    of ASYMBOL to carry ISA annotation.  The encoding used is the same as
15667    with the ST_OTHER member of the ELF symbol.  */
15668
15669 long
15670 _bfd_mips_elf_get_synthetic_symtab (bfd *abfd,
15671                                     long symcount ATTRIBUTE_UNUSED,
15672                                     asymbol **syms ATTRIBUTE_UNUSED,
15673                                     long dynsymcount, asymbol **dynsyms,
15674                                     asymbol **ret)
15675 {
15676   static const char pltname[] = "_PROCEDURE_LINKAGE_TABLE_";
15677   static const char microsuffix[] = "@micromipsplt";
15678   static const char m16suffix[] = "@mips16plt";
15679   static const char mipssuffix[] = "@plt";
15680
15681   bfd_boolean (*slurp_relocs) (bfd *, asection *, asymbol **, bfd_boolean);
15682   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
15683   bfd_boolean micromips_p = MICROMIPS_P (abfd);
15684   Elf_Internal_Shdr *hdr;
15685   bfd_byte *plt_data;
15686   bfd_vma plt_offset;
15687   unsigned int other;
15688   bfd_vma entry_size;
15689   bfd_vma plt0_size;
15690   asection *relplt;
15691   bfd_vma opcode;
15692   asection *plt;
15693   asymbol *send;
15694   size_t size;
15695   char *names;
15696   long counti;
15697   arelent *p;
15698   asymbol *s;
15699   char *nend;
15700   long count;
15701   long pi;
15702   long i;
15703   long n;
15704
15705   *ret = NULL;
15706
15707   if ((abfd->flags & (DYNAMIC | EXEC_P)) == 0 || dynsymcount <= 0)
15708     return 0;
15709
15710   relplt = bfd_get_section_by_name (abfd, ".rel.plt");
15711   if (relplt == NULL)
15712     return 0;
15713
15714   hdr = &elf_section_data (relplt)->this_hdr;
15715   if (hdr->sh_link != elf_dynsymtab (abfd) || hdr->sh_type != SHT_REL)
15716     return 0;
15717
15718   plt = bfd_get_section_by_name (abfd, ".plt");
15719   if (plt == NULL)
15720     return 0;
15721
15722   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
15723   if (!(*slurp_relocs) (abfd, relplt, dynsyms, TRUE))
15724     return -1;
15725   p = relplt->relocation;
15726
15727   /* Calculating the exact amount of space required for symbols would
15728      require two passes over the PLT, so just pessimise assuming two
15729      PLT slots per relocation.  */
15730   count = relplt->size / hdr->sh_entsize;
15731   counti = count * bed->s->int_rels_per_ext_rel;
15732   size = 2 * count * sizeof (asymbol);
15733   size += count * (sizeof (mipssuffix) +
15734                    (micromips_p ? sizeof (microsuffix) : sizeof (m16suffix)));
15735   for (pi = 0; pi < counti; pi += bed->s->int_rels_per_ext_rel)
15736     size += 2 * strlen ((*p[pi].sym_ptr_ptr)->name);
15737
15738   /* Add the size of "_PROCEDURE_LINKAGE_TABLE_" too.  */
15739   size += sizeof (asymbol) + sizeof (pltname);
15740
15741   if (!bfd_malloc_and_get_section (abfd, plt, &plt_data))
15742     return -1;
15743
15744   if (plt->size < 16)
15745     return -1;
15746
15747   s = *ret = bfd_malloc (size);
15748   if (s == NULL)
15749     return -1;
15750   send = s + 2 * count + 1;
15751
15752   names = (char *) send;
15753   nend = (char *) s + size;
15754   n = 0;
15755
15756   opcode = bfd_get_micromips_32 (abfd, plt_data + 12);
15757   if (opcode == 0x3302fffe)
15758     {
15759       if (!micromips_p)
15760         return -1;
15761       plt0_size = 2 * ARRAY_SIZE (micromips_o32_exec_plt0_entry);
15762       other = STO_MICROMIPS;
15763     }
15764   else if (opcode == 0x0398c1d0)
15765     {
15766       if (!micromips_p)
15767         return -1;
15768       plt0_size = 2 * ARRAY_SIZE (micromips_insn32_o32_exec_plt0_entry);
15769       other = STO_MICROMIPS;
15770     }
15771   else
15772     {
15773       plt0_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
15774       other = 0;
15775     }
15776
15777   s->the_bfd = abfd;
15778   s->flags = BSF_SYNTHETIC | BSF_FUNCTION | BSF_LOCAL;
15779   s->section = plt;
15780   s->value = 0;
15781   s->name = names;
15782   s->udata.i = other;
15783   memcpy (names, pltname, sizeof (pltname));
15784   names += sizeof (pltname);
15785   ++s, ++n;
15786
15787   pi = 0;
15788   for (plt_offset = plt0_size;
15789        plt_offset + 8 <= plt->size && s < send;
15790        plt_offset += entry_size)
15791     {
15792       bfd_vma gotplt_addr;
15793       const char *suffix;
15794       bfd_vma gotplt_hi;
15795       bfd_vma gotplt_lo;
15796       size_t suffixlen;
15797
15798       opcode = bfd_get_micromips_32 (abfd, plt_data + plt_offset + 4);
15799
15800       /* Check if the second word matches the expected MIPS16 instruction.  */
15801       if (opcode == 0x651aeb00)
15802         {
15803           if (micromips_p)
15804             return -1;
15805           /* Truncated table???  */
15806           if (plt_offset + 16 > plt->size)
15807             break;
15808           gotplt_addr = bfd_get_32 (abfd, plt_data + plt_offset + 12);
15809           entry_size = 2 * ARRAY_SIZE (mips16_o32_exec_plt_entry);
15810           suffixlen = sizeof (m16suffix);
15811           suffix = m16suffix;
15812           other = STO_MIPS16;
15813         }
15814       /* Likewise the expected microMIPS instruction (no insn32 mode).  */
15815       else if (opcode == 0xff220000)
15816         {
15817           if (!micromips_p)
15818             return -1;
15819           gotplt_hi = bfd_get_16 (abfd, plt_data + plt_offset) & 0x7f;
15820           gotplt_lo = bfd_get_16 (abfd, plt_data + plt_offset + 2) & 0xffff;
15821           gotplt_hi = ((gotplt_hi ^ 0x40) - 0x40) << 18;
15822           gotplt_lo <<= 2;
15823           gotplt_addr = gotplt_hi + gotplt_lo;
15824           gotplt_addr += ((plt->vma + plt_offset) | 3) ^ 3;
15825           entry_size = 2 * ARRAY_SIZE (micromips_o32_exec_plt_entry);
15826           suffixlen = sizeof (microsuffix);
15827           suffix = microsuffix;
15828           other = STO_MICROMIPS;
15829         }
15830       /* Likewise the expected microMIPS instruction (insn32 mode).  */
15831       else if ((opcode & 0xffff0000) == 0xff2f0000)
15832         {
15833           gotplt_hi = bfd_get_16 (abfd, plt_data + plt_offset + 2) & 0xffff;
15834           gotplt_lo = bfd_get_16 (abfd, plt_data + plt_offset + 6) & 0xffff;
15835           gotplt_hi = ((gotplt_hi ^ 0x8000) - 0x8000) << 16;
15836           gotplt_lo = (gotplt_lo ^ 0x8000) - 0x8000;
15837           gotplt_addr = gotplt_hi + gotplt_lo;
15838           entry_size = 2 * ARRAY_SIZE (micromips_insn32_o32_exec_plt_entry);
15839           suffixlen = sizeof (microsuffix);
15840           suffix = microsuffix;
15841           other = STO_MICROMIPS;
15842         }
15843       /* Otherwise assume standard MIPS code.  */
15844       else
15845         {
15846           gotplt_hi = bfd_get_32 (abfd, plt_data + plt_offset) & 0xffff;
15847           gotplt_lo = bfd_get_32 (abfd, plt_data + plt_offset + 4) & 0xffff;
15848           gotplt_hi = ((gotplt_hi ^ 0x8000) - 0x8000) << 16;
15849           gotplt_lo = (gotplt_lo ^ 0x8000) - 0x8000;
15850           gotplt_addr = gotplt_hi + gotplt_lo;
15851           entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
15852           suffixlen = sizeof (mipssuffix);
15853           suffix = mipssuffix;
15854           other = 0;
15855         }
15856       /* Truncated table???  */
15857       if (plt_offset + entry_size > plt->size)
15858         break;
15859
15860       for (i = 0;
15861            i < count && p[pi].address != gotplt_addr;
15862            i++, pi = (pi + bed->s->int_rels_per_ext_rel) % counti);
15863
15864       if (i < count)
15865         {
15866           size_t namelen;
15867           size_t len;
15868
15869           *s = **p[pi].sym_ptr_ptr;
15870           /* Undefined syms won't have BSF_LOCAL or BSF_GLOBAL set.  Since
15871              we are defining a symbol, ensure one of them is set.  */
15872           if ((s->flags & BSF_LOCAL) == 0)
15873             s->flags |= BSF_GLOBAL;
15874           s->flags |= BSF_SYNTHETIC;
15875           s->section = plt;
15876           s->value = plt_offset;
15877           s->name = names;
15878           s->udata.i = other;
15879
15880           len = strlen ((*p[pi].sym_ptr_ptr)->name);
15881           namelen = len + suffixlen;
15882           if (names + namelen > nend)
15883             break;
15884
15885           memcpy (names, (*p[pi].sym_ptr_ptr)->name, len);
15886           names += len;
15887           memcpy (names, suffix, suffixlen);
15888           names += suffixlen;
15889
15890           ++s, ++n;
15891           pi = (pi + bed->s->int_rels_per_ext_rel) % counti;
15892         }
15893     }
15894
15895   free (plt_data);
15896
15897   return n;
15898 }
15899
15900 void
15901 _bfd_mips_post_process_headers (bfd *abfd, struct bfd_link_info *link_info)
15902 {
15903   struct mips_elf_link_hash_table *htab;
15904   Elf_Internal_Ehdr *i_ehdrp;
15905
15906   i_ehdrp = elf_elfheader (abfd);
15907   if (link_info)
15908     {
15909       htab = mips_elf_hash_table (link_info);
15910       BFD_ASSERT (htab != NULL);
15911
15912       if (htab->use_plts_and_copy_relocs && !htab->is_vxworks)
15913         i_ehdrp->e_ident[EI_ABIVERSION] = 1;
15914     }
15915
15916   _bfd_elf_post_process_headers (abfd, link_info);
15917
15918   if (mips_elf_tdata (abfd)->abiflags.fp_abi == Val_GNU_MIPS_ABI_FP_64
15919       || mips_elf_tdata (abfd)->abiflags.fp_abi == Val_GNU_MIPS_ABI_FP_64A)
15920     i_ehdrp->e_ident[EI_ABIVERSION] = 3;
15921 }