bfd/
[platform/upstream/binutils.git] / bfd / elfxx-mips.c
1 /* MIPS-specific support for ELF
2    Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
4    Free Software Foundation, Inc.
5
6    Most of the information added by Ian Lance Taylor, Cygnus Support,
7    <ian@cygnus.com>.
8    N32/64 ABI support added by Mark Mitchell, CodeSourcery, LLC.
9    <mark@codesourcery.com>
10    Traditional MIPS targets support added by Koundinya.K, Dansk Data
11    Elektronik & Operations Research Group. <kk@ddeorg.soft.net>
12
13    This file is part of BFD, the Binary File Descriptor library.
14
15    This program is free software; you can redistribute it and/or modify
16    it under the terms of the GNU General Public License as published by
17    the Free Software Foundation; either version 3 of the License, or
18    (at your option) any later version.
19
20    This program is distributed in the hope that it will be useful,
21    but WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23    GNU General Public License for more details.
24
25    You should have received a copy of the GNU General Public License
26    along with this program; if not, write to the Free Software
27    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
28    MA 02110-1301, USA.  */
29
30
31 /* This file handles functionality common to the different MIPS ABI's.  */
32
33 #include "sysdep.h"
34 #include "bfd.h"
35 #include "libbfd.h"
36 #include "libiberty.h"
37 #include "elf-bfd.h"
38 #include "elfxx-mips.h"
39 #include "elf/mips.h"
40 #include "elf-vxworks.h"
41
42 /* Get the ECOFF swapping routines.  */
43 #include "coff/sym.h"
44 #include "coff/symconst.h"
45 #include "coff/ecoff.h"
46 #include "coff/mips.h"
47
48 #include "hashtab.h"
49
50 /* This structure is used to hold information about one GOT entry.
51    There are three types of entry:
52
53       (1) absolute addresses
54             (abfd == NULL)
55       (2) SYMBOL + OFFSET addresses, where SYMBOL is local to an input bfd
56             (abfd != NULL, symndx >= 0)
57       (3) SYMBOL addresses, where SYMBOL is not local to an input bfd
58             (abfd != NULL, symndx == -1)
59
60    Type (3) entries are treated differently for different types of GOT.
61    In the "master" GOT -- i.e.  the one that describes every GOT
62    reference needed in the link -- the mips_got_entry is keyed on both
63    the symbol and the input bfd that references it.  If it turns out
64    that we need multiple GOTs, we can then use this information to
65    create separate GOTs for each input bfd.
66
67    However, we want each of these separate GOTs to have at most one
68    entry for a given symbol, so their type (3) entries are keyed only
69    on the symbol.  The input bfd given by the "abfd" field is somewhat
70    arbitrary in this case.
71
72    This means that when there are multiple GOTs, each GOT has a unique
73    mips_got_entry for every symbol within it.  We can therefore use the
74    mips_got_entry fields (tls_type and gotidx) to track the symbol's
75    GOT index.
76
77    However, if it turns out that we need only a single GOT, we continue
78    to use the master GOT to describe it.  There may therefore be several
79    mips_got_entries for the same symbol, each with a different input bfd.
80    We want to make sure that each symbol gets a unique GOT entry, so when
81    there's a single GOT, we use the symbol's hash entry, not the
82    mips_got_entry fields, to track a symbol's GOT index.  */
83 struct mips_got_entry
84 {
85   /* The input bfd in which the symbol is defined.  */
86   bfd *abfd;
87   /* The index of the symbol, as stored in the relocation r_info, if
88      we have a local symbol; -1 otherwise.  */
89   long symndx;
90   union
91   {
92     /* If abfd == NULL, an address that must be stored in the got.  */
93     bfd_vma address;
94     /* If abfd != NULL && symndx != -1, the addend of the relocation
95        that should be added to the symbol value.  */
96     bfd_vma addend;
97     /* If abfd != NULL && symndx == -1, the hash table entry
98        corresponding to symbol in the GOT.  The symbol's entry
99        is in the local area if h->global_got_area is GGA_NONE,
100        otherwise it is in the global area.  */
101     struct mips_elf_link_hash_entry *h;
102   } d;
103
104   /* The TLS type of this GOT entry: GOT_NORMAL, GOT_TLS_IE, GOT_TLS_GD
105      or GOT_TLS_LDM.  An LDM GOT entry will be a local symbol entry with
106      r_symndx == 0.  */
107   unsigned char tls_type;
108
109   /* The offset from the beginning of the .got section to the entry
110      corresponding to this symbol+addend.  If it's a global symbol
111      whose offset is yet to be decided, it's going to be -1.  */
112   long gotidx;
113 };
114
115 /* This structure describes a range of addends: [MIN_ADDEND, MAX_ADDEND].
116    The structures form a non-overlapping list that is sorted by increasing
117    MIN_ADDEND.  */
118 struct mips_got_page_range
119 {
120   struct mips_got_page_range *next;
121   bfd_signed_vma min_addend;
122   bfd_signed_vma max_addend;
123 };
124
125 /* This structure describes the range of addends that are applied to page
126    relocations against a given symbol.  */
127 struct mips_got_page_entry
128 {
129   /* The input bfd in which the symbol is defined.  */
130   bfd *abfd;
131   /* The index of the symbol, as stored in the relocation r_info.  */
132   long symndx;
133   /* The ranges for this page entry.  */
134   struct mips_got_page_range *ranges;
135   /* The maximum number of page entries needed for RANGES.  */
136   bfd_vma num_pages;
137 };
138
139 /* This structure is used to hold .got information when linking.  */
140
141 struct mips_got_info
142 {
143   /* The number of global .got entries.  */
144   unsigned int global_gotno;
145   /* The number of global .got entries that are in the GGA_RELOC_ONLY area.  */
146   unsigned int reloc_only_gotno;
147   /* The number of .got slots used for TLS.  */
148   unsigned int tls_gotno;
149   /* The first unused TLS .got entry.  Used only during
150      mips_elf_initialize_tls_index.  */
151   unsigned int tls_assigned_gotno;
152   /* The number of local .got entries, eventually including page entries.  */
153   unsigned int local_gotno;
154   /* The maximum number of page entries needed.  */
155   unsigned int page_gotno;
156   /* The number of local .got entries we have used.  */
157   unsigned int assigned_gotno;
158   /* A hash table holding members of the got.  */
159   struct htab *got_entries;
160   /* A hash table of mips_got_page_entry structures.  */
161   struct htab *got_page_entries;
162   /* A hash table mapping input bfds to other mips_got_info.  NULL
163      unless multi-got was necessary.  */
164   struct htab *bfd2got;
165   /* In multi-got links, a pointer to the next got (err, rather, most
166      of the time, it points to the previous got).  */
167   struct mips_got_info *next;
168   /* This is the GOT index of the TLS LDM entry for the GOT, MINUS_ONE
169      for none, or MINUS_TWO for not yet assigned.  This is needed
170      because a single-GOT link may have multiple hash table entries
171      for the LDM.  It does not get initialized in multi-GOT mode.  */
172   bfd_vma tls_ldm_offset;
173 };
174
175 /* Map an input bfd to a got in a multi-got link.  */
176
177 struct mips_elf_bfd2got_hash
178 {
179   bfd *bfd;
180   struct mips_got_info *g;
181 };
182
183 /* Structure passed when traversing the bfd2got hash table, used to
184    create and merge bfd's gots.  */
185
186 struct mips_elf_got_per_bfd_arg
187 {
188   /* A hashtable that maps bfds to gots.  */
189   htab_t bfd2got;
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 /* Another structure used to pass arguments for got entries traversal.  */
214
215 struct mips_elf_set_global_got_offset_arg
216 {
217   struct mips_got_info *g;
218   int value;
219   unsigned int needed_relocs;
220   struct bfd_link_info *info;
221 };
222
223 /* A structure used to count TLS relocations or GOT entries, for GOT
224    entry or ELF symbol table traversal.  */
225
226 struct mips_elf_count_tls_arg
227 {
228   struct bfd_link_info *info;
229   unsigned int needed;
230 };
231
232 struct _mips_elf_section_data
233 {
234   struct bfd_elf_section_data elf;
235   union
236   {
237     bfd_byte *tdata;
238   } u;
239 };
240
241 #define mips_elf_section_data(sec) \
242   ((struct _mips_elf_section_data *) elf_section_data (sec))
243
244 #define is_mips_elf(bfd)                                \
245   (bfd_get_flavour (bfd) == bfd_target_elf_flavour      \
246    && elf_tdata (bfd) != NULL                           \
247    && elf_object_id (bfd) == MIPS_ELF_DATA)
248
249 /* The ABI says that every symbol used by dynamic relocations must have
250    a global GOT entry.  Among other things, this provides the dynamic
251    linker with a free, directly-indexed cache.  The GOT can therefore
252    contain symbols that are not referenced by GOT relocations themselves
253    (in other words, it may have symbols that are not referenced by things
254    like R_MIPS_GOT16 and R_MIPS_GOT_PAGE).
255
256    GOT relocations are less likely to overflow if we put the associated
257    GOT entries towards the beginning.  We therefore divide the global
258    GOT entries into two areas: "normal" and "reloc-only".  Entries in
259    the first area can be used for both dynamic relocations and GP-relative
260    accesses, while those in the "reloc-only" area are for dynamic
261    relocations only.
262
263    These GGA_* ("Global GOT Area") values are organised so that lower
264    values are more general than higher values.  Also, non-GGA_NONE
265    values are ordered by the position of the area in the GOT.  */
266 #define GGA_NORMAL 0
267 #define GGA_RELOC_ONLY 1
268 #define GGA_NONE 2
269
270 /* Information about a non-PIC interface to a PIC function.  There are
271    two ways of creating these interfaces.  The first is to add:
272
273         lui     $25,%hi(func)
274         addiu   $25,$25,%lo(func)
275
276    immediately before a PIC function "func".  The second is to add:
277
278         lui     $25,%hi(func)
279         j       func
280         addiu   $25,$25,%lo(func)
281
282    to a separate trampoline section.
283
284    Stubs of the first kind go in a new section immediately before the
285    target function.  Stubs of the second kind go in a single section
286    pointed to by the hash table's "strampoline" field.  */
287 struct mips_elf_la25_stub {
288   /* The generated section that contains this stub.  */
289   asection *stub_section;
290
291   /* The offset of the stub from the start of STUB_SECTION.  */
292   bfd_vma offset;
293
294   /* One symbol for the original function.  Its location is available
295      in H->root.root.u.def.  */
296   struct mips_elf_link_hash_entry *h;
297 };
298
299 /* Macros for populating a mips_elf_la25_stub.  */
300
301 #define LA25_LUI(VAL) (0x3c190000 | (VAL))      /* lui t9,VAL */
302 #define LA25_J(VAL) (0x08000000 | (((VAL) >> 2) & 0x3ffffff)) /* j VAL */
303 #define LA25_ADDIU(VAL) (0x27390000 | (VAL))    /* addiu t9,t9,VAL */
304 #define LA25_LUI_MICROMIPS(VAL)                                         \
305   (0x41b90000 | (VAL))                          /* lui t9,VAL */
306 #define LA25_J_MICROMIPS(VAL)                                           \
307   (0xd4000000 | (((VAL) >> 1) & 0x3ffffff))     /* j VAL */
308 #define LA25_ADDIU_MICROMIPS(VAL)                                       \
309   (0x33390000 | (VAL))                          /* addiu t9,t9,VAL */
310
311 /* This structure is passed to mips_elf_sort_hash_table_f when sorting
312    the dynamic symbols.  */
313
314 struct mips_elf_hash_sort_data
315 {
316   /* The symbol in the global GOT with the lowest dynamic symbol table
317      index.  */
318   struct elf_link_hash_entry *low;
319   /* The least dynamic symbol table index corresponding to a non-TLS
320      symbol with a GOT entry.  */
321   long min_got_dynindx;
322   /* The greatest dynamic symbol table index corresponding to a symbol
323      with a GOT entry that is not referenced (e.g., a dynamic symbol
324      with dynamic relocations pointing to it from non-primary GOTs).  */
325   long max_unref_got_dynindx;
326   /* The greatest dynamic symbol table index not corresponding to a
327      symbol without a GOT entry.  */
328   long max_non_got_dynindx;
329 };
330
331 /* The MIPS ELF linker needs additional information for each symbol in
332    the global hash table.  */
333
334 struct mips_elf_link_hash_entry
335 {
336   struct elf_link_hash_entry root;
337
338   /* External symbol information.  */
339   EXTR esym;
340
341   /* The la25 stub we have created for ths symbol, if any.  */
342   struct mips_elf_la25_stub *la25_stub;
343
344   /* Number of R_MIPS_32, R_MIPS_REL32, or R_MIPS_64 relocs against
345      this symbol.  */
346   unsigned int possibly_dynamic_relocs;
347
348   /* If there is a stub that 32 bit functions should use to call this
349      16 bit function, this points to the section containing the stub.  */
350   asection *fn_stub;
351
352   /* If there is a stub that 16 bit functions should use to call this
353      32 bit function, this points to the section containing the stub.  */
354   asection *call_stub;
355
356   /* This is like the call_stub field, but it is used if the function
357      being called returns a floating point value.  */
358   asection *call_fp_stub;
359
360 #define GOT_NORMAL      0
361 #define GOT_TLS_GD      1
362 #define GOT_TLS_LDM     2
363 #define GOT_TLS_IE      4
364 #define GOT_TLS_TYPE    7
365 #define GOT_TLS_OFFSET_DONE    0x40
366 #define GOT_TLS_DONE    0x80
367   unsigned char tls_ie_type;
368   unsigned char tls_gd_type;
369
370   /* These fields are only used in single-GOT mode; in multi-GOT mode there
371      is one mips_got_entry per GOT entry, so the offset is stored
372      there.  In single-GOT mode there may be many mips_got_entry
373      structures all referring to the same GOT slot.  */
374   bfd_vma tls_ie_got_offset;
375   bfd_vma tls_gd_got_offset;
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
414 /* MIPS ELF linker hash table.  */
415
416 struct mips_elf_link_hash_table
417 {
418   struct elf_link_hash_table root;
419
420   /* The number of .rtproc entries.  */
421   bfd_size_type procedure_count;
422
423   /* The size of the .compact_rel section (if SGI_COMPAT).  */
424   bfd_size_type compact_rel_size;
425
426   /* This flag indicates that the value of DT_MIPS_RLD_MAP dynamic entry
427      is set to the address of __rld_obj_head as in IRIX5 and IRIX6.  */
428   bfd_boolean use_rld_obj_head;
429
430   /* The  __rld_map or __rld_obj_head symbol. */
431   struct elf_link_hash_entry *rld_symbol;
432
433   /* This is set if we see any mips16 stub sections.  */
434   bfd_boolean mips16_stubs_seen;
435
436   /* True if we can generate copy relocs and PLTs.  */
437   bfd_boolean use_plts_and_copy_relocs;
438
439   /* True if we're generating code for VxWorks.  */
440   bfd_boolean is_vxworks;
441
442   /* True if we already reported the small-data section overflow.  */
443   bfd_boolean small_data_overflow_reported;
444
445   /* Shortcuts to some dynamic sections, or NULL if they are not
446      being used.  */
447   asection *srelbss;
448   asection *sdynbss;
449   asection *srelplt;
450   asection *srelplt2;
451   asection *sgotplt;
452   asection *splt;
453   asection *sstubs;
454   asection *sgot;
455
456   /* The master GOT information.  */
457   struct mips_got_info *got_info;
458
459   /* The global symbol in the GOT with the lowest index in the dynamic
460      symbol table.  */
461   struct elf_link_hash_entry *global_gotsym;
462
463   /* The size of the PLT header in bytes.  */
464   bfd_vma plt_header_size;
465
466   /* The size of a PLT entry in bytes.  */
467   bfd_vma plt_entry_size;
468
469   /* The number of functions that need a lazy-binding stub.  */
470   bfd_vma lazy_stub_count;
471
472   /* The size of a function stub entry in bytes.  */
473   bfd_vma function_stub_size;
474
475   /* The number of reserved entries at the beginning of the GOT.  */
476   unsigned int reserved_gotno;
477
478   /* The section used for mips_elf_la25_stub trampolines.
479      See the comment above that structure for details.  */
480   asection *strampoline;
481
482   /* A table of mips_elf_la25_stubs, indexed by (input_section, offset)
483      pairs.  */
484   htab_t la25_stubs;
485
486   /* A function FN (NAME, IS, OS) that creates a new input section
487      called NAME and links it to output section OS.  If IS is nonnull,
488      the new section should go immediately before it, otherwise it
489      should go at the (current) beginning of OS.
490
491      The function returns the new section on success, otherwise it
492      returns null.  */
493   asection *(*add_stub_section) (const char *, asection *, asection *);
494 };
495
496 /* Get the MIPS ELF linker hash table from a link_info structure.  */
497
498 #define mips_elf_hash_table(p) \
499   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
500   == MIPS_ELF_DATA ? ((struct mips_elf_link_hash_table *) ((p)->hash)) : NULL)
501
502 /* A structure used to communicate with htab_traverse callbacks.  */
503 struct mips_htab_traverse_info
504 {
505   /* The usual link-wide information.  */
506   struct bfd_link_info *info;
507   bfd *output_bfd;
508
509   /* Starts off FALSE and is set to TRUE if the link should be aborted.  */
510   bfd_boolean error;
511 };
512
513 /* MIPS ELF private object data.  */
514
515 struct mips_elf_obj_tdata
516 {
517   /* Generic ELF private object data.  */
518   struct elf_obj_tdata root;
519
520   /* Input BFD providing Tag_GNU_MIPS_ABI_FP attribute for output.  */
521   bfd *abi_fp_bfd;
522 };
523
524 /* Get MIPS ELF private object data from BFD's tdata.  */
525
526 #define mips_elf_tdata(bfd) \
527   ((struct mips_elf_obj_tdata *) (bfd)->tdata.any)
528
529 #define TLS_RELOC_P(r_type) \
530   (r_type == R_MIPS_TLS_DTPMOD32                \
531    || r_type == R_MIPS_TLS_DTPMOD64             \
532    || r_type == R_MIPS_TLS_DTPREL32             \
533    || r_type == R_MIPS_TLS_DTPREL64             \
534    || r_type == R_MIPS_TLS_GD                   \
535    || r_type == R_MIPS_TLS_LDM                  \
536    || r_type == R_MIPS_TLS_DTPREL_HI16          \
537    || r_type == R_MIPS_TLS_DTPREL_LO16          \
538    || r_type == R_MIPS_TLS_GOTTPREL             \
539    || r_type == R_MIPS_TLS_TPREL32              \
540    || r_type == R_MIPS_TLS_TPREL64              \
541    || r_type == R_MIPS_TLS_TPREL_HI16           \
542    || r_type == R_MIPS_TLS_TPREL_LO16           \
543    || r_type == R_MIPS16_TLS_GD                 \
544    || r_type == R_MIPS16_TLS_LDM                \
545    || r_type == R_MIPS16_TLS_DTPREL_HI16        \
546    || r_type == R_MIPS16_TLS_DTPREL_LO16        \
547    || r_type == R_MIPS16_TLS_GOTTPREL           \
548    || r_type == R_MIPS16_TLS_TPREL_HI16         \
549    || r_type == R_MIPS16_TLS_TPREL_LO16         \
550    || r_type == R_MICROMIPS_TLS_GD              \
551    || r_type == R_MICROMIPS_TLS_LDM             \
552    || r_type == R_MICROMIPS_TLS_DTPREL_HI16     \
553    || r_type == R_MICROMIPS_TLS_DTPREL_LO16     \
554    || r_type == R_MICROMIPS_TLS_GOTTPREL        \
555    || r_type == R_MICROMIPS_TLS_TPREL_HI16      \
556    || r_type == R_MICROMIPS_TLS_TPREL_LO16)
557
558 /* Structure used to pass information to mips_elf_output_extsym.  */
559
560 struct extsym_info
561 {
562   bfd *abfd;
563   struct bfd_link_info *info;
564   struct ecoff_debug_info *debug;
565   const struct ecoff_debug_swap *swap;
566   bfd_boolean failed;
567 };
568
569 /* The names of the runtime procedure table symbols used on IRIX5.  */
570
571 static const char * const mips_elf_dynsym_rtproc_names[] =
572 {
573   "_procedure_table",
574   "_procedure_string_table",
575   "_procedure_table_size",
576   NULL
577 };
578
579 /* These structures are used to generate the .compact_rel section on
580    IRIX5.  */
581
582 typedef struct
583 {
584   unsigned long id1;            /* Always one?  */
585   unsigned long num;            /* Number of compact relocation entries.  */
586   unsigned long id2;            /* Always two?  */
587   unsigned long offset;         /* The file offset of the first relocation.  */
588   unsigned long reserved0;      /* Zero?  */
589   unsigned long reserved1;      /* Zero?  */
590 } Elf32_compact_rel;
591
592 typedef struct
593 {
594   bfd_byte id1[4];
595   bfd_byte num[4];
596   bfd_byte id2[4];
597   bfd_byte offset[4];
598   bfd_byte reserved0[4];
599   bfd_byte reserved1[4];
600 } Elf32_External_compact_rel;
601
602 typedef struct
603 {
604   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
605   unsigned int rtype : 4;       /* Relocation types. See below.  */
606   unsigned int dist2to : 8;
607   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
608   unsigned long konst;          /* KONST field. See below.  */
609   unsigned long vaddr;          /* VADDR to be relocated.  */
610 } Elf32_crinfo;
611
612 typedef struct
613 {
614   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
615   unsigned int rtype : 4;       /* Relocation types. See below.  */
616   unsigned int dist2to : 8;
617   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
618   unsigned long konst;          /* KONST field. See below.  */
619 } Elf32_crinfo2;
620
621 typedef struct
622 {
623   bfd_byte info[4];
624   bfd_byte konst[4];
625   bfd_byte vaddr[4];
626 } Elf32_External_crinfo;
627
628 typedef struct
629 {
630   bfd_byte info[4];
631   bfd_byte konst[4];
632 } Elf32_External_crinfo2;
633
634 /* These are the constants used to swap the bitfields in a crinfo.  */
635
636 #define CRINFO_CTYPE (0x1)
637 #define CRINFO_CTYPE_SH (31)
638 #define CRINFO_RTYPE (0xf)
639 #define CRINFO_RTYPE_SH (27)
640 #define CRINFO_DIST2TO (0xff)
641 #define CRINFO_DIST2TO_SH (19)
642 #define CRINFO_RELVADDR (0x7ffff)
643 #define CRINFO_RELVADDR_SH (0)
644
645 /* A compact relocation info has long (3 words) or short (2 words)
646    formats.  A short format doesn't have VADDR field and relvaddr
647    fields contains ((VADDR - vaddr of the previous entry) >> 2).  */
648 #define CRF_MIPS_LONG                   1
649 #define CRF_MIPS_SHORT                  0
650
651 /* There are 4 types of compact relocation at least. The value KONST
652    has different meaning for each type:
653
654    (type)               (konst)
655    CT_MIPS_REL32        Address in data
656    CT_MIPS_WORD         Address in word (XXX)
657    CT_MIPS_GPHI_LO      GP - vaddr
658    CT_MIPS_JMPAD        Address to jump
659    */
660
661 #define CRT_MIPS_REL32                  0xa
662 #define CRT_MIPS_WORD                   0xb
663 #define CRT_MIPS_GPHI_LO                0xc
664 #define CRT_MIPS_JMPAD                  0xd
665
666 #define mips_elf_set_cr_format(x,format)        ((x).ctype = (format))
667 #define mips_elf_set_cr_type(x,type)            ((x).rtype = (type))
668 #define mips_elf_set_cr_dist2to(x,v)            ((x).dist2to = (v))
669 #define mips_elf_set_cr_relvaddr(x,d)           ((x).relvaddr = (d)<<2)
670 \f
671 /* The structure of the runtime procedure descriptor created by the
672    loader for use by the static exception system.  */
673
674 typedef struct runtime_pdr {
675         bfd_vma adr;            /* Memory address of start of procedure.  */
676         long    regmask;        /* Save register mask.  */
677         long    regoffset;      /* Save register offset.  */
678         long    fregmask;       /* Save floating point register mask.  */
679         long    fregoffset;     /* Save floating point register offset.  */
680         long    frameoffset;    /* Frame size.  */
681         short   framereg;       /* Frame pointer register.  */
682         short   pcreg;          /* Offset or reg of return pc.  */
683         long    irpss;          /* Index into the runtime string table.  */
684         long    reserved;
685         struct exception_info *exception_info;/* Pointer to exception array.  */
686 } RPDR, *pRPDR;
687 #define cbRPDR sizeof (RPDR)
688 #define rpdNil ((pRPDR) 0)
689 \f
690 static struct mips_got_entry *mips_elf_create_local_got_entry
691   (bfd *, struct bfd_link_info *, bfd *, bfd_vma, unsigned long,
692    struct mips_elf_link_hash_entry *, int);
693 static bfd_boolean mips_elf_sort_hash_table_f
694   (struct mips_elf_link_hash_entry *, void *);
695 static bfd_vma mips_elf_high
696   (bfd_vma);
697 static bfd_boolean mips_elf_create_dynamic_relocation
698   (bfd *, struct bfd_link_info *, const Elf_Internal_Rela *,
699    struct mips_elf_link_hash_entry *, asection *, bfd_vma,
700    bfd_vma *, asection *);
701 static bfd_vma mips_elf_adjust_gp
702   (bfd *, struct mips_got_info *, bfd *);
703 static struct mips_got_info *mips_elf_got_for_ibfd
704   (struct mips_got_info *, bfd *);
705
706 /* This will be used when we sort the dynamic relocation records.  */
707 static bfd *reldyn_sorting_bfd;
708
709 /* True if ABFD is for CPUs with load interlocking that include
710    non-MIPS1 CPUs and R3900.  */
711 #define LOAD_INTERLOCKS_P(abfd) \
712   (   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) != E_MIPS_ARCH_1) \
713    || ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_3900))
714
715 /* True if ABFD is for CPUs that are faster if JAL is converted to BAL.
716    This should be safe for all architectures.  We enable this predicate
717    for RM9000 for now.  */
718 #define JAL_TO_BAL_P(abfd) \
719   ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_9000)
720
721 /* True if ABFD is for CPUs that are faster if JALR is converted to BAL.
722    This should be safe for all architectures.  We enable this predicate for
723    all CPUs.  */
724 #define JALR_TO_BAL_P(abfd) 1
725
726 /* True if ABFD is for CPUs that are faster if JR is converted to B.
727    This should be safe for all architectures.  We enable this predicate for
728    all CPUs.  */
729 #define JR_TO_B_P(abfd) 1
730
731 /* True if ABFD is a PIC object.  */
732 #define PIC_OBJECT_P(abfd) \
733   ((elf_elfheader (abfd)->e_flags & EF_MIPS_PIC) != 0)
734
735 /* Nonzero if ABFD is using the N32 ABI.  */
736 #define ABI_N32_P(abfd) \
737   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI2) != 0)
738
739 /* Nonzero if ABFD is using the N64 ABI.  */
740 #define ABI_64_P(abfd) \
741   (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS64)
742
743 /* Nonzero if ABFD is using NewABI conventions.  */
744 #define NEWABI_P(abfd) (ABI_N32_P (abfd) || ABI_64_P (abfd))
745
746 /* The IRIX compatibility level we are striving for.  */
747 #define IRIX_COMPAT(abfd) \
748   (get_elf_backend_data (abfd)->elf_backend_mips_irix_compat (abfd))
749
750 /* Whether we are trying to be compatible with IRIX at all.  */
751 #define SGI_COMPAT(abfd) \
752   (IRIX_COMPAT (abfd) != ict_none)
753
754 /* The name of the options section.  */
755 #define MIPS_ELF_OPTIONS_SECTION_NAME(abfd) \
756   (NEWABI_P (abfd) ? ".MIPS.options" : ".options")
757
758 /* True if NAME is the recognized name of any SHT_MIPS_OPTIONS section.
759    Some IRIX system files do not use MIPS_ELF_OPTIONS_SECTION_NAME.  */
760 #define MIPS_ELF_OPTIONS_SECTION_NAME_P(NAME) \
761   (strcmp (NAME, ".MIPS.options") == 0 || strcmp (NAME, ".options") == 0)
762
763 /* Whether the section is readonly.  */
764 #define MIPS_ELF_READONLY_SECTION(sec) \
765   ((sec->flags & (SEC_ALLOC | SEC_LOAD | SEC_READONLY))         \
766    == (SEC_ALLOC | SEC_LOAD | SEC_READONLY))
767
768 /* The name of the stub section.  */
769 #define MIPS_ELF_STUB_SECTION_NAME(abfd) ".MIPS.stubs"
770
771 /* The size of an external REL relocation.  */
772 #define MIPS_ELF_REL_SIZE(abfd) \
773   (get_elf_backend_data (abfd)->s->sizeof_rel)
774
775 /* The size of an external RELA relocation.  */
776 #define MIPS_ELF_RELA_SIZE(abfd) \
777   (get_elf_backend_data (abfd)->s->sizeof_rela)
778
779 /* The size of an external dynamic table entry.  */
780 #define MIPS_ELF_DYN_SIZE(abfd) \
781   (get_elf_backend_data (abfd)->s->sizeof_dyn)
782
783 /* The size of a GOT entry.  */
784 #define MIPS_ELF_GOT_SIZE(abfd) \
785   (get_elf_backend_data (abfd)->s->arch_size / 8)
786
787 /* The size of the .rld_map section. */
788 #define MIPS_ELF_RLD_MAP_SIZE(abfd) \
789   (get_elf_backend_data (abfd)->s->arch_size / 8)
790
791 /* The size of a symbol-table entry.  */
792 #define MIPS_ELF_SYM_SIZE(abfd) \
793   (get_elf_backend_data (abfd)->s->sizeof_sym)
794
795 /* The default alignment for sections, as a power of two.  */
796 #define MIPS_ELF_LOG_FILE_ALIGN(abfd)                           \
797   (get_elf_backend_data (abfd)->s->log_file_align)
798
799 /* Get word-sized data.  */
800 #define MIPS_ELF_GET_WORD(abfd, ptr) \
801   (ABI_64_P (abfd) ? bfd_get_64 (abfd, ptr) : bfd_get_32 (abfd, ptr))
802
803 /* Put out word-sized data.  */
804 #define MIPS_ELF_PUT_WORD(abfd, val, ptr)       \
805   (ABI_64_P (abfd)                              \
806    ? bfd_put_64 (abfd, val, ptr)                \
807    : bfd_put_32 (abfd, val, ptr))
808
809 /* The opcode for word-sized loads (LW or LD).  */
810 #define MIPS_ELF_LOAD_WORD(abfd) \
811   (ABI_64_P (abfd) ? 0xdc000000 : 0x8c000000)
812
813 /* Add a dynamic symbol table-entry.  */
814 #define MIPS_ELF_ADD_DYNAMIC_ENTRY(info, tag, val)      \
815   _bfd_elf_add_dynamic_entry (info, tag, val)
816
817 #define MIPS_ELF_RTYPE_TO_HOWTO(abfd, rtype, rela)                      \
818   (get_elf_backend_data (abfd)->elf_backend_mips_rtype_to_howto (rtype, rela))
819
820 /* The name of the dynamic relocation section.  */
821 #define MIPS_ELF_REL_DYN_NAME(INFO) \
822   (mips_elf_hash_table (INFO)->is_vxworks ? ".rela.dyn" : ".rel.dyn")
823
824 /* In case we're on a 32-bit machine, construct a 64-bit "-1" value
825    from smaller values.  Start with zero, widen, *then* decrement.  */
826 #define MINUS_ONE       (((bfd_vma)0) - 1)
827 #define MINUS_TWO       (((bfd_vma)0) - 2)
828
829 /* The value to write into got[1] for SVR4 targets, to identify it is
830    a GNU object.  The dynamic linker can then use got[1] to store the
831    module pointer.  */
832 #define MIPS_ELF_GNU_GOT1_MASK(abfd) \
833   ((bfd_vma) 1 << (ABI_64_P (abfd) ? 63 : 31))
834
835 /* The offset of $gp from the beginning of the .got section.  */
836 #define ELF_MIPS_GP_OFFSET(INFO) \
837   (mips_elf_hash_table (INFO)->is_vxworks ? 0x0 : 0x7ff0)
838
839 /* The maximum size of the GOT for it to be addressable using 16-bit
840    offsets from $gp.  */
841 #define MIPS_ELF_GOT_MAX_SIZE(INFO) (ELF_MIPS_GP_OFFSET (INFO) + 0x7fff)
842
843 /* Instructions which appear in a stub.  */
844 #define STUB_LW(abfd)                                                   \
845   ((ABI_64_P (abfd)                                                     \
846     ? 0xdf998010                                /* ld t9,0x8010(gp) */  \
847     : 0x8f998010))                              /* lw t9,0x8010(gp) */
848 #define STUB_MOVE(abfd)                                                 \
849    ((ABI_64_P (abfd)                                                    \
850      ? 0x03e0782d                               /* daddu t7,ra */       \
851      : 0x03e07821))                             /* addu t7,ra */
852 #define STUB_LUI(VAL) (0x3c180000 + (VAL))      /* lui t8,VAL */
853 #define STUB_JALR 0x0320f809                    /* jalr t9,ra */
854 #define STUB_ORI(VAL) (0x37180000 + (VAL))      /* ori t8,t8,VAL */
855 #define STUB_LI16U(VAL) (0x34180000 + (VAL))    /* ori t8,zero,VAL unsigned */
856 #define STUB_LI16S(abfd, VAL)                                           \
857    ((ABI_64_P (abfd)                                                    \
858     ? (0x64180000 + (VAL))      /* daddiu t8,zero,VAL sign extended */  \
859     : (0x24180000 + (VAL))))    /* addiu t8,zero,VAL sign extended */
860
861 #define MIPS_FUNCTION_STUB_NORMAL_SIZE 16
862 #define MIPS_FUNCTION_STUB_BIG_SIZE 20
863
864 /* The name of the dynamic interpreter.  This is put in the .interp
865    section.  */
866
867 #define ELF_DYNAMIC_INTERPRETER(abfd)           \
868    (ABI_N32_P (abfd) ? "/usr/lib32/libc.so.1"   \
869     : ABI_64_P (abfd) ? "/usr/lib64/libc.so.1"  \
870     : "/usr/lib/libc.so.1")
871
872 #ifdef BFD64
873 #define MNAME(bfd,pre,pos) \
874   (ABI_64_P (bfd) ? CONCAT4 (pre,64,_,pos) : CONCAT4 (pre,32,_,pos))
875 #define ELF_R_SYM(bfd, i)                                       \
876   (ABI_64_P (bfd) ? ELF64_R_SYM (i) : ELF32_R_SYM (i))
877 #define ELF_R_TYPE(bfd, i)                                      \
878   (ABI_64_P (bfd) ? ELF64_MIPS_R_TYPE (i) : ELF32_R_TYPE (i))
879 #define ELF_R_INFO(bfd, s, t)                                   \
880   (ABI_64_P (bfd) ? ELF64_R_INFO (s, t) : ELF32_R_INFO (s, t))
881 #else
882 #define MNAME(bfd,pre,pos) CONCAT4 (pre,32,_,pos)
883 #define ELF_R_SYM(bfd, i)                                       \
884   (ELF32_R_SYM (i))
885 #define ELF_R_TYPE(bfd, i)                                      \
886   (ELF32_R_TYPE (i))
887 #define ELF_R_INFO(bfd, s, t)                                   \
888   (ELF32_R_INFO (s, t))
889 #endif
890 \f
891   /* The mips16 compiler uses a couple of special sections to handle
892      floating point arguments.
893
894      Section names that look like .mips16.fn.FNNAME contain stubs that
895      copy floating point arguments from the fp regs to the gp regs and
896      then jump to FNNAME.  If any 32 bit function calls FNNAME, the
897      call should be redirected to the stub instead.  If no 32 bit
898      function calls FNNAME, the stub should be discarded.  We need to
899      consider any reference to the function, not just a call, because
900      if the address of the function is taken we will need the stub,
901      since the address might be passed to a 32 bit function.
902
903      Section names that look like .mips16.call.FNNAME contain stubs
904      that copy floating point arguments from the gp regs to the fp
905      regs and then jump to FNNAME.  If FNNAME is a 32 bit function,
906      then any 16 bit function that calls FNNAME should be redirected
907      to the stub instead.  If FNNAME is not a 32 bit function, the
908      stub should be discarded.
909
910      .mips16.call.fp.FNNAME sections are similar, but contain stubs
911      which call FNNAME and then copy the return value from the fp regs
912      to the gp regs.  These stubs store the return value in $18 while
913      calling FNNAME; any function which might call one of these stubs
914      must arrange to save $18 around the call.  (This case is not
915      needed for 32 bit functions that call 16 bit functions, because
916      16 bit functions always return floating point values in both
917      $f0/$f1 and $2/$3.)
918
919      Note that in all cases FNNAME might be defined statically.
920      Therefore, FNNAME is not used literally.  Instead, the relocation
921      information will indicate which symbol the section is for.
922
923      We record any stubs that we find in the symbol table.  */
924
925 #define FN_STUB ".mips16.fn."
926 #define CALL_STUB ".mips16.call."
927 #define CALL_FP_STUB ".mips16.call.fp."
928
929 #define FN_STUB_P(name) CONST_STRNEQ (name, FN_STUB)
930 #define CALL_STUB_P(name) CONST_STRNEQ (name, CALL_STUB)
931 #define CALL_FP_STUB_P(name) CONST_STRNEQ (name, CALL_FP_STUB)
932 \f
933 /* The format of the first PLT entry in an O32 executable.  */
934 static const bfd_vma mips_o32_exec_plt0_entry[] =
935 {
936   0x3c1c0000,   /* lui $28, %hi(&GOTPLT[0])                             */
937   0x8f990000,   /* lw $25, %lo(&GOTPLT[0])($28)                         */
938   0x279c0000,   /* addiu $28, $28, %lo(&GOTPLT[0])                      */
939   0x031cc023,   /* subu $24, $24, $28                                   */
940   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
941   0x0018c082,   /* srl $24, $24, 2                                      */
942   0x0320f809,   /* jalr $25                                             */
943   0x2718fffe    /* subu $24, $24, 2                                     */
944 };
945
946 /* The format of the first PLT entry in an N32 executable.  Different
947    because gp ($28) is not available; we use t2 ($14) instead.  */
948 static const bfd_vma mips_n32_exec_plt0_entry[] =
949 {
950   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
951   0x8dd90000,   /* lw $25, %lo(&GOTPLT[0])($14)                         */
952   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
953   0x030ec023,   /* subu $24, $24, $14                                   */
954   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
955   0x0018c082,   /* srl $24, $24, 2                                      */
956   0x0320f809,   /* jalr $25                                             */
957   0x2718fffe    /* subu $24, $24, 2                                     */
958 };
959
960 /* The format of the first PLT entry in an N64 executable.  Different
961    from N32 because of the increased size of GOT entries.  */
962 static const bfd_vma mips_n64_exec_plt0_entry[] =
963 {
964   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
965   0xddd90000,   /* ld $25, %lo(&GOTPLT[0])($14)                         */
966   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
967   0x030ec023,   /* subu $24, $24, $14                                   */
968   0x03e0782d,   /* move $15, $31        # 64-bit move (daddu)           */
969   0x0018c0c2,   /* srl $24, $24, 3                                      */
970   0x0320f809,   /* jalr $25                                             */
971   0x2718fffe    /* subu $24, $24, 2                                     */
972 };
973
974 /* The format of subsequent PLT entries.  */
975 static const bfd_vma mips_exec_plt_entry[] =
976 {
977   0x3c0f0000,   /* lui $15, %hi(.got.plt entry)                 */
978   0x01f90000,   /* l[wd] $25, %lo(.got.plt entry)($15)          */
979   0x25f80000,   /* addiu $24, $15, %lo(.got.plt entry)          */
980   0x03200008    /* jr $25                                       */
981 };
982
983 /* The format of the first PLT entry in a VxWorks executable.  */
984 static const bfd_vma mips_vxworks_exec_plt0_entry[] =
985 {
986   0x3c190000,   /* lui t9, %hi(_GLOBAL_OFFSET_TABLE_)           */
987   0x27390000,   /* addiu t9, t9, %lo(_GLOBAL_OFFSET_TABLE_)     */
988   0x8f390008,   /* lw t9, 8(t9)                                 */
989   0x00000000,   /* nop                                          */
990   0x03200008,   /* jr t9                                        */
991   0x00000000    /* nop                                          */
992 };
993
994 /* The format of subsequent PLT entries.  */
995 static const bfd_vma mips_vxworks_exec_plt_entry[] =
996 {
997   0x10000000,   /* b .PLT_resolver                      */
998   0x24180000,   /* li t8, <pltindex>                    */
999   0x3c190000,   /* lui t9, %hi(<.got.plt slot>)         */
1000   0x27390000,   /* addiu t9, t9, %lo(<.got.plt slot>)   */
1001   0x8f390000,   /* lw t9, 0(t9)                         */
1002   0x00000000,   /* nop                                  */
1003   0x03200008,   /* jr t9                                */
1004   0x00000000    /* nop                                  */
1005 };
1006
1007 /* The format of the first PLT entry in a VxWorks shared object.  */
1008 static const bfd_vma mips_vxworks_shared_plt0_entry[] =
1009 {
1010   0x8f990008,   /* lw t9, 8(gp)         */
1011   0x00000000,   /* nop                  */
1012   0x03200008,   /* jr t9                */
1013   0x00000000,   /* nop                  */
1014   0x00000000,   /* nop                  */
1015   0x00000000    /* nop                  */
1016 };
1017
1018 /* The format of subsequent PLT entries.  */
1019 static const bfd_vma mips_vxworks_shared_plt_entry[] =
1020 {
1021   0x10000000,   /* b .PLT_resolver      */
1022   0x24180000    /* li t8, <pltindex>    */
1023 };
1024 \f
1025 /* microMIPS 32-bit opcode helper installer.  */
1026
1027 static void
1028 bfd_put_micromips_32 (const bfd *abfd, bfd_vma opcode, bfd_byte *ptr)
1029 {
1030   bfd_put_16 (abfd, (opcode >> 16) & 0xffff, ptr);
1031   bfd_put_16 (abfd,  opcode        & 0xffff, ptr + 2);
1032 }
1033
1034 /* microMIPS 32-bit opcode helper retriever.  */
1035
1036 static bfd_vma
1037 bfd_get_micromips_32 (const bfd *abfd, const bfd_byte *ptr)
1038 {
1039   return (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
1040 }
1041 \f
1042 /* Look up an entry in a MIPS ELF linker hash table.  */
1043
1044 #define mips_elf_link_hash_lookup(table, string, create, copy, follow)  \
1045   ((struct mips_elf_link_hash_entry *)                                  \
1046    elf_link_hash_lookup (&(table)->root, (string), (create),            \
1047                          (copy), (follow)))
1048
1049 /* Traverse a MIPS ELF linker hash table.  */
1050
1051 #define mips_elf_link_hash_traverse(table, func, info)                  \
1052   (elf_link_hash_traverse                                               \
1053    (&(table)->root,                                                     \
1054     (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func),    \
1055     (info)))
1056
1057 /* Find the base offsets for thread-local storage in this object,
1058    for GD/LD and IE/LE respectively.  */
1059
1060 #define TP_OFFSET 0x7000
1061 #define DTP_OFFSET 0x8000
1062
1063 static bfd_vma
1064 dtprel_base (struct bfd_link_info *info)
1065 {
1066   /* If tls_sec is NULL, we should have signalled an error already.  */
1067   if (elf_hash_table (info)->tls_sec == NULL)
1068     return 0;
1069   return elf_hash_table (info)->tls_sec->vma + DTP_OFFSET;
1070 }
1071
1072 static bfd_vma
1073 tprel_base (struct bfd_link_info *info)
1074 {
1075   /* If tls_sec is NULL, we should have signalled an error already.  */
1076   if (elf_hash_table (info)->tls_sec == NULL)
1077     return 0;
1078   return elf_hash_table (info)->tls_sec->vma + TP_OFFSET;
1079 }
1080
1081 /* Create an entry in a MIPS ELF linker hash table.  */
1082
1083 static struct bfd_hash_entry *
1084 mips_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
1085                             struct bfd_hash_table *table, const char *string)
1086 {
1087   struct mips_elf_link_hash_entry *ret =
1088     (struct mips_elf_link_hash_entry *) entry;
1089
1090   /* Allocate the structure if it has not already been allocated by a
1091      subclass.  */
1092   if (ret == NULL)
1093     ret = bfd_hash_allocate (table, sizeof (struct mips_elf_link_hash_entry));
1094   if (ret == NULL)
1095     return (struct bfd_hash_entry *) ret;
1096
1097   /* Call the allocation method of the superclass.  */
1098   ret = ((struct mips_elf_link_hash_entry *)
1099          _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret,
1100                                      table, string));
1101   if (ret != NULL)
1102     {
1103       /* Set local fields.  */
1104       memset (&ret->esym, 0, sizeof (EXTR));
1105       /* We use -2 as a marker to indicate that the information has
1106          not been set.  -1 means there is no associated ifd.  */
1107       ret->esym.ifd = -2;
1108       ret->la25_stub = 0;
1109       ret->possibly_dynamic_relocs = 0;
1110       ret->fn_stub = NULL;
1111       ret->call_stub = NULL;
1112       ret->call_fp_stub = NULL;
1113       ret->tls_ie_type = GOT_NORMAL;
1114       ret->tls_gd_type = GOT_NORMAL;
1115       ret->global_got_area = GGA_NONE;
1116       ret->got_only_for_calls = TRUE;
1117       ret->readonly_reloc = FALSE;
1118       ret->has_static_relocs = FALSE;
1119       ret->no_fn_stub = FALSE;
1120       ret->need_fn_stub = FALSE;
1121       ret->has_nonpic_branches = FALSE;
1122       ret->needs_lazy_stub = FALSE;
1123     }
1124
1125   return (struct bfd_hash_entry *) ret;
1126 }
1127
1128 /* Allocate MIPS ELF private object data.  */
1129
1130 bfd_boolean
1131 _bfd_mips_elf_mkobject (bfd *abfd)
1132 {
1133   return bfd_elf_allocate_object (abfd, sizeof (struct mips_elf_obj_tdata),
1134                                   MIPS_ELF_DATA);
1135 }
1136
1137 bfd_boolean
1138 _bfd_mips_elf_new_section_hook (bfd *abfd, asection *sec)
1139 {
1140   if (!sec->used_by_bfd)
1141     {
1142       struct _mips_elf_section_data *sdata;
1143       bfd_size_type amt = sizeof (*sdata);
1144
1145       sdata = bfd_zalloc (abfd, amt);
1146       if (sdata == NULL)
1147         return FALSE;
1148       sec->used_by_bfd = sdata;
1149     }
1150
1151   return _bfd_elf_new_section_hook (abfd, sec);
1152 }
1153 \f
1154 /* Read ECOFF debugging information from a .mdebug section into a
1155    ecoff_debug_info structure.  */
1156
1157 bfd_boolean
1158 _bfd_mips_elf_read_ecoff_info (bfd *abfd, asection *section,
1159                                struct ecoff_debug_info *debug)
1160 {
1161   HDRR *symhdr;
1162   const struct ecoff_debug_swap *swap;
1163   char *ext_hdr;
1164
1165   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1166   memset (debug, 0, sizeof (*debug));
1167
1168   ext_hdr = bfd_malloc (swap->external_hdr_size);
1169   if (ext_hdr == NULL && swap->external_hdr_size != 0)
1170     goto error_return;
1171
1172   if (! bfd_get_section_contents (abfd, section, ext_hdr, 0,
1173                                   swap->external_hdr_size))
1174     goto error_return;
1175
1176   symhdr = &debug->symbolic_header;
1177   (*swap->swap_hdr_in) (abfd, ext_hdr, symhdr);
1178
1179   /* The symbolic header contains absolute file offsets and sizes to
1180      read.  */
1181 #define READ(ptr, offset, count, size, type)                            \
1182   if (symhdr->count == 0)                                               \
1183     debug->ptr = NULL;                                                  \
1184   else                                                                  \
1185     {                                                                   \
1186       bfd_size_type amt = (bfd_size_type) size * symhdr->count;         \
1187       debug->ptr = bfd_malloc (amt);                                    \
1188       if (debug->ptr == NULL)                                           \
1189         goto error_return;                                              \
1190       if (bfd_seek (abfd, symhdr->offset, SEEK_SET) != 0                \
1191           || bfd_bread (debug->ptr, amt, abfd) != amt)                  \
1192         goto error_return;                                              \
1193     }
1194
1195   READ (line, cbLineOffset, cbLine, sizeof (unsigned char), unsigned char *);
1196   READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *);
1197   READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *);
1198   READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *);
1199   READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *);
1200   READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext),
1201         union aux_ext *);
1202   READ (ss, cbSsOffset, issMax, sizeof (char), char *);
1203   READ (ssext, cbSsExtOffset, issExtMax, sizeof (char), char *);
1204   READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *);
1205   READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *);
1206   READ (external_ext, cbExtOffset, iextMax, swap->external_ext_size, void *);
1207 #undef READ
1208
1209   debug->fdr = NULL;
1210
1211   return TRUE;
1212
1213  error_return:
1214   if (ext_hdr != NULL)
1215     free (ext_hdr);
1216   if (debug->line != NULL)
1217     free (debug->line);
1218   if (debug->external_dnr != NULL)
1219     free (debug->external_dnr);
1220   if (debug->external_pdr != NULL)
1221     free (debug->external_pdr);
1222   if (debug->external_sym != NULL)
1223     free (debug->external_sym);
1224   if (debug->external_opt != NULL)
1225     free (debug->external_opt);
1226   if (debug->external_aux != NULL)
1227     free (debug->external_aux);
1228   if (debug->ss != NULL)
1229     free (debug->ss);
1230   if (debug->ssext != NULL)
1231     free (debug->ssext);
1232   if (debug->external_fdr != NULL)
1233     free (debug->external_fdr);
1234   if (debug->external_rfd != NULL)
1235     free (debug->external_rfd);
1236   if (debug->external_ext != NULL)
1237     free (debug->external_ext);
1238   return FALSE;
1239 }
1240 \f
1241 /* Swap RPDR (runtime procedure table entry) for output.  */
1242
1243 static void
1244 ecoff_swap_rpdr_out (bfd *abfd, const RPDR *in, struct rpdr_ext *ex)
1245 {
1246   H_PUT_S32 (abfd, in->adr, ex->p_adr);
1247   H_PUT_32 (abfd, in->regmask, ex->p_regmask);
1248   H_PUT_32 (abfd, in->regoffset, ex->p_regoffset);
1249   H_PUT_32 (abfd, in->fregmask, ex->p_fregmask);
1250   H_PUT_32 (abfd, in->fregoffset, ex->p_fregoffset);
1251   H_PUT_32 (abfd, in->frameoffset, ex->p_frameoffset);
1252
1253   H_PUT_16 (abfd, in->framereg, ex->p_framereg);
1254   H_PUT_16 (abfd, in->pcreg, ex->p_pcreg);
1255
1256   H_PUT_32 (abfd, in->irpss, ex->p_irpss);
1257 }
1258
1259 /* Create a runtime procedure table from the .mdebug section.  */
1260
1261 static bfd_boolean
1262 mips_elf_create_procedure_table (void *handle, bfd *abfd,
1263                                  struct bfd_link_info *info, asection *s,
1264                                  struct ecoff_debug_info *debug)
1265 {
1266   const struct ecoff_debug_swap *swap;
1267   HDRR *hdr = &debug->symbolic_header;
1268   RPDR *rpdr, *rp;
1269   struct rpdr_ext *erp;
1270   void *rtproc;
1271   struct pdr_ext *epdr;
1272   struct sym_ext *esym;
1273   char *ss, **sv;
1274   char *str;
1275   bfd_size_type size;
1276   bfd_size_type count;
1277   unsigned long sindex;
1278   unsigned long i;
1279   PDR pdr;
1280   SYMR sym;
1281   const char *no_name_func = _("static procedure (no name)");
1282
1283   epdr = NULL;
1284   rpdr = NULL;
1285   esym = NULL;
1286   ss = NULL;
1287   sv = NULL;
1288
1289   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1290
1291   sindex = strlen (no_name_func) + 1;
1292   count = hdr->ipdMax;
1293   if (count > 0)
1294     {
1295       size = swap->external_pdr_size;
1296
1297       epdr = bfd_malloc (size * count);
1298       if (epdr == NULL)
1299         goto error_return;
1300
1301       if (! _bfd_ecoff_get_accumulated_pdr (handle, (bfd_byte *) epdr))
1302         goto error_return;
1303
1304       size = sizeof (RPDR);
1305       rp = rpdr = bfd_malloc (size * count);
1306       if (rpdr == NULL)
1307         goto error_return;
1308
1309       size = sizeof (char *);
1310       sv = bfd_malloc (size * count);
1311       if (sv == NULL)
1312         goto error_return;
1313
1314       count = hdr->isymMax;
1315       size = swap->external_sym_size;
1316       esym = bfd_malloc (size * count);
1317       if (esym == NULL)
1318         goto error_return;
1319
1320       if (! _bfd_ecoff_get_accumulated_sym (handle, (bfd_byte *) esym))
1321         goto error_return;
1322
1323       count = hdr->issMax;
1324       ss = bfd_malloc (count);
1325       if (ss == NULL)
1326         goto error_return;
1327       if (! _bfd_ecoff_get_accumulated_ss (handle, (bfd_byte *) ss))
1328         goto error_return;
1329
1330       count = hdr->ipdMax;
1331       for (i = 0; i < (unsigned long) count; i++, rp++)
1332         {
1333           (*swap->swap_pdr_in) (abfd, epdr + i, &pdr);
1334           (*swap->swap_sym_in) (abfd, &esym[pdr.isym], &sym);
1335           rp->adr = sym.value;
1336           rp->regmask = pdr.regmask;
1337           rp->regoffset = pdr.regoffset;
1338           rp->fregmask = pdr.fregmask;
1339           rp->fregoffset = pdr.fregoffset;
1340           rp->frameoffset = pdr.frameoffset;
1341           rp->framereg = pdr.framereg;
1342           rp->pcreg = pdr.pcreg;
1343           rp->irpss = sindex;
1344           sv[i] = ss + sym.iss;
1345           sindex += strlen (sv[i]) + 1;
1346         }
1347     }
1348
1349   size = sizeof (struct rpdr_ext) * (count + 2) + sindex;
1350   size = BFD_ALIGN (size, 16);
1351   rtproc = bfd_alloc (abfd, size);
1352   if (rtproc == NULL)
1353     {
1354       mips_elf_hash_table (info)->procedure_count = 0;
1355       goto error_return;
1356     }
1357
1358   mips_elf_hash_table (info)->procedure_count = count + 2;
1359
1360   erp = rtproc;
1361   memset (erp, 0, sizeof (struct rpdr_ext));
1362   erp++;
1363   str = (char *) rtproc + sizeof (struct rpdr_ext) * (count + 2);
1364   strcpy (str, no_name_func);
1365   str += strlen (no_name_func) + 1;
1366   for (i = 0; i < count; i++)
1367     {
1368       ecoff_swap_rpdr_out (abfd, rpdr + i, erp + i);
1369       strcpy (str, sv[i]);
1370       str += strlen (sv[i]) + 1;
1371     }
1372   H_PUT_S32 (abfd, -1, (erp + count)->p_adr);
1373
1374   /* Set the size and contents of .rtproc section.  */
1375   s->size = size;
1376   s->contents = rtproc;
1377
1378   /* Skip this section later on (I don't think this currently
1379      matters, but someday it might).  */
1380   s->map_head.link_order = NULL;
1381
1382   if (epdr != NULL)
1383     free (epdr);
1384   if (rpdr != NULL)
1385     free (rpdr);
1386   if (esym != NULL)
1387     free (esym);
1388   if (ss != NULL)
1389     free (ss);
1390   if (sv != NULL)
1391     free (sv);
1392
1393   return TRUE;
1394
1395  error_return:
1396   if (epdr != NULL)
1397     free (epdr);
1398   if (rpdr != NULL)
1399     free (rpdr);
1400   if (esym != NULL)
1401     free (esym);
1402   if (ss != NULL)
1403     free (ss);
1404   if (sv != NULL)
1405     free (sv);
1406   return FALSE;
1407 }
1408 \f
1409 /* We're going to create a stub for H.  Create a symbol for the stub's
1410    value and size, to help make the disassembly easier to read.  */
1411
1412 static bfd_boolean
1413 mips_elf_create_stub_symbol (struct bfd_link_info *info,
1414                              struct mips_elf_link_hash_entry *h,
1415                              const char *prefix, asection *s, bfd_vma value,
1416                              bfd_vma size)
1417 {
1418   struct bfd_link_hash_entry *bh;
1419   struct elf_link_hash_entry *elfh;
1420   const char *name;
1421
1422   if (ELF_ST_IS_MICROMIPS (h->root.other))
1423     value |= 1;
1424
1425   /* Create a new symbol.  */
1426   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1427   bh = NULL;
1428   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1429                                          BSF_LOCAL, s, value, NULL,
1430                                          TRUE, FALSE, &bh))
1431     return FALSE;
1432
1433   /* Make it a local function.  */
1434   elfh = (struct elf_link_hash_entry *) bh;
1435   elfh->type = ELF_ST_INFO (STB_LOCAL, STT_FUNC);
1436   elfh->size = size;
1437   elfh->forced_local = 1;
1438   return TRUE;
1439 }
1440
1441 /* We're about to redefine H.  Create a symbol to represent H's
1442    current value and size, to help make the disassembly easier
1443    to read.  */
1444
1445 static bfd_boolean
1446 mips_elf_create_shadow_symbol (struct bfd_link_info *info,
1447                                struct mips_elf_link_hash_entry *h,
1448                                const char *prefix)
1449 {
1450   struct bfd_link_hash_entry *bh;
1451   struct elf_link_hash_entry *elfh;
1452   const char *name;
1453   asection *s;
1454   bfd_vma value;
1455
1456   /* Read the symbol's value.  */
1457   BFD_ASSERT (h->root.root.type == bfd_link_hash_defined
1458               || h->root.root.type == bfd_link_hash_defweak);
1459   s = h->root.root.u.def.section;
1460   value = h->root.root.u.def.value;
1461
1462   /* Create a new symbol.  */
1463   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1464   bh = NULL;
1465   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1466                                          BSF_LOCAL, s, value, NULL,
1467                                          TRUE, FALSE, &bh))
1468     return FALSE;
1469
1470   /* Make it local and copy the other attributes from H.  */
1471   elfh = (struct elf_link_hash_entry *) bh;
1472   elfh->type = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (h->root.type));
1473   elfh->other = h->root.other;
1474   elfh->size = h->root.size;
1475   elfh->forced_local = 1;
1476   return TRUE;
1477 }
1478
1479 /* Return TRUE if relocations in SECTION can refer directly to a MIPS16
1480    function rather than to a hard-float stub.  */
1481
1482 static bfd_boolean
1483 section_allows_mips16_refs_p (asection *section)
1484 {
1485   const char *name;
1486
1487   name = bfd_get_section_name (section->owner, section);
1488   return (FN_STUB_P (name)
1489           || CALL_STUB_P (name)
1490           || CALL_FP_STUB_P (name)
1491           || strcmp (name, ".pdr") == 0);
1492 }
1493
1494 /* [RELOCS, RELEND) are the relocations against SEC, which is a MIPS16
1495    stub section of some kind.  Return the R_SYMNDX of the target
1496    function, or 0 if we can't decide which function that is.  */
1497
1498 static unsigned long
1499 mips16_stub_symndx (const struct elf_backend_data *bed,
1500                     asection *sec ATTRIBUTE_UNUSED,
1501                     const Elf_Internal_Rela *relocs,
1502                     const Elf_Internal_Rela *relend)
1503 {
1504   int int_rels_per_ext_rel = bed->s->int_rels_per_ext_rel;
1505   const Elf_Internal_Rela *rel;
1506
1507   /* Trust the first R_MIPS_NONE relocation, if any, but not a subsequent
1508      one in a compound relocation.  */
1509   for (rel = relocs; rel < relend; rel += int_rels_per_ext_rel)
1510     if (ELF_R_TYPE (sec->owner, rel->r_info) == R_MIPS_NONE)
1511       return ELF_R_SYM (sec->owner, rel->r_info);
1512
1513   /* Otherwise trust the first relocation, whatever its kind.  This is
1514      the traditional behavior.  */
1515   if (relocs < relend)
1516     return ELF_R_SYM (sec->owner, relocs->r_info);
1517
1518   return 0;
1519 }
1520
1521 /* Check the mips16 stubs for a particular symbol, and see if we can
1522    discard them.  */
1523
1524 static void
1525 mips_elf_check_mips16_stubs (struct bfd_link_info *info,
1526                              struct mips_elf_link_hash_entry *h)
1527 {
1528   /* Dynamic symbols must use the standard call interface, in case other
1529      objects try to call them.  */
1530   if (h->fn_stub != NULL
1531       && h->root.dynindx != -1)
1532     {
1533       mips_elf_create_shadow_symbol (info, h, ".mips16.");
1534       h->need_fn_stub = TRUE;
1535     }
1536
1537   if (h->fn_stub != NULL
1538       && ! h->need_fn_stub)
1539     {
1540       /* We don't need the fn_stub; the only references to this symbol
1541          are 16 bit calls.  Clobber the size to 0 to prevent it from
1542          being included in the link.  */
1543       h->fn_stub->size = 0;
1544       h->fn_stub->flags &= ~SEC_RELOC;
1545       h->fn_stub->reloc_count = 0;
1546       h->fn_stub->flags |= SEC_EXCLUDE;
1547     }
1548
1549   if (h->call_stub != NULL
1550       && ELF_ST_IS_MIPS16 (h->root.other))
1551     {
1552       /* We don't need the call_stub; this is a 16 bit function, so
1553          calls from other 16 bit functions are OK.  Clobber the size
1554          to 0 to prevent it from being included in the link.  */
1555       h->call_stub->size = 0;
1556       h->call_stub->flags &= ~SEC_RELOC;
1557       h->call_stub->reloc_count = 0;
1558       h->call_stub->flags |= SEC_EXCLUDE;
1559     }
1560
1561   if (h->call_fp_stub != NULL
1562       && ELF_ST_IS_MIPS16 (h->root.other))
1563     {
1564       /* We don't need the call_stub; this is a 16 bit function, so
1565          calls from other 16 bit functions are OK.  Clobber the size
1566          to 0 to prevent it from being included in the link.  */
1567       h->call_fp_stub->size = 0;
1568       h->call_fp_stub->flags &= ~SEC_RELOC;
1569       h->call_fp_stub->reloc_count = 0;
1570       h->call_fp_stub->flags |= SEC_EXCLUDE;
1571     }
1572 }
1573
1574 /* Hashtable callbacks for mips_elf_la25_stubs.  */
1575
1576 static hashval_t
1577 mips_elf_la25_stub_hash (const void *entry_)
1578 {
1579   const struct mips_elf_la25_stub *entry;
1580
1581   entry = (struct mips_elf_la25_stub *) entry_;
1582   return entry->h->root.root.u.def.section->id
1583     + entry->h->root.root.u.def.value;
1584 }
1585
1586 static int
1587 mips_elf_la25_stub_eq (const void *entry1_, const void *entry2_)
1588 {
1589   const struct mips_elf_la25_stub *entry1, *entry2;
1590
1591   entry1 = (struct mips_elf_la25_stub *) entry1_;
1592   entry2 = (struct mips_elf_la25_stub *) entry2_;
1593   return ((entry1->h->root.root.u.def.section
1594            == entry2->h->root.root.u.def.section)
1595           && (entry1->h->root.root.u.def.value
1596               == entry2->h->root.root.u.def.value));
1597 }
1598
1599 /* Called by the linker to set up the la25 stub-creation code.  FN is
1600    the linker's implementation of add_stub_function.  Return true on
1601    success.  */
1602
1603 bfd_boolean
1604 _bfd_mips_elf_init_stubs (struct bfd_link_info *info,
1605                           asection *(*fn) (const char *, asection *,
1606                                            asection *))
1607 {
1608   struct mips_elf_link_hash_table *htab;
1609
1610   htab = mips_elf_hash_table (info);
1611   if (htab == NULL)
1612     return FALSE;
1613
1614   htab->add_stub_section = fn;
1615   htab->la25_stubs = htab_try_create (1, mips_elf_la25_stub_hash,
1616                                       mips_elf_la25_stub_eq, NULL);
1617   if (htab->la25_stubs == NULL)
1618     return FALSE;
1619
1620   return TRUE;
1621 }
1622
1623 /* Return true if H is a locally-defined PIC function, in the sense
1624    that it or its fn_stub might need $25 to be valid on entry.
1625    Note that MIPS16 functions set up $gp using PC-relative instructions,
1626    so they themselves never need $25 to be valid.  Only non-MIPS16
1627    entry points are of interest here.  */
1628
1629 static bfd_boolean
1630 mips_elf_local_pic_function_p (struct mips_elf_link_hash_entry *h)
1631 {
1632   return ((h->root.root.type == bfd_link_hash_defined
1633            || h->root.root.type == bfd_link_hash_defweak)
1634           && h->root.def_regular
1635           && !bfd_is_abs_section (h->root.root.u.def.section)
1636           && (!ELF_ST_IS_MIPS16 (h->root.other)
1637               || (h->fn_stub && h->need_fn_stub))
1638           && (PIC_OBJECT_P (h->root.root.u.def.section->owner)
1639               || ELF_ST_IS_MIPS_PIC (h->root.other)));
1640 }
1641
1642 /* Set *SEC to the input section that contains the target of STUB.
1643    Return the offset of the target from the start of that section.  */
1644
1645 static bfd_vma
1646 mips_elf_get_la25_target (struct mips_elf_la25_stub *stub,
1647                           asection **sec)
1648 {
1649   if (ELF_ST_IS_MIPS16 (stub->h->root.other))
1650     {
1651       BFD_ASSERT (stub->h->need_fn_stub);
1652       *sec = stub->h->fn_stub;
1653       return 0;
1654     }
1655   else
1656     {
1657       *sec = stub->h->root.root.u.def.section;
1658       return stub->h->root.root.u.def.value;
1659     }
1660 }
1661
1662 /* STUB describes an la25 stub that we have decided to implement
1663    by inserting an LUI/ADDIU pair before the target function.
1664    Create the section and redirect the function symbol to it.  */
1665
1666 static bfd_boolean
1667 mips_elf_add_la25_intro (struct mips_elf_la25_stub *stub,
1668                          struct bfd_link_info *info)
1669 {
1670   struct mips_elf_link_hash_table *htab;
1671   char *name;
1672   asection *s, *input_section;
1673   unsigned int align;
1674
1675   htab = mips_elf_hash_table (info);
1676   if (htab == NULL)
1677     return FALSE;
1678
1679   /* Create a unique name for the new section.  */
1680   name = bfd_malloc (11 + sizeof (".text.stub."));
1681   if (name == NULL)
1682     return FALSE;
1683   sprintf (name, ".text.stub.%d", (int) htab_elements (htab->la25_stubs));
1684
1685   /* Create the section.  */
1686   mips_elf_get_la25_target (stub, &input_section);
1687   s = htab->add_stub_section (name, input_section,
1688                               input_section->output_section);
1689   if (s == NULL)
1690     return FALSE;
1691
1692   /* Make sure that any padding goes before the stub.  */
1693   align = input_section->alignment_power;
1694   if (!bfd_set_section_alignment (s->owner, s, align))
1695     return FALSE;
1696   if (align > 3)
1697     s->size = (1 << align) - 8;
1698
1699   /* Create a symbol for the stub.  */
1700   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 8);
1701   stub->stub_section = s;
1702   stub->offset = s->size;
1703
1704   /* Allocate room for it.  */
1705   s->size += 8;
1706   return TRUE;
1707 }
1708
1709 /* STUB describes an la25 stub that we have decided to implement
1710    with a separate trampoline.  Allocate room for it and redirect
1711    the function symbol to it.  */
1712
1713 static bfd_boolean
1714 mips_elf_add_la25_trampoline (struct mips_elf_la25_stub *stub,
1715                               struct bfd_link_info *info)
1716 {
1717   struct mips_elf_link_hash_table *htab;
1718   asection *s;
1719
1720   htab = mips_elf_hash_table (info);
1721   if (htab == NULL)
1722     return FALSE;
1723
1724   /* Create a trampoline section, if we haven't already.  */
1725   s = htab->strampoline;
1726   if (s == NULL)
1727     {
1728       asection *input_section = stub->h->root.root.u.def.section;
1729       s = htab->add_stub_section (".text", NULL,
1730                                   input_section->output_section);
1731       if (s == NULL || !bfd_set_section_alignment (s->owner, s, 4))
1732         return FALSE;
1733       htab->strampoline = s;
1734     }
1735
1736   /* Create a symbol for the stub.  */
1737   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 16);
1738   stub->stub_section = s;
1739   stub->offset = s->size;
1740
1741   /* Allocate room for it.  */
1742   s->size += 16;
1743   return TRUE;
1744 }
1745
1746 /* H describes a symbol that needs an la25 stub.  Make sure that an
1747    appropriate stub exists and point H at it.  */
1748
1749 static bfd_boolean
1750 mips_elf_add_la25_stub (struct bfd_link_info *info,
1751                         struct mips_elf_link_hash_entry *h)
1752 {
1753   struct mips_elf_link_hash_table *htab;
1754   struct mips_elf_la25_stub search, *stub;
1755   bfd_boolean use_trampoline_p;
1756   asection *s;
1757   bfd_vma value;
1758   void **slot;
1759
1760   /* Describe the stub we want.  */
1761   search.stub_section = NULL;
1762   search.offset = 0;
1763   search.h = h;
1764
1765   /* See if we've already created an equivalent stub.  */
1766   htab = mips_elf_hash_table (info);
1767   if (htab == NULL)
1768     return FALSE;
1769
1770   slot = htab_find_slot (htab->la25_stubs, &search, INSERT);
1771   if (slot == NULL)
1772     return FALSE;
1773
1774   stub = (struct mips_elf_la25_stub *) *slot;
1775   if (stub != NULL)
1776     {
1777       /* We can reuse the existing stub.  */
1778       h->la25_stub = stub;
1779       return TRUE;
1780     }
1781
1782   /* Create a permanent copy of ENTRY and add it to the hash table.  */
1783   stub = bfd_malloc (sizeof (search));
1784   if (stub == NULL)
1785     return FALSE;
1786   *stub = search;
1787   *slot = stub;
1788
1789   /* Prefer to use LUI/ADDIU stubs if the function is at the beginning
1790      of the section and if we would need no more than 2 nops.  */
1791   value = mips_elf_get_la25_target (stub, &s);
1792   use_trampoline_p = (value != 0 || s->alignment_power > 4);
1793
1794   h->la25_stub = stub;
1795   return (use_trampoline_p
1796           ? mips_elf_add_la25_trampoline (stub, info)
1797           : mips_elf_add_la25_intro (stub, info));
1798 }
1799
1800 /* A mips_elf_link_hash_traverse callback that is called before sizing
1801    sections.  DATA points to a mips_htab_traverse_info structure.  */
1802
1803 static bfd_boolean
1804 mips_elf_check_symbols (struct mips_elf_link_hash_entry *h, void *data)
1805 {
1806   struct mips_htab_traverse_info *hti;
1807
1808   hti = (struct mips_htab_traverse_info *) data;
1809   if (!hti->info->relocatable)
1810     mips_elf_check_mips16_stubs (hti->info, h);
1811
1812   if (mips_elf_local_pic_function_p (h))
1813     {
1814       /* PR 12845: If H is in a section that has been garbage
1815          collected it will have its output section set to *ABS*.  */
1816       if (bfd_is_abs_section (h->root.root.u.def.section->output_section))
1817         return TRUE;
1818
1819       /* H is a function that might need $25 to be valid on entry.
1820          If we're creating a non-PIC relocatable object, mark H as
1821          being PIC.  If we're creating a non-relocatable object with
1822          non-PIC branches and jumps to H, make sure that H has an la25
1823          stub.  */
1824       if (hti->info->relocatable)
1825         {
1826           if (!PIC_OBJECT_P (hti->output_bfd))
1827             h->root.other = ELF_ST_SET_MIPS_PIC (h->root.other);
1828         }
1829       else if (h->has_nonpic_branches && !mips_elf_add_la25_stub (hti->info, h))
1830         {
1831           hti->error = TRUE;
1832           return FALSE;
1833         }
1834     }
1835   return TRUE;
1836 }
1837 \f
1838 /* R_MIPS16_26 is used for the mips16 jal and jalx instructions.
1839    Most mips16 instructions are 16 bits, but these instructions
1840    are 32 bits.
1841
1842    The format of these instructions is:
1843
1844    +--------------+--------------------------------+
1845    |     JALX     | X|   Imm 20:16  |   Imm 25:21  |
1846    +--------------+--------------------------------+
1847    |                Immediate  15:0                |
1848    +-----------------------------------------------+
1849
1850    JALX is the 5-bit value 00011.  X is 0 for jal, 1 for jalx.
1851    Note that the immediate value in the first word is swapped.
1852
1853    When producing a relocatable object file, R_MIPS16_26 is
1854    handled mostly like R_MIPS_26.  In particular, the addend is
1855    stored as a straight 26-bit value in a 32-bit instruction.
1856    (gas makes life simpler for itself by never adjusting a
1857    R_MIPS16_26 reloc to be against a section, so the addend is
1858    always zero).  However, the 32 bit instruction is stored as 2
1859    16-bit values, rather than a single 32-bit value.  In a
1860    big-endian file, the result is the same; in a little-endian
1861    file, the two 16-bit halves of the 32 bit value are swapped.
1862    This is so that a disassembler can recognize the jal
1863    instruction.
1864
1865    When doing a final link, R_MIPS16_26 is treated as a 32 bit
1866    instruction stored as two 16-bit values.  The addend A is the
1867    contents of the targ26 field.  The calculation is the same as
1868    R_MIPS_26.  When storing the calculated value, reorder the
1869    immediate value as shown above, and don't forget to store the
1870    value as two 16-bit values.
1871
1872    To put it in MIPS ABI terms, the relocation field is T-targ26-16,
1873    defined as
1874
1875    big-endian:
1876    +--------+----------------------+
1877    |        |                      |
1878    |        |    targ26-16         |
1879    |31    26|25                   0|
1880    +--------+----------------------+
1881
1882    little-endian:
1883    +----------+------+-------------+
1884    |          |      |             |
1885    |  sub1    |      |     sub2    |
1886    |0        9|10  15|16         31|
1887    +----------+--------------------+
1888    where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is
1889    ((sub1 << 16) | sub2)).
1890
1891    When producing a relocatable object file, the calculation is
1892    (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1893    When producing a fully linked file, the calculation is
1894    let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1895    ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff)
1896
1897    The table below lists the other MIPS16 instruction relocations.
1898    Each one is calculated in the same way as the non-MIPS16 relocation
1899    given on the right, but using the extended MIPS16 layout of 16-bit
1900    immediate fields:
1901
1902         R_MIPS16_GPREL          R_MIPS_GPREL16
1903         R_MIPS16_GOT16          R_MIPS_GOT16
1904         R_MIPS16_CALL16         R_MIPS_CALL16
1905         R_MIPS16_HI16           R_MIPS_HI16
1906         R_MIPS16_LO16           R_MIPS_LO16
1907
1908    A typical instruction will have a format like this:
1909
1910    +--------------+--------------------------------+
1911    |    EXTEND    |     Imm 10:5    |   Imm 15:11  |
1912    +--------------+--------------------------------+
1913    |    Major     |   rx   |   ry   |   Imm  4:0   |
1914    +--------------+--------------------------------+
1915
1916    EXTEND is the five bit value 11110.  Major is the instruction
1917    opcode.
1918
1919    All we need to do here is shuffle the bits appropriately.
1920    As above, the two 16-bit halves must be swapped on a
1921    little-endian system.  */
1922
1923 static inline bfd_boolean
1924 mips16_reloc_p (int r_type)
1925 {
1926   switch (r_type)
1927     {
1928     case R_MIPS16_26:
1929     case R_MIPS16_GPREL:
1930     case R_MIPS16_GOT16:
1931     case R_MIPS16_CALL16:
1932     case R_MIPS16_HI16:
1933     case R_MIPS16_LO16:
1934     case R_MIPS16_TLS_GD:
1935     case R_MIPS16_TLS_LDM:
1936     case R_MIPS16_TLS_DTPREL_HI16:
1937     case R_MIPS16_TLS_DTPREL_LO16:
1938     case R_MIPS16_TLS_GOTTPREL:
1939     case R_MIPS16_TLS_TPREL_HI16:
1940     case R_MIPS16_TLS_TPREL_LO16:
1941       return TRUE;
1942
1943     default:
1944       return FALSE;
1945     }
1946 }
1947
1948 /* Check if a microMIPS reloc.  */
1949
1950 static inline bfd_boolean
1951 micromips_reloc_p (unsigned int r_type)
1952 {
1953   return r_type >= R_MICROMIPS_min && r_type < R_MICROMIPS_max;
1954 }
1955
1956 /* Similar to MIPS16, the two 16-bit halves in microMIPS must be swapped
1957    on a little-endian system.  This does not apply to R_MICROMIPS_PC7_S1
1958    and R_MICROMIPS_PC10_S1 relocs that apply to 16-bit instructions.  */
1959
1960 static inline bfd_boolean
1961 micromips_reloc_shuffle_p (unsigned int r_type)
1962 {
1963   return (micromips_reloc_p (r_type)
1964           && r_type != R_MICROMIPS_PC7_S1
1965           && r_type != R_MICROMIPS_PC10_S1);
1966 }
1967
1968 static inline bfd_boolean
1969 got16_reloc_p (int r_type)
1970 {
1971   return (r_type == R_MIPS_GOT16
1972           || r_type == R_MIPS16_GOT16
1973           || r_type == R_MICROMIPS_GOT16);
1974 }
1975
1976 static inline bfd_boolean
1977 call16_reloc_p (int r_type)
1978 {
1979   return (r_type == R_MIPS_CALL16
1980           || r_type == R_MIPS16_CALL16
1981           || r_type == R_MICROMIPS_CALL16);
1982 }
1983
1984 static inline bfd_boolean
1985 got_disp_reloc_p (unsigned int r_type)
1986 {
1987   return r_type == R_MIPS_GOT_DISP || r_type == R_MICROMIPS_GOT_DISP;
1988 }
1989
1990 static inline bfd_boolean
1991 got_page_reloc_p (unsigned int r_type)
1992 {
1993   return r_type == R_MIPS_GOT_PAGE || r_type == R_MICROMIPS_GOT_PAGE;
1994 }
1995
1996 static inline bfd_boolean
1997 got_ofst_reloc_p (unsigned int r_type)
1998 {
1999   return r_type == R_MIPS_GOT_OFST || r_type == R_MICROMIPS_GOT_OFST;
2000 }
2001
2002 static inline bfd_boolean
2003 got_hi16_reloc_p (unsigned int r_type)
2004 {
2005   return r_type == R_MIPS_GOT_HI16 || r_type == R_MICROMIPS_GOT_HI16;
2006 }
2007
2008 static inline bfd_boolean
2009 got_lo16_reloc_p (unsigned int r_type)
2010 {
2011   return r_type == R_MIPS_GOT_LO16 || r_type == R_MICROMIPS_GOT_LO16;
2012 }
2013
2014 static inline bfd_boolean
2015 call_hi16_reloc_p (unsigned int r_type)
2016 {
2017   return r_type == R_MIPS_CALL_HI16 || r_type == R_MICROMIPS_CALL_HI16;
2018 }
2019
2020 static inline bfd_boolean
2021 call_lo16_reloc_p (unsigned int r_type)
2022 {
2023   return r_type == R_MIPS_CALL_LO16 || r_type == R_MICROMIPS_CALL_LO16;
2024 }
2025
2026 static inline bfd_boolean
2027 hi16_reloc_p (int r_type)
2028 {
2029   return (r_type == R_MIPS_HI16
2030           || r_type == R_MIPS16_HI16
2031           || r_type == R_MICROMIPS_HI16);
2032 }
2033
2034 static inline bfd_boolean
2035 lo16_reloc_p (int r_type)
2036 {
2037   return (r_type == R_MIPS_LO16
2038           || r_type == R_MIPS16_LO16
2039           || r_type == R_MICROMIPS_LO16);
2040 }
2041
2042 static inline bfd_boolean
2043 mips16_call_reloc_p (int r_type)
2044 {
2045   return r_type == R_MIPS16_26 || r_type == R_MIPS16_CALL16;
2046 }
2047
2048 static inline bfd_boolean
2049 jal_reloc_p (int r_type)
2050 {
2051   return (r_type == R_MIPS_26
2052           || r_type == R_MIPS16_26
2053           || r_type == R_MICROMIPS_26_S1);
2054 }
2055
2056 static inline bfd_boolean
2057 micromips_branch_reloc_p (int r_type)
2058 {
2059   return (r_type == R_MICROMIPS_26_S1
2060           || r_type == R_MICROMIPS_PC16_S1
2061           || r_type == R_MICROMIPS_PC10_S1
2062           || r_type == R_MICROMIPS_PC7_S1);
2063 }
2064
2065 static inline bfd_boolean
2066 tls_gd_reloc_p (unsigned int r_type)
2067 {
2068   return (r_type == R_MIPS_TLS_GD
2069           || r_type == R_MIPS16_TLS_GD
2070           || r_type == R_MICROMIPS_TLS_GD);
2071 }
2072
2073 static inline bfd_boolean
2074 tls_ldm_reloc_p (unsigned int r_type)
2075 {
2076   return (r_type == R_MIPS_TLS_LDM
2077           || r_type == R_MIPS16_TLS_LDM
2078           || r_type == R_MICROMIPS_TLS_LDM);
2079 }
2080
2081 static inline bfd_boolean
2082 tls_gottprel_reloc_p (unsigned int r_type)
2083 {
2084   return (r_type == R_MIPS_TLS_GOTTPREL
2085           || r_type == R_MIPS16_TLS_GOTTPREL
2086           || r_type == R_MICROMIPS_TLS_GOTTPREL);
2087 }
2088
2089 void
2090 _bfd_mips_elf_reloc_unshuffle (bfd *abfd, int r_type,
2091                                bfd_boolean jal_shuffle, bfd_byte *data)
2092 {
2093   bfd_vma first, second, val;
2094
2095   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2096     return;
2097
2098   /* Pick up the first and second halfwords of the instruction.  */
2099   first = bfd_get_16 (abfd, data);
2100   second = bfd_get_16 (abfd, data + 2);
2101   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2102     val = first << 16 | second;
2103   else if (r_type != R_MIPS16_26)
2104     val = (((first & 0xf800) << 16) | ((second & 0xffe0) << 11)
2105            | ((first & 0x1f) << 11) | (first & 0x7e0) | (second & 0x1f));
2106   else
2107     val = (((first & 0xfc00) << 16) | ((first & 0x3e0) << 11)
2108            | ((first & 0x1f) << 21) | second);
2109   bfd_put_32 (abfd, val, data);
2110 }
2111
2112 void
2113 _bfd_mips_elf_reloc_shuffle (bfd *abfd, int r_type,
2114                              bfd_boolean jal_shuffle, bfd_byte *data)
2115 {
2116   bfd_vma first, second, val;
2117
2118   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2119     return;
2120
2121   val = bfd_get_32 (abfd, data);
2122   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2123     {
2124       second = val & 0xffff;
2125       first = val >> 16;
2126     }
2127   else if (r_type != R_MIPS16_26)
2128     {
2129       second = ((val >> 11) & 0xffe0) | (val & 0x1f);
2130       first = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0);
2131     }
2132   else
2133     {
2134       second = val & 0xffff;
2135       first = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0)
2136                | ((val >> 21) & 0x1f);
2137     }
2138   bfd_put_16 (abfd, second, data + 2);
2139   bfd_put_16 (abfd, first, data);
2140 }
2141
2142 bfd_reloc_status_type
2143 _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol,
2144                                arelent *reloc_entry, asection *input_section,
2145                                bfd_boolean relocatable, void *data, bfd_vma gp)
2146 {
2147   bfd_vma relocation;
2148   bfd_signed_vma val;
2149   bfd_reloc_status_type status;
2150
2151   if (bfd_is_com_section (symbol->section))
2152     relocation = 0;
2153   else
2154     relocation = symbol->value;
2155
2156   relocation += symbol->section->output_section->vma;
2157   relocation += symbol->section->output_offset;
2158
2159   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2160     return bfd_reloc_outofrange;
2161
2162   /* Set val to the offset into the section or symbol.  */
2163   val = reloc_entry->addend;
2164
2165   _bfd_mips_elf_sign_extend (val, 16);
2166
2167   /* Adjust val for the final section location and GP value.  If we
2168      are producing relocatable output, we don't want to do this for
2169      an external symbol.  */
2170   if (! relocatable
2171       || (symbol->flags & BSF_SECTION_SYM) != 0)
2172     val += relocation - gp;
2173
2174   if (reloc_entry->howto->partial_inplace)
2175     {
2176       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2177                                        (bfd_byte *) data
2178                                        + reloc_entry->address);
2179       if (status != bfd_reloc_ok)
2180         return status;
2181     }
2182   else
2183     reloc_entry->addend = val;
2184
2185   if (relocatable)
2186     reloc_entry->address += input_section->output_offset;
2187
2188   return bfd_reloc_ok;
2189 }
2190
2191 /* Used to store a REL high-part relocation such as R_MIPS_HI16 or
2192    R_MIPS_GOT16.  REL is the relocation, INPUT_SECTION is the section
2193    that contains the relocation field and DATA points to the start of
2194    INPUT_SECTION.  */
2195
2196 struct mips_hi16
2197 {
2198   struct mips_hi16 *next;
2199   bfd_byte *data;
2200   asection *input_section;
2201   arelent rel;
2202 };
2203
2204 /* FIXME: This should not be a static variable.  */
2205
2206 static struct mips_hi16 *mips_hi16_list;
2207
2208 /* A howto special_function for REL *HI16 relocations.  We can only
2209    calculate the correct value once we've seen the partnering
2210    *LO16 relocation, so just save the information for later.
2211
2212    The ABI requires that the *LO16 immediately follow the *HI16.
2213    However, as a GNU extension, we permit an arbitrary number of
2214    *HI16s to be associated with a single *LO16.  This significantly
2215    simplies the relocation handling in gcc.  */
2216
2217 bfd_reloc_status_type
2218 _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2219                           asymbol *symbol ATTRIBUTE_UNUSED, void *data,
2220                           asection *input_section, bfd *output_bfd,
2221                           char **error_message ATTRIBUTE_UNUSED)
2222 {
2223   struct mips_hi16 *n;
2224
2225   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2226     return bfd_reloc_outofrange;
2227
2228   n = bfd_malloc (sizeof *n);
2229   if (n == NULL)
2230     return bfd_reloc_outofrange;
2231
2232   n->next = mips_hi16_list;
2233   n->data = data;
2234   n->input_section = input_section;
2235   n->rel = *reloc_entry;
2236   mips_hi16_list = n;
2237
2238   if (output_bfd != NULL)
2239     reloc_entry->address += input_section->output_offset;
2240
2241   return bfd_reloc_ok;
2242 }
2243
2244 /* A howto special_function for REL R_MIPS*_GOT16 relocations.  This is just
2245    like any other 16-bit relocation when applied to global symbols, but is
2246    treated in the same as R_MIPS_HI16 when applied to local symbols.  */
2247
2248 bfd_reloc_status_type
2249 _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2250                            void *data, asection *input_section,
2251                            bfd *output_bfd, char **error_message)
2252 {
2253   if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2254       || bfd_is_und_section (bfd_get_section (symbol))
2255       || bfd_is_com_section (bfd_get_section (symbol)))
2256     /* The relocation is against a global symbol.  */
2257     return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2258                                         input_section, output_bfd,
2259                                         error_message);
2260
2261   return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
2262                                    input_section, output_bfd, error_message);
2263 }
2264
2265 /* A howto special_function for REL *LO16 relocations.  The *LO16 itself
2266    is a straightforward 16 bit inplace relocation, but we must deal with
2267    any partnering high-part relocations as well.  */
2268
2269 bfd_reloc_status_type
2270 _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2271                           void *data, asection *input_section,
2272                           bfd *output_bfd, char **error_message)
2273 {
2274   bfd_vma vallo;
2275   bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2276
2277   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2278     return bfd_reloc_outofrange;
2279
2280   _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2281                                  location);
2282   vallo = bfd_get_32 (abfd, location);
2283   _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2284                                location);
2285
2286   while (mips_hi16_list != NULL)
2287     {
2288       bfd_reloc_status_type ret;
2289       struct mips_hi16 *hi;
2290
2291       hi = mips_hi16_list;
2292
2293       /* R_MIPS*_GOT16 relocations are something of a special case.  We
2294          want to install the addend in the same way as for a R_MIPS*_HI16
2295          relocation (with a rightshift of 16).  However, since GOT16
2296          relocations can also be used with global symbols, their howto
2297          has a rightshift of 0.  */
2298       if (hi->rel.howto->type == R_MIPS_GOT16)
2299         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE);
2300       else if (hi->rel.howto->type == R_MIPS16_GOT16)
2301         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS16_HI16, FALSE);
2302       else if (hi->rel.howto->type == R_MICROMIPS_GOT16)
2303         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MICROMIPS_HI16, FALSE);
2304
2305       /* VALLO is a signed 16-bit number.  Bias it by 0x8000 so that any
2306          carry or borrow will induce a change of +1 or -1 in the high part.  */
2307       hi->rel.addend += (vallo + 0x8000) & 0xffff;
2308
2309       ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data,
2310                                          hi->input_section, output_bfd,
2311                                          error_message);
2312       if (ret != bfd_reloc_ok)
2313         return ret;
2314
2315       mips_hi16_list = hi->next;
2316       free (hi);
2317     }
2318
2319   return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2320                                       input_section, output_bfd,
2321                                       error_message);
2322 }
2323
2324 /* A generic howto special_function.  This calculates and installs the
2325    relocation itself, thus avoiding the oft-discussed problems in
2326    bfd_perform_relocation and bfd_install_relocation.  */
2327
2328 bfd_reloc_status_type
2329 _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2330                              asymbol *symbol, void *data ATTRIBUTE_UNUSED,
2331                              asection *input_section, bfd *output_bfd,
2332                              char **error_message ATTRIBUTE_UNUSED)
2333 {
2334   bfd_signed_vma val;
2335   bfd_reloc_status_type status;
2336   bfd_boolean relocatable;
2337
2338   relocatable = (output_bfd != NULL);
2339
2340   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2341     return bfd_reloc_outofrange;
2342
2343   /* Build up the field adjustment in VAL.  */
2344   val = 0;
2345   if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)
2346     {
2347       /* Either we're calculating the final field value or we have a
2348          relocation against a section symbol.  Add in the section's
2349          offset or address.  */
2350       val += symbol->section->output_section->vma;
2351       val += symbol->section->output_offset;
2352     }
2353
2354   if (!relocatable)
2355     {
2356       /* We're calculating the final field value.  Add in the symbol's value
2357          and, if pc-relative, subtract the address of the field itself.  */
2358       val += symbol->value;
2359       if (reloc_entry->howto->pc_relative)
2360         {
2361           val -= input_section->output_section->vma;
2362           val -= input_section->output_offset;
2363           val -= reloc_entry->address;
2364         }
2365     }
2366
2367   /* VAL is now the final adjustment.  If we're keeping this relocation
2368      in the output file, and if the relocation uses a separate addend,
2369      we just need to add VAL to that addend.  Otherwise we need to add
2370      VAL to the relocation field itself.  */
2371   if (relocatable && !reloc_entry->howto->partial_inplace)
2372     reloc_entry->addend += val;
2373   else
2374     {
2375       bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2376
2377       /* Add in the separate addend, if any.  */
2378       val += reloc_entry->addend;
2379
2380       /* Add VAL to the relocation field.  */
2381       _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2382                                      location);
2383       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2384                                        location);
2385       _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2386                                    location);
2387
2388       if (status != bfd_reloc_ok)
2389         return status;
2390     }
2391
2392   if (relocatable)
2393     reloc_entry->address += input_section->output_offset;
2394
2395   return bfd_reloc_ok;
2396 }
2397 \f
2398 /* Swap an entry in a .gptab section.  Note that these routines rely
2399    on the equivalence of the two elements of the union.  */
2400
2401 static void
2402 bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex,
2403                               Elf32_gptab *in)
2404 {
2405   in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value);
2406   in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes);
2407 }
2408
2409 static void
2410 bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in,
2411                                Elf32_External_gptab *ex)
2412 {
2413   H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value);
2414   H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes);
2415 }
2416
2417 static void
2418 bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in,
2419                                 Elf32_External_compact_rel *ex)
2420 {
2421   H_PUT_32 (abfd, in->id1, ex->id1);
2422   H_PUT_32 (abfd, in->num, ex->num);
2423   H_PUT_32 (abfd, in->id2, ex->id2);
2424   H_PUT_32 (abfd, in->offset, ex->offset);
2425   H_PUT_32 (abfd, in->reserved0, ex->reserved0);
2426   H_PUT_32 (abfd, in->reserved1, ex->reserved1);
2427 }
2428
2429 static void
2430 bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in,
2431                            Elf32_External_crinfo *ex)
2432 {
2433   unsigned long l;
2434
2435   l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH)
2436        | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH)
2437        | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH)
2438        | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH));
2439   H_PUT_32 (abfd, l, ex->info);
2440   H_PUT_32 (abfd, in->konst, ex->konst);
2441   H_PUT_32 (abfd, in->vaddr, ex->vaddr);
2442 }
2443 \f
2444 /* A .reginfo section holds a single Elf32_RegInfo structure.  These
2445    routines swap this structure in and out.  They are used outside of
2446    BFD, so they are globally visible.  */
2447
2448 void
2449 bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex,
2450                                 Elf32_RegInfo *in)
2451 {
2452   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2453   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2454   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2455   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2456   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2457   in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value);
2458 }
2459
2460 void
2461 bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in,
2462                                  Elf32_External_RegInfo *ex)
2463 {
2464   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2465   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2466   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2467   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2468   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2469   H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value);
2470 }
2471
2472 /* In the 64 bit ABI, the .MIPS.options section holds register
2473    information in an Elf64_Reginfo structure.  These routines swap
2474    them in and out.  They are globally visible because they are used
2475    outside of BFD.  These routines are here so that gas can call them
2476    without worrying about whether the 64 bit ABI has been included.  */
2477
2478 void
2479 bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex,
2480                                 Elf64_Internal_RegInfo *in)
2481 {
2482   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2483   in->ri_pad = H_GET_32 (abfd, ex->ri_pad);
2484   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2485   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2486   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2487   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2488   in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value);
2489 }
2490
2491 void
2492 bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in,
2493                                  Elf64_External_RegInfo *ex)
2494 {
2495   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2496   H_PUT_32 (abfd, in->ri_pad, ex->ri_pad);
2497   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2498   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2499   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2500   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2501   H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value);
2502 }
2503
2504 /* Swap in an options header.  */
2505
2506 void
2507 bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex,
2508                               Elf_Internal_Options *in)
2509 {
2510   in->kind = H_GET_8 (abfd, ex->kind);
2511   in->size = H_GET_8 (abfd, ex->size);
2512   in->section = H_GET_16 (abfd, ex->section);
2513   in->info = H_GET_32 (abfd, ex->info);
2514 }
2515
2516 /* Swap out an options header.  */
2517
2518 void
2519 bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in,
2520                                Elf_External_Options *ex)
2521 {
2522   H_PUT_8 (abfd, in->kind, ex->kind);
2523   H_PUT_8 (abfd, in->size, ex->size);
2524   H_PUT_16 (abfd, in->section, ex->section);
2525   H_PUT_32 (abfd, in->info, ex->info);
2526 }
2527 \f
2528 /* This function is called via qsort() to sort the dynamic relocation
2529    entries by increasing r_symndx value.  */
2530
2531 static int
2532 sort_dynamic_relocs (const void *arg1, const void *arg2)
2533 {
2534   Elf_Internal_Rela int_reloc1;
2535   Elf_Internal_Rela int_reloc2;
2536   int diff;
2537
2538   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
2539   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
2540
2541   diff = ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info);
2542   if (diff != 0)
2543     return diff;
2544
2545   if (int_reloc1.r_offset < int_reloc2.r_offset)
2546     return -1;
2547   if (int_reloc1.r_offset > int_reloc2.r_offset)
2548     return 1;
2549   return 0;
2550 }
2551
2552 /* Like sort_dynamic_relocs, but used for elf64 relocations.  */
2553
2554 static int
2555 sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED,
2556                         const void *arg2 ATTRIBUTE_UNUSED)
2557 {
2558 #ifdef BFD64
2559   Elf_Internal_Rela int_reloc1[3];
2560   Elf_Internal_Rela int_reloc2[3];
2561
2562   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2563     (reldyn_sorting_bfd, arg1, int_reloc1);
2564   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2565     (reldyn_sorting_bfd, arg2, int_reloc2);
2566
2567   if (ELF64_R_SYM (int_reloc1[0].r_info) < ELF64_R_SYM (int_reloc2[0].r_info))
2568     return -1;
2569   if (ELF64_R_SYM (int_reloc1[0].r_info) > ELF64_R_SYM (int_reloc2[0].r_info))
2570     return 1;
2571
2572   if (int_reloc1[0].r_offset < int_reloc2[0].r_offset)
2573     return -1;
2574   if (int_reloc1[0].r_offset > int_reloc2[0].r_offset)
2575     return 1;
2576   return 0;
2577 #else
2578   abort ();
2579 #endif
2580 }
2581
2582
2583 /* This routine is used to write out ECOFF debugging external symbol
2584    information.  It is called via mips_elf_link_hash_traverse.  The
2585    ECOFF external symbol information must match the ELF external
2586    symbol information.  Unfortunately, at this point we don't know
2587    whether a symbol is required by reloc information, so the two
2588    tables may wind up being different.  We must sort out the external
2589    symbol information before we can set the final size of the .mdebug
2590    section, and we must set the size of the .mdebug section before we
2591    can relocate any sections, and we can't know which symbols are
2592    required by relocation until we relocate the sections.
2593    Fortunately, it is relatively unlikely that any symbol will be
2594    stripped but required by a reloc.  In particular, it can not happen
2595    when generating a final executable.  */
2596
2597 static bfd_boolean
2598 mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data)
2599 {
2600   struct extsym_info *einfo = data;
2601   bfd_boolean strip;
2602   asection *sec, *output_section;
2603
2604   if (h->root.indx == -2)
2605     strip = FALSE;
2606   else if ((h->root.def_dynamic
2607             || h->root.ref_dynamic
2608             || h->root.type == bfd_link_hash_new)
2609            && !h->root.def_regular
2610            && !h->root.ref_regular)
2611     strip = TRUE;
2612   else if (einfo->info->strip == strip_all
2613            || (einfo->info->strip == strip_some
2614                && bfd_hash_lookup (einfo->info->keep_hash,
2615                                    h->root.root.root.string,
2616                                    FALSE, FALSE) == NULL))
2617     strip = TRUE;
2618   else
2619     strip = FALSE;
2620
2621   if (strip)
2622     return TRUE;
2623
2624   if (h->esym.ifd == -2)
2625     {
2626       h->esym.jmptbl = 0;
2627       h->esym.cobol_main = 0;
2628       h->esym.weakext = 0;
2629       h->esym.reserved = 0;
2630       h->esym.ifd = ifdNil;
2631       h->esym.asym.value = 0;
2632       h->esym.asym.st = stGlobal;
2633
2634       if (h->root.root.type == bfd_link_hash_undefined
2635           || h->root.root.type == bfd_link_hash_undefweak)
2636         {
2637           const char *name;
2638
2639           /* Use undefined class.  Also, set class and type for some
2640              special symbols.  */
2641           name = h->root.root.root.string;
2642           if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
2643               || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
2644             {
2645               h->esym.asym.sc = scData;
2646               h->esym.asym.st = stLabel;
2647               h->esym.asym.value = 0;
2648             }
2649           else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
2650             {
2651               h->esym.asym.sc = scAbs;
2652               h->esym.asym.st = stLabel;
2653               h->esym.asym.value =
2654                 mips_elf_hash_table (einfo->info)->procedure_count;
2655             }
2656           else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd))
2657             {
2658               h->esym.asym.sc = scAbs;
2659               h->esym.asym.st = stLabel;
2660               h->esym.asym.value = elf_gp (einfo->abfd);
2661             }
2662           else
2663             h->esym.asym.sc = scUndefined;
2664         }
2665       else if (h->root.root.type != bfd_link_hash_defined
2666           && h->root.root.type != bfd_link_hash_defweak)
2667         h->esym.asym.sc = scAbs;
2668       else
2669         {
2670           const char *name;
2671
2672           sec = h->root.root.u.def.section;
2673           output_section = sec->output_section;
2674
2675           /* When making a shared library and symbol h is the one from
2676              the another shared library, OUTPUT_SECTION may be null.  */
2677           if (output_section == NULL)
2678             h->esym.asym.sc = scUndefined;
2679           else
2680             {
2681               name = bfd_section_name (output_section->owner, output_section);
2682
2683               if (strcmp (name, ".text") == 0)
2684                 h->esym.asym.sc = scText;
2685               else if (strcmp (name, ".data") == 0)
2686                 h->esym.asym.sc = scData;
2687               else if (strcmp (name, ".sdata") == 0)
2688                 h->esym.asym.sc = scSData;
2689               else if (strcmp (name, ".rodata") == 0
2690                        || strcmp (name, ".rdata") == 0)
2691                 h->esym.asym.sc = scRData;
2692               else if (strcmp (name, ".bss") == 0)
2693                 h->esym.asym.sc = scBss;
2694               else if (strcmp (name, ".sbss") == 0)
2695                 h->esym.asym.sc = scSBss;
2696               else if (strcmp (name, ".init") == 0)
2697                 h->esym.asym.sc = scInit;
2698               else if (strcmp (name, ".fini") == 0)
2699                 h->esym.asym.sc = scFini;
2700               else
2701                 h->esym.asym.sc = scAbs;
2702             }
2703         }
2704
2705       h->esym.asym.reserved = 0;
2706       h->esym.asym.index = indexNil;
2707     }
2708
2709   if (h->root.root.type == bfd_link_hash_common)
2710     h->esym.asym.value = h->root.root.u.c.size;
2711   else if (h->root.root.type == bfd_link_hash_defined
2712            || h->root.root.type == bfd_link_hash_defweak)
2713     {
2714       if (h->esym.asym.sc == scCommon)
2715         h->esym.asym.sc = scBss;
2716       else if (h->esym.asym.sc == scSCommon)
2717         h->esym.asym.sc = scSBss;
2718
2719       sec = h->root.root.u.def.section;
2720       output_section = sec->output_section;
2721       if (output_section != NULL)
2722         h->esym.asym.value = (h->root.root.u.def.value
2723                               + sec->output_offset
2724                               + output_section->vma);
2725       else
2726         h->esym.asym.value = 0;
2727     }
2728   else
2729     {
2730       struct mips_elf_link_hash_entry *hd = h;
2731
2732       while (hd->root.root.type == bfd_link_hash_indirect)
2733         hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link;
2734
2735       if (hd->needs_lazy_stub)
2736         {
2737           /* Set type and value for a symbol with a function stub.  */
2738           h->esym.asym.st = stProc;
2739           sec = hd->root.root.u.def.section;
2740           if (sec == NULL)
2741             h->esym.asym.value = 0;
2742           else
2743             {
2744               output_section = sec->output_section;
2745               if (output_section != NULL)
2746                 h->esym.asym.value = (hd->root.plt.offset
2747                                       + sec->output_offset
2748                                       + output_section->vma);
2749               else
2750                 h->esym.asym.value = 0;
2751             }
2752         }
2753     }
2754
2755   if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap,
2756                                       h->root.root.root.string,
2757                                       &h->esym))
2758     {
2759       einfo->failed = TRUE;
2760       return FALSE;
2761     }
2762
2763   return TRUE;
2764 }
2765
2766 /* A comparison routine used to sort .gptab entries.  */
2767
2768 static int
2769 gptab_compare (const void *p1, const void *p2)
2770 {
2771   const Elf32_gptab *a1 = p1;
2772   const Elf32_gptab *a2 = p2;
2773
2774   return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value;
2775 }
2776 \f
2777 /* Functions to manage the got entry hash table.  */
2778
2779 /* Use all 64 bits of a bfd_vma for the computation of a 32-bit
2780    hash number.  */
2781
2782 static INLINE hashval_t
2783 mips_elf_hash_bfd_vma (bfd_vma addr)
2784 {
2785 #ifdef BFD64
2786   return addr + (addr >> 32);
2787 #else
2788   return addr;
2789 #endif
2790 }
2791
2792 /* got_entries only match if they're identical, except for gotidx, so
2793    use all fields to compute the hash, and compare the appropriate
2794    union members.  */
2795
2796 static int
2797 mips_elf_got_entry_eq (const void *entry1, const void *entry2)
2798 {
2799   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2800   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2801
2802   return (e1->abfd == e2->abfd
2803           && e1->symndx == e2->symndx
2804           && (e1->tls_type & GOT_TLS_TYPE) == (e2->tls_type & GOT_TLS_TYPE)
2805           && (!e1->abfd ? e1->d.address == e2->d.address
2806               : e1->symndx >= 0 ? e1->d.addend == e2->d.addend
2807               : e1->d.h == e2->d.h));
2808 }
2809
2810 /* multi_got_entries are still a match in the case of global objects,
2811    even if the input bfd in which they're referenced differs, so the
2812    hash computation and compare functions are adjusted
2813    accordingly.  */
2814
2815 static hashval_t
2816 mips_elf_got_entry_hash (const void *entry_)
2817 {
2818   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2819
2820   return (entry->symndx
2821           + (((entry->tls_type & GOT_TLS_TYPE) == GOT_TLS_LDM) << 18)
2822           + ((entry->tls_type & GOT_TLS_TYPE) == GOT_TLS_LDM ? 0
2823              : !entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address)
2824              : entry->symndx >= 0 ? (entry->abfd->id
2825                                      + mips_elf_hash_bfd_vma (entry->d.addend))
2826              : entry->d.h->root.root.root.hash));
2827 }
2828
2829 static int
2830 mips_elf_multi_got_entry_eq (const void *entry1, const void *entry2)
2831 {
2832   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2833   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2834
2835   return (e1->symndx == e2->symndx
2836           && (e1->tls_type & GOT_TLS_TYPE) == (e2->tls_type & GOT_TLS_TYPE)
2837           && ((e1->tls_type & GOT_TLS_TYPE) == GOT_TLS_LDM ? TRUE
2838               : !e1->abfd ? !e2->abfd && e1->d.address == e2->d.address
2839               : e1->symndx >= 0 ? (e1->abfd == e2->abfd
2840                                    && e1->d.addend == e2->d.addend)
2841               : e2->abfd && e1->d.h == e2->d.h));
2842 }
2843
2844 static hashval_t
2845 mips_got_page_entry_hash (const void *entry_)
2846 {
2847   const struct mips_got_page_entry *entry;
2848
2849   entry = (const struct mips_got_page_entry *) entry_;
2850   return entry->abfd->id + entry->symndx;
2851 }
2852
2853 static int
2854 mips_got_page_entry_eq (const void *entry1_, const void *entry2_)
2855 {
2856   const struct mips_got_page_entry *entry1, *entry2;
2857
2858   entry1 = (const struct mips_got_page_entry *) entry1_;
2859   entry2 = (const struct mips_got_page_entry *) entry2_;
2860   return entry1->abfd == entry2->abfd && entry1->symndx == entry2->symndx;
2861 }
2862 \f
2863 /* Create and return a new mips_got_info structure.  MASTER_GOT_P
2864    is true if this is the master GOT rather than a multigot.  */
2865
2866 static struct mips_got_info *
2867 mips_elf_create_got_info (bfd *abfd, bfd_boolean master_got_p)
2868 {
2869   struct mips_got_info *g;
2870
2871   g = bfd_zalloc (abfd, sizeof (struct mips_got_info));
2872   if (g == NULL)
2873     return NULL;
2874
2875   g->tls_ldm_offset = MINUS_ONE;
2876   if (master_got_p)
2877     g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
2878                                       mips_elf_got_entry_eq, NULL);
2879   else
2880     g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
2881                                       mips_elf_multi_got_entry_eq, NULL);
2882   if (g->got_entries == NULL)
2883     return NULL;
2884
2885   g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
2886                                          mips_got_page_entry_eq, NULL);
2887   if (g->got_page_entries == NULL)
2888     return NULL;
2889
2890   return g;
2891 }
2892
2893 /* Return the dynamic relocation section.  If it doesn't exist, try to
2894    create a new it if CREATE_P, otherwise return NULL.  Also return NULL
2895    if creation fails.  */
2896
2897 static asection *
2898 mips_elf_rel_dyn_section (struct bfd_link_info *info, bfd_boolean create_p)
2899 {
2900   const char *dname;
2901   asection *sreloc;
2902   bfd *dynobj;
2903
2904   dname = MIPS_ELF_REL_DYN_NAME (info);
2905   dynobj = elf_hash_table (info)->dynobj;
2906   sreloc = bfd_get_linker_section (dynobj, dname);
2907   if (sreloc == NULL && create_p)
2908     {
2909       sreloc = bfd_make_section_anyway_with_flags (dynobj, dname,
2910                                                    (SEC_ALLOC
2911                                                     | SEC_LOAD
2912                                                     | SEC_HAS_CONTENTS
2913                                                     | SEC_IN_MEMORY
2914                                                     | SEC_LINKER_CREATED
2915                                                     | SEC_READONLY));
2916       if (sreloc == NULL
2917           || ! bfd_set_section_alignment (dynobj, sreloc,
2918                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
2919         return NULL;
2920     }
2921   return sreloc;
2922 }
2923
2924 /* Return the GOT_TLS_* type required by relocation type R_TYPE.  */
2925
2926 static int
2927 mips_elf_reloc_tls_type (unsigned int r_type)
2928 {
2929   if (tls_gd_reloc_p (r_type))
2930     return GOT_TLS_GD;
2931
2932   if (tls_ldm_reloc_p (r_type))
2933     return GOT_TLS_LDM;
2934
2935   if (tls_gottprel_reloc_p (r_type))
2936     return GOT_TLS_IE;
2937
2938   return GOT_NORMAL;
2939 }
2940
2941 /* Return the number of GOT slots needed for GOT TLS type TYPE.  */
2942
2943 static int
2944 mips_tls_got_entries (unsigned int type)
2945 {
2946   switch (type)
2947     {
2948     case GOT_TLS_GD:
2949     case GOT_TLS_LDM:
2950       return 2;
2951
2952     case GOT_TLS_IE:
2953       return 1;
2954
2955     case GOT_NORMAL:
2956       return 0;
2957     }
2958   abort ();
2959 }
2960
2961 /* Count the number of relocations needed for a TLS GOT entry, with
2962    access types from TLS_TYPE, and symbol H (or a local symbol if H
2963    is NULL).  */
2964
2965 static int
2966 mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type,
2967                      struct elf_link_hash_entry *h)
2968 {
2969   int indx = 0;
2970   bfd_boolean need_relocs = FALSE;
2971   bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
2972
2973   if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, h)
2974       && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, h)))
2975     indx = h->dynindx;
2976
2977   if ((info->shared || indx != 0)
2978       && (h == NULL
2979           || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2980           || h->root.type != bfd_link_hash_undefweak))
2981     need_relocs = TRUE;
2982
2983   if (!need_relocs)
2984     return 0;
2985
2986   switch (tls_type & GOT_TLS_TYPE)
2987     {
2988     case GOT_TLS_GD:
2989       return indx != 0 ? 2 : 1;
2990
2991     case GOT_TLS_IE:
2992       return 1;
2993
2994     case GOT_TLS_LDM:
2995       return info->shared ? 1 : 0;
2996
2997     default:
2998       return 0;
2999     }
3000 }
3001
3002 /* Count the number of TLS relocations required for the GOT entry in
3003    ARG1, if it describes a local symbol.  */
3004
3005 static int
3006 mips_elf_count_local_tls_relocs (void **arg1, void *arg2)
3007 {
3008   struct mips_got_entry *entry = * (struct mips_got_entry **) arg1;
3009   struct mips_elf_count_tls_arg *arg = arg2;
3010
3011   if (entry->abfd != NULL && entry->symndx != -1)
3012     arg->needed += mips_tls_got_relocs (arg->info, entry->tls_type, NULL);
3013
3014   return 1;
3015 }
3016
3017 /* Count the number of TLS GOT entries required for the global (or
3018    forced-local) symbol in ARG1.  */
3019
3020 static int
3021 mips_elf_count_global_tls_entries (void *arg1, void *arg2)
3022 {
3023   struct mips_elf_link_hash_entry *hm
3024     = (struct mips_elf_link_hash_entry *) arg1;
3025   struct mips_elf_count_tls_arg *arg = arg2;
3026
3027   if (hm->root.root.type == bfd_link_hash_indirect
3028       || hm->root.root.type == bfd_link_hash_warning)
3029     return 1;
3030
3031   if (hm->tls_gd_type)
3032     arg->needed += 2;
3033   if (hm->tls_ie_type)
3034     arg->needed += 1;
3035
3036   return 1;
3037 }
3038
3039 /* Count the number of TLS relocations required for the global (or
3040    forced-local) symbol in ARG1.  */
3041
3042 static int
3043 mips_elf_count_global_tls_relocs (void *arg1, void *arg2)
3044 {
3045   struct mips_elf_link_hash_entry *hm
3046     = (struct mips_elf_link_hash_entry *) arg1;
3047   struct mips_elf_count_tls_arg *arg = arg2;
3048
3049   if (hm->root.root.type == bfd_link_hash_indirect
3050       || hm->root.root.type == bfd_link_hash_warning)
3051     return 1;
3052
3053   arg->needed += mips_tls_got_relocs (arg->info, hm->tls_ie_type, &hm->root);
3054   arg->needed += mips_tls_got_relocs (arg->info, hm->tls_gd_type, &hm->root);
3055
3056   return 1;
3057 }
3058
3059 /* Output a simple dynamic relocation into SRELOC.  */
3060
3061 static void
3062 mips_elf_output_dynamic_relocation (bfd *output_bfd,
3063                                     asection *sreloc,
3064                                     unsigned long reloc_index,
3065                                     unsigned long indx,
3066                                     int r_type,
3067                                     bfd_vma offset)
3068 {
3069   Elf_Internal_Rela rel[3];
3070
3071   memset (rel, 0, sizeof (rel));
3072
3073   rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type);
3074   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
3075
3076   if (ABI_64_P (output_bfd))
3077     {
3078       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
3079         (output_bfd, &rel[0],
3080          (sreloc->contents
3081           + reloc_index * sizeof (Elf64_Mips_External_Rel)));
3082     }
3083   else
3084     bfd_elf32_swap_reloc_out
3085       (output_bfd, &rel[0],
3086        (sreloc->contents
3087         + reloc_index * sizeof (Elf32_External_Rel)));
3088 }
3089
3090 /* Initialize a set of TLS GOT entries for one symbol.  */
3091
3092 static void
3093 mips_elf_initialize_tls_slots (bfd *abfd, bfd_vma got_offset,
3094                                unsigned char *tls_type_p,
3095                                struct bfd_link_info *info,
3096                                struct mips_elf_link_hash_entry *h,
3097                                bfd_vma value)
3098 {
3099   struct mips_elf_link_hash_table *htab;
3100   int indx;
3101   asection *sreloc, *sgot;
3102   bfd_vma got_offset2;
3103   bfd_boolean need_relocs = FALSE;
3104
3105   htab = mips_elf_hash_table (info);
3106   if (htab == NULL)
3107     return;
3108
3109   sgot = htab->sgot;
3110
3111   indx = 0;
3112   if (h != NULL)
3113     {
3114       bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3115
3116       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, &h->root)
3117           && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3118         indx = h->root.dynindx;
3119     }
3120
3121   if (*tls_type_p & GOT_TLS_DONE)
3122     return;
3123
3124   if ((info->shared || indx != 0)
3125       && (h == NULL
3126           || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT
3127           || h->root.type != bfd_link_hash_undefweak))
3128     need_relocs = TRUE;
3129
3130   /* MINUS_ONE means the symbol is not defined in this object.  It may not
3131      be defined at all; assume that the value doesn't matter in that
3132      case.  Otherwise complain if we would use the value.  */
3133   BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs)
3134               || h->root.root.type == bfd_link_hash_undefweak);
3135
3136   /* Emit necessary relocations.  */
3137   sreloc = mips_elf_rel_dyn_section (info, FALSE);
3138
3139   switch (*tls_type_p & GOT_TLS_TYPE)
3140     {
3141     case GOT_TLS_GD:
3142       /* General Dynamic.  */
3143       got_offset2 = got_offset + MIPS_ELF_GOT_SIZE (abfd);
3144
3145       if (need_relocs)
3146         {
3147           mips_elf_output_dynamic_relocation
3148             (abfd, sreloc, sreloc->reloc_count++, indx,
3149              ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3150              sgot->output_offset + sgot->output_section->vma + got_offset);
3151
3152           if (indx)
3153             mips_elf_output_dynamic_relocation
3154               (abfd, sreloc, sreloc->reloc_count++, indx,
3155                ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32,
3156                sgot->output_offset + sgot->output_section->vma + got_offset2);
3157           else
3158             MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3159                                sgot->contents + got_offset2);
3160         }
3161       else
3162         {
3163           MIPS_ELF_PUT_WORD (abfd, 1,
3164                              sgot->contents + got_offset);
3165           MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3166                              sgot->contents + got_offset2);
3167         }
3168       break;
3169
3170     case GOT_TLS_IE:
3171       /* Initial Exec model.  */
3172       if (need_relocs)
3173         {
3174           if (indx == 0)
3175             MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma,
3176                                sgot->contents + got_offset);
3177           else
3178             MIPS_ELF_PUT_WORD (abfd, 0,
3179                                sgot->contents + got_offset);
3180
3181           mips_elf_output_dynamic_relocation
3182             (abfd, sreloc, sreloc->reloc_count++, indx,
3183              ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32,
3184              sgot->output_offset + sgot->output_section->vma + got_offset);
3185         }
3186       else
3187         MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info),
3188                            sgot->contents + got_offset);
3189       break;
3190
3191     case GOT_TLS_LDM:
3192       /* The initial offset is zero, and the LD offsets will include the
3193          bias by DTP_OFFSET.  */
3194       MIPS_ELF_PUT_WORD (abfd, 0,
3195                          sgot->contents + got_offset
3196                          + MIPS_ELF_GOT_SIZE (abfd));
3197
3198       if (!info->shared)
3199         MIPS_ELF_PUT_WORD (abfd, 1,
3200                            sgot->contents + got_offset);
3201       else
3202         mips_elf_output_dynamic_relocation
3203           (abfd, sreloc, sreloc->reloc_count++, indx,
3204            ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3205            sgot->output_offset + sgot->output_section->vma + got_offset);
3206       break;
3207
3208     default:
3209       abort ();
3210     }
3211
3212   *tls_type_p |= GOT_TLS_DONE;
3213 }
3214
3215 /* Return the GOT index to use for a relocation against H using the
3216    TLS model in *TLS_TYPE.  The GOT entries for this symbol/model
3217    combination start at GOT_INDEX into ABFD's GOT.  This function
3218    initializes the GOT entries and corresponding relocations.  */
3219
3220 static bfd_vma
3221 mips_tls_got_index (bfd *abfd, bfd_vma got_index, unsigned char *tls_type,
3222                     struct bfd_link_info *info,
3223                     struct mips_elf_link_hash_entry *h, bfd_vma symbol)
3224 {
3225   mips_elf_initialize_tls_slots (abfd, got_index, tls_type, info, h, symbol);
3226   return got_index;
3227 }
3228
3229 /* Return the GOT index to use for a relocation of type R_TYPE against H
3230    in ABFD.  */
3231
3232 static bfd_vma
3233 mips_tls_single_got_index (bfd *abfd, int r_type, struct bfd_link_info *info,
3234                            struct mips_elf_link_hash_entry *h, bfd_vma symbol)
3235 {
3236   if (tls_gottprel_reloc_p (r_type))
3237     return mips_tls_got_index (abfd, h->tls_ie_got_offset, &h->tls_ie_type,
3238                                info, h, symbol);
3239   if (tls_gd_reloc_p (r_type))
3240     return mips_tls_got_index (abfd, h->tls_gd_got_offset, &h->tls_gd_type,
3241                                info, h, symbol);
3242   abort ();
3243 }
3244
3245 /* Return the offset from _GLOBAL_OFFSET_TABLE_ of the .got.plt entry
3246    for global symbol H.  .got.plt comes before the GOT, so the offset
3247    will be negative.  */
3248
3249 static bfd_vma
3250 mips_elf_gotplt_index (struct bfd_link_info *info,
3251                        struct elf_link_hash_entry *h)
3252 {
3253   bfd_vma plt_index, got_address, got_value;
3254   struct mips_elf_link_hash_table *htab;
3255
3256   htab = mips_elf_hash_table (info);
3257   BFD_ASSERT (htab != NULL);
3258
3259   BFD_ASSERT (h->plt.offset != (bfd_vma) -1);
3260
3261   /* This function only works for VxWorks, because a non-VxWorks .got.plt
3262      section starts with reserved entries.  */
3263   BFD_ASSERT (htab->is_vxworks);
3264
3265   /* Calculate the index of the symbol's PLT entry.  */
3266   plt_index = (h->plt.offset - htab->plt_header_size) / htab->plt_entry_size;
3267
3268   /* Calculate the address of the associated .got.plt entry.  */
3269   got_address = (htab->sgotplt->output_section->vma
3270                  + htab->sgotplt->output_offset
3271                  + plt_index * 4);
3272
3273   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
3274   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
3275                + htab->root.hgot->root.u.def.section->output_offset
3276                + htab->root.hgot->root.u.def.value);
3277
3278   return got_address - got_value;
3279 }
3280
3281 /* Return the GOT offset for address VALUE.   If there is not yet a GOT
3282    entry for this value, create one.  If R_SYMNDX refers to a TLS symbol,
3283    create a TLS GOT entry instead.  Return -1 if no satisfactory GOT
3284    offset can be found.  */
3285
3286 static bfd_vma
3287 mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3288                           bfd_vma value, unsigned long r_symndx,
3289                           struct mips_elf_link_hash_entry *h, int r_type)
3290 {
3291   struct mips_elf_link_hash_table *htab;
3292   struct mips_got_entry *entry;
3293
3294   htab = mips_elf_hash_table (info);
3295   BFD_ASSERT (htab != NULL);
3296
3297   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value,
3298                                            r_symndx, h, r_type);
3299   if (!entry)
3300     return MINUS_ONE;
3301
3302   if (entry->tls_type)
3303     {
3304       if (entry->symndx == -1 && htab->got_info->next == NULL)
3305         /* A type (3) entry in the single-GOT case.  We use the symbol's
3306            hash table entry to track the index.  */
3307         return mips_tls_single_got_index (abfd, r_type, info, h, value);
3308       else
3309         return mips_tls_got_index (abfd, entry->gotidx, &entry->tls_type,
3310                                    info, h, value);
3311     }
3312   else
3313     return entry->gotidx;
3314 }
3315
3316 /* Returns the GOT index for the global symbol indicated by H.  */
3317
3318 static bfd_vma
3319 mips_elf_global_got_index (bfd *abfd, bfd *ibfd, struct elf_link_hash_entry *h,
3320                            int r_type, struct bfd_link_info *info)
3321 {
3322   struct mips_elf_link_hash_table *htab;
3323   bfd_vma got_index;
3324   struct mips_got_info *g, *gg;
3325   long global_got_dynindx = 0;
3326
3327   htab = mips_elf_hash_table (info);
3328   BFD_ASSERT (htab != NULL);
3329
3330   gg = g = htab->got_info;
3331   if (g->bfd2got && ibfd)
3332     {
3333       struct mips_got_entry e, *p;
3334
3335       BFD_ASSERT (h->dynindx >= 0);
3336
3337       g = mips_elf_got_for_ibfd (g, ibfd);
3338       if (g->next != gg || TLS_RELOC_P (r_type))
3339         {
3340           e.abfd = ibfd;
3341           e.symndx = -1;
3342           e.d.h = (struct mips_elf_link_hash_entry *)h;
3343           e.tls_type = mips_elf_reloc_tls_type (r_type);
3344
3345           p = htab_find (g->got_entries, &e);
3346
3347           BFD_ASSERT (p && p->gotidx > 0);
3348
3349           if (p->tls_type)
3350             {
3351               bfd_vma value = MINUS_ONE;
3352               if ((h->root.type == bfd_link_hash_defined
3353                    || h->root.type == bfd_link_hash_defweak)
3354                   && h->root.u.def.section->output_section)
3355                 value = (h->root.u.def.value
3356                          + h->root.u.def.section->output_offset
3357                          + h->root.u.def.section->output_section->vma);
3358
3359               return mips_tls_got_index (abfd, p->gotidx, &p->tls_type,
3360                                          info, e.d.h, value);
3361             }
3362           else
3363             return p->gotidx;
3364         }
3365     }
3366
3367   if (htab->global_gotsym != NULL)
3368     global_got_dynindx = htab->global_gotsym->dynindx;
3369
3370   if (TLS_RELOC_P (r_type))
3371     {
3372       struct mips_elf_link_hash_entry *hm
3373         = (struct mips_elf_link_hash_entry *) h;
3374       bfd_vma value = MINUS_ONE;
3375
3376       if ((h->root.type == bfd_link_hash_defined
3377            || h->root.type == bfd_link_hash_defweak)
3378           && h->root.u.def.section->output_section)
3379         value = (h->root.u.def.value
3380                  + h->root.u.def.section->output_offset
3381                  + h->root.u.def.section->output_section->vma);
3382
3383       got_index = mips_tls_single_got_index (abfd, r_type, info, hm, value);
3384     }
3385   else
3386     {
3387       /* Once we determine the global GOT entry with the lowest dynamic
3388          symbol table index, we must put all dynamic symbols with greater
3389          indices into the GOT.  That makes it easy to calculate the GOT
3390          offset.  */
3391       BFD_ASSERT (h->dynindx >= global_got_dynindx);
3392       got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3393                    * MIPS_ELF_GOT_SIZE (abfd));
3394     }
3395   BFD_ASSERT (got_index < htab->sgot->size);
3396
3397   return got_index;
3398 }
3399
3400 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3401    entries are supposed to be placed at small offsets in the GOT, i.e.,
3402    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3403    entry could be created.  If OFFSETP is nonnull, use it to return the
3404    offset of the GOT entry from VALUE.  */
3405
3406 static bfd_vma
3407 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3408                    bfd_vma value, bfd_vma *offsetp)
3409 {
3410   bfd_vma page, got_index;
3411   struct mips_got_entry *entry;
3412
3413   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3414   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3415                                            NULL, R_MIPS_GOT_PAGE);
3416
3417   if (!entry)
3418     return MINUS_ONE;
3419
3420   got_index = entry->gotidx;
3421
3422   if (offsetp)
3423     *offsetp = value - entry->d.address;
3424
3425   return got_index;
3426 }
3427
3428 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3429    EXTERNAL is true if the relocation was originally against a global
3430    symbol that binds locally.  */
3431
3432 static bfd_vma
3433 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3434                       bfd_vma value, bfd_boolean external)
3435 {
3436   struct mips_got_entry *entry;
3437
3438   /* GOT16 relocations against local symbols are followed by a LO16
3439      relocation; those against global symbols are not.  Thus if the
3440      symbol was originally local, the GOT16 relocation should load the
3441      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3442   if (! external)
3443     value = mips_elf_high (value) << 16;
3444
3445   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3446      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3447      same in all cases.  */
3448   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3449                                            NULL, R_MIPS_GOT16);
3450   if (entry)
3451     return entry->gotidx;
3452   else
3453     return MINUS_ONE;
3454 }
3455
3456 /* Returns the offset for the entry at the INDEXth position
3457    in the GOT.  */
3458
3459 static bfd_vma
3460 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3461                                 bfd *input_bfd, bfd_vma got_index)
3462 {
3463   struct mips_elf_link_hash_table *htab;
3464   asection *sgot;
3465   bfd_vma gp;
3466
3467   htab = mips_elf_hash_table (info);
3468   BFD_ASSERT (htab != NULL);
3469
3470   sgot = htab->sgot;
3471   gp = _bfd_get_gp_value (output_bfd)
3472     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3473
3474   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3475 }
3476
3477 /* Create and return a local GOT entry for VALUE, which was calculated
3478    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3479    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3480    instead.  */
3481
3482 static struct mips_got_entry *
3483 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3484                                  bfd *ibfd, bfd_vma value,
3485                                  unsigned long r_symndx,
3486                                  struct mips_elf_link_hash_entry *h,
3487                                  int r_type)
3488 {
3489   struct mips_got_entry entry, **loc;
3490   struct mips_got_info *g;
3491   struct mips_elf_link_hash_table *htab;
3492
3493   htab = mips_elf_hash_table (info);
3494   BFD_ASSERT (htab != NULL);
3495
3496   entry.abfd = NULL;
3497   entry.symndx = -1;
3498   entry.d.address = value;
3499   entry.tls_type = mips_elf_reloc_tls_type (r_type);
3500
3501   g = mips_elf_got_for_ibfd (htab->got_info, ibfd);
3502   if (g == NULL)
3503     {
3504       g = mips_elf_got_for_ibfd (htab->got_info, abfd);
3505       BFD_ASSERT (g != NULL);
3506     }
3507
3508   /* This function shouldn't be called for symbols that live in the global
3509      area of the GOT.  */
3510   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3511   if (entry.tls_type)
3512     {
3513       struct mips_got_entry *p;
3514
3515       entry.abfd = ibfd;
3516       if (tls_ldm_reloc_p (r_type))
3517         {
3518           entry.symndx = 0;
3519           entry.d.addend = 0;
3520         }
3521       else if (h == NULL)
3522         {
3523           entry.symndx = r_symndx;
3524           entry.d.addend = 0;
3525         }
3526       else
3527         entry.d.h = h;
3528
3529       p = (struct mips_got_entry *)
3530         htab_find (g->got_entries, &entry);
3531
3532       BFD_ASSERT (p);
3533       return p;
3534     }
3535
3536   loc = (struct mips_got_entry **) htab_find_slot (g->got_entries, &entry,
3537                                                    INSERT);
3538   if (*loc)
3539     return *loc;
3540
3541   entry.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_gotno++;
3542
3543   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3544
3545   if (! *loc)
3546     return NULL;
3547
3548   memcpy (*loc, &entry, sizeof entry);
3549
3550   if (g->assigned_gotno > g->local_gotno)
3551     {
3552       (*loc)->gotidx = -1;
3553       /* We didn't allocate enough space in the GOT.  */
3554       (*_bfd_error_handler)
3555         (_("not enough GOT space for local GOT entries"));
3556       bfd_set_error (bfd_error_bad_value);
3557       return NULL;
3558     }
3559
3560   MIPS_ELF_PUT_WORD (abfd, value,
3561                      (htab->sgot->contents + entry.gotidx));
3562
3563   /* These GOT entries need a dynamic relocation on VxWorks.  */
3564   if (htab->is_vxworks)
3565     {
3566       Elf_Internal_Rela outrel;
3567       asection *s;
3568       bfd_byte *rloc;
3569       bfd_vma got_address;
3570
3571       s = mips_elf_rel_dyn_section (info, FALSE);
3572       got_address = (htab->sgot->output_section->vma
3573                      + htab->sgot->output_offset
3574                      + entry.gotidx);
3575
3576       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3577       outrel.r_offset = got_address;
3578       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3579       outrel.r_addend = value;
3580       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3581     }
3582
3583   return *loc;
3584 }
3585
3586 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3587    The number might be exact or a worst-case estimate, depending on how
3588    much information is available to elf_backend_omit_section_dynsym at
3589    the current linking stage.  */
3590
3591 static bfd_size_type
3592 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3593 {
3594   bfd_size_type count;
3595
3596   count = 0;
3597   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
3598     {
3599       asection *p;
3600       const struct elf_backend_data *bed;
3601
3602       bed = get_elf_backend_data (output_bfd);
3603       for (p = output_bfd->sections; p ; p = p->next)
3604         if ((p->flags & SEC_EXCLUDE) == 0
3605             && (p->flags & SEC_ALLOC) != 0
3606             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3607           ++count;
3608     }
3609   return count;
3610 }
3611
3612 /* Sort the dynamic symbol table so that symbols that need GOT entries
3613    appear towards the end.  */
3614
3615 static bfd_boolean
3616 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3617 {
3618   struct mips_elf_link_hash_table *htab;
3619   struct mips_elf_hash_sort_data hsd;
3620   struct mips_got_info *g;
3621
3622   if (elf_hash_table (info)->dynsymcount == 0)
3623     return TRUE;
3624
3625   htab = mips_elf_hash_table (info);
3626   BFD_ASSERT (htab != NULL);
3627
3628   g = htab->got_info;
3629   if (g == NULL)
3630     return TRUE;
3631
3632   hsd.low = NULL;
3633   hsd.max_unref_got_dynindx
3634     = hsd.min_got_dynindx
3635     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3636   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3637   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3638                                 elf_hash_table (info)),
3639                                mips_elf_sort_hash_table_f,
3640                                &hsd);
3641
3642   /* There should have been enough room in the symbol table to
3643      accommodate both the GOT and non-GOT symbols.  */
3644   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3645   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3646               == elf_hash_table (info)->dynsymcount);
3647   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3648               == g->global_gotno);
3649
3650   /* Now we know which dynamic symbol has the lowest dynamic symbol
3651      table index in the GOT.  */
3652   htab->global_gotsym = hsd.low;
3653
3654   return TRUE;
3655 }
3656
3657 /* If H needs a GOT entry, assign it the highest available dynamic
3658    index.  Otherwise, assign it the lowest available dynamic
3659    index.  */
3660
3661 static bfd_boolean
3662 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3663 {
3664   struct mips_elf_hash_sort_data *hsd = data;
3665
3666   /* Symbols without dynamic symbol table entries aren't interesting
3667      at all.  */
3668   if (h->root.dynindx == -1)
3669     return TRUE;
3670
3671   switch (h->global_got_area)
3672     {
3673     case GGA_NONE:
3674       h->root.dynindx = hsd->max_non_got_dynindx++;
3675       break;
3676
3677     case GGA_NORMAL:
3678       h->root.dynindx = --hsd->min_got_dynindx;
3679       hsd->low = (struct elf_link_hash_entry *) h;
3680       break;
3681
3682     case GGA_RELOC_ONLY:
3683       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3684         hsd->low = (struct elf_link_hash_entry *) h;
3685       h->root.dynindx = hsd->max_unref_got_dynindx++;
3686       break;
3687     }
3688
3689   return TRUE;
3690 }
3691
3692 /* ABFD has a GOT relocation of type R_TYPE against H.  Reserve a GOT
3693    entry for it.  FOR_CALL is true if the caller is only interested in
3694    using the GOT entry for calls.  */
3695
3696 static bfd_boolean
3697 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3698                                    bfd *abfd, struct bfd_link_info *info,
3699                                    bfd_boolean for_call, int r_type)
3700 {
3701   struct mips_elf_link_hash_table *htab;
3702   struct mips_elf_link_hash_entry *hmips;
3703   struct mips_got_entry entry, **loc;
3704   struct mips_got_info *g;
3705
3706   htab = mips_elf_hash_table (info);
3707   BFD_ASSERT (htab != NULL);
3708
3709   hmips = (struct mips_elf_link_hash_entry *) h;
3710   if (!for_call)
3711     hmips->got_only_for_calls = FALSE;
3712
3713   /* A global symbol in the GOT must also be in the dynamic symbol
3714      table.  */
3715   if (h->dynindx == -1)
3716     {
3717       switch (ELF_ST_VISIBILITY (h->other))
3718         {
3719         case STV_INTERNAL:
3720         case STV_HIDDEN:
3721           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3722           break;
3723         }
3724       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3725         return FALSE;
3726     }
3727
3728   /* Make sure we have a GOT to put this entry into.  */
3729   g = htab->got_info;
3730   BFD_ASSERT (g != NULL);
3731
3732   entry.abfd = abfd;
3733   entry.symndx = -1;
3734   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3735   entry.tls_type = mips_elf_reloc_tls_type (r_type);
3736
3737   loc = (struct mips_got_entry **) htab_find_slot (g->got_entries, &entry,
3738                                                    INSERT);
3739
3740   /* If we've already marked this entry as needing GOT space, we don't
3741      need to do it again.  */
3742   if (*loc)
3743     return TRUE;
3744
3745   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3746
3747   if (! *loc)
3748     return FALSE;
3749
3750   entry.gotidx = -1;
3751
3752   memcpy (*loc, &entry, sizeof entry);
3753
3754   if (entry.tls_type == GOT_NORMAL)
3755     hmips->global_got_area = GGA_NORMAL;
3756   else if (entry.tls_type == GOT_TLS_IE)
3757     hmips->tls_ie_type = entry.tls_type;
3758   else if (entry.tls_type == GOT_TLS_GD)
3759     hmips->tls_gd_type = entry.tls_type;
3760
3761   return TRUE;
3762 }
3763
3764 /* ABFD has a GOT relocation of type R_TYPE against symbol SYMNDX + ADDEND,
3765    where SYMNDX is a local symbol.  Reserve a GOT entry for it.  */
3766
3767 static bfd_boolean
3768 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
3769                                   struct bfd_link_info *info, int r_type)
3770 {
3771   struct mips_elf_link_hash_table *htab;
3772   struct mips_got_info *g;
3773   struct mips_got_entry entry, **loc;
3774
3775   htab = mips_elf_hash_table (info);
3776   BFD_ASSERT (htab != NULL);
3777
3778   g = htab->got_info;
3779   BFD_ASSERT (g != NULL);
3780
3781   entry.abfd = abfd;
3782   entry.symndx = symndx;
3783   entry.d.addend = addend;
3784   entry.tls_type = mips_elf_reloc_tls_type (r_type);
3785   loc = (struct mips_got_entry **)
3786     htab_find_slot (g->got_entries, &entry, INSERT);
3787
3788   if (*loc)
3789     return TRUE;
3790
3791   entry.gotidx = -1;
3792   if (entry.tls_type)
3793     {
3794       if (entry.tls_type != GOT_TLS_LDM)
3795         g->tls_gotno += mips_tls_got_entries (entry.tls_type);
3796       else if (g->tls_ldm_offset == MINUS_ONE)
3797         {
3798           g->tls_ldm_offset = MINUS_TWO;
3799           g->tls_gotno += mips_tls_got_entries (entry.tls_type);
3800         }
3801     }
3802   else
3803     g->local_gotno += 1;
3804
3805   *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry);
3806
3807   if (! *loc)
3808     return FALSE;
3809
3810   memcpy (*loc, &entry, sizeof entry);
3811
3812   return TRUE;
3813 }
3814
3815 /* Return the maximum number of GOT page entries required for RANGE.  */
3816
3817 static bfd_vma
3818 mips_elf_pages_for_range (const struct mips_got_page_range *range)
3819 {
3820   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
3821 }
3822
3823 /* Record that ABFD has a page relocation against symbol SYMNDX and
3824    that ADDEND is the addend for that relocation.
3825
3826    This function creates an upper bound on the number of GOT slots
3827    required; no attempt is made to combine references to non-overridable
3828    global symbols across multiple input files.  */
3829
3830 static bfd_boolean
3831 mips_elf_record_got_page_entry (struct bfd_link_info *info, bfd *abfd,
3832                                 long symndx, bfd_signed_vma addend)
3833 {
3834   struct mips_elf_link_hash_table *htab;
3835   struct mips_got_info *g;
3836   struct mips_got_page_entry lookup, *entry;
3837   struct mips_got_page_range **range_ptr, *range;
3838   bfd_vma old_pages, new_pages;
3839   void **loc;
3840
3841   htab = mips_elf_hash_table (info);
3842   BFD_ASSERT (htab != NULL);
3843
3844   g = htab->got_info;
3845   BFD_ASSERT (g != NULL);
3846
3847   /* Find the mips_got_page_entry hash table entry for this symbol.  */
3848   lookup.abfd = abfd;
3849   lookup.symndx = symndx;
3850   loc = htab_find_slot (g->got_page_entries, &lookup, INSERT);
3851   if (loc == NULL)
3852     return FALSE;
3853
3854   /* Create a mips_got_page_entry if this is the first time we've
3855      seen the symbol.  */
3856   entry = (struct mips_got_page_entry *) *loc;
3857   if (!entry)
3858     {
3859       entry = bfd_alloc (abfd, sizeof (*entry));
3860       if (!entry)
3861         return FALSE;
3862
3863       entry->abfd = abfd;
3864       entry->symndx = symndx;
3865       entry->ranges = NULL;
3866       entry->num_pages = 0;
3867       *loc = entry;
3868     }
3869
3870   /* Skip over ranges whose maximum extent cannot share a page entry
3871      with ADDEND.  */
3872   range_ptr = &entry->ranges;
3873   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
3874     range_ptr = &(*range_ptr)->next;
3875
3876   /* If we scanned to the end of the list, or found a range whose
3877      minimum extent cannot share a page entry with ADDEND, create
3878      a new singleton range.  */
3879   range = *range_ptr;
3880   if (!range || addend < range->min_addend - 0xffff)
3881     {
3882       range = bfd_alloc (abfd, sizeof (*range));
3883       if (!range)
3884         return FALSE;
3885
3886       range->next = *range_ptr;
3887       range->min_addend = addend;
3888       range->max_addend = addend;
3889
3890       *range_ptr = range;
3891       entry->num_pages++;
3892       g->page_gotno++;
3893       return TRUE;
3894     }
3895
3896   /* Remember how many pages the old range contributed.  */
3897   old_pages = mips_elf_pages_for_range (range);
3898
3899   /* Update the ranges.  */
3900   if (addend < range->min_addend)
3901     range->min_addend = addend;
3902   else if (addend > range->max_addend)
3903     {
3904       if (range->next && addend >= range->next->min_addend - 0xffff)
3905         {
3906           old_pages += mips_elf_pages_for_range (range->next);
3907           range->max_addend = range->next->max_addend;
3908           range->next = range->next->next;
3909         }
3910       else
3911         range->max_addend = addend;
3912     }
3913
3914   /* Record any change in the total estimate.  */
3915   new_pages = mips_elf_pages_for_range (range);
3916   if (old_pages != new_pages)
3917     {
3918       entry->num_pages += new_pages - old_pages;
3919       g->page_gotno += new_pages - old_pages;
3920     }
3921
3922   return TRUE;
3923 }
3924
3925 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
3926
3927 static void
3928 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
3929                                        unsigned int n)
3930 {
3931   asection *s;
3932   struct mips_elf_link_hash_table *htab;
3933
3934   htab = mips_elf_hash_table (info);
3935   BFD_ASSERT (htab != NULL);
3936
3937   s = mips_elf_rel_dyn_section (info, FALSE);
3938   BFD_ASSERT (s != NULL);
3939
3940   if (htab->is_vxworks)
3941     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
3942   else
3943     {
3944       if (s->size == 0)
3945         {
3946           /* Make room for a null element.  */
3947           s->size += MIPS_ELF_REL_SIZE (abfd);
3948           ++s->reloc_count;
3949         }
3950       s->size += n * MIPS_ELF_REL_SIZE (abfd);
3951     }
3952 }
3953 \f
3954 /* A htab_traverse callback for GOT entries.  Set boolean *DATA to true
3955    if the GOT entry is for an indirect or warning symbol.  */
3956
3957 static int
3958 mips_elf_check_recreate_got (void **entryp, void *data)
3959 {
3960   struct mips_got_entry *entry;
3961   bfd_boolean *must_recreate;
3962
3963   entry = (struct mips_got_entry *) *entryp;
3964   must_recreate = (bfd_boolean *) data;
3965   if (entry->abfd != NULL && entry->symndx == -1)
3966     {
3967       struct mips_elf_link_hash_entry *h;
3968
3969       h = entry->d.h;
3970       if (h->root.root.type == bfd_link_hash_indirect
3971           || h->root.root.type == bfd_link_hash_warning)
3972         {
3973           *must_recreate = TRUE;
3974           return 0;
3975         }
3976     }
3977   return 1;
3978 }
3979
3980 /* A htab_traverse callback for GOT entries.  Add all entries to
3981    hash table *DATA, converting entries for indirect and warning
3982    symbols into entries for the target symbol.  Set *DATA to null
3983    on error.  */
3984
3985 static int
3986 mips_elf_recreate_got (void **entryp, void *data)
3987 {
3988   htab_t *new_got;
3989   struct mips_got_entry *entry;
3990   void **slot;
3991
3992   new_got = (htab_t *) data;
3993   entry = (struct mips_got_entry *) *entryp;
3994   if (entry->abfd != NULL && entry->symndx == -1)
3995     {
3996       struct mips_elf_link_hash_entry *h;
3997
3998       h = entry->d.h;
3999       while (h->root.root.type == bfd_link_hash_indirect
4000              || h->root.root.type == bfd_link_hash_warning)
4001         {
4002           BFD_ASSERT (h->global_got_area == GGA_NONE);
4003           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
4004         }
4005       entry->d.h = h;
4006     }
4007   slot = htab_find_slot (*new_got, entry, INSERT);
4008   if (slot == NULL)
4009     {
4010       *new_got = NULL;
4011       return 0;
4012     }
4013   if (*slot == NULL)
4014     *slot = entry;
4015   return 1;
4016 }
4017
4018 /* If any entries in G->got_entries are for indirect or warning symbols,
4019    replace them with entries for the target symbol.  */
4020
4021 static bfd_boolean
4022 mips_elf_resolve_final_got_entries (struct mips_got_info *g)
4023 {
4024   bfd_boolean must_recreate;
4025   htab_t new_got;
4026
4027   must_recreate = FALSE;
4028   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &must_recreate);
4029   if (must_recreate)
4030     {
4031       new_got = htab_create (htab_size (g->got_entries),
4032                              mips_elf_got_entry_hash,
4033                              mips_elf_got_entry_eq, NULL);
4034       htab_traverse (g->got_entries, mips_elf_recreate_got, &new_got);
4035       if (new_got == NULL)
4036         return FALSE;
4037
4038       htab_delete (g->got_entries);
4039       g->got_entries = new_got;
4040     }
4041   return TRUE;
4042 }
4043
4044 /* A mips_elf_link_hash_traverse callback for which DATA points
4045    to the link_info structure.  Count the number of type (3) entries
4046    in the master GOT.  */
4047
4048 static int
4049 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
4050 {
4051   struct bfd_link_info *info;
4052   struct mips_elf_link_hash_table *htab;
4053   struct mips_got_info *g;
4054
4055   info = (struct bfd_link_info *) data;
4056   htab = mips_elf_hash_table (info);
4057   g = htab->got_info;
4058   if (h->global_got_area != GGA_NONE)
4059     {
4060       /* Make a final decision about whether the symbol belongs in the
4061          local or global GOT.  Symbols that bind locally can (and in the
4062          case of forced-local symbols, must) live in the local GOT.
4063          Those that are aren't in the dynamic symbol table must also
4064          live in the local GOT.
4065
4066          Note that the former condition does not always imply the
4067          latter: symbols do not bind locally if they are completely
4068          undefined.  We'll report undefined symbols later if appropriate.  */
4069       if (h->root.dynindx == -1
4070           || (h->got_only_for_calls
4071               ? SYMBOL_CALLS_LOCAL (info, &h->root)
4072               : SYMBOL_REFERENCES_LOCAL (info, &h->root)))
4073         {
4074           /* The symbol belongs in the local GOT.  We no longer need this
4075              entry if it was only used for relocations; those relocations
4076              will be against the null or section symbol instead of H.  */
4077           if (h->global_got_area != GGA_RELOC_ONLY)
4078             g->local_gotno++;
4079           h->global_got_area = GGA_NONE;
4080         }
4081       else if (htab->is_vxworks
4082                && h->got_only_for_calls
4083                && h->root.plt.offset != MINUS_ONE)
4084         /* On VxWorks, calls can refer directly to the .got.plt entry;
4085            they don't need entries in the regular GOT.  .got.plt entries
4086            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4087         h->global_got_area = GGA_NONE;
4088       else
4089         {
4090           g->global_gotno++;
4091           if (h->global_got_area == GGA_RELOC_ONLY)
4092             g->reloc_only_gotno++;
4093         }
4094     }
4095   return 1;
4096 }
4097 \f
4098 /* Compute the hash value of the bfd in a bfd2got hash entry.  */
4099
4100 static hashval_t
4101 mips_elf_bfd2got_entry_hash (const void *entry_)
4102 {
4103   const struct mips_elf_bfd2got_hash *entry
4104     = (struct mips_elf_bfd2got_hash *)entry_;
4105
4106   return entry->bfd->id;
4107 }
4108
4109 /* Check whether two hash entries have the same bfd.  */
4110
4111 static int
4112 mips_elf_bfd2got_entry_eq (const void *entry1, const void *entry2)
4113 {
4114   const struct mips_elf_bfd2got_hash *e1
4115     = (const struct mips_elf_bfd2got_hash *)entry1;
4116   const struct mips_elf_bfd2got_hash *e2
4117     = (const struct mips_elf_bfd2got_hash *)entry2;
4118
4119   return e1->bfd == e2->bfd;
4120 }
4121
4122 /* In a multi-got link, determine the GOT to be used for IBFD.  G must
4123    be the master GOT data.  */
4124
4125 static struct mips_got_info *
4126 mips_elf_got_for_ibfd (struct mips_got_info *g, bfd *ibfd)
4127 {
4128   struct mips_elf_bfd2got_hash e, *p;
4129
4130   if (! g->bfd2got)
4131     return g;
4132
4133   e.bfd = ibfd;
4134   p = htab_find (g->bfd2got, &e);
4135   return p ? p->g : NULL;
4136 }
4137
4138 /* Use BFD2GOT to find ABFD's got entry, creating one if none exists.
4139    Return NULL if an error occured.  */
4140
4141 static struct mips_got_info *
4142 mips_elf_get_got_for_bfd (struct htab *bfd2got, bfd *output_bfd,
4143                           bfd *input_bfd)
4144 {
4145   struct mips_elf_bfd2got_hash bfdgot_entry, *bfdgot;
4146   void **bfdgotp;
4147
4148   bfdgot_entry.bfd = input_bfd;
4149   bfdgotp = htab_find_slot (bfd2got, &bfdgot_entry, INSERT);
4150   bfdgot = (struct mips_elf_bfd2got_hash *) *bfdgotp;
4151
4152   if (bfdgot == NULL)
4153     {
4154       bfdgot = ((struct mips_elf_bfd2got_hash *)
4155                 bfd_alloc (output_bfd, sizeof (struct mips_elf_bfd2got_hash)));
4156       if (bfdgot == NULL)
4157         return NULL;
4158
4159       *bfdgotp = bfdgot;
4160
4161       bfdgot->bfd = input_bfd;
4162       bfdgot->g = mips_elf_create_got_info (input_bfd, FALSE);
4163       if (bfdgot->g == NULL)
4164         return NULL;
4165     }
4166
4167   return bfdgot->g;
4168 }
4169
4170 /* A htab_traverse callback for the entries in the master got.
4171    Create one separate got for each bfd that has entries in the global
4172    got, such that we can tell how many local and global entries each
4173    bfd requires.  */
4174
4175 static int
4176 mips_elf_make_got_per_bfd (void **entryp, void *p)
4177 {
4178   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4179   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *)p;
4180   struct mips_got_info *g;
4181
4182   g = mips_elf_get_got_for_bfd (arg->bfd2got, arg->obfd, entry->abfd);
4183   if (g == NULL)
4184     {
4185       arg->obfd = NULL;
4186       return 0;
4187     }
4188
4189   /* Insert the GOT entry in the bfd's got entry hash table.  */
4190   entryp = htab_find_slot (g->got_entries, entry, INSERT);
4191   if (*entryp != NULL)
4192     return 1;
4193
4194   *entryp = entry;
4195
4196   if (entry->tls_type)
4197     g->tls_gotno += mips_tls_got_entries (entry->tls_type & GOT_TLS_TYPE);
4198   else if (entry->symndx >= 0 || entry->d.h->global_got_area == GGA_NONE)
4199     g->local_gotno += 1;
4200   else
4201     g->global_gotno += 1;
4202
4203   return 1;
4204 }
4205
4206 /* A htab_traverse callback for the page entries in the master got.
4207    Associate each page entry with the bfd's got.  */
4208
4209 static int
4210 mips_elf_make_got_pages_per_bfd (void **entryp, void *p)
4211 {
4212   struct mips_got_page_entry *entry = (struct mips_got_page_entry *) *entryp;
4213   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *) p;
4214   struct mips_got_info *g;
4215
4216   g = mips_elf_get_got_for_bfd (arg->bfd2got, arg->obfd, entry->abfd);
4217   if (g == NULL)
4218     {
4219       arg->obfd = NULL;
4220       return 0;
4221     }
4222
4223   /* Insert the GOT entry in the bfd's got entry hash table.  */
4224   entryp = htab_find_slot (g->got_page_entries, entry, INSERT);
4225   if (*entryp != NULL)
4226     return 1;
4227
4228   *entryp = entry;
4229   g->page_gotno += entry->num_pages;
4230   return 1;
4231 }
4232
4233 /* Consider merging the got described by BFD2GOT with TO, using the
4234    information given by ARG.  Return -1 if this would lead to overflow,
4235    1 if they were merged successfully, and 0 if a merge failed due to
4236    lack of memory.  (These values are chosen so that nonnegative return
4237    values can be returned by a htab_traverse callback.)  */
4238
4239 static int
4240 mips_elf_merge_got_with (struct mips_elf_bfd2got_hash *bfd2got,
4241                          struct mips_got_info *to,
4242                          struct mips_elf_got_per_bfd_arg *arg)
4243 {
4244   struct mips_got_info *from = bfd2got->g;
4245   unsigned int estimate;
4246
4247   /* Work out how many page entries we would need for the combined GOT.  */
4248   estimate = arg->max_pages;
4249   if (estimate >= from->page_gotno + to->page_gotno)
4250     estimate = from->page_gotno + to->page_gotno;
4251
4252   /* And conservatively estimate how many local and TLS entries
4253      would be needed.  */
4254   estimate += from->local_gotno + to->local_gotno;
4255   estimate += from->tls_gotno + to->tls_gotno;
4256
4257   /* If we're merging with the primary got, any TLS relocations will
4258      come after the full set of global entries.  Otherwise estimate those
4259      conservatively as well.  */
4260   if (to == arg->primary && from->tls_gotno + to->tls_gotno)
4261     estimate += arg->global_count;
4262   else
4263     estimate += from->global_gotno + to->global_gotno;
4264
4265   /* Bail out if the combined GOT might be too big.  */
4266   if (estimate > arg->max_count)
4267     return -1;
4268
4269   /* Commit to the merge.  Record that TO is now the bfd for this got.  */
4270   bfd2got->g = to;
4271
4272   /* Transfer the bfd's got information from FROM to TO.  */
4273   htab_traverse (from->got_entries, mips_elf_make_got_per_bfd, arg);
4274   if (arg->obfd == NULL)
4275     return 0;
4276
4277   htab_traverse (from->got_page_entries, mips_elf_make_got_pages_per_bfd, arg);
4278   if (arg->obfd == NULL)
4279     return 0;
4280
4281   /* We don't have to worry about releasing memory of the actual
4282      got entries, since they're all in the master got_entries hash
4283      table anyway.  */
4284   htab_delete (from->got_entries);
4285   htab_delete (from->got_page_entries);
4286   return 1;
4287 }
4288
4289 /* Attempt to merge gots of different input bfds.  Try to use as much
4290    as possible of the primary got, since it doesn't require explicit
4291    dynamic relocations, but don't use bfds that would reference global
4292    symbols out of the addressable range.  Failing the primary got,
4293    attempt to merge with the current got, or finish the current got
4294    and then make make the new got current.  */
4295
4296 static int
4297 mips_elf_merge_gots (void **bfd2got_, void *p)
4298 {
4299   struct mips_elf_bfd2got_hash *bfd2got
4300     = (struct mips_elf_bfd2got_hash *)*bfd2got_;
4301   struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *)p;
4302   struct mips_got_info *g;
4303   unsigned int estimate;
4304   int result;
4305
4306   g = bfd2got->g;
4307
4308   /* Work out the number of page, local and TLS entries.  */
4309   estimate = arg->max_pages;
4310   if (estimate > g->page_gotno)
4311     estimate = g->page_gotno;
4312   estimate += g->local_gotno + g->tls_gotno;
4313
4314   /* We place TLS GOT entries after both locals and globals.  The globals
4315      for the primary GOT may overflow the normal GOT size limit, so be
4316      sure not to merge a GOT which requires TLS with the primary GOT in that
4317      case.  This doesn't affect non-primary GOTs.  */
4318   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4319
4320   if (estimate <= arg->max_count)
4321     {
4322       /* If we don't have a primary GOT, use it as
4323          a starting point for the primary GOT.  */
4324       if (!arg->primary)
4325         {
4326           arg->primary = bfd2got->g;
4327           return 1;
4328         }
4329
4330       /* Try merging with the primary GOT.  */
4331       result = mips_elf_merge_got_with (bfd2got, arg->primary, arg);
4332       if (result >= 0)
4333         return result;
4334     }
4335
4336   /* If we can merge with the last-created got, do it.  */
4337   if (arg->current)
4338     {
4339       result = mips_elf_merge_got_with (bfd2got, arg->current, arg);
4340       if (result >= 0)
4341         return result;
4342     }
4343
4344   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4345      fits; if it turns out that it doesn't, we'll get relocation
4346      overflows anyway.  */
4347   g->next = arg->current;
4348   arg->current = g;
4349
4350   return 1;
4351 }
4352
4353 /* Set the TLS GOT index for the GOT entry in ENTRYP.  ENTRYP's NEXT field
4354    is null iff there is just a single GOT.  */
4355
4356 static int
4357 mips_elf_initialize_tls_index (void **entryp, void *p)
4358 {
4359   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4360   struct mips_got_info *g = p;
4361   bfd_vma next_index;
4362   unsigned char tls_type;
4363
4364   /* We're only interested in TLS symbols.  */
4365   tls_type = (entry->tls_type & GOT_TLS_TYPE);
4366   if (tls_type == 0)
4367     return 1;
4368
4369   next_index = MIPS_ELF_GOT_SIZE (entry->abfd) * (long) g->tls_assigned_gotno;
4370
4371   if (entry->symndx == -1 && g->next == NULL)
4372     {
4373       /* A type (3) got entry in the single-GOT case.  We use the symbol's
4374          hash table entry to track its index.  */
4375       if (tls_type == GOT_TLS_IE)
4376         {
4377           if (entry->d.h->tls_ie_type & GOT_TLS_OFFSET_DONE)
4378             return 1;
4379           entry->d.h->tls_ie_type |= GOT_TLS_OFFSET_DONE;
4380           entry->d.h->tls_ie_got_offset = next_index;
4381         }
4382       else
4383         {
4384           BFD_ASSERT (tls_type == GOT_TLS_GD);
4385           if (entry->d.h->tls_gd_type & GOT_TLS_OFFSET_DONE)
4386             return 1;
4387           entry->d.h->tls_gd_type |= GOT_TLS_OFFSET_DONE;
4388           entry->d.h->tls_gd_got_offset = next_index;
4389         }
4390     }
4391   else
4392     {
4393       if (tls_type == GOT_TLS_LDM)
4394         {
4395           /* There are separate mips_got_entry objects for each input bfd
4396              that requires an LDM entry.  Make sure that all LDM entries in
4397              a GOT resolve to the same index.  */
4398           if (g->tls_ldm_offset != MINUS_TWO && g->tls_ldm_offset != MINUS_ONE)
4399             {
4400               entry->gotidx = g->tls_ldm_offset;
4401               return 1;
4402             }
4403           g->tls_ldm_offset = next_index;
4404         }
4405       entry->gotidx = next_index;
4406     }
4407
4408   /* Account for the entries we've just allocated.  */
4409   g->tls_assigned_gotno += mips_tls_got_entries (tls_type);
4410   return 1;
4411 }
4412
4413 /* If passed a NULL mips_got_info in the argument, set the marker used
4414    to tell whether a global symbol needs a got entry (in the primary
4415    got) to the given VALUE.
4416
4417    If passed a pointer G to a mips_got_info in the argument (it must
4418    not be the primary GOT), compute the offset from the beginning of
4419    the (primary) GOT section to the entry in G corresponding to the
4420    global symbol.  G's assigned_gotno must contain the index of the
4421    first available global GOT entry in G.  VALUE must contain the size
4422    of a GOT entry in bytes.  For each global GOT entry that requires a
4423    dynamic relocation, NEEDED_RELOCS is incremented, and the symbol is
4424    marked as not eligible for lazy resolution through a function
4425    stub.  */
4426 static int
4427 mips_elf_set_global_got_offset (void **entryp, void *p)
4428 {
4429   struct mips_got_entry *entry = (struct mips_got_entry *)*entryp;
4430   struct mips_elf_set_global_got_offset_arg *arg
4431     = (struct mips_elf_set_global_got_offset_arg *)p;
4432   struct mips_got_info *g = arg->g;
4433
4434   if (g && entry->tls_type != GOT_NORMAL)
4435     arg->needed_relocs +=
4436       mips_tls_got_relocs (arg->info, entry->tls_type,
4437                            entry->symndx == -1 ? &entry->d.h->root : NULL);
4438
4439   if (entry->abfd != NULL
4440       && entry->symndx == -1
4441       && entry->d.h->global_got_area != GGA_NONE)
4442     {
4443       if (g)
4444         {
4445           entry->gotidx = arg->value * (long) g->assigned_gotno++;
4446           if (arg->info->shared
4447               || (elf_hash_table (arg->info)->dynamic_sections_created
4448                   && entry->d.h->root.def_dynamic
4449                   && !entry->d.h->root.def_regular))
4450             ++arg->needed_relocs;
4451         }
4452       else
4453         entry->d.h->global_got_area = arg->value;
4454     }
4455
4456   return 1;
4457 }
4458
4459 /* A htab_traverse callback for GOT entries for which DATA is the
4460    bfd_link_info.  Forbid any global symbols from having traditional
4461    lazy-binding stubs.  */
4462
4463 static int
4464 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4465 {
4466   struct bfd_link_info *info;
4467   struct mips_elf_link_hash_table *htab;
4468   struct mips_got_entry *entry;
4469
4470   entry = (struct mips_got_entry *) *entryp;
4471   info = (struct bfd_link_info *) data;
4472   htab = mips_elf_hash_table (info);
4473   BFD_ASSERT (htab != NULL);
4474
4475   if (entry->abfd != NULL
4476       && entry->symndx == -1
4477       && entry->d.h->needs_lazy_stub)
4478     {
4479       entry->d.h->needs_lazy_stub = FALSE;
4480       htab->lazy_stub_count--;
4481     }
4482
4483   return 1;
4484 }
4485
4486 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4487    the primary GOT.  */
4488 static bfd_vma
4489 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4490 {
4491   if (g->bfd2got == NULL)
4492     return 0;
4493
4494   g = mips_elf_got_for_ibfd (g, ibfd);
4495   if (! g)
4496     return 0;
4497
4498   BFD_ASSERT (g->next);
4499
4500   g = g->next;
4501
4502   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4503     * MIPS_ELF_GOT_SIZE (abfd);
4504 }
4505
4506 /* Turn a single GOT that is too big for 16-bit addressing into
4507    a sequence of GOTs, each one 16-bit addressable.  */
4508
4509 static bfd_boolean
4510 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4511                     asection *got, bfd_size_type pages)
4512 {
4513   struct mips_elf_link_hash_table *htab;
4514   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4515   struct mips_elf_set_global_got_offset_arg set_got_offset_arg;
4516   struct mips_got_info *g, *gg;
4517   unsigned int assign, needed_relocs;
4518   bfd *dynobj;
4519
4520   dynobj = elf_hash_table (info)->dynobj;
4521   htab = mips_elf_hash_table (info);
4522   BFD_ASSERT (htab != NULL);
4523
4524   g = htab->got_info;
4525   g->bfd2got = htab_try_create (1, mips_elf_bfd2got_entry_hash,
4526                                 mips_elf_bfd2got_entry_eq, NULL);
4527   if (g->bfd2got == NULL)
4528     return FALSE;
4529
4530   got_per_bfd_arg.bfd2got = g->bfd2got;
4531   got_per_bfd_arg.obfd = abfd;
4532   got_per_bfd_arg.info = info;
4533
4534   /* Count how many GOT entries each input bfd requires, creating a
4535      map from bfd to got info while at that.  */
4536   htab_traverse (g->got_entries, mips_elf_make_got_per_bfd, &got_per_bfd_arg);
4537   if (got_per_bfd_arg.obfd == NULL)
4538     return FALSE;
4539
4540   /* Also count how many page entries each input bfd requires.  */
4541   htab_traverse (g->got_page_entries, mips_elf_make_got_pages_per_bfd,
4542                  &got_per_bfd_arg);
4543   if (got_per_bfd_arg.obfd == NULL)
4544     return FALSE;
4545
4546   got_per_bfd_arg.current = NULL;
4547   got_per_bfd_arg.primary = NULL;
4548   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4549                                 / MIPS_ELF_GOT_SIZE (abfd))
4550                                - htab->reserved_gotno);
4551   got_per_bfd_arg.max_pages = pages;
4552   /* The number of globals that will be included in the primary GOT.
4553      See the calls to mips_elf_set_global_got_offset below for more
4554      information.  */
4555   got_per_bfd_arg.global_count = g->global_gotno;
4556
4557   /* Try to merge the GOTs of input bfds together, as long as they
4558      don't seem to exceed the maximum GOT size, choosing one of them
4559      to be the primary GOT.  */
4560   htab_traverse (g->bfd2got, mips_elf_merge_gots, &got_per_bfd_arg);
4561   if (got_per_bfd_arg.obfd == NULL)
4562     return FALSE;
4563
4564   /* If we do not find any suitable primary GOT, create an empty one.  */
4565   if (got_per_bfd_arg.primary == NULL)
4566     g->next = mips_elf_create_got_info (abfd, FALSE);
4567   else
4568     g->next = got_per_bfd_arg.primary;
4569   g->next->next = got_per_bfd_arg.current;
4570
4571   /* GG is now the master GOT, and G is the primary GOT.  */
4572   gg = g;
4573   g = g->next;
4574
4575   /* Map the output bfd to the primary got.  That's what we're going
4576      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4577      didn't mark in check_relocs, and we want a quick way to find it.
4578      We can't just use gg->next because we're going to reverse the
4579      list.  */
4580   {
4581     struct mips_elf_bfd2got_hash *bfdgot;
4582     void **bfdgotp;
4583
4584     bfdgot = (struct mips_elf_bfd2got_hash *)bfd_alloc
4585       (abfd, sizeof (struct mips_elf_bfd2got_hash));
4586
4587     if (bfdgot == NULL)
4588       return FALSE;
4589
4590     bfdgot->bfd = abfd;
4591     bfdgot->g = g;
4592     bfdgotp = htab_find_slot (gg->bfd2got, bfdgot, INSERT);
4593
4594     BFD_ASSERT (*bfdgotp == NULL);
4595     *bfdgotp = bfdgot;
4596   }
4597
4598   /* Every symbol that is referenced in a dynamic relocation must be
4599      present in the primary GOT, so arrange for them to appear after
4600      those that are actually referenced.  */
4601   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4602   g->global_gotno = gg->global_gotno;
4603
4604   set_got_offset_arg.g = NULL;
4605   set_got_offset_arg.value = GGA_RELOC_ONLY;
4606   htab_traverse (gg->got_entries, mips_elf_set_global_got_offset,
4607                  &set_got_offset_arg);
4608   set_got_offset_arg.value = GGA_NORMAL;
4609   htab_traverse (g->got_entries, mips_elf_set_global_got_offset,
4610                  &set_got_offset_arg);
4611
4612   /* Now go through the GOTs assigning them offset ranges.
4613      [assigned_gotno, local_gotno[ will be set to the range of local
4614      entries in each GOT.  We can then compute the end of a GOT by
4615      adding local_gotno to global_gotno.  We reverse the list and make
4616      it circular since then we'll be able to quickly compute the
4617      beginning of a GOT, by computing the end of its predecessor.  To
4618      avoid special cases for the primary GOT, while still preserving
4619      assertions that are valid for both single- and multi-got links,
4620      we arrange for the main got struct to have the right number of
4621      global entries, but set its local_gotno such that the initial
4622      offset of the primary GOT is zero.  Remember that the primary GOT
4623      will become the last item in the circular linked list, so it
4624      points back to the master GOT.  */
4625   gg->local_gotno = -g->global_gotno;
4626   gg->global_gotno = g->global_gotno;
4627   gg->tls_gotno = 0;
4628   assign = 0;
4629   gg->next = gg;
4630
4631   do
4632     {
4633       struct mips_got_info *gn;
4634
4635       assign += htab->reserved_gotno;
4636       g->assigned_gotno = assign;
4637       g->local_gotno += assign;
4638       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4639       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4640
4641       /* Take g out of the direct list, and push it onto the reversed
4642          list that gg points to.  g->next is guaranteed to be nonnull after
4643          this operation, as required by mips_elf_initialize_tls_index. */
4644       gn = g->next;
4645       g->next = gg->next;
4646       gg->next = g;
4647
4648       /* Set up any TLS entries.  We always place the TLS entries after
4649          all non-TLS entries.  */
4650       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4651       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, g);
4652       BFD_ASSERT (g->tls_assigned_gotno == assign);
4653
4654       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4655       g = gn;
4656
4657       /* Forbid global symbols in every non-primary GOT from having
4658          lazy-binding stubs.  */
4659       if (g)
4660         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4661     }
4662   while (g);
4663
4664   got->size = assign * MIPS_ELF_GOT_SIZE (abfd);
4665
4666   needed_relocs = 0;
4667   set_got_offset_arg.value = MIPS_ELF_GOT_SIZE (abfd);
4668   set_got_offset_arg.info = info;
4669   for (g = gg->next; g && g->next != gg; g = g->next)
4670     {
4671       unsigned int save_assign;
4672
4673       /* Assign offsets to global GOT entries.  */
4674       save_assign = g->assigned_gotno;
4675       g->assigned_gotno = g->local_gotno;
4676       set_got_offset_arg.g = g;
4677       set_got_offset_arg.needed_relocs = 0;
4678       htab_traverse (g->got_entries,
4679                      mips_elf_set_global_got_offset,
4680                      &set_got_offset_arg);
4681       needed_relocs += set_got_offset_arg.needed_relocs;
4682       BFD_ASSERT (g->assigned_gotno - g->local_gotno <= g->global_gotno);
4683
4684       g->assigned_gotno = save_assign;
4685       if (info->shared)
4686         {
4687           needed_relocs += g->local_gotno - g->assigned_gotno;
4688           BFD_ASSERT (g->assigned_gotno == g->next->local_gotno
4689                       + g->next->global_gotno
4690                       + g->next->tls_gotno
4691                       + htab->reserved_gotno);
4692         }
4693     }
4694
4695   if (needed_relocs)
4696     mips_elf_allocate_dynamic_relocations (dynobj, info,
4697                                            needed_relocs);
4698
4699   return TRUE;
4700 }
4701
4702 \f
4703 /* Returns the first relocation of type r_type found, beginning with
4704    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4705
4706 static const Elf_Internal_Rela *
4707 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4708                           const Elf_Internal_Rela *relocation,
4709                           const Elf_Internal_Rela *relend)
4710 {
4711   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4712
4713   while (relocation < relend)
4714     {
4715       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4716           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4717         return relocation;
4718
4719       ++relocation;
4720     }
4721
4722   /* We didn't find it.  */
4723   return NULL;
4724 }
4725
4726 /* Return whether an input relocation is against a local symbol.  */
4727
4728 static bfd_boolean
4729 mips_elf_local_relocation_p (bfd *input_bfd,
4730                              const Elf_Internal_Rela *relocation,
4731                              asection **local_sections)
4732 {
4733   unsigned long r_symndx;
4734   Elf_Internal_Shdr *symtab_hdr;
4735   size_t extsymoff;
4736
4737   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4738   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4739   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
4740
4741   if (r_symndx < extsymoff)
4742     return TRUE;
4743   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
4744     return TRUE;
4745
4746   return FALSE;
4747 }
4748 \f
4749 /* Sign-extend VALUE, which has the indicated number of BITS.  */
4750
4751 bfd_vma
4752 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
4753 {
4754   if (value & ((bfd_vma) 1 << (bits - 1)))
4755     /* VALUE is negative.  */
4756     value |= ((bfd_vma) - 1) << bits;
4757
4758   return value;
4759 }
4760
4761 /* Return non-zero if the indicated VALUE has overflowed the maximum
4762    range expressible by a signed number with the indicated number of
4763    BITS.  */
4764
4765 static bfd_boolean
4766 mips_elf_overflow_p (bfd_vma value, int bits)
4767 {
4768   bfd_signed_vma svalue = (bfd_signed_vma) value;
4769
4770   if (svalue > (1 << (bits - 1)) - 1)
4771     /* The value is too big.  */
4772     return TRUE;
4773   else if (svalue < -(1 << (bits - 1)))
4774     /* The value is too small.  */
4775     return TRUE;
4776
4777   /* All is well.  */
4778   return FALSE;
4779 }
4780
4781 /* Calculate the %high function.  */
4782
4783 static bfd_vma
4784 mips_elf_high (bfd_vma value)
4785 {
4786   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
4787 }
4788
4789 /* Calculate the %higher function.  */
4790
4791 static bfd_vma
4792 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
4793 {
4794 #ifdef BFD64
4795   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
4796 #else
4797   abort ();
4798   return MINUS_ONE;
4799 #endif
4800 }
4801
4802 /* Calculate the %highest function.  */
4803
4804 static bfd_vma
4805 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
4806 {
4807 #ifdef BFD64
4808   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
4809 #else
4810   abort ();
4811   return MINUS_ONE;
4812 #endif
4813 }
4814 \f
4815 /* Create the .compact_rel section.  */
4816
4817 static bfd_boolean
4818 mips_elf_create_compact_rel_section
4819   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
4820 {
4821   flagword flags;
4822   register asection *s;
4823
4824   if (bfd_get_linker_section (abfd, ".compact_rel") == NULL)
4825     {
4826       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
4827                | SEC_READONLY);
4828
4829       s = bfd_make_section_anyway_with_flags (abfd, ".compact_rel", flags);
4830       if (s == NULL
4831           || ! bfd_set_section_alignment (abfd, s,
4832                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
4833         return FALSE;
4834
4835       s->size = sizeof (Elf32_External_compact_rel);
4836     }
4837
4838   return TRUE;
4839 }
4840
4841 /* Create the .got section to hold the global offset table.  */
4842
4843 static bfd_boolean
4844 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
4845 {
4846   flagword flags;
4847   register asection *s;
4848   struct elf_link_hash_entry *h;
4849   struct bfd_link_hash_entry *bh;
4850   struct mips_elf_link_hash_table *htab;
4851
4852   htab = mips_elf_hash_table (info);
4853   BFD_ASSERT (htab != NULL);
4854
4855   /* This function may be called more than once.  */
4856   if (htab->sgot)
4857     return TRUE;
4858
4859   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
4860            | SEC_LINKER_CREATED);
4861
4862   /* We have to use an alignment of 2**4 here because this is hardcoded
4863      in the function stub generation and in the linker script.  */
4864   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
4865   if (s == NULL
4866       || ! bfd_set_section_alignment (abfd, s, 4))
4867     return FALSE;
4868   htab->sgot = s;
4869
4870   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
4871      linker script because we don't want to define the symbol if we
4872      are not creating a global offset table.  */
4873   bh = NULL;
4874   if (! (_bfd_generic_link_add_one_symbol
4875          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
4876           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
4877     return FALSE;
4878
4879   h = (struct elf_link_hash_entry *) bh;
4880   h->non_elf = 0;
4881   h->def_regular = 1;
4882   h->type = STT_OBJECT;
4883   elf_hash_table (info)->hgot = h;
4884
4885   if (info->shared
4886       && ! bfd_elf_link_record_dynamic_symbol (info, h))
4887     return FALSE;
4888
4889   htab->got_info = mips_elf_create_got_info (abfd, TRUE);
4890   mips_elf_section_data (s)->elf.this_hdr.sh_flags
4891     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
4892
4893   /* We also need a .got.plt section when generating PLTs.  */
4894   s = bfd_make_section_anyway_with_flags (abfd, ".got.plt",
4895                                           SEC_ALLOC | SEC_LOAD
4896                                           | SEC_HAS_CONTENTS
4897                                           | SEC_IN_MEMORY
4898                                           | SEC_LINKER_CREATED);
4899   if (s == NULL)
4900     return FALSE;
4901   htab->sgotplt = s;
4902
4903   return TRUE;
4904 }
4905 \f
4906 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
4907    __GOTT_INDEX__ symbols.  These symbols are only special for
4908    shared objects; they are not used in executables.  */
4909
4910 static bfd_boolean
4911 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
4912 {
4913   return (mips_elf_hash_table (info)->is_vxworks
4914           && info->shared
4915           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
4916               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
4917 }
4918
4919 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
4920    require an la25 stub.  See also mips_elf_local_pic_function_p,
4921    which determines whether the destination function ever requires a
4922    stub.  */
4923
4924 static bfd_boolean
4925 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type,
4926                                      bfd_boolean target_is_16_bit_code_p)
4927 {
4928   /* We specifically ignore branches and jumps from EF_PIC objects,
4929      where the onus is on the compiler or programmer to perform any
4930      necessary initialization of $25.  Sometimes such initialization
4931      is unnecessary; for example, -mno-shared functions do not use
4932      the incoming value of $25, and may therefore be called directly.  */
4933   if (PIC_OBJECT_P (input_bfd))
4934     return FALSE;
4935
4936   switch (r_type)
4937     {
4938     case R_MIPS_26:
4939     case R_MIPS_PC16:
4940     case R_MICROMIPS_26_S1:
4941     case R_MICROMIPS_PC7_S1:
4942     case R_MICROMIPS_PC10_S1:
4943     case R_MICROMIPS_PC16_S1:
4944     case R_MICROMIPS_PC23_S2:
4945       return TRUE;
4946
4947     case R_MIPS16_26:
4948       return !target_is_16_bit_code_p;
4949
4950     default:
4951       return FALSE;
4952     }
4953 }
4954 \f
4955 /* Calculate the value produced by the RELOCATION (which comes from
4956    the INPUT_BFD).  The ADDEND is the addend to use for this
4957    RELOCATION; RELOCATION->R_ADDEND is ignored.
4958
4959    The result of the relocation calculation is stored in VALUEP.
4960    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
4961    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
4962
4963    This function returns bfd_reloc_continue if the caller need take no
4964    further action regarding this relocation, bfd_reloc_notsupported if
4965    something goes dramatically wrong, bfd_reloc_overflow if an
4966    overflow occurs, and bfd_reloc_ok to indicate success.  */
4967
4968 static bfd_reloc_status_type
4969 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
4970                                asection *input_section,
4971                                struct bfd_link_info *info,
4972                                const Elf_Internal_Rela *relocation,
4973                                bfd_vma addend, reloc_howto_type *howto,
4974                                Elf_Internal_Sym *local_syms,
4975                                asection **local_sections, bfd_vma *valuep,
4976                                const char **namep,
4977                                bfd_boolean *cross_mode_jump_p,
4978                                bfd_boolean save_addend)
4979 {
4980   /* The eventual value we will return.  */
4981   bfd_vma value;
4982   /* The address of the symbol against which the relocation is
4983      occurring.  */
4984   bfd_vma symbol = 0;
4985   /* The final GP value to be used for the relocatable, executable, or
4986      shared object file being produced.  */
4987   bfd_vma gp;
4988   /* The place (section offset or address) of the storage unit being
4989      relocated.  */
4990   bfd_vma p;
4991   /* The value of GP used to create the relocatable object.  */
4992   bfd_vma gp0;
4993   /* The offset into the global offset table at which the address of
4994      the relocation entry symbol, adjusted by the addend, resides
4995      during execution.  */
4996   bfd_vma g = MINUS_ONE;
4997   /* The section in which the symbol referenced by the relocation is
4998      located.  */
4999   asection *sec = NULL;
5000   struct mips_elf_link_hash_entry *h = NULL;
5001   /* TRUE if the symbol referred to by this relocation is a local
5002      symbol.  */
5003   bfd_boolean local_p, was_local_p;
5004   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
5005   bfd_boolean gp_disp_p = FALSE;
5006   /* TRUE if the symbol referred to by this relocation is
5007      "__gnu_local_gp".  */
5008   bfd_boolean gnu_local_gp_p = FALSE;
5009   Elf_Internal_Shdr *symtab_hdr;
5010   size_t extsymoff;
5011   unsigned long r_symndx;
5012   int r_type;
5013   /* TRUE if overflow occurred during the calculation of the
5014      relocation value.  */
5015   bfd_boolean overflowed_p;
5016   /* TRUE if this relocation refers to a MIPS16 function.  */
5017   bfd_boolean target_is_16_bit_code_p = FALSE;
5018   bfd_boolean target_is_micromips_code_p = FALSE;
5019   struct mips_elf_link_hash_table *htab;
5020   bfd *dynobj;
5021
5022   dynobj = elf_hash_table (info)->dynobj;
5023   htab = mips_elf_hash_table (info);
5024   BFD_ASSERT (htab != NULL);
5025
5026   /* Parse the relocation.  */
5027   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
5028   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5029   p = (input_section->output_section->vma
5030        + input_section->output_offset
5031        + relocation->r_offset);
5032
5033   /* Assume that there will be no overflow.  */
5034   overflowed_p = FALSE;
5035
5036   /* Figure out whether or not the symbol is local, and get the offset
5037      used in the array of hash table entries.  */
5038   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
5039   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
5040                                          local_sections);
5041   was_local_p = local_p;
5042   if (! elf_bad_symtab (input_bfd))
5043     extsymoff = symtab_hdr->sh_info;
5044   else
5045     {
5046       /* The symbol table does not follow the rule that local symbols
5047          must come before globals.  */
5048       extsymoff = 0;
5049     }
5050
5051   /* Figure out the value of the symbol.  */
5052   if (local_p)
5053     {
5054       Elf_Internal_Sym *sym;
5055
5056       sym = local_syms + r_symndx;
5057       sec = local_sections[r_symndx];
5058
5059       symbol = sec->output_section->vma + sec->output_offset;
5060       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION
5061           || (sec->flags & SEC_MERGE))
5062         symbol += sym->st_value;
5063       if ((sec->flags & SEC_MERGE)
5064           && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
5065         {
5066           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
5067           addend -= symbol;
5068           addend += sec->output_section->vma + sec->output_offset;
5069         }
5070
5071       /* MIPS16/microMIPS text labels should be treated as odd.  */
5072       if (ELF_ST_IS_COMPRESSED (sym->st_other))
5073         ++symbol;
5074
5075       /* Record the name of this symbol, for our caller.  */
5076       *namep = bfd_elf_string_from_elf_section (input_bfd,
5077                                                 symtab_hdr->sh_link,
5078                                                 sym->st_name);
5079       if (*namep == '\0')
5080         *namep = bfd_section_name (input_bfd, sec);
5081
5082       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
5083       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
5084     }
5085   else
5086     {
5087       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
5088
5089       /* For global symbols we look up the symbol in the hash-table.  */
5090       h = ((struct mips_elf_link_hash_entry *)
5091            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
5092       /* Find the real hash-table entry for this symbol.  */
5093       while (h->root.root.type == bfd_link_hash_indirect
5094              || h->root.root.type == bfd_link_hash_warning)
5095         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
5096
5097       /* Record the name of this symbol, for our caller.  */
5098       *namep = h->root.root.root.string;
5099
5100       /* See if this is the special _gp_disp symbol.  Note that such a
5101          symbol must always be a global symbol.  */
5102       if (strcmp (*namep, "_gp_disp") == 0
5103           && ! NEWABI_P (input_bfd))
5104         {
5105           /* Relocations against _gp_disp are permitted only with
5106              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
5107           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
5108             return bfd_reloc_notsupported;
5109
5110           gp_disp_p = TRUE;
5111         }
5112       /* See if this is the special _gp symbol.  Note that such a
5113          symbol must always be a global symbol.  */
5114       else if (strcmp (*namep, "__gnu_local_gp") == 0)
5115         gnu_local_gp_p = TRUE;
5116
5117
5118       /* If this symbol is defined, calculate its address.  Note that
5119          _gp_disp is a magic symbol, always implicitly defined by the
5120          linker, so it's inappropriate to check to see whether or not
5121          its defined.  */
5122       else if ((h->root.root.type == bfd_link_hash_defined
5123                 || h->root.root.type == bfd_link_hash_defweak)
5124                && h->root.root.u.def.section)
5125         {
5126           sec = h->root.root.u.def.section;
5127           if (sec->output_section)
5128             symbol = (h->root.root.u.def.value
5129                       + sec->output_section->vma
5130                       + sec->output_offset);
5131           else
5132             symbol = h->root.root.u.def.value;
5133         }
5134       else if (h->root.root.type == bfd_link_hash_undefweak)
5135         /* We allow relocations against undefined weak symbols, giving
5136            it the value zero, so that you can undefined weak functions
5137            and check to see if they exist by looking at their
5138            addresses.  */
5139         symbol = 0;
5140       else if (info->unresolved_syms_in_objects == RM_IGNORE
5141                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5142         symbol = 0;
5143       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
5144                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
5145         {
5146           /* If this is a dynamic link, we should have created a
5147              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
5148              in in _bfd_mips_elf_create_dynamic_sections.
5149              Otherwise, we should define the symbol with a value of 0.
5150              FIXME: It should probably get into the symbol table
5151              somehow as well.  */
5152           BFD_ASSERT (! info->shared);
5153           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
5154           symbol = 0;
5155         }
5156       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
5157         {
5158           /* This is an optional symbol - an Irix specific extension to the
5159              ELF spec.  Ignore it for now.
5160              XXX - FIXME - there is more to the spec for OPTIONAL symbols
5161              than simply ignoring them, but we do not handle this for now.
5162              For information see the "64-bit ELF Object File Specification"
5163              which is available from here:
5164              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
5165           symbol = 0;
5166         }
5167       else if ((*info->callbacks->undefined_symbol)
5168                (info, h->root.root.root.string, input_bfd,
5169                 input_section, relocation->r_offset,
5170                 (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
5171                  || ELF_ST_VISIBILITY (h->root.other)))
5172         {
5173           return bfd_reloc_undefined;
5174         }
5175       else
5176         {
5177           return bfd_reloc_notsupported;
5178         }
5179
5180       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
5181       /* If the output section is the PLT section,
5182          then the target is not microMIPS.  */
5183       target_is_micromips_code_p = (htab->splt != sec
5184                                     && ELF_ST_IS_MICROMIPS (h->root.other));
5185     }
5186
5187   /* If this is a reference to a 16-bit function with a stub, we need
5188      to redirect the relocation to the stub unless:
5189
5190      (a) the relocation is for a MIPS16 JAL;
5191
5192      (b) the relocation is for a MIPS16 PIC call, and there are no
5193          non-MIPS16 uses of the GOT slot; or
5194
5195      (c) the section allows direct references to MIPS16 functions.  */
5196   if (r_type != R_MIPS16_26
5197       && !info->relocatable
5198       && ((h != NULL
5199            && h->fn_stub != NULL
5200            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5201           || (local_p
5202               && elf_tdata (input_bfd)->local_stubs != NULL
5203               && elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5204       && !section_allows_mips16_refs_p (input_section))
5205     {
5206       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5207          have already noticed that we were going to need the
5208          stub.  */
5209       if (local_p)
5210         {
5211           sec = elf_tdata (input_bfd)->local_stubs[r_symndx];
5212           value = 0;
5213         }
5214       else
5215         {
5216           BFD_ASSERT (h->need_fn_stub);
5217           if (h->la25_stub)
5218             {
5219               /* If a LA25 header for the stub itself exists, point to the
5220                  prepended LUI/ADDIU sequence.  */
5221               sec = h->la25_stub->stub_section;
5222               value = h->la25_stub->offset;
5223             }
5224           else
5225             {
5226               sec = h->fn_stub;
5227               value = 0;
5228             }
5229         }
5230
5231       symbol = sec->output_section->vma + sec->output_offset + value;
5232       /* The target is 16-bit, but the stub isn't.  */
5233       target_is_16_bit_code_p = FALSE;
5234     }
5235   /* If this is a 16-bit call to a 32- or 64-bit function with a stub, we
5236      need to redirect the call to the stub.  Note that we specifically
5237      exclude R_MIPS16_CALL16 from this behavior; indirect calls should
5238      use an indirect stub instead.  */
5239   else if (r_type == R_MIPS16_26 && !info->relocatable
5240            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5241                || (local_p
5242                    && elf_tdata (input_bfd)->local_call_stubs != NULL
5243                    && elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5244            && !target_is_16_bit_code_p)
5245     {
5246       if (local_p)
5247         sec = elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5248       else
5249         {
5250           /* If both call_stub and call_fp_stub are defined, we can figure
5251              out which one to use by checking which one appears in the input
5252              file.  */
5253           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5254             {
5255               asection *o;
5256
5257               sec = NULL;
5258               for (o = input_bfd->sections; o != NULL; o = o->next)
5259                 {
5260                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5261                     {
5262                       sec = h->call_fp_stub;
5263                       break;
5264                     }
5265                 }
5266               if (sec == NULL)
5267                 sec = h->call_stub;
5268             }
5269           else if (h->call_stub != NULL)
5270             sec = h->call_stub;
5271           else
5272             sec = h->call_fp_stub;
5273         }
5274
5275       BFD_ASSERT (sec->size > 0);
5276       symbol = sec->output_section->vma + sec->output_offset;
5277     }
5278   /* If this is a direct call to a PIC function, redirect to the
5279      non-PIC stub.  */
5280   else if (h != NULL && h->la25_stub
5281            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type,
5282                                                    target_is_16_bit_code_p))
5283     symbol = (h->la25_stub->stub_section->output_section->vma
5284               + h->la25_stub->stub_section->output_offset
5285               + h->la25_stub->offset);
5286
5287   /* Make sure MIPS16 and microMIPS are not used together.  */
5288   if ((r_type == R_MIPS16_26 && target_is_micromips_code_p)
5289       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5290    {
5291       (*_bfd_error_handler)
5292         (_("MIPS16 and microMIPS functions cannot call each other"));
5293       return bfd_reloc_notsupported;
5294    }
5295
5296   /* Calls from 16-bit code to 32-bit code and vice versa require the
5297      mode change.  However, we can ignore calls to undefined weak symbols,
5298      which should never be executed at runtime.  This exception is important
5299      because the assembly writer may have "known" that any definition of the
5300      symbol would be 16-bit code, and that direct jumps were therefore
5301      acceptable.  */
5302   *cross_mode_jump_p = (!info->relocatable
5303                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5304                         && ((r_type == R_MIPS16_26 && !target_is_16_bit_code_p)
5305                             || (r_type == R_MICROMIPS_26_S1
5306                                 && !target_is_micromips_code_p)
5307                             || ((r_type == R_MIPS_26 || r_type == R_MIPS_JALR)
5308                                 && (target_is_16_bit_code_p
5309                                     || target_is_micromips_code_p))));
5310
5311   local_p = (h == NULL
5312              || (h->got_only_for_calls
5313                  ? SYMBOL_CALLS_LOCAL (info, &h->root)
5314                  : SYMBOL_REFERENCES_LOCAL (info, &h->root)));
5315
5316   gp0 = _bfd_get_gp_value (input_bfd);
5317   gp = _bfd_get_gp_value (abfd);
5318   if (htab->got_info)
5319     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5320
5321   if (gnu_local_gp_p)
5322     symbol = gp;
5323
5324   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5325      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5326      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5327   if (got_page_reloc_p (r_type) && !local_p)
5328     {
5329       r_type = (micromips_reloc_p (r_type)
5330                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5331       addend = 0;
5332     }
5333
5334   /* If we haven't already determined the GOT offset, and we're going
5335      to need it, get it now.  */
5336   switch (r_type)
5337     {
5338     case R_MIPS16_CALL16:
5339     case R_MIPS16_GOT16:
5340     case R_MIPS_CALL16:
5341     case R_MIPS_GOT16:
5342     case R_MIPS_GOT_DISP:
5343     case R_MIPS_GOT_HI16:
5344     case R_MIPS_CALL_HI16:
5345     case R_MIPS_GOT_LO16:
5346     case R_MIPS_CALL_LO16:
5347     case R_MICROMIPS_CALL16:
5348     case R_MICROMIPS_GOT16:
5349     case R_MICROMIPS_GOT_DISP:
5350     case R_MICROMIPS_GOT_HI16:
5351     case R_MICROMIPS_CALL_HI16:
5352     case R_MICROMIPS_GOT_LO16:
5353     case R_MICROMIPS_CALL_LO16:
5354     case R_MIPS_TLS_GD:
5355     case R_MIPS_TLS_GOTTPREL:
5356     case R_MIPS_TLS_LDM:
5357     case R_MIPS16_TLS_GD:
5358     case R_MIPS16_TLS_GOTTPREL:
5359     case R_MIPS16_TLS_LDM:
5360     case R_MICROMIPS_TLS_GD:
5361     case R_MICROMIPS_TLS_GOTTPREL:
5362     case R_MICROMIPS_TLS_LDM:
5363       /* Find the index into the GOT where this value is located.  */
5364       if (tls_ldm_reloc_p (r_type))
5365         {
5366           g = mips_elf_local_got_index (abfd, input_bfd, info,
5367                                         0, 0, NULL, r_type);
5368           if (g == MINUS_ONE)
5369             return bfd_reloc_outofrange;
5370         }
5371       else if (!local_p)
5372         {
5373           /* On VxWorks, CALL relocations should refer to the .got.plt
5374              entry, which is initialized to point at the PLT stub.  */
5375           if (htab->is_vxworks
5376               && (call_hi16_reloc_p (r_type)
5377                   || call_lo16_reloc_p (r_type)
5378                   || call16_reloc_p (r_type)))
5379             {
5380               BFD_ASSERT (addend == 0);
5381               BFD_ASSERT (h->root.needs_plt);
5382               g = mips_elf_gotplt_index (info, &h->root);
5383             }
5384           else
5385             {
5386               BFD_ASSERT (addend == 0);
5387               g = mips_elf_global_got_index (dynobj, input_bfd,
5388                                              &h->root, r_type, info);
5389               if (!TLS_RELOC_P (r_type)
5390                   && !elf_hash_table (info)->dynamic_sections_created)
5391                 /* This is a static link.  We must initialize the GOT entry.  */
5392                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->sgot->contents + g);
5393             }
5394         }
5395       else if (!htab->is_vxworks
5396                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5397         /* The calculation below does not involve "g".  */
5398         break;
5399       else
5400         {
5401           g = mips_elf_local_got_index (abfd, input_bfd, info,
5402                                         symbol + addend, r_symndx, h, r_type);
5403           if (g == MINUS_ONE)
5404             return bfd_reloc_outofrange;
5405         }
5406
5407       /* Convert GOT indices to actual offsets.  */
5408       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5409       break;
5410     }
5411
5412   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5413      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5414   if (h != NULL && is_gott_symbol (info, &h->root))
5415     {
5416       Elf_Internal_Rela outrel;
5417       bfd_byte *loc;
5418       asection *s;
5419
5420       s = mips_elf_rel_dyn_section (info, FALSE);
5421       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5422
5423       outrel.r_offset = (input_section->output_section->vma
5424                          + input_section->output_offset
5425                          + relocation->r_offset);
5426       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5427       outrel.r_addend = addend;
5428       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5429
5430       /* If we've written this relocation for a readonly section,
5431          we need to set DF_TEXTREL again, so that we do not delete the
5432          DT_TEXTREL tag.  */
5433       if (MIPS_ELF_READONLY_SECTION (input_section))
5434         info->flags |= DF_TEXTREL;
5435
5436       *valuep = 0;
5437       return bfd_reloc_ok;
5438     }
5439
5440   /* Figure out what kind of relocation is being performed.  */
5441   switch (r_type)
5442     {
5443     case R_MIPS_NONE:
5444       return bfd_reloc_continue;
5445
5446     case R_MIPS_16:
5447       value = symbol + _bfd_mips_elf_sign_extend (addend, 16);
5448       overflowed_p = mips_elf_overflow_p (value, 16);
5449       break;
5450
5451     case R_MIPS_32:
5452     case R_MIPS_REL32:
5453     case R_MIPS_64:
5454       if ((info->shared
5455            || (htab->root.dynamic_sections_created
5456                && h != NULL
5457                && h->root.def_dynamic
5458                && !h->root.def_regular
5459                && !h->has_static_relocs))
5460           && r_symndx != STN_UNDEF
5461           && (h == NULL
5462               || h->root.root.type != bfd_link_hash_undefweak
5463               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5464           && (input_section->flags & SEC_ALLOC) != 0)
5465         {
5466           /* If we're creating a shared library, then we can't know
5467              where the symbol will end up.  So, we create a relocation
5468              record in the output, and leave the job up to the dynamic
5469              linker.  We must do the same for executable references to
5470              shared library symbols, unless we've decided to use copy
5471              relocs or PLTs instead.  */
5472           value = addend;
5473           if (!mips_elf_create_dynamic_relocation (abfd,
5474                                                    info,
5475                                                    relocation,
5476                                                    h,
5477                                                    sec,
5478                                                    symbol,
5479                                                    &value,
5480                                                    input_section))
5481             return bfd_reloc_undefined;
5482         }
5483       else
5484         {
5485           if (r_type != R_MIPS_REL32)
5486             value = symbol + addend;
5487           else
5488             value = addend;
5489         }
5490       value &= howto->dst_mask;
5491       break;
5492
5493     case R_MIPS_PC32:
5494       value = symbol + addend - p;
5495       value &= howto->dst_mask;
5496       break;
5497
5498     case R_MIPS16_26:
5499       /* The calculation for R_MIPS16_26 is just the same as for an
5500          R_MIPS_26.  It's only the storage of the relocated field into
5501          the output file that's different.  That's handled in
5502          mips_elf_perform_relocation.  So, we just fall through to the
5503          R_MIPS_26 case here.  */
5504     case R_MIPS_26:
5505     case R_MICROMIPS_26_S1:
5506       {
5507         unsigned int shift;
5508
5509         /* Make sure the target of JALX is word-aligned.  Bit 0 must be
5510            the correct ISA mode selector and bit 1 must be 0.  */
5511         if (*cross_mode_jump_p && (symbol & 3) != (r_type == R_MIPS_26))
5512           return bfd_reloc_outofrange;
5513
5514         /* Shift is 2, unusually, for microMIPS JALX.  */
5515         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5516
5517         if (was_local_p)
5518           value = addend | ((p + 4) & (0xfc000000 << shift));
5519         else
5520           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5521         value = (value + symbol) >> shift;
5522         if (!was_local_p && h->root.root.type != bfd_link_hash_undefweak)
5523           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5524         value &= howto->dst_mask;
5525       }
5526       break;
5527
5528     case R_MIPS_TLS_DTPREL_HI16:
5529     case R_MIPS16_TLS_DTPREL_HI16:
5530     case R_MICROMIPS_TLS_DTPREL_HI16:
5531       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5532                & howto->dst_mask);
5533       break;
5534
5535     case R_MIPS_TLS_DTPREL_LO16:
5536     case R_MIPS_TLS_DTPREL32:
5537     case R_MIPS_TLS_DTPREL64:
5538     case R_MIPS16_TLS_DTPREL_LO16:
5539     case R_MICROMIPS_TLS_DTPREL_LO16:
5540       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5541       break;
5542
5543     case R_MIPS_TLS_TPREL_HI16:
5544     case R_MIPS16_TLS_TPREL_HI16:
5545     case R_MICROMIPS_TLS_TPREL_HI16:
5546       value = (mips_elf_high (addend + symbol - tprel_base (info))
5547                & howto->dst_mask);
5548       break;
5549
5550     case R_MIPS_TLS_TPREL_LO16:
5551     case R_MIPS_TLS_TPREL32:
5552     case R_MIPS_TLS_TPREL64:
5553     case R_MIPS16_TLS_TPREL_LO16:
5554     case R_MICROMIPS_TLS_TPREL_LO16:
5555       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5556       break;
5557
5558     case R_MIPS_HI16:
5559     case R_MIPS16_HI16:
5560     case R_MICROMIPS_HI16:
5561       if (!gp_disp_p)
5562         {
5563           value = mips_elf_high (addend + symbol);
5564           value &= howto->dst_mask;
5565         }
5566       else
5567         {
5568           /* For MIPS16 ABI code we generate this sequence
5569                 0: li      $v0,%hi(_gp_disp)
5570                 4: addiupc $v1,%lo(_gp_disp)
5571                 8: sll     $v0,16
5572                12: addu    $v0,$v1
5573                14: move    $gp,$v0
5574              So the offsets of hi and lo relocs are the same, but the
5575              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5576              ADDIUPC clears the low two bits of the instruction address,
5577              so the base is ($t9 + 4) & ~3.  */
5578           if (r_type == R_MIPS16_HI16)
5579             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5580           /* The microMIPS .cpload sequence uses the same assembly
5581              instructions as the traditional psABI version, but the
5582              incoming $t9 has the low bit set.  */
5583           else if (r_type == R_MICROMIPS_HI16)
5584             value = mips_elf_high (addend + gp - p - 1);
5585           else
5586             value = mips_elf_high (addend + gp - p);
5587           overflowed_p = mips_elf_overflow_p (value, 16);
5588         }
5589       break;
5590
5591     case R_MIPS_LO16:
5592     case R_MIPS16_LO16:
5593     case R_MICROMIPS_LO16:
5594     case R_MICROMIPS_HI0_LO16:
5595       if (!gp_disp_p)
5596         value = (symbol + addend) & howto->dst_mask;
5597       else
5598         {
5599           /* See the comment for R_MIPS16_HI16 above for the reason
5600              for this conditional.  */
5601           if (r_type == R_MIPS16_LO16)
5602             value = addend + gp - (p & ~(bfd_vma) 0x3);
5603           else if (r_type == R_MICROMIPS_LO16
5604                    || r_type == R_MICROMIPS_HI0_LO16)
5605             value = addend + gp - p + 3;
5606           else
5607             value = addend + gp - p + 4;
5608           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5609              for overflow.  But, on, say, IRIX5, relocations against
5610              _gp_disp are normally generated from the .cpload
5611              pseudo-op.  It generates code that normally looks like
5612              this:
5613
5614                lui    $gp,%hi(_gp_disp)
5615                addiu  $gp,$gp,%lo(_gp_disp)
5616                addu   $gp,$gp,$t9
5617
5618              Here $t9 holds the address of the function being called,
5619              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5620              relocation can easily overflow in this situation, but the
5621              R_MIPS_HI16 relocation will handle the overflow.
5622              Therefore, we consider this a bug in the MIPS ABI, and do
5623              not check for overflow here.  */
5624         }
5625       break;
5626
5627     case R_MIPS_LITERAL:
5628     case R_MICROMIPS_LITERAL:
5629       /* Because we don't merge literal sections, we can handle this
5630          just like R_MIPS_GPREL16.  In the long run, we should merge
5631          shared literals, and then we will need to additional work
5632          here.  */
5633
5634       /* Fall through.  */
5635
5636     case R_MIPS16_GPREL:
5637       /* The R_MIPS16_GPREL performs the same calculation as
5638          R_MIPS_GPREL16, but stores the relocated bits in a different
5639          order.  We don't need to do anything special here; the
5640          differences are handled in mips_elf_perform_relocation.  */
5641     case R_MIPS_GPREL16:
5642     case R_MICROMIPS_GPREL7_S2:
5643     case R_MICROMIPS_GPREL16:
5644       /* Only sign-extend the addend if it was extracted from the
5645          instruction.  If the addend was separate, leave it alone,
5646          otherwise we may lose significant bits.  */
5647       if (howto->partial_inplace)
5648         addend = _bfd_mips_elf_sign_extend (addend, 16);
5649       value = symbol + addend - gp;
5650       /* If the symbol was local, any earlier relocatable links will
5651          have adjusted its addend with the gp offset, so compensate
5652          for that now.  Don't do it for symbols forced local in this
5653          link, though, since they won't have had the gp offset applied
5654          to them before.  */
5655       if (was_local_p)
5656         value += gp0;
5657       overflowed_p = mips_elf_overflow_p (value, 16);
5658       break;
5659
5660     case R_MIPS16_GOT16:
5661     case R_MIPS16_CALL16:
5662     case R_MIPS_GOT16:
5663     case R_MIPS_CALL16:
5664     case R_MICROMIPS_GOT16:
5665     case R_MICROMIPS_CALL16:
5666       /* VxWorks does not have separate local and global semantics for
5667          R_MIPS*_GOT16; every relocation evaluates to "G".  */
5668       if (!htab->is_vxworks && local_p)
5669         {
5670           value = mips_elf_got16_entry (abfd, input_bfd, info,
5671                                         symbol + addend, !was_local_p);
5672           if (value == MINUS_ONE)
5673             return bfd_reloc_outofrange;
5674           value
5675             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5676           overflowed_p = mips_elf_overflow_p (value, 16);
5677           break;
5678         }
5679
5680       /* Fall through.  */
5681
5682     case R_MIPS_TLS_GD:
5683     case R_MIPS_TLS_GOTTPREL:
5684     case R_MIPS_TLS_LDM:
5685     case R_MIPS_GOT_DISP:
5686     case R_MIPS16_TLS_GD:
5687     case R_MIPS16_TLS_GOTTPREL:
5688     case R_MIPS16_TLS_LDM:
5689     case R_MICROMIPS_TLS_GD:
5690     case R_MICROMIPS_TLS_GOTTPREL:
5691     case R_MICROMIPS_TLS_LDM:
5692     case R_MICROMIPS_GOT_DISP:
5693       value = g;
5694       overflowed_p = mips_elf_overflow_p (value, 16);
5695       break;
5696
5697     case R_MIPS_GPREL32:
5698       value = (addend + symbol + gp0 - gp);
5699       if (!save_addend)
5700         value &= howto->dst_mask;
5701       break;
5702
5703     case R_MIPS_PC16:
5704     case R_MIPS_GNU_REL16_S2:
5705       value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p;
5706       overflowed_p = mips_elf_overflow_p (value, 18);
5707       value >>= howto->rightshift;
5708       value &= howto->dst_mask;
5709       break;
5710
5711     case R_MICROMIPS_PC7_S1:
5712       value = symbol + _bfd_mips_elf_sign_extend (addend, 8) - p;
5713       overflowed_p = mips_elf_overflow_p (value, 8);
5714       value >>= howto->rightshift;
5715       value &= howto->dst_mask;
5716       break;
5717
5718     case R_MICROMIPS_PC10_S1:
5719       value = symbol + _bfd_mips_elf_sign_extend (addend, 11) - p;
5720       overflowed_p = mips_elf_overflow_p (value, 11);
5721       value >>= howto->rightshift;
5722       value &= howto->dst_mask;
5723       break;
5724
5725     case R_MICROMIPS_PC16_S1:
5726       value = symbol + _bfd_mips_elf_sign_extend (addend, 17) - p;
5727       overflowed_p = mips_elf_overflow_p (value, 17);
5728       value >>= howto->rightshift;
5729       value &= howto->dst_mask;
5730       break;
5731
5732     case R_MICROMIPS_PC23_S2:
5733       value = symbol + _bfd_mips_elf_sign_extend (addend, 25) - ((p | 3) ^ 3);
5734       overflowed_p = mips_elf_overflow_p (value, 25);
5735       value >>= howto->rightshift;
5736       value &= howto->dst_mask;
5737       break;
5738
5739     case R_MIPS_GOT_HI16:
5740     case R_MIPS_CALL_HI16:
5741     case R_MICROMIPS_GOT_HI16:
5742     case R_MICROMIPS_CALL_HI16:
5743       /* We're allowed to handle these two relocations identically.
5744          The dynamic linker is allowed to handle the CALL relocations
5745          differently by creating a lazy evaluation stub.  */
5746       value = g;
5747       value = mips_elf_high (value);
5748       value &= howto->dst_mask;
5749       break;
5750
5751     case R_MIPS_GOT_LO16:
5752     case R_MIPS_CALL_LO16:
5753     case R_MICROMIPS_GOT_LO16:
5754     case R_MICROMIPS_CALL_LO16:
5755       value = g & howto->dst_mask;
5756       break;
5757
5758     case R_MIPS_GOT_PAGE:
5759     case R_MICROMIPS_GOT_PAGE:
5760       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
5761       if (value == MINUS_ONE)
5762         return bfd_reloc_outofrange;
5763       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5764       overflowed_p = mips_elf_overflow_p (value, 16);
5765       break;
5766
5767     case R_MIPS_GOT_OFST:
5768     case R_MICROMIPS_GOT_OFST:
5769       if (local_p)
5770         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
5771       else
5772         value = addend;
5773       overflowed_p = mips_elf_overflow_p (value, 16);
5774       break;
5775
5776     case R_MIPS_SUB:
5777     case R_MICROMIPS_SUB:
5778       value = symbol - addend;
5779       value &= howto->dst_mask;
5780       break;
5781
5782     case R_MIPS_HIGHER:
5783     case R_MICROMIPS_HIGHER:
5784       value = mips_elf_higher (addend + symbol);
5785       value &= howto->dst_mask;
5786       break;
5787
5788     case R_MIPS_HIGHEST:
5789     case R_MICROMIPS_HIGHEST:
5790       value = mips_elf_highest (addend + symbol);
5791       value &= howto->dst_mask;
5792       break;
5793
5794     case R_MIPS_SCN_DISP:
5795     case R_MICROMIPS_SCN_DISP:
5796       value = symbol + addend - sec->output_offset;
5797       value &= howto->dst_mask;
5798       break;
5799
5800     case R_MIPS_JALR:
5801     case R_MICROMIPS_JALR:
5802       /* This relocation is only a hint.  In some cases, we optimize
5803          it into a bal instruction.  But we don't try to optimize
5804          when the symbol does not resolve locally.  */
5805       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
5806         return bfd_reloc_continue;
5807       value = symbol + addend;
5808       break;
5809
5810     case R_MIPS_PJUMP:
5811     case R_MIPS_GNU_VTINHERIT:
5812     case R_MIPS_GNU_VTENTRY:
5813       /* We don't do anything with these at present.  */
5814       return bfd_reloc_continue;
5815
5816     default:
5817       /* An unrecognized relocation type.  */
5818       return bfd_reloc_notsupported;
5819     }
5820
5821   /* Store the VALUE for our caller.  */
5822   *valuep = value;
5823   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
5824 }
5825
5826 /* Obtain the field relocated by RELOCATION.  */
5827
5828 static bfd_vma
5829 mips_elf_obtain_contents (reloc_howto_type *howto,
5830                           const Elf_Internal_Rela *relocation,
5831                           bfd *input_bfd, bfd_byte *contents)
5832 {
5833   bfd_vma x;
5834   bfd_byte *location = contents + relocation->r_offset;
5835
5836   /* Obtain the bytes.  */
5837   x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location);
5838
5839   return x;
5840 }
5841
5842 /* It has been determined that the result of the RELOCATION is the
5843    VALUE.  Use HOWTO to place VALUE into the output file at the
5844    appropriate position.  The SECTION is the section to which the
5845    relocation applies.
5846    CROSS_MODE_JUMP_P is true if the relocation field
5847    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5848
5849    Returns FALSE if anything goes wrong.  */
5850
5851 static bfd_boolean
5852 mips_elf_perform_relocation (struct bfd_link_info *info,
5853                              reloc_howto_type *howto,
5854                              const Elf_Internal_Rela *relocation,
5855                              bfd_vma value, bfd *input_bfd,
5856                              asection *input_section, bfd_byte *contents,
5857                              bfd_boolean cross_mode_jump_p)
5858 {
5859   bfd_vma x;
5860   bfd_byte *location;
5861   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5862
5863   /* Figure out where the relocation is occurring.  */
5864   location = contents + relocation->r_offset;
5865
5866   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
5867
5868   /* Obtain the current value.  */
5869   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
5870
5871   /* Clear the field we are setting.  */
5872   x &= ~howto->dst_mask;
5873
5874   /* Set the field.  */
5875   x |= (value & howto->dst_mask);
5876
5877   /* If required, turn JAL into JALX.  */
5878   if (cross_mode_jump_p && jal_reloc_p (r_type))
5879     {
5880       bfd_boolean ok;
5881       bfd_vma opcode = x >> 26;
5882       bfd_vma jalx_opcode;
5883
5884       /* Check to see if the opcode is already JAL or JALX.  */
5885       if (r_type == R_MIPS16_26)
5886         {
5887           ok = ((opcode == 0x6) || (opcode == 0x7));
5888           jalx_opcode = 0x7;
5889         }
5890       else if (r_type == R_MICROMIPS_26_S1)
5891         {
5892           ok = ((opcode == 0x3d) || (opcode == 0x3c));
5893           jalx_opcode = 0x3c;
5894         }
5895       else
5896         {
5897           ok = ((opcode == 0x3) || (opcode == 0x1d));
5898           jalx_opcode = 0x1d;
5899         }
5900
5901       /* If the opcode is not JAL or JALX, there's a problem.  We cannot
5902          convert J or JALS to JALX.  */
5903       if (!ok)
5904         {
5905           (*_bfd_error_handler)
5906             (_("%B: %A+0x%lx: Unsupported jump between ISA modes; consider recompiling with interlinking enabled."),
5907              input_bfd,
5908              input_section,
5909              (unsigned long) relocation->r_offset);
5910           bfd_set_error (bfd_error_bad_value);
5911           return FALSE;
5912         }
5913
5914       /* Make this the JALX opcode.  */
5915       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
5916     }
5917
5918   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
5919      range.  */
5920   if (!info->relocatable
5921       && !cross_mode_jump_p
5922       && ((JAL_TO_BAL_P (input_bfd)
5923            && r_type == R_MIPS_26
5924            && (x >> 26) == 0x3)         /* jal addr */
5925           || (JALR_TO_BAL_P (input_bfd)
5926               && r_type == R_MIPS_JALR
5927               && x == 0x0320f809)       /* jalr t9 */
5928           || (JR_TO_B_P (input_bfd)
5929               && r_type == R_MIPS_JALR
5930               && x == 0x03200008)))     /* jr t9 */
5931     {
5932       bfd_vma addr;
5933       bfd_vma dest;
5934       bfd_signed_vma off;
5935
5936       addr = (input_section->output_section->vma
5937               + input_section->output_offset
5938               + relocation->r_offset
5939               + 4);
5940       if (r_type == R_MIPS_26)
5941         dest = (value << 2) | ((addr >> 28) << 28);
5942       else
5943         dest = value;
5944       off = dest - addr;
5945       if (off <= 0x1ffff && off >= -0x20000)
5946         {
5947           if (x == 0x03200008)  /* jr t9 */
5948             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
5949           else
5950             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
5951         }
5952     }
5953
5954   /* Put the value into the output.  */
5955   bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location);
5956
5957   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !info->relocatable,
5958                                location);
5959
5960   return TRUE;
5961 }
5962 \f
5963 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
5964    is the original relocation, which is now being transformed into a
5965    dynamic relocation.  The ADDENDP is adjusted if necessary; the
5966    caller should store the result in place of the original addend.  */
5967
5968 static bfd_boolean
5969 mips_elf_create_dynamic_relocation (bfd *output_bfd,
5970                                     struct bfd_link_info *info,
5971                                     const Elf_Internal_Rela *rel,
5972                                     struct mips_elf_link_hash_entry *h,
5973                                     asection *sec, bfd_vma symbol,
5974                                     bfd_vma *addendp, asection *input_section)
5975 {
5976   Elf_Internal_Rela outrel[3];
5977   asection *sreloc;
5978   bfd *dynobj;
5979   int r_type;
5980   long indx;
5981   bfd_boolean defined_p;
5982   struct mips_elf_link_hash_table *htab;
5983
5984   htab = mips_elf_hash_table (info);
5985   BFD_ASSERT (htab != NULL);
5986
5987   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
5988   dynobj = elf_hash_table (info)->dynobj;
5989   sreloc = mips_elf_rel_dyn_section (info, FALSE);
5990   BFD_ASSERT (sreloc != NULL);
5991   BFD_ASSERT (sreloc->contents != NULL);
5992   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
5993               < sreloc->size);
5994
5995   outrel[0].r_offset =
5996     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
5997   if (ABI_64_P (output_bfd))
5998     {
5999       outrel[1].r_offset =
6000         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
6001       outrel[2].r_offset =
6002         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
6003     }
6004
6005   if (outrel[0].r_offset == MINUS_ONE)
6006     /* The relocation field has been deleted.  */
6007     return TRUE;
6008
6009   if (outrel[0].r_offset == MINUS_TWO)
6010     {
6011       /* The relocation field has been converted into a relative value of
6012          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
6013          the field to be fully relocated, so add in the symbol's value.  */
6014       *addendp += symbol;
6015       return TRUE;
6016     }
6017
6018   /* We must now calculate the dynamic symbol table index to use
6019      in the relocation.  */
6020   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
6021     {
6022       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
6023       indx = h->root.dynindx;
6024       if (SGI_COMPAT (output_bfd))
6025         defined_p = h->root.def_regular;
6026       else
6027         /* ??? glibc's ld.so just adds the final GOT entry to the
6028            relocation field.  It therefore treats relocs against
6029            defined symbols in the same way as relocs against
6030            undefined symbols.  */
6031         defined_p = FALSE;
6032     }
6033   else
6034     {
6035       if (sec != NULL && bfd_is_abs_section (sec))
6036         indx = 0;
6037       else if (sec == NULL || sec->owner == NULL)
6038         {
6039           bfd_set_error (bfd_error_bad_value);
6040           return FALSE;
6041         }
6042       else
6043         {
6044           indx = elf_section_data (sec->output_section)->dynindx;
6045           if (indx == 0)
6046             {
6047               asection *osec = htab->root.text_index_section;
6048               indx = elf_section_data (osec)->dynindx;
6049             }
6050           if (indx == 0)
6051             abort ();
6052         }
6053
6054       /* Instead of generating a relocation using the section
6055          symbol, we may as well make it a fully relative
6056          relocation.  We want to avoid generating relocations to
6057          local symbols because we used to generate them
6058          incorrectly, without adding the original symbol value,
6059          which is mandated by the ABI for section symbols.  In
6060          order to give dynamic loaders and applications time to
6061          phase out the incorrect use, we refrain from emitting
6062          section-relative relocations.  It's not like they're
6063          useful, after all.  This should be a bit more efficient
6064          as well.  */
6065       /* ??? Although this behavior is compatible with glibc's ld.so,
6066          the ABI says that relocations against STN_UNDEF should have
6067          a symbol value of 0.  Irix rld honors this, so relocations
6068          against STN_UNDEF have no effect.  */
6069       if (!SGI_COMPAT (output_bfd))
6070         indx = 0;
6071       defined_p = TRUE;
6072     }
6073
6074   /* If the relocation was previously an absolute relocation and
6075      this symbol will not be referred to by the relocation, we must
6076      adjust it by the value we give it in the dynamic symbol table.
6077      Otherwise leave the job up to the dynamic linker.  */
6078   if (defined_p && r_type != R_MIPS_REL32)
6079     *addendp += symbol;
6080
6081   if (htab->is_vxworks)
6082     /* VxWorks uses non-relative relocations for this.  */
6083     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
6084   else
6085     /* The relocation is always an REL32 relocation because we don't
6086        know where the shared library will wind up at load-time.  */
6087     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
6088                                    R_MIPS_REL32);
6089
6090   /* For strict adherence to the ABI specification, we should
6091      generate a R_MIPS_64 relocation record by itself before the
6092      _REL32/_64 record as well, such that the addend is read in as
6093      a 64-bit value (REL32 is a 32-bit relocation, after all).
6094      However, since none of the existing ELF64 MIPS dynamic
6095      loaders seems to care, we don't waste space with these
6096      artificial relocations.  If this turns out to not be true,
6097      mips_elf_allocate_dynamic_relocation() should be tweaked so
6098      as to make room for a pair of dynamic relocations per
6099      invocation if ABI_64_P, and here we should generate an
6100      additional relocation record with R_MIPS_64 by itself for a
6101      NULL symbol before this relocation record.  */
6102   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
6103                                  ABI_64_P (output_bfd)
6104                                  ? R_MIPS_64
6105                                  : R_MIPS_NONE);
6106   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
6107
6108   /* Adjust the output offset of the relocation to reference the
6109      correct location in the output file.  */
6110   outrel[0].r_offset += (input_section->output_section->vma
6111                          + input_section->output_offset);
6112   outrel[1].r_offset += (input_section->output_section->vma
6113                          + input_section->output_offset);
6114   outrel[2].r_offset += (input_section->output_section->vma
6115                          + input_section->output_offset);
6116
6117   /* Put the relocation back out.  We have to use the special
6118      relocation outputter in the 64-bit case since the 64-bit
6119      relocation format is non-standard.  */
6120   if (ABI_64_P (output_bfd))
6121     {
6122       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
6123         (output_bfd, &outrel[0],
6124          (sreloc->contents
6125           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
6126     }
6127   else if (htab->is_vxworks)
6128     {
6129       /* VxWorks uses RELA rather than REL dynamic relocations.  */
6130       outrel[0].r_addend = *addendp;
6131       bfd_elf32_swap_reloca_out
6132         (output_bfd, &outrel[0],
6133          (sreloc->contents
6134           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
6135     }
6136   else
6137     bfd_elf32_swap_reloc_out
6138       (output_bfd, &outrel[0],
6139        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
6140
6141   /* We've now added another relocation.  */
6142   ++sreloc->reloc_count;
6143
6144   /* Make sure the output section is writable.  The dynamic linker
6145      will be writing to it.  */
6146   elf_section_data (input_section->output_section)->this_hdr.sh_flags
6147     |= SHF_WRITE;
6148
6149   /* On IRIX5, make an entry of compact relocation info.  */
6150   if (IRIX_COMPAT (output_bfd) == ict_irix5)
6151     {
6152       asection *scpt = bfd_get_linker_section (dynobj, ".compact_rel");
6153       bfd_byte *cr;
6154
6155       if (scpt)
6156         {
6157           Elf32_crinfo cptrel;
6158
6159           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
6160           cptrel.vaddr = (rel->r_offset
6161                           + input_section->output_section->vma
6162                           + input_section->output_offset);
6163           if (r_type == R_MIPS_REL32)
6164             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
6165           else
6166             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
6167           mips_elf_set_cr_dist2to (cptrel, 0);
6168           cptrel.konst = *addendp;
6169
6170           cr = (scpt->contents
6171                 + sizeof (Elf32_External_compact_rel));
6172           mips_elf_set_cr_relvaddr (cptrel, 0);
6173           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
6174                                      ((Elf32_External_crinfo *) cr
6175                                       + scpt->reloc_count));
6176           ++scpt->reloc_count;
6177         }
6178     }
6179
6180   /* If we've written this relocation for a readonly section,
6181      we need to set DF_TEXTREL again, so that we do not delete the
6182      DT_TEXTREL tag.  */
6183   if (MIPS_ELF_READONLY_SECTION (input_section))
6184     info->flags |= DF_TEXTREL;
6185
6186   return TRUE;
6187 }
6188 \f
6189 /* Return the MACH for a MIPS e_flags value.  */
6190
6191 unsigned long
6192 _bfd_elf_mips_mach (flagword flags)
6193 {
6194   switch (flags & EF_MIPS_MACH)
6195     {
6196     case E_MIPS_MACH_3900:
6197       return bfd_mach_mips3900;
6198
6199     case E_MIPS_MACH_4010:
6200       return bfd_mach_mips4010;
6201
6202     case E_MIPS_MACH_4100:
6203       return bfd_mach_mips4100;
6204
6205     case E_MIPS_MACH_4111:
6206       return bfd_mach_mips4111;
6207
6208     case E_MIPS_MACH_4120:
6209       return bfd_mach_mips4120;
6210
6211     case E_MIPS_MACH_4650:
6212       return bfd_mach_mips4650;
6213
6214     case E_MIPS_MACH_5400:
6215       return bfd_mach_mips5400;
6216
6217     case E_MIPS_MACH_5500:
6218       return bfd_mach_mips5500;
6219
6220     case E_MIPS_MACH_5900:
6221       return bfd_mach_mips5900;
6222
6223     case E_MIPS_MACH_9000:
6224       return bfd_mach_mips9000;
6225
6226     case E_MIPS_MACH_SB1:
6227       return bfd_mach_mips_sb1;
6228
6229     case E_MIPS_MACH_LS2E:
6230       return bfd_mach_mips_loongson_2e;
6231
6232     case E_MIPS_MACH_LS2F:
6233       return bfd_mach_mips_loongson_2f;
6234
6235     case E_MIPS_MACH_LS3A:
6236       return bfd_mach_mips_loongson_3a;
6237
6238     case E_MIPS_MACH_OCTEON2:
6239       return bfd_mach_mips_octeon2;
6240
6241     case E_MIPS_MACH_OCTEON:
6242       return bfd_mach_mips_octeon;
6243
6244     case E_MIPS_MACH_XLR:
6245       return bfd_mach_mips_xlr;
6246
6247     default:
6248       switch (flags & EF_MIPS_ARCH)
6249         {
6250         default:
6251         case E_MIPS_ARCH_1:
6252           return bfd_mach_mips3000;
6253
6254         case E_MIPS_ARCH_2:
6255           return bfd_mach_mips6000;
6256
6257         case E_MIPS_ARCH_3:
6258           return bfd_mach_mips4000;
6259
6260         case E_MIPS_ARCH_4:
6261           return bfd_mach_mips8000;
6262
6263         case E_MIPS_ARCH_5:
6264           return bfd_mach_mips5;
6265
6266         case E_MIPS_ARCH_32:
6267           return bfd_mach_mipsisa32;
6268
6269         case E_MIPS_ARCH_64:
6270           return bfd_mach_mipsisa64;
6271
6272         case E_MIPS_ARCH_32R2:
6273           return bfd_mach_mipsisa32r2;
6274
6275         case E_MIPS_ARCH_64R2:
6276           return bfd_mach_mipsisa64r2;
6277         }
6278     }
6279
6280   return 0;
6281 }
6282
6283 /* Return printable name for ABI.  */
6284
6285 static INLINE char *
6286 elf_mips_abi_name (bfd *abfd)
6287 {
6288   flagword flags;
6289
6290   flags = elf_elfheader (abfd)->e_flags;
6291   switch (flags & EF_MIPS_ABI)
6292     {
6293     case 0:
6294       if (ABI_N32_P (abfd))
6295         return "N32";
6296       else if (ABI_64_P (abfd))
6297         return "64";
6298       else
6299         return "none";
6300     case E_MIPS_ABI_O32:
6301       return "O32";
6302     case E_MIPS_ABI_O64:
6303       return "O64";
6304     case E_MIPS_ABI_EABI32:
6305       return "EABI32";
6306     case E_MIPS_ABI_EABI64:
6307       return "EABI64";
6308     default:
6309       return "unknown abi";
6310     }
6311 }
6312 \f
6313 /* MIPS ELF uses two common sections.  One is the usual one, and the
6314    other is for small objects.  All the small objects are kept
6315    together, and then referenced via the gp pointer, which yields
6316    faster assembler code.  This is what we use for the small common
6317    section.  This approach is copied from ecoff.c.  */
6318 static asection mips_elf_scom_section;
6319 static asymbol mips_elf_scom_symbol;
6320 static asymbol *mips_elf_scom_symbol_ptr;
6321
6322 /* MIPS ELF also uses an acommon section, which represents an
6323    allocated common symbol which may be overridden by a
6324    definition in a shared library.  */
6325 static asection mips_elf_acom_section;
6326 static asymbol mips_elf_acom_symbol;
6327 static asymbol *mips_elf_acom_symbol_ptr;
6328
6329 /* This is used for both the 32-bit and the 64-bit ABI.  */
6330
6331 void
6332 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6333 {
6334   elf_symbol_type *elfsym;
6335
6336   /* Handle the special MIPS section numbers that a symbol may use.  */
6337   elfsym = (elf_symbol_type *) asym;
6338   switch (elfsym->internal_elf_sym.st_shndx)
6339     {
6340     case SHN_MIPS_ACOMMON:
6341       /* This section is used in a dynamically linked executable file.
6342          It is an allocated common section.  The dynamic linker can
6343          either resolve these symbols to something in a shared
6344          library, or it can just leave them here.  For our purposes,
6345          we can consider these symbols to be in a new section.  */
6346       if (mips_elf_acom_section.name == NULL)
6347         {
6348           /* Initialize the acommon section.  */
6349           mips_elf_acom_section.name = ".acommon";
6350           mips_elf_acom_section.flags = SEC_ALLOC;
6351           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6352           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6353           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6354           mips_elf_acom_symbol.name = ".acommon";
6355           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6356           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6357           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6358         }
6359       asym->section = &mips_elf_acom_section;
6360       break;
6361
6362     case SHN_COMMON:
6363       /* Common symbols less than the GP size are automatically
6364          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6365       if (asym->value > elf_gp_size (abfd)
6366           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6367           || IRIX_COMPAT (abfd) == ict_irix6)
6368         break;
6369       /* Fall through.  */
6370     case SHN_MIPS_SCOMMON:
6371       if (mips_elf_scom_section.name == NULL)
6372         {
6373           /* Initialize the small common section.  */
6374           mips_elf_scom_section.name = ".scommon";
6375           mips_elf_scom_section.flags = SEC_IS_COMMON;
6376           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6377           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6378           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6379           mips_elf_scom_symbol.name = ".scommon";
6380           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6381           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6382           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6383         }
6384       asym->section = &mips_elf_scom_section;
6385       asym->value = elfsym->internal_elf_sym.st_size;
6386       break;
6387
6388     case SHN_MIPS_SUNDEFINED:
6389       asym->section = bfd_und_section_ptr;
6390       break;
6391
6392     case SHN_MIPS_TEXT:
6393       {
6394         asection *section = bfd_get_section_by_name (abfd, ".text");
6395
6396         if (section != NULL)
6397           {
6398             asym->section = section;
6399             /* MIPS_TEXT is a bit special, the address is not an offset
6400                to the base of the .text section.  So substract the section
6401                base address to make it an offset.  */
6402             asym->value -= section->vma;
6403           }
6404       }
6405       break;
6406
6407     case SHN_MIPS_DATA:
6408       {
6409         asection *section = bfd_get_section_by_name (abfd, ".data");
6410
6411         if (section != NULL)
6412           {
6413             asym->section = section;
6414             /* MIPS_DATA is a bit special, the address is not an offset
6415                to the base of the .data section.  So substract the section
6416                base address to make it an offset.  */
6417             asym->value -= section->vma;
6418           }
6419       }
6420       break;
6421     }
6422
6423   /* If this is an odd-valued function symbol, assume it's a MIPS16
6424      or microMIPS one.  */
6425   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6426       && (asym->value & 1) != 0)
6427     {
6428       asym->value--;
6429       if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
6430         elfsym->internal_elf_sym.st_other
6431           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6432       else
6433         elfsym->internal_elf_sym.st_other
6434           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6435     }
6436 }
6437 \f
6438 /* Implement elf_backend_eh_frame_address_size.  This differs from
6439    the default in the way it handles EABI64.
6440
6441    EABI64 was originally specified as an LP64 ABI, and that is what
6442    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6443    historically accepted the combination of -mabi=eabi and -mlong32,
6444    and this ILP32 variation has become semi-official over time.
6445    Both forms use elf32 and have pointer-sized FDE addresses.
6446
6447    If an EABI object was generated by GCC 4.0 or above, it will have
6448    an empty .gcc_compiled_longXX section, where XX is the size of longs
6449    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6450    have no special marking to distinguish them from LP64 objects.
6451
6452    We don't want users of the official LP64 ABI to be punished for the
6453    existence of the ILP32 variant, but at the same time, we don't want
6454    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6455    We therefore take the following approach:
6456
6457       - If ABFD contains a .gcc_compiled_longXX section, use it to
6458         determine the pointer size.
6459
6460       - Otherwise check the type of the first relocation.  Assume that
6461         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
6462
6463       - Otherwise punt.
6464
6465    The second check is enough to detect LP64 objects generated by pre-4.0
6466    compilers because, in the kind of output generated by those compilers,
6467    the first relocation will be associated with either a CIE personality
6468    routine or an FDE start address.  Furthermore, the compilers never
6469    used a special (non-pointer) encoding for this ABI.
6470
6471    Checking the relocation type should also be safe because there is no
6472    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
6473    did so.  */
6474
6475 unsigned int
6476 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
6477 {
6478   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
6479     return 8;
6480   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
6481     {
6482       bfd_boolean long32_p, long64_p;
6483
6484       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
6485       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
6486       if (long32_p && long64_p)
6487         return 0;
6488       if (long32_p)
6489         return 4;
6490       if (long64_p)
6491         return 8;
6492
6493       if (sec->reloc_count > 0
6494           && elf_section_data (sec)->relocs != NULL
6495           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
6496               == R_MIPS_64))
6497         return 8;
6498
6499       return 0;
6500     }
6501   return 4;
6502 }
6503 \f
6504 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
6505    relocations against two unnamed section symbols to resolve to the
6506    same address.  For example, if we have code like:
6507
6508         lw      $4,%got_disp(.data)($gp)
6509         lw      $25,%got_disp(.text)($gp)
6510         jalr    $25
6511
6512    then the linker will resolve both relocations to .data and the program
6513    will jump there rather than to .text.
6514
6515    We can work around this problem by giving names to local section symbols.
6516    This is also what the MIPSpro tools do.  */
6517
6518 bfd_boolean
6519 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
6520 {
6521   return SGI_COMPAT (abfd);
6522 }
6523 \f
6524 /* Work over a section just before writing it out.  This routine is
6525    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
6526    sections that need the SHF_MIPS_GPREL flag by name; there has to be
6527    a better way.  */
6528
6529 bfd_boolean
6530 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
6531 {
6532   if (hdr->sh_type == SHT_MIPS_REGINFO
6533       && hdr->sh_size > 0)
6534     {
6535       bfd_byte buf[4];
6536
6537       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
6538       BFD_ASSERT (hdr->contents == NULL);
6539
6540       if (bfd_seek (abfd,
6541                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
6542                     SEEK_SET) != 0)
6543         return FALSE;
6544       H_PUT_32 (abfd, elf_gp (abfd), buf);
6545       if (bfd_bwrite (buf, 4, abfd) != 4)
6546         return FALSE;
6547     }
6548
6549   if (hdr->sh_type == SHT_MIPS_OPTIONS
6550       && hdr->bfd_section != NULL
6551       && mips_elf_section_data (hdr->bfd_section) != NULL
6552       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
6553     {
6554       bfd_byte *contents, *l, *lend;
6555
6556       /* We stored the section contents in the tdata field in the
6557          set_section_contents routine.  We save the section contents
6558          so that we don't have to read them again.
6559          At this point we know that elf_gp is set, so we can look
6560          through the section contents to see if there is an
6561          ODK_REGINFO structure.  */
6562
6563       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
6564       l = contents;
6565       lend = contents + hdr->sh_size;
6566       while (l + sizeof (Elf_External_Options) <= lend)
6567         {
6568           Elf_Internal_Options intopt;
6569
6570           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6571                                         &intopt);
6572           if (intopt.size < sizeof (Elf_External_Options))
6573             {
6574               (*_bfd_error_handler)
6575                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6576                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6577               break;
6578             }
6579           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6580             {
6581               bfd_byte buf[8];
6582
6583               if (bfd_seek (abfd,
6584                             (hdr->sh_offset
6585                              + (l - contents)
6586                              + sizeof (Elf_External_Options)
6587                              + (sizeof (Elf64_External_RegInfo) - 8)),
6588                              SEEK_SET) != 0)
6589                 return FALSE;
6590               H_PUT_64 (abfd, elf_gp (abfd), buf);
6591               if (bfd_bwrite (buf, 8, abfd) != 8)
6592                 return FALSE;
6593             }
6594           else if (intopt.kind == ODK_REGINFO)
6595             {
6596               bfd_byte buf[4];
6597
6598               if (bfd_seek (abfd,
6599                             (hdr->sh_offset
6600                              + (l - contents)
6601                              + sizeof (Elf_External_Options)
6602                              + (sizeof (Elf32_External_RegInfo) - 4)),
6603                             SEEK_SET) != 0)
6604                 return FALSE;
6605               H_PUT_32 (abfd, elf_gp (abfd), buf);
6606               if (bfd_bwrite (buf, 4, abfd) != 4)
6607                 return FALSE;
6608             }
6609           l += intopt.size;
6610         }
6611     }
6612
6613   if (hdr->bfd_section != NULL)
6614     {
6615       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
6616
6617       /* .sbss is not handled specially here because the GNU/Linux
6618          prelinker can convert .sbss from NOBITS to PROGBITS and
6619          changing it back to NOBITS breaks the binary.  The entry in
6620          _bfd_mips_elf_special_sections will ensure the correct flags
6621          are set on .sbss if BFD creates it without reading it from an
6622          input file, and without special handling here the flags set
6623          on it in an input file will be followed.  */
6624       if (strcmp (name, ".sdata") == 0
6625           || strcmp (name, ".lit8") == 0
6626           || strcmp (name, ".lit4") == 0)
6627         {
6628           hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
6629           hdr->sh_type = SHT_PROGBITS;
6630         }
6631       else if (strcmp (name, ".srdata") == 0)
6632         {
6633           hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
6634           hdr->sh_type = SHT_PROGBITS;
6635         }
6636       else if (strcmp (name, ".compact_rel") == 0)
6637         {
6638           hdr->sh_flags = 0;
6639           hdr->sh_type = SHT_PROGBITS;
6640         }
6641       else if (strcmp (name, ".rtproc") == 0)
6642         {
6643           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
6644             {
6645               unsigned int adjust;
6646
6647               adjust = hdr->sh_size % hdr->sh_addralign;
6648               if (adjust != 0)
6649                 hdr->sh_size += hdr->sh_addralign - adjust;
6650             }
6651         }
6652     }
6653
6654   return TRUE;
6655 }
6656
6657 /* Handle a MIPS specific section when reading an object file.  This
6658    is called when elfcode.h finds a section with an unknown type.
6659    This routine supports both the 32-bit and 64-bit ELF ABI.
6660
6661    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
6662    how to.  */
6663
6664 bfd_boolean
6665 _bfd_mips_elf_section_from_shdr (bfd *abfd,
6666                                  Elf_Internal_Shdr *hdr,
6667                                  const char *name,
6668                                  int shindex)
6669 {
6670   flagword flags = 0;
6671
6672   /* There ought to be a place to keep ELF backend specific flags, but
6673      at the moment there isn't one.  We just keep track of the
6674      sections by their name, instead.  Fortunately, the ABI gives
6675      suggested names for all the MIPS specific sections, so we will
6676      probably get away with this.  */
6677   switch (hdr->sh_type)
6678     {
6679     case SHT_MIPS_LIBLIST:
6680       if (strcmp (name, ".liblist") != 0)
6681         return FALSE;
6682       break;
6683     case SHT_MIPS_MSYM:
6684       if (strcmp (name, ".msym") != 0)
6685         return FALSE;
6686       break;
6687     case SHT_MIPS_CONFLICT:
6688       if (strcmp (name, ".conflict") != 0)
6689         return FALSE;
6690       break;
6691     case SHT_MIPS_GPTAB:
6692       if (! CONST_STRNEQ (name, ".gptab."))
6693         return FALSE;
6694       break;
6695     case SHT_MIPS_UCODE:
6696       if (strcmp (name, ".ucode") != 0)
6697         return FALSE;
6698       break;
6699     case SHT_MIPS_DEBUG:
6700       if (strcmp (name, ".mdebug") != 0)
6701         return FALSE;
6702       flags = SEC_DEBUGGING;
6703       break;
6704     case SHT_MIPS_REGINFO:
6705       if (strcmp (name, ".reginfo") != 0
6706           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
6707         return FALSE;
6708       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6709       break;
6710     case SHT_MIPS_IFACE:
6711       if (strcmp (name, ".MIPS.interfaces") != 0)
6712         return FALSE;
6713       break;
6714     case SHT_MIPS_CONTENT:
6715       if (! CONST_STRNEQ (name, ".MIPS.content"))
6716         return FALSE;
6717       break;
6718     case SHT_MIPS_OPTIONS:
6719       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6720         return FALSE;
6721       break;
6722     case SHT_MIPS_DWARF:
6723       if (! CONST_STRNEQ (name, ".debug_")
6724           && ! CONST_STRNEQ (name, ".zdebug_"))
6725         return FALSE;
6726       break;
6727     case SHT_MIPS_SYMBOL_LIB:
6728       if (strcmp (name, ".MIPS.symlib") != 0)
6729         return FALSE;
6730       break;
6731     case SHT_MIPS_EVENTS:
6732       if (! CONST_STRNEQ (name, ".MIPS.events")
6733           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
6734         return FALSE;
6735       break;
6736     default:
6737       break;
6738     }
6739
6740   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
6741     return FALSE;
6742
6743   if (flags)
6744     {
6745       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
6746                                    (bfd_get_section_flags (abfd,
6747                                                            hdr->bfd_section)
6748                                     | flags)))
6749         return FALSE;
6750     }
6751
6752   /* FIXME: We should record sh_info for a .gptab section.  */
6753
6754   /* For a .reginfo section, set the gp value in the tdata information
6755      from the contents of this section.  We need the gp value while
6756      processing relocs, so we just get it now.  The .reginfo section
6757      is not used in the 64-bit MIPS ELF ABI.  */
6758   if (hdr->sh_type == SHT_MIPS_REGINFO)
6759     {
6760       Elf32_External_RegInfo ext;
6761       Elf32_RegInfo s;
6762
6763       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
6764                                       &ext, 0, sizeof ext))
6765         return FALSE;
6766       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
6767       elf_gp (abfd) = s.ri_gp_value;
6768     }
6769
6770   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
6771      set the gp value based on what we find.  We may see both
6772      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
6773      they should agree.  */
6774   if (hdr->sh_type == SHT_MIPS_OPTIONS)
6775     {
6776       bfd_byte *contents, *l, *lend;
6777
6778       contents = bfd_malloc (hdr->sh_size);
6779       if (contents == NULL)
6780         return FALSE;
6781       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
6782                                       0, hdr->sh_size))
6783         {
6784           free (contents);
6785           return FALSE;
6786         }
6787       l = contents;
6788       lend = contents + hdr->sh_size;
6789       while (l + sizeof (Elf_External_Options) <= lend)
6790         {
6791           Elf_Internal_Options intopt;
6792
6793           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6794                                         &intopt);
6795           if (intopt.size < sizeof (Elf_External_Options))
6796             {
6797               (*_bfd_error_handler)
6798                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6799                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6800               break;
6801             }
6802           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6803             {
6804               Elf64_Internal_RegInfo intreg;
6805
6806               bfd_mips_elf64_swap_reginfo_in
6807                 (abfd,
6808                  ((Elf64_External_RegInfo *)
6809                   (l + sizeof (Elf_External_Options))),
6810                  &intreg);
6811               elf_gp (abfd) = intreg.ri_gp_value;
6812             }
6813           else if (intopt.kind == ODK_REGINFO)
6814             {
6815               Elf32_RegInfo intreg;
6816
6817               bfd_mips_elf32_swap_reginfo_in
6818                 (abfd,
6819                  ((Elf32_External_RegInfo *)
6820                   (l + sizeof (Elf_External_Options))),
6821                  &intreg);
6822               elf_gp (abfd) = intreg.ri_gp_value;
6823             }
6824           l += intopt.size;
6825         }
6826       free (contents);
6827     }
6828
6829   return TRUE;
6830 }
6831
6832 /* Set the correct type for a MIPS ELF section.  We do this by the
6833    section name, which is a hack, but ought to work.  This routine is
6834    used by both the 32-bit and the 64-bit ABI.  */
6835
6836 bfd_boolean
6837 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
6838 {
6839   const char *name = bfd_get_section_name (abfd, sec);
6840
6841   if (strcmp (name, ".liblist") == 0)
6842     {
6843       hdr->sh_type = SHT_MIPS_LIBLIST;
6844       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
6845       /* The sh_link field is set in final_write_processing.  */
6846     }
6847   else if (strcmp (name, ".conflict") == 0)
6848     hdr->sh_type = SHT_MIPS_CONFLICT;
6849   else if (CONST_STRNEQ (name, ".gptab."))
6850     {
6851       hdr->sh_type = SHT_MIPS_GPTAB;
6852       hdr->sh_entsize = sizeof (Elf32_External_gptab);
6853       /* The sh_info field is set in final_write_processing.  */
6854     }
6855   else if (strcmp (name, ".ucode") == 0)
6856     hdr->sh_type = SHT_MIPS_UCODE;
6857   else if (strcmp (name, ".mdebug") == 0)
6858     {
6859       hdr->sh_type = SHT_MIPS_DEBUG;
6860       /* In a shared object on IRIX 5.3, the .mdebug section has an
6861          entsize of 0.  FIXME: Does this matter?  */
6862       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
6863         hdr->sh_entsize = 0;
6864       else
6865         hdr->sh_entsize = 1;
6866     }
6867   else if (strcmp (name, ".reginfo") == 0)
6868     {
6869       hdr->sh_type = SHT_MIPS_REGINFO;
6870       /* In a shared object on IRIX 5.3, the .reginfo section has an
6871          entsize of 0x18.  FIXME: Does this matter?  */
6872       if (SGI_COMPAT (abfd))
6873         {
6874           if ((abfd->flags & DYNAMIC) != 0)
6875             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6876           else
6877             hdr->sh_entsize = 1;
6878         }
6879       else
6880         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6881     }
6882   else if (SGI_COMPAT (abfd)
6883            && (strcmp (name, ".hash") == 0
6884                || strcmp (name, ".dynamic") == 0
6885                || strcmp (name, ".dynstr") == 0))
6886     {
6887       if (SGI_COMPAT (abfd))
6888         hdr->sh_entsize = 0;
6889 #if 0
6890       /* This isn't how the IRIX6 linker behaves.  */
6891       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
6892 #endif
6893     }
6894   else if (strcmp (name, ".got") == 0
6895            || strcmp (name, ".srdata") == 0
6896            || strcmp (name, ".sdata") == 0
6897            || strcmp (name, ".sbss") == 0
6898            || strcmp (name, ".lit4") == 0
6899            || strcmp (name, ".lit8") == 0)
6900     hdr->sh_flags |= SHF_MIPS_GPREL;
6901   else if (strcmp (name, ".MIPS.interfaces") == 0)
6902     {
6903       hdr->sh_type = SHT_MIPS_IFACE;
6904       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6905     }
6906   else if (CONST_STRNEQ (name, ".MIPS.content"))
6907     {
6908       hdr->sh_type = SHT_MIPS_CONTENT;
6909       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6910       /* The sh_info field is set in final_write_processing.  */
6911     }
6912   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6913     {
6914       hdr->sh_type = SHT_MIPS_OPTIONS;
6915       hdr->sh_entsize = 1;
6916       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6917     }
6918   else if (CONST_STRNEQ (name, ".debug_")
6919            || CONST_STRNEQ (name, ".zdebug_"))
6920     {
6921       hdr->sh_type = SHT_MIPS_DWARF;
6922
6923       /* Irix facilities such as libexc expect a single .debug_frame
6924          per executable, the system ones have NOSTRIP set and the linker
6925          doesn't merge sections with different flags so ...  */
6926       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
6927         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6928     }
6929   else if (strcmp (name, ".MIPS.symlib") == 0)
6930     {
6931       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
6932       /* The sh_link and sh_info fields are set in
6933          final_write_processing.  */
6934     }
6935   else if (CONST_STRNEQ (name, ".MIPS.events")
6936            || CONST_STRNEQ (name, ".MIPS.post_rel"))
6937     {
6938       hdr->sh_type = SHT_MIPS_EVENTS;
6939       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6940       /* The sh_link field is set in final_write_processing.  */
6941     }
6942   else if (strcmp (name, ".msym") == 0)
6943     {
6944       hdr->sh_type = SHT_MIPS_MSYM;
6945       hdr->sh_flags |= SHF_ALLOC;
6946       hdr->sh_entsize = 8;
6947     }
6948
6949   /* The generic elf_fake_sections will set up REL_HDR using the default
6950    kind of relocations.  We used to set up a second header for the
6951    non-default kind of relocations here, but only NewABI would use
6952    these, and the IRIX ld doesn't like resulting empty RELA sections.
6953    Thus we create those header only on demand now.  */
6954
6955   return TRUE;
6956 }
6957
6958 /* Given a BFD section, try to locate the corresponding ELF section
6959    index.  This is used by both the 32-bit and the 64-bit ABI.
6960    Actually, it's not clear to me that the 64-bit ABI supports these,
6961    but for non-PIC objects we will certainly want support for at least
6962    the .scommon section.  */
6963
6964 bfd_boolean
6965 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
6966                                         asection *sec, int *retval)
6967 {
6968   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
6969     {
6970       *retval = SHN_MIPS_SCOMMON;
6971       return TRUE;
6972     }
6973   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
6974     {
6975       *retval = SHN_MIPS_ACOMMON;
6976       return TRUE;
6977     }
6978   return FALSE;
6979 }
6980 \f
6981 /* Hook called by the linker routine which adds symbols from an object
6982    file.  We must handle the special MIPS section numbers here.  */
6983
6984 bfd_boolean
6985 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
6986                                Elf_Internal_Sym *sym, const char **namep,
6987                                flagword *flagsp ATTRIBUTE_UNUSED,
6988                                asection **secp, bfd_vma *valp)
6989 {
6990   if (SGI_COMPAT (abfd)
6991       && (abfd->flags & DYNAMIC) != 0
6992       && strcmp (*namep, "_rld_new_interface") == 0)
6993     {
6994       /* Skip IRIX5 rld entry name.  */
6995       *namep = NULL;
6996       return TRUE;
6997     }
6998
6999   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
7000      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
7001      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
7002      a magic symbol resolved by the linker, we ignore this bogus definition
7003      of _gp_disp.  New ABI objects do not suffer from this problem so this
7004      is not done for them. */
7005   if (!NEWABI_P(abfd)
7006       && (sym->st_shndx == SHN_ABS)
7007       && (strcmp (*namep, "_gp_disp") == 0))
7008     {
7009       *namep = NULL;
7010       return TRUE;
7011     }
7012
7013   switch (sym->st_shndx)
7014     {
7015     case SHN_COMMON:
7016       /* Common symbols less than the GP size are automatically
7017          treated as SHN_MIPS_SCOMMON symbols.  */
7018       if (sym->st_size > elf_gp_size (abfd)
7019           || ELF_ST_TYPE (sym->st_info) == STT_TLS
7020           || IRIX_COMPAT (abfd) == ict_irix6)
7021         break;
7022       /* Fall through.  */
7023     case SHN_MIPS_SCOMMON:
7024       *secp = bfd_make_section_old_way (abfd, ".scommon");
7025       (*secp)->flags |= SEC_IS_COMMON;
7026       *valp = sym->st_size;
7027       break;
7028
7029     case SHN_MIPS_TEXT:
7030       /* This section is used in a shared object.  */
7031       if (elf_tdata (abfd)->elf_text_section == NULL)
7032         {
7033           asymbol *elf_text_symbol;
7034           asection *elf_text_section;
7035           bfd_size_type amt = sizeof (asection);
7036
7037           elf_text_section = bfd_zalloc (abfd, amt);
7038           if (elf_text_section == NULL)
7039             return FALSE;
7040
7041           amt = sizeof (asymbol);
7042           elf_text_symbol = bfd_zalloc (abfd, amt);
7043           if (elf_text_symbol == NULL)
7044             return FALSE;
7045
7046           /* Initialize the section.  */
7047
7048           elf_tdata (abfd)->elf_text_section = elf_text_section;
7049           elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
7050
7051           elf_text_section->symbol = elf_text_symbol;
7052           elf_text_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_text_symbol;
7053
7054           elf_text_section->name = ".text";
7055           elf_text_section->flags = SEC_NO_FLAGS;
7056           elf_text_section->output_section = NULL;
7057           elf_text_section->owner = abfd;
7058           elf_text_symbol->name = ".text";
7059           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7060           elf_text_symbol->section = elf_text_section;
7061         }
7062       /* This code used to do *secp = bfd_und_section_ptr if
7063          info->shared.  I don't know why, and that doesn't make sense,
7064          so I took it out.  */
7065       *secp = elf_tdata (abfd)->elf_text_section;
7066       break;
7067
7068     case SHN_MIPS_ACOMMON:
7069       /* Fall through. XXX Can we treat this as allocated data?  */
7070     case SHN_MIPS_DATA:
7071       /* This section is used in a shared object.  */
7072       if (elf_tdata (abfd)->elf_data_section == NULL)
7073         {
7074           asymbol *elf_data_symbol;
7075           asection *elf_data_section;
7076           bfd_size_type amt = sizeof (asection);
7077
7078           elf_data_section = bfd_zalloc (abfd, amt);
7079           if (elf_data_section == NULL)
7080             return FALSE;
7081
7082           amt = sizeof (asymbol);
7083           elf_data_symbol = bfd_zalloc (abfd, amt);
7084           if (elf_data_symbol == NULL)
7085             return FALSE;
7086
7087           /* Initialize the section.  */
7088
7089           elf_tdata (abfd)->elf_data_section = elf_data_section;
7090           elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
7091
7092           elf_data_section->symbol = elf_data_symbol;
7093           elf_data_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_data_symbol;
7094
7095           elf_data_section->name = ".data";
7096           elf_data_section->flags = SEC_NO_FLAGS;
7097           elf_data_section->output_section = NULL;
7098           elf_data_section->owner = abfd;
7099           elf_data_symbol->name = ".data";
7100           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7101           elf_data_symbol->section = elf_data_section;
7102         }
7103       /* This code used to do *secp = bfd_und_section_ptr if
7104          info->shared.  I don't know why, and that doesn't make sense,
7105          so I took it out.  */
7106       *secp = elf_tdata (abfd)->elf_data_section;
7107       break;
7108
7109     case SHN_MIPS_SUNDEFINED:
7110       *secp = bfd_und_section_ptr;
7111       break;
7112     }
7113
7114   if (SGI_COMPAT (abfd)
7115       && ! info->shared
7116       && info->output_bfd->xvec == abfd->xvec
7117       && strcmp (*namep, "__rld_obj_head") == 0)
7118     {
7119       struct elf_link_hash_entry *h;
7120       struct bfd_link_hash_entry *bh;
7121
7122       /* Mark __rld_obj_head as dynamic.  */
7123       bh = NULL;
7124       if (! (_bfd_generic_link_add_one_symbol
7125              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
7126               get_elf_backend_data (abfd)->collect, &bh)))
7127         return FALSE;
7128
7129       h = (struct elf_link_hash_entry *) bh;
7130       h->non_elf = 0;
7131       h->def_regular = 1;
7132       h->type = STT_OBJECT;
7133
7134       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7135         return FALSE;
7136
7137       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
7138       mips_elf_hash_table (info)->rld_symbol = h;
7139     }
7140
7141   /* If this is a mips16 text symbol, add 1 to the value to make it
7142      odd.  This will cause something like .word SYM to come up with
7143      the right value when it is loaded into the PC.  */
7144   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7145     ++*valp;
7146
7147   return TRUE;
7148 }
7149
7150 /* This hook function is called before the linker writes out a global
7151    symbol.  We mark symbols as small common if appropriate.  This is
7152    also where we undo the increment of the value for a mips16 symbol.  */
7153
7154 int
7155 _bfd_mips_elf_link_output_symbol_hook
7156   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
7157    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
7158    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
7159 {
7160   /* If we see a common symbol, which implies a relocatable link, then
7161      if a symbol was small common in an input file, mark it as small
7162      common in the output file.  */
7163   if (sym->st_shndx == SHN_COMMON
7164       && strcmp (input_sec->name, ".scommon") == 0)
7165     sym->st_shndx = SHN_MIPS_SCOMMON;
7166
7167   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7168     sym->st_value &= ~1;
7169
7170   return 1;
7171 }
7172 \f
7173 /* Functions for the dynamic linker.  */
7174
7175 /* Create dynamic sections when linking against a dynamic object.  */
7176
7177 bfd_boolean
7178 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
7179 {
7180   struct elf_link_hash_entry *h;
7181   struct bfd_link_hash_entry *bh;
7182   flagword flags;
7183   register asection *s;
7184   const char * const *namep;
7185   struct mips_elf_link_hash_table *htab;
7186
7187   htab = mips_elf_hash_table (info);
7188   BFD_ASSERT (htab != NULL);
7189
7190   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
7191            | SEC_LINKER_CREATED | SEC_READONLY);
7192
7193   /* The psABI requires a read-only .dynamic section, but the VxWorks
7194      EABI doesn't.  */
7195   if (!htab->is_vxworks)
7196     {
7197       s = bfd_get_linker_section (abfd, ".dynamic");
7198       if (s != NULL)
7199         {
7200           if (! bfd_set_section_flags (abfd, s, flags))
7201             return FALSE;
7202         }
7203     }
7204
7205   /* We need to create .got section.  */
7206   if (!mips_elf_create_got_section (abfd, info))
7207     return FALSE;
7208
7209   if (! mips_elf_rel_dyn_section (info, TRUE))
7210     return FALSE;
7211
7212   /* Create .stub section.  */
7213   s = bfd_make_section_anyway_with_flags (abfd,
7214                                           MIPS_ELF_STUB_SECTION_NAME (abfd),
7215                                           flags | SEC_CODE);
7216   if (s == NULL
7217       || ! bfd_set_section_alignment (abfd, s,
7218                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7219     return FALSE;
7220   htab->sstubs = s;
7221
7222   if (!mips_elf_hash_table (info)->use_rld_obj_head
7223       && !info->shared
7224       && bfd_get_linker_section (abfd, ".rld_map") == NULL)
7225     {
7226       s = bfd_make_section_anyway_with_flags (abfd, ".rld_map",
7227                                               flags &~ (flagword) SEC_READONLY);
7228       if (s == NULL
7229           || ! bfd_set_section_alignment (abfd, s,
7230                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7231         return FALSE;
7232     }
7233
7234   /* On IRIX5, we adjust add some additional symbols and change the
7235      alignments of several sections.  There is no ABI documentation
7236      indicating that this is necessary on IRIX6, nor any evidence that
7237      the linker takes such action.  */
7238   if (IRIX_COMPAT (abfd) == ict_irix5)
7239     {
7240       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7241         {
7242           bh = NULL;
7243           if (! (_bfd_generic_link_add_one_symbol
7244                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7245                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7246             return FALSE;
7247
7248           h = (struct elf_link_hash_entry *) bh;
7249           h->non_elf = 0;
7250           h->def_regular = 1;
7251           h->type = STT_SECTION;
7252
7253           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7254             return FALSE;
7255         }
7256
7257       /* We need to create a .compact_rel section.  */
7258       if (SGI_COMPAT (abfd))
7259         {
7260           if (!mips_elf_create_compact_rel_section (abfd, info))
7261             return FALSE;
7262         }
7263
7264       /* Change alignments of some sections.  */
7265       s = bfd_get_linker_section (abfd, ".hash");
7266       if (s != NULL)
7267         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7268       s = bfd_get_linker_section (abfd, ".dynsym");
7269       if (s != NULL)
7270         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7271       s = bfd_get_linker_section (abfd, ".dynstr");
7272       if (s != NULL)
7273         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7274       /* ??? */
7275       s = bfd_get_section_by_name (abfd, ".reginfo");
7276       if (s != NULL)
7277         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7278       s = bfd_get_linker_section (abfd, ".dynamic");
7279       if (s != NULL)
7280         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7281     }
7282
7283   if (!info->shared)
7284     {
7285       const char *name;
7286
7287       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7288       bh = NULL;
7289       if (!(_bfd_generic_link_add_one_symbol
7290             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7291              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7292         return FALSE;
7293
7294       h = (struct elf_link_hash_entry *) bh;
7295       h->non_elf = 0;
7296       h->def_regular = 1;
7297       h->type = STT_SECTION;
7298
7299       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7300         return FALSE;
7301
7302       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7303         {
7304           /* __rld_map is a four byte word located in the .data section
7305              and is filled in by the rtld to contain a pointer to
7306              the _r_debug structure. Its symbol value will be set in
7307              _bfd_mips_elf_finish_dynamic_symbol.  */
7308           s = bfd_get_linker_section (abfd, ".rld_map");
7309           BFD_ASSERT (s != NULL);
7310
7311           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7312           bh = NULL;
7313           if (!(_bfd_generic_link_add_one_symbol
7314                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7315                  get_elf_backend_data (abfd)->collect, &bh)))
7316             return FALSE;
7317
7318           h = (struct elf_link_hash_entry *) bh;
7319           h->non_elf = 0;
7320           h->def_regular = 1;
7321           h->type = STT_OBJECT;
7322
7323           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7324             return FALSE;
7325           mips_elf_hash_table (info)->rld_symbol = h;
7326         }
7327     }
7328
7329   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7330      Also create the _PROCEDURE_LINKAGE_TABLE symbol.  */
7331   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7332     return FALSE;
7333
7334   /* Cache the sections created above.  */
7335   htab->splt = bfd_get_linker_section (abfd, ".plt");
7336   htab->sdynbss = bfd_get_linker_section (abfd, ".dynbss");
7337   if (htab->is_vxworks)
7338     {
7339       htab->srelbss = bfd_get_linker_section (abfd, ".rela.bss");
7340       htab->srelplt = bfd_get_linker_section (abfd, ".rela.plt");
7341     }
7342   else
7343     htab->srelplt = bfd_get_linker_section (abfd, ".rel.plt");
7344   if (!htab->sdynbss
7345       || (htab->is_vxworks && !htab->srelbss && !info->shared)
7346       || !htab->srelplt
7347       || !htab->splt)
7348     abort ();
7349
7350   if (htab->is_vxworks)
7351     {
7352       /* Do the usual VxWorks handling.  */
7353       if (!elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7354         return FALSE;
7355
7356       /* Work out the PLT sizes.  */
7357       if (info->shared)
7358         {
7359           htab->plt_header_size
7360             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
7361           htab->plt_entry_size
7362             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
7363         }
7364       else
7365         {
7366           htab->plt_header_size
7367             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
7368           htab->plt_entry_size
7369             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
7370         }
7371     }
7372   else if (!info->shared)
7373     {
7374       /* All variants of the plt0 entry are the same size.  */
7375       htab->plt_header_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
7376       htab->plt_entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
7377     }
7378
7379   return TRUE;
7380 }
7381 \f
7382 /* Return true if relocation REL against section SEC is a REL rather than
7383    RELA relocation.  RELOCS is the first relocation in the section and
7384    ABFD is the bfd that contains SEC.  */
7385
7386 static bfd_boolean
7387 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7388                            const Elf_Internal_Rela *relocs,
7389                            const Elf_Internal_Rela *rel)
7390 {
7391   Elf_Internal_Shdr *rel_hdr;
7392   const struct elf_backend_data *bed;
7393
7394   /* To determine which flavor of relocation this is, we depend on the
7395      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7396   rel_hdr = elf_section_data (sec)->rel.hdr;
7397   if (rel_hdr == NULL)
7398     return FALSE;
7399   bed = get_elf_backend_data (abfd);
7400   return ((size_t) (rel - relocs)
7401           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7402 }
7403
7404 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7405    HOWTO is the relocation's howto and CONTENTS points to the contents
7406    of the section that REL is against.  */
7407
7408 static bfd_vma
7409 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7410                           reloc_howto_type *howto, bfd_byte *contents)
7411 {
7412   bfd_byte *location;
7413   unsigned int r_type;
7414   bfd_vma addend;
7415
7416   r_type = ELF_R_TYPE (abfd, rel->r_info);
7417   location = contents + rel->r_offset;
7418
7419   /* Get the addend, which is stored in the input file.  */
7420   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7421   addend = mips_elf_obtain_contents (howto, rel, abfd, contents);
7422   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7423
7424   return addend & howto->src_mask;
7425 }
7426
7427 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7428    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7429    and update *ADDEND with the final addend.  Return true on success
7430    or false if the LO16 could not be found.  RELEND is the exclusive
7431    upper bound on the relocations for REL's section.  */
7432
7433 static bfd_boolean
7434 mips_elf_add_lo16_rel_addend (bfd *abfd,
7435                               const Elf_Internal_Rela *rel,
7436                               const Elf_Internal_Rela *relend,
7437                               bfd_byte *contents, bfd_vma *addend)
7438 {
7439   unsigned int r_type, lo16_type;
7440   const Elf_Internal_Rela *lo16_relocation;
7441   reloc_howto_type *lo16_howto;
7442   bfd_vma l;
7443
7444   r_type = ELF_R_TYPE (abfd, rel->r_info);
7445   if (mips16_reloc_p (r_type))
7446     lo16_type = R_MIPS16_LO16;
7447   else if (micromips_reloc_p (r_type))
7448     lo16_type = R_MICROMIPS_LO16;
7449   else
7450     lo16_type = R_MIPS_LO16;
7451
7452   /* The combined value is the sum of the HI16 addend, left-shifted by
7453      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7454      code does a `lui' of the HI16 value, and then an `addiu' of the
7455      LO16 value.)
7456
7457      Scan ahead to find a matching LO16 relocation.
7458
7459      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7460      be immediately following.  However, for the IRIX6 ABI, the next
7461      relocation may be a composed relocation consisting of several
7462      relocations for the same address.  In that case, the R_MIPS_LO16
7463      relocation may occur as one of these.  We permit a similar
7464      extension in general, as that is useful for GCC.
7465
7466      In some cases GCC dead code elimination removes the LO16 but keeps
7467      the corresponding HI16.  This is strictly speaking a violation of
7468      the ABI but not immediately harmful.  */
7469   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
7470   if (lo16_relocation == NULL)
7471     return FALSE;
7472
7473   /* Obtain the addend kept there.  */
7474   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
7475   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
7476
7477   l <<= lo16_howto->rightshift;
7478   l = _bfd_mips_elf_sign_extend (l, 16);
7479
7480   *addend <<= 16;
7481   *addend += l;
7482   return TRUE;
7483 }
7484
7485 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
7486    store the contents in *CONTENTS on success.  Assume that *CONTENTS
7487    already holds the contents if it is nonull on entry.  */
7488
7489 static bfd_boolean
7490 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
7491 {
7492   if (*contents)
7493     return TRUE;
7494
7495   /* Get cached copy if it exists.  */
7496   if (elf_section_data (sec)->this_hdr.contents != NULL)
7497     {
7498       *contents = elf_section_data (sec)->this_hdr.contents;
7499       return TRUE;
7500     }
7501
7502   return bfd_malloc_and_get_section (abfd, sec, contents);
7503 }
7504
7505 /* Look through the relocs for a section during the first phase, and
7506    allocate space in the global offset table.  */
7507
7508 bfd_boolean
7509 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
7510                             asection *sec, const Elf_Internal_Rela *relocs)
7511 {
7512   const char *name;
7513   bfd *dynobj;
7514   Elf_Internal_Shdr *symtab_hdr;
7515   struct elf_link_hash_entry **sym_hashes;
7516   size_t extsymoff;
7517   const Elf_Internal_Rela *rel;
7518   const Elf_Internal_Rela *rel_end;
7519   asection *sreloc;
7520   const struct elf_backend_data *bed;
7521   struct mips_elf_link_hash_table *htab;
7522   bfd_byte *contents;
7523   bfd_vma addend;
7524   reloc_howto_type *howto;
7525
7526   if (info->relocatable)
7527     return TRUE;
7528
7529   htab = mips_elf_hash_table (info);
7530   BFD_ASSERT (htab != NULL);
7531
7532   dynobj = elf_hash_table (info)->dynobj;
7533   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7534   sym_hashes = elf_sym_hashes (abfd);
7535   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
7536
7537   bed = get_elf_backend_data (abfd);
7538   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
7539
7540   /* Check for the mips16 stub sections.  */
7541
7542   name = bfd_get_section_name (abfd, sec);
7543   if (FN_STUB_P (name))
7544     {
7545       unsigned long r_symndx;
7546
7547       /* Look at the relocation information to figure out which symbol
7548          this is for.  */
7549
7550       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7551       if (r_symndx == 0)
7552         {
7553           (*_bfd_error_handler)
7554             (_("%B: Warning: cannot determine the target function for"
7555                " stub section `%s'"),
7556              abfd, name);
7557           bfd_set_error (bfd_error_bad_value);
7558           return FALSE;
7559         }
7560
7561       if (r_symndx < extsymoff
7562           || sym_hashes[r_symndx - extsymoff] == NULL)
7563         {
7564           asection *o;
7565
7566           /* This stub is for a local symbol.  This stub will only be
7567              needed if there is some relocation in this BFD, other
7568              than a 16 bit function call, which refers to this symbol.  */
7569           for (o = abfd->sections; o != NULL; o = o->next)
7570             {
7571               Elf_Internal_Rela *sec_relocs;
7572               const Elf_Internal_Rela *r, *rend;
7573
7574               /* We can ignore stub sections when looking for relocs.  */
7575               if ((o->flags & SEC_RELOC) == 0
7576                   || o->reloc_count == 0
7577                   || section_allows_mips16_refs_p (o))
7578                 continue;
7579
7580               sec_relocs
7581                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7582                                              info->keep_memory);
7583               if (sec_relocs == NULL)
7584                 return FALSE;
7585
7586               rend = sec_relocs + o->reloc_count;
7587               for (r = sec_relocs; r < rend; r++)
7588                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7589                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
7590                   break;
7591
7592               if (elf_section_data (o)->relocs != sec_relocs)
7593                 free (sec_relocs);
7594
7595               if (r < rend)
7596                 break;
7597             }
7598
7599           if (o == NULL)
7600             {
7601               /* There is no non-call reloc for this stub, so we do
7602                  not need it.  Since this function is called before
7603                  the linker maps input sections to output sections, we
7604                  can easily discard it by setting the SEC_EXCLUDE
7605                  flag.  */
7606               sec->flags |= SEC_EXCLUDE;
7607               return TRUE;
7608             }
7609
7610           /* Record this stub in an array of local symbol stubs for
7611              this BFD.  */
7612           if (elf_tdata (abfd)->local_stubs == NULL)
7613             {
7614               unsigned long symcount;
7615               asection **n;
7616               bfd_size_type amt;
7617
7618               if (elf_bad_symtab (abfd))
7619                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7620               else
7621                 symcount = symtab_hdr->sh_info;
7622               amt = symcount * sizeof (asection *);
7623               n = bfd_zalloc (abfd, amt);
7624               if (n == NULL)
7625                 return FALSE;
7626               elf_tdata (abfd)->local_stubs = n;
7627             }
7628
7629           sec->flags |= SEC_KEEP;
7630           elf_tdata (abfd)->local_stubs[r_symndx] = sec;
7631
7632           /* We don't need to set mips16_stubs_seen in this case.
7633              That flag is used to see whether we need to look through
7634              the global symbol table for stubs.  We don't need to set
7635              it here, because we just have a local stub.  */
7636         }
7637       else
7638         {
7639           struct mips_elf_link_hash_entry *h;
7640
7641           h = ((struct mips_elf_link_hash_entry *)
7642                sym_hashes[r_symndx - extsymoff]);
7643
7644           while (h->root.root.type == bfd_link_hash_indirect
7645                  || h->root.root.type == bfd_link_hash_warning)
7646             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
7647
7648           /* H is the symbol this stub is for.  */
7649
7650           /* If we already have an appropriate stub for this function, we
7651              don't need another one, so we can discard this one.  Since
7652              this function is called before the linker maps input sections
7653              to output sections, we can easily discard it by setting the
7654              SEC_EXCLUDE flag.  */
7655           if (h->fn_stub != NULL)
7656             {
7657               sec->flags |= SEC_EXCLUDE;
7658               return TRUE;
7659             }
7660
7661           sec->flags |= SEC_KEEP;
7662           h->fn_stub = sec;
7663           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7664         }
7665     }
7666   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
7667     {
7668       unsigned long r_symndx;
7669       struct mips_elf_link_hash_entry *h;
7670       asection **loc;
7671
7672       /* Look at the relocation information to figure out which symbol
7673          this is for.  */
7674
7675       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7676       if (r_symndx == 0)
7677         {
7678           (*_bfd_error_handler)
7679             (_("%B: Warning: cannot determine the target function for"
7680                " stub section `%s'"),
7681              abfd, name);
7682           bfd_set_error (bfd_error_bad_value);
7683           return FALSE;
7684         }
7685
7686       if (r_symndx < extsymoff
7687           || sym_hashes[r_symndx - extsymoff] == NULL)
7688         {
7689           asection *o;
7690
7691           /* This stub is for a local symbol.  This stub will only be
7692              needed if there is some relocation (R_MIPS16_26) in this BFD
7693              that refers to this symbol.  */
7694           for (o = abfd->sections; o != NULL; o = o->next)
7695             {
7696               Elf_Internal_Rela *sec_relocs;
7697               const Elf_Internal_Rela *r, *rend;
7698
7699               /* We can ignore stub sections when looking for relocs.  */
7700               if ((o->flags & SEC_RELOC) == 0
7701                   || o->reloc_count == 0
7702                   || section_allows_mips16_refs_p (o))
7703                 continue;
7704
7705               sec_relocs
7706                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7707                                              info->keep_memory);
7708               if (sec_relocs == NULL)
7709                 return FALSE;
7710
7711               rend = sec_relocs + o->reloc_count;
7712               for (r = sec_relocs; r < rend; r++)
7713                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7714                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
7715                     break;
7716
7717               if (elf_section_data (o)->relocs != sec_relocs)
7718                 free (sec_relocs);
7719
7720               if (r < rend)
7721                 break;
7722             }
7723
7724           if (o == NULL)
7725             {
7726               /* There is no non-call reloc for this stub, so we do
7727                  not need it.  Since this function is called before
7728                  the linker maps input sections to output sections, we
7729                  can easily discard it by setting the SEC_EXCLUDE
7730                  flag.  */
7731               sec->flags |= SEC_EXCLUDE;
7732               return TRUE;
7733             }
7734
7735           /* Record this stub in an array of local symbol call_stubs for
7736              this BFD.  */
7737           if (elf_tdata (abfd)->local_call_stubs == NULL)
7738             {
7739               unsigned long symcount;
7740               asection **n;
7741               bfd_size_type amt;
7742
7743               if (elf_bad_symtab (abfd))
7744                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7745               else
7746                 symcount = symtab_hdr->sh_info;
7747               amt = symcount * sizeof (asection *);
7748               n = bfd_zalloc (abfd, amt);
7749               if (n == NULL)
7750                 return FALSE;
7751               elf_tdata (abfd)->local_call_stubs = n;
7752             }
7753
7754           sec->flags |= SEC_KEEP;
7755           elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
7756
7757           /* We don't need to set mips16_stubs_seen in this case.
7758              That flag is used to see whether we need to look through
7759              the global symbol table for stubs.  We don't need to set
7760              it here, because we just have a local stub.  */
7761         }
7762       else
7763         {
7764           h = ((struct mips_elf_link_hash_entry *)
7765                sym_hashes[r_symndx - extsymoff]);
7766
7767           /* H is the symbol this stub is for.  */
7768
7769           if (CALL_FP_STUB_P (name))
7770             loc = &h->call_fp_stub;
7771           else
7772             loc = &h->call_stub;
7773
7774           /* If we already have an appropriate stub for this function, we
7775              don't need another one, so we can discard this one.  Since
7776              this function is called before the linker maps input sections
7777              to output sections, we can easily discard it by setting the
7778              SEC_EXCLUDE flag.  */
7779           if (*loc != NULL)
7780             {
7781               sec->flags |= SEC_EXCLUDE;
7782               return TRUE;
7783             }
7784
7785           sec->flags |= SEC_KEEP;
7786           *loc = sec;
7787           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7788         }
7789     }
7790
7791   sreloc = NULL;
7792   contents = NULL;
7793   for (rel = relocs; rel < rel_end; ++rel)
7794     {
7795       unsigned long r_symndx;
7796       unsigned int r_type;
7797       struct elf_link_hash_entry *h;
7798       bfd_boolean can_make_dynamic_p;
7799
7800       r_symndx = ELF_R_SYM (abfd, rel->r_info);
7801       r_type = ELF_R_TYPE (abfd, rel->r_info);
7802
7803       if (r_symndx < extsymoff)
7804         h = NULL;
7805       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
7806         {
7807           (*_bfd_error_handler)
7808             (_("%B: Malformed reloc detected for section %s"),
7809              abfd, name);
7810           bfd_set_error (bfd_error_bad_value);
7811           return FALSE;
7812         }
7813       else
7814         {
7815           h = sym_hashes[r_symndx - extsymoff];
7816           while (h != NULL
7817                  && (h->root.type == bfd_link_hash_indirect
7818                      || h->root.type == bfd_link_hash_warning))
7819             h = (struct elf_link_hash_entry *) h->root.u.i.link;
7820         }
7821
7822       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
7823          relocation into a dynamic one.  */
7824       can_make_dynamic_p = FALSE;
7825       switch (r_type)
7826         {
7827         case R_MIPS_GOT16:
7828         case R_MIPS_CALL16:
7829         case R_MIPS_CALL_HI16:
7830         case R_MIPS_CALL_LO16:
7831         case R_MIPS_GOT_HI16:
7832         case R_MIPS_GOT_LO16:
7833         case R_MIPS_GOT_PAGE:
7834         case R_MIPS_GOT_OFST:
7835         case R_MIPS_GOT_DISP:
7836         case R_MIPS_TLS_GOTTPREL:
7837         case R_MIPS_TLS_GD:
7838         case R_MIPS_TLS_LDM:
7839         case R_MIPS16_GOT16:
7840         case R_MIPS16_CALL16:
7841         case R_MIPS16_TLS_GOTTPREL:
7842         case R_MIPS16_TLS_GD:
7843         case R_MIPS16_TLS_LDM:
7844         case R_MICROMIPS_GOT16:
7845         case R_MICROMIPS_CALL16:
7846         case R_MICROMIPS_CALL_HI16:
7847         case R_MICROMIPS_CALL_LO16:
7848         case R_MICROMIPS_GOT_HI16:
7849         case R_MICROMIPS_GOT_LO16:
7850         case R_MICROMIPS_GOT_PAGE:
7851         case R_MICROMIPS_GOT_OFST:
7852         case R_MICROMIPS_GOT_DISP:
7853         case R_MICROMIPS_TLS_GOTTPREL:
7854         case R_MICROMIPS_TLS_GD:
7855         case R_MICROMIPS_TLS_LDM:
7856           if (dynobj == NULL)
7857             elf_hash_table (info)->dynobj = dynobj = abfd;
7858           if (!mips_elf_create_got_section (dynobj, info))
7859             return FALSE;
7860           if (htab->is_vxworks && !info->shared)
7861             {
7862               (*_bfd_error_handler)
7863                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
7864                  abfd, (unsigned long) rel->r_offset);
7865               bfd_set_error (bfd_error_bad_value);
7866               return FALSE;
7867             }
7868           break;
7869
7870           /* This is just a hint; it can safely be ignored.  Don't set
7871              has_static_relocs for the corresponding symbol.  */
7872         case R_MIPS_JALR:
7873         case R_MICROMIPS_JALR:
7874           break;
7875
7876         case R_MIPS_32:
7877         case R_MIPS_REL32:
7878         case R_MIPS_64:
7879           /* In VxWorks executables, references to external symbols
7880              must be handled using copy relocs or PLT entries; it is not
7881              possible to convert this relocation into a dynamic one.
7882
7883              For executables that use PLTs and copy-relocs, we have a
7884              choice between converting the relocation into a dynamic
7885              one or using copy relocations or PLT entries.  It is
7886              usually better to do the former, unless the relocation is
7887              against a read-only section.  */
7888           if ((info->shared
7889                || (h != NULL
7890                    && !htab->is_vxworks
7891                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
7892                    && !(!info->nocopyreloc
7893                         && !PIC_OBJECT_P (abfd)
7894                         && MIPS_ELF_READONLY_SECTION (sec))))
7895               && (sec->flags & SEC_ALLOC) != 0)
7896             {
7897               can_make_dynamic_p = TRUE;
7898               if (dynobj == NULL)
7899                 elf_hash_table (info)->dynobj = dynobj = abfd;
7900               break;
7901             }
7902           /* For sections that are not SEC_ALLOC a copy reloc would be
7903              output if possible (implying questionable semantics for
7904              read-only data objects) or otherwise the final link would
7905              fail as ld.so will not process them and could not therefore
7906              handle any outstanding dynamic relocations.
7907
7908              For such sections that are also SEC_DEBUGGING, we can avoid
7909              these problems by simply ignoring any relocs as these
7910              sections have a predefined use and we know it is safe to do
7911              so.
7912
7913              This is needed in cases such as a global symbol definition
7914              in a shared library causing a common symbol from an object
7915              file to be converted to an undefined reference.  If that
7916              happens, then all the relocations against this symbol from
7917              SEC_DEBUGGING sections in the object file will resolve to
7918              nil.  */
7919           if ((sec->flags & SEC_DEBUGGING) != 0)
7920             break;
7921           /* Fall through.  */
7922
7923         default:
7924           /* Most static relocations require pointer equality, except
7925              for branches.  */
7926           if (h)
7927             h->pointer_equality_needed = TRUE;
7928           /* Fall through.  */
7929
7930         case R_MIPS_26:
7931         case R_MIPS_PC16:
7932         case R_MIPS16_26:
7933         case R_MICROMIPS_26_S1:
7934         case R_MICROMIPS_PC7_S1:
7935         case R_MICROMIPS_PC10_S1:
7936         case R_MICROMIPS_PC16_S1:
7937         case R_MICROMIPS_PC23_S2:
7938           if (h)
7939             ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = TRUE;
7940           break;
7941         }
7942
7943       if (h)
7944         {
7945           /* Relocations against the special VxWorks __GOTT_BASE__ and
7946              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
7947              room for them in .rela.dyn.  */
7948           if (is_gott_symbol (info, h))
7949             {
7950               if (sreloc == NULL)
7951                 {
7952                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
7953                   if (sreloc == NULL)
7954                     return FALSE;
7955                 }
7956               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
7957               if (MIPS_ELF_READONLY_SECTION (sec))
7958                 /* We tell the dynamic linker that there are
7959                    relocations against the text segment.  */
7960                 info->flags |= DF_TEXTREL;
7961             }
7962         }
7963       else if (call_lo16_reloc_p (r_type)
7964                || got_lo16_reloc_p (r_type)
7965                || got_disp_reloc_p (r_type)
7966                || (got16_reloc_p (r_type) && htab->is_vxworks))
7967         {
7968           /* We may need a local GOT entry for this relocation.  We
7969              don't count R_MIPS_GOT_PAGE because we can estimate the
7970              maximum number of pages needed by looking at the size of
7971              the segment.  Similar comments apply to R_MIPS*_GOT16 and
7972              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
7973              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
7974              R_MIPS_CALL_HI16 because these are always followed by an
7975              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
7976           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
7977                                                  rel->r_addend, info, r_type))
7978             return FALSE;
7979         }
7980
7981       if (h != NULL
7982           && mips_elf_relocation_needs_la25_stub (abfd, r_type,
7983                                                   ELF_ST_IS_MIPS16 (h->other)))
7984         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
7985
7986       switch (r_type)
7987         {
7988         case R_MIPS_CALL16:
7989         case R_MIPS16_CALL16:
7990         case R_MICROMIPS_CALL16:
7991           if (h == NULL)
7992             {
7993               (*_bfd_error_handler)
7994                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
7995                  abfd, (unsigned long) rel->r_offset);
7996               bfd_set_error (bfd_error_bad_value);
7997               return FALSE;
7998             }
7999           /* Fall through.  */
8000
8001         case R_MIPS_CALL_HI16:
8002         case R_MIPS_CALL_LO16:
8003         case R_MICROMIPS_CALL_HI16:
8004         case R_MICROMIPS_CALL_LO16:
8005           if (h != NULL)
8006             {
8007               /* Make sure there is room in the regular GOT to hold the
8008                  function's address.  We may eliminate it in favour of
8009                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
8010               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE,
8011                                                       r_type))
8012                 return FALSE;
8013
8014               /* We need a stub, not a plt entry for the undefined
8015                  function.  But we record it as if it needs plt.  See
8016                  _bfd_elf_adjust_dynamic_symbol.  */
8017               h->needs_plt = 1;
8018               h->type = STT_FUNC;
8019             }
8020           break;
8021
8022         case R_MIPS_GOT_PAGE:
8023         case R_MICROMIPS_GOT_PAGE:
8024           /* If this is a global, overridable symbol, GOT_PAGE will
8025              decay to GOT_DISP, so we'll need a GOT entry for it.  */
8026           if (h)
8027             {
8028               struct mips_elf_link_hash_entry *hmips =
8029                 (struct mips_elf_link_hash_entry *) h;
8030
8031               /* This symbol is definitely not overridable.  */
8032               if (hmips->root.def_regular
8033                   && ! (info->shared && ! info->symbolic
8034                         && ! hmips->root.forced_local))
8035                 h = NULL;
8036             }
8037           /* Fall through.  */
8038
8039         case R_MIPS16_GOT16:
8040         case R_MIPS_GOT16:
8041         case R_MIPS_GOT_HI16:
8042         case R_MIPS_GOT_LO16:
8043         case R_MICROMIPS_GOT16:
8044         case R_MICROMIPS_GOT_HI16:
8045         case R_MICROMIPS_GOT_LO16:
8046           if (!h || got_page_reloc_p (r_type))
8047             {
8048               /* This relocation needs (or may need, if h != NULL) a
8049                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
8050                  know for sure until we know whether the symbol is
8051                  preemptible.  */
8052               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
8053                 {
8054                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
8055                     return FALSE;
8056                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8057                   addend = mips_elf_read_rel_addend (abfd, rel,
8058                                                      howto, contents);
8059                   if (got16_reloc_p (r_type))
8060                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
8061                                                   contents, &addend);
8062                   else
8063                     addend <<= howto->rightshift;
8064                 }
8065               else
8066                 addend = rel->r_addend;
8067               if (!mips_elf_record_got_page_entry (info, abfd, r_symndx,
8068                                                    addend))
8069                 return FALSE;
8070             }
8071           /* Fall through.  */
8072
8073         case R_MIPS_GOT_DISP:
8074         case R_MICROMIPS_GOT_DISP:
8075           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8076                                                        FALSE, r_type))
8077             return FALSE;
8078           break;
8079
8080         case R_MIPS_TLS_GOTTPREL:
8081         case R_MIPS16_TLS_GOTTPREL:
8082         case R_MICROMIPS_TLS_GOTTPREL:
8083           if (info->shared)
8084             info->flags |= DF_STATIC_TLS;
8085           /* Fall through */
8086
8087         case R_MIPS_TLS_LDM:
8088         case R_MIPS16_TLS_LDM:
8089         case R_MICROMIPS_TLS_LDM:
8090           if (tls_ldm_reloc_p (r_type))
8091             {
8092               r_symndx = STN_UNDEF;
8093               h = NULL;
8094             }
8095           /* Fall through */
8096
8097         case R_MIPS_TLS_GD:
8098         case R_MIPS16_TLS_GD:
8099         case R_MICROMIPS_TLS_GD:
8100           /* This symbol requires a global offset table entry, or two
8101              for TLS GD relocations.  */
8102           if (h != NULL)
8103             {
8104               if (!mips_elf_record_global_got_symbol (h, abfd, info,
8105                                                       FALSE, r_type))
8106                 return FALSE;
8107             }
8108           else
8109             {
8110               if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8111                                                      rel->r_addend,
8112                                                      info, r_type))
8113                 return FALSE;
8114             }
8115           break;
8116
8117         case R_MIPS_32:
8118         case R_MIPS_REL32:
8119         case R_MIPS_64:
8120           /* In VxWorks executables, references to external symbols
8121              are handled using copy relocs or PLT stubs, so there's
8122              no need to add a .rela.dyn entry for this relocation.  */
8123           if (can_make_dynamic_p)
8124             {
8125               if (sreloc == NULL)
8126                 {
8127                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8128                   if (sreloc == NULL)
8129                     return FALSE;
8130                 }
8131               if (info->shared && h == NULL)
8132                 {
8133                   /* When creating a shared object, we must copy these
8134                      reloc types into the output file as R_MIPS_REL32
8135                      relocs.  Make room for this reloc in .rel(a).dyn.  */
8136                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8137                   if (MIPS_ELF_READONLY_SECTION (sec))
8138                     /* We tell the dynamic linker that there are
8139                        relocations against the text segment.  */
8140                     info->flags |= DF_TEXTREL;
8141                 }
8142               else
8143                 {
8144                   struct mips_elf_link_hash_entry *hmips;
8145
8146                   /* For a shared object, we must copy this relocation
8147                      unless the symbol turns out to be undefined and
8148                      weak with non-default visibility, in which case
8149                      it will be left as zero.
8150
8151                      We could elide R_MIPS_REL32 for locally binding symbols
8152                      in shared libraries, but do not yet do so.
8153
8154                      For an executable, we only need to copy this
8155                      reloc if the symbol is defined in a dynamic
8156                      object.  */
8157                   hmips = (struct mips_elf_link_hash_entry *) h;
8158                   ++hmips->possibly_dynamic_relocs;
8159                   if (MIPS_ELF_READONLY_SECTION (sec))
8160                     /* We need it to tell the dynamic linker if there
8161                        are relocations against the text segment.  */
8162                     hmips->readonly_reloc = TRUE;
8163                 }
8164             }
8165
8166           if (SGI_COMPAT (abfd))
8167             mips_elf_hash_table (info)->compact_rel_size +=
8168               sizeof (Elf32_External_crinfo);
8169           break;
8170
8171         case R_MIPS_26:
8172         case R_MIPS_GPREL16:
8173         case R_MIPS_LITERAL:
8174         case R_MIPS_GPREL32:
8175         case R_MICROMIPS_26_S1:
8176         case R_MICROMIPS_GPREL16:
8177         case R_MICROMIPS_LITERAL:
8178         case R_MICROMIPS_GPREL7_S2:
8179           if (SGI_COMPAT (abfd))
8180             mips_elf_hash_table (info)->compact_rel_size +=
8181               sizeof (Elf32_External_crinfo);
8182           break;
8183
8184           /* This relocation describes the C++ object vtable hierarchy.
8185              Reconstruct it for later use during GC.  */
8186         case R_MIPS_GNU_VTINHERIT:
8187           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
8188             return FALSE;
8189           break;
8190
8191           /* This relocation describes which C++ vtable entries are actually
8192              used.  Record for later use during GC.  */
8193         case R_MIPS_GNU_VTENTRY:
8194           BFD_ASSERT (h != NULL);
8195           if (h != NULL
8196               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
8197             return FALSE;
8198           break;
8199
8200         default:
8201           break;
8202         }
8203
8204       /* We must not create a stub for a symbol that has relocations
8205          related to taking the function's address.  This doesn't apply to
8206          VxWorks, where CALL relocs refer to a .got.plt entry instead of
8207          a normal .got entry.  */
8208       if (!htab->is_vxworks && h != NULL)
8209         switch (r_type)
8210           {
8211           default:
8212             ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8213             break;
8214           case R_MIPS16_CALL16:
8215           case R_MIPS_CALL16:
8216           case R_MIPS_CALL_HI16:
8217           case R_MIPS_CALL_LO16:
8218           case R_MIPS_JALR:
8219           case R_MICROMIPS_CALL16:
8220           case R_MICROMIPS_CALL_HI16:
8221           case R_MICROMIPS_CALL_LO16:
8222           case R_MICROMIPS_JALR:
8223             break;
8224           }
8225
8226       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8227          if there is one.  We only need to handle global symbols here;
8228          we decide whether to keep or delete stubs for local symbols
8229          when processing the stub's relocations.  */
8230       if (h != NULL
8231           && !mips16_call_reloc_p (r_type)
8232           && !section_allows_mips16_refs_p (sec))
8233         {
8234           struct mips_elf_link_hash_entry *mh;
8235
8236           mh = (struct mips_elf_link_hash_entry *) h;
8237           mh->need_fn_stub = TRUE;
8238         }
8239
8240       /* Refuse some position-dependent relocations when creating a
8241          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8242          not PIC, but we can create dynamic relocations and the result
8243          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8244          combined with R_MIPS_GOT16.  */
8245       if (info->shared)
8246         {
8247           switch (r_type)
8248             {
8249             case R_MIPS16_HI16:
8250             case R_MIPS_HI16:
8251             case R_MIPS_HIGHER:
8252             case R_MIPS_HIGHEST:
8253             case R_MICROMIPS_HI16:
8254             case R_MICROMIPS_HIGHER:
8255             case R_MICROMIPS_HIGHEST:
8256               /* Don't refuse a high part relocation if it's against
8257                  no symbol (e.g. part of a compound relocation).  */
8258               if (r_symndx == STN_UNDEF)
8259                 break;
8260
8261               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8262                  and has a special meaning.  */
8263               if (!NEWABI_P (abfd) && h != NULL
8264                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8265                 break;
8266
8267               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8268               if (is_gott_symbol (info, h))
8269                 break;
8270
8271               /* FALLTHROUGH */
8272
8273             case R_MIPS16_26:
8274             case R_MIPS_26:
8275             case R_MICROMIPS_26_S1:
8276               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8277               (*_bfd_error_handler)
8278                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8279                  abfd, howto->name,
8280                  (h) ? h->root.root.string : "a local symbol");
8281               bfd_set_error (bfd_error_bad_value);
8282               return FALSE;
8283             default:
8284               break;
8285             }
8286         }
8287     }
8288
8289   return TRUE;
8290 }
8291 \f
8292 bfd_boolean
8293 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8294                          struct bfd_link_info *link_info,
8295                          bfd_boolean *again)
8296 {
8297   Elf_Internal_Rela *internal_relocs;
8298   Elf_Internal_Rela *irel, *irelend;
8299   Elf_Internal_Shdr *symtab_hdr;
8300   bfd_byte *contents = NULL;
8301   size_t extsymoff;
8302   bfd_boolean changed_contents = FALSE;
8303   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8304   Elf_Internal_Sym *isymbuf = NULL;
8305
8306   /* We are not currently changing any sizes, so only one pass.  */
8307   *again = FALSE;
8308
8309   if (link_info->relocatable)
8310     return TRUE;
8311
8312   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8313                                                link_info->keep_memory);
8314   if (internal_relocs == NULL)
8315     return TRUE;
8316
8317   irelend = internal_relocs + sec->reloc_count
8318     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8319   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8320   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8321
8322   for (irel = internal_relocs; irel < irelend; irel++)
8323     {
8324       bfd_vma symval;
8325       bfd_signed_vma sym_offset;
8326       unsigned int r_type;
8327       unsigned long r_symndx;
8328       asection *sym_sec;
8329       unsigned long instruction;
8330
8331       /* Turn jalr into bgezal, and jr into beq, if they're marked
8332          with a JALR relocation, that indicate where they jump to.
8333          This saves some pipeline bubbles.  */
8334       r_type = ELF_R_TYPE (abfd, irel->r_info);
8335       if (r_type != R_MIPS_JALR)
8336         continue;
8337
8338       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8339       /* Compute the address of the jump target.  */
8340       if (r_symndx >= extsymoff)
8341         {
8342           struct mips_elf_link_hash_entry *h
8343             = ((struct mips_elf_link_hash_entry *)
8344                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8345
8346           while (h->root.root.type == bfd_link_hash_indirect
8347                  || h->root.root.type == bfd_link_hash_warning)
8348             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8349
8350           /* If a symbol is undefined, or if it may be overridden,
8351              skip it.  */
8352           if (! ((h->root.root.type == bfd_link_hash_defined
8353                   || h->root.root.type == bfd_link_hash_defweak)
8354                  && h->root.root.u.def.section)
8355               || (link_info->shared && ! link_info->symbolic
8356                   && !h->root.forced_local))
8357             continue;
8358
8359           sym_sec = h->root.root.u.def.section;
8360           if (sym_sec->output_section)
8361             symval = (h->root.root.u.def.value
8362                       + sym_sec->output_section->vma
8363                       + sym_sec->output_offset);
8364           else
8365             symval = h->root.root.u.def.value;
8366         }
8367       else
8368         {
8369           Elf_Internal_Sym *isym;
8370
8371           /* Read this BFD's symbols if we haven't done so already.  */
8372           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8373             {
8374               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8375               if (isymbuf == NULL)
8376                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8377                                                 symtab_hdr->sh_info, 0,
8378                                                 NULL, NULL, NULL);
8379               if (isymbuf == NULL)
8380                 goto relax_return;
8381             }
8382
8383           isym = isymbuf + r_symndx;
8384           if (isym->st_shndx == SHN_UNDEF)
8385             continue;
8386           else if (isym->st_shndx == SHN_ABS)
8387             sym_sec = bfd_abs_section_ptr;
8388           else if (isym->st_shndx == SHN_COMMON)
8389             sym_sec = bfd_com_section_ptr;
8390           else
8391             sym_sec
8392               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8393           symval = isym->st_value
8394             + sym_sec->output_section->vma
8395             + sym_sec->output_offset;
8396         }
8397
8398       /* Compute branch offset, from delay slot of the jump to the
8399          branch target.  */
8400       sym_offset = (symval + irel->r_addend)
8401         - (sec_start + irel->r_offset + 4);
8402
8403       /* Branch offset must be properly aligned.  */
8404       if ((sym_offset & 3) != 0)
8405         continue;
8406
8407       sym_offset >>= 2;
8408
8409       /* Check that it's in range.  */
8410       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
8411         continue;
8412
8413       /* Get the section contents if we haven't done so already.  */
8414       if (!mips_elf_get_section_contents (abfd, sec, &contents))
8415         goto relax_return;
8416
8417       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
8418
8419       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
8420       if ((instruction & 0xfc1fffff) == 0x0000f809)
8421         instruction = 0x04110000;
8422       /* If it was jr <reg>, turn it into b <target>.  */
8423       else if ((instruction & 0xfc1fffff) == 0x00000008)
8424         instruction = 0x10000000;
8425       else
8426         continue;
8427
8428       instruction |= (sym_offset & 0xffff);
8429       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
8430       changed_contents = TRUE;
8431     }
8432
8433   if (contents != NULL
8434       && elf_section_data (sec)->this_hdr.contents != contents)
8435     {
8436       if (!changed_contents && !link_info->keep_memory)
8437         free (contents);
8438       else
8439         {
8440           /* Cache the section contents for elf_link_input_bfd.  */
8441           elf_section_data (sec)->this_hdr.contents = contents;
8442         }
8443     }
8444   return TRUE;
8445
8446  relax_return:
8447   if (contents != NULL
8448       && elf_section_data (sec)->this_hdr.contents != contents)
8449     free (contents);
8450   return FALSE;
8451 }
8452 \f
8453 /* Allocate space for global sym dynamic relocs.  */
8454
8455 static bfd_boolean
8456 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
8457 {
8458   struct bfd_link_info *info = inf;
8459   bfd *dynobj;
8460   struct mips_elf_link_hash_entry *hmips;
8461   struct mips_elf_link_hash_table *htab;
8462
8463   htab = mips_elf_hash_table (info);
8464   BFD_ASSERT (htab != NULL);
8465
8466   dynobj = elf_hash_table (info)->dynobj;
8467   hmips = (struct mips_elf_link_hash_entry *) h;
8468
8469   /* VxWorks executables are handled elsewhere; we only need to
8470      allocate relocations in shared objects.  */
8471   if (htab->is_vxworks && !info->shared)
8472     return TRUE;
8473
8474   /* Ignore indirect symbols.  All relocations against such symbols
8475      will be redirected to the target symbol.  */
8476   if (h->root.type == bfd_link_hash_indirect)
8477     return TRUE;
8478
8479   /* If this symbol is defined in a dynamic object, or we are creating
8480      a shared library, we will need to copy any R_MIPS_32 or
8481      R_MIPS_REL32 relocs against it into the output file.  */
8482   if (! info->relocatable
8483       && hmips->possibly_dynamic_relocs != 0
8484       && (h->root.type == bfd_link_hash_defweak
8485           || (!h->def_regular && !ELF_COMMON_DEF_P (h))
8486           || info->shared))
8487     {
8488       bfd_boolean do_copy = TRUE;
8489
8490       if (h->root.type == bfd_link_hash_undefweak)
8491         {
8492           /* Do not copy relocations for undefined weak symbols with
8493              non-default visibility.  */
8494           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
8495             do_copy = FALSE;
8496
8497           /* Make sure undefined weak symbols are output as a dynamic
8498              symbol in PIEs.  */
8499           else if (h->dynindx == -1 && !h->forced_local)
8500             {
8501               if (! bfd_elf_link_record_dynamic_symbol (info, h))
8502                 return FALSE;
8503             }
8504         }
8505
8506       if (do_copy)
8507         {
8508           /* Even though we don't directly need a GOT entry for this symbol,
8509              the SVR4 psABI requires it to have a dynamic symbol table
8510              index greater that DT_MIPS_GOTSYM if there are dynamic
8511              relocations against it.
8512
8513              VxWorks does not enforce the same mapping between the GOT
8514              and the symbol table, so the same requirement does not
8515              apply there.  */
8516           if (!htab->is_vxworks)
8517             {
8518               if (hmips->global_got_area > GGA_RELOC_ONLY)
8519                 hmips->global_got_area = GGA_RELOC_ONLY;
8520               hmips->got_only_for_calls = FALSE;
8521             }
8522
8523           mips_elf_allocate_dynamic_relocations
8524             (dynobj, info, hmips->possibly_dynamic_relocs);
8525           if (hmips->readonly_reloc)
8526             /* We tell the dynamic linker that there are relocations
8527                against the text segment.  */
8528             info->flags |= DF_TEXTREL;
8529         }
8530     }
8531
8532   return TRUE;
8533 }
8534
8535 /* Adjust a symbol defined by a dynamic object and referenced by a
8536    regular object.  The current definition is in some section of the
8537    dynamic object, but we're not including those sections.  We have to
8538    change the definition to something the rest of the link can
8539    understand.  */
8540
8541 bfd_boolean
8542 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
8543                                      struct elf_link_hash_entry *h)
8544 {
8545   bfd *dynobj;
8546   struct mips_elf_link_hash_entry *hmips;
8547   struct mips_elf_link_hash_table *htab;
8548
8549   htab = mips_elf_hash_table (info);
8550   BFD_ASSERT (htab != NULL);
8551
8552   dynobj = elf_hash_table (info)->dynobj;
8553   hmips = (struct mips_elf_link_hash_entry *) h;
8554
8555   /* Make sure we know what is going on here.  */
8556   BFD_ASSERT (dynobj != NULL
8557               && (h->needs_plt
8558                   || h->u.weakdef != NULL
8559                   || (h->def_dynamic
8560                       && h->ref_regular
8561                       && !h->def_regular)));
8562
8563   hmips = (struct mips_elf_link_hash_entry *) h;
8564
8565   /* If there are call relocations against an externally-defined symbol,
8566      see whether we can create a MIPS lazy-binding stub for it.  We can
8567      only do this if all references to the function are through call
8568      relocations, and in that case, the traditional lazy-binding stubs
8569      are much more efficient than PLT entries.
8570
8571      Traditional stubs are only available on SVR4 psABI-based systems;
8572      VxWorks always uses PLTs instead.  */
8573   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
8574     {
8575       if (! elf_hash_table (info)->dynamic_sections_created)
8576         return TRUE;
8577
8578       /* If this symbol is not defined in a regular file, then set
8579          the symbol to the stub location.  This is required to make
8580          function pointers compare as equal between the normal
8581          executable and the shared library.  */
8582       if (!h->def_regular)
8583         {
8584           hmips->needs_lazy_stub = TRUE;
8585           htab->lazy_stub_count++;
8586           return TRUE;
8587         }
8588     }
8589   /* As above, VxWorks requires PLT entries for externally-defined
8590      functions that are only accessed through call relocations.
8591
8592      Both VxWorks and non-VxWorks targets also need PLT entries if there
8593      are static-only relocations against an externally-defined function.
8594      This can technically occur for shared libraries if there are
8595      branches to the symbol, although it is unlikely that this will be
8596      used in practice due to the short ranges involved.  It can occur
8597      for any relative or absolute relocation in executables; in that
8598      case, the PLT entry becomes the function's canonical address.  */
8599   else if (((h->needs_plt && !hmips->no_fn_stub)
8600             || (h->type == STT_FUNC && hmips->has_static_relocs))
8601            && htab->use_plts_and_copy_relocs
8602            && !SYMBOL_CALLS_LOCAL (info, h)
8603            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
8604                 && h->root.type == bfd_link_hash_undefweak))
8605     {
8606       /* If this is the first symbol to need a PLT entry, allocate room
8607          for the header.  */
8608       if (htab->splt->size == 0)
8609         {
8610           BFD_ASSERT (htab->sgotplt->size == 0);
8611
8612           /* If we're using the PLT additions to the psABI, each PLT
8613              entry is 16 bytes and the PLT0 entry is 32 bytes.
8614              Encourage better cache usage by aligning.  We do this
8615              lazily to avoid pessimizing traditional objects.  */
8616           if (!htab->is_vxworks
8617               && !bfd_set_section_alignment (dynobj, htab->splt, 5))
8618             return FALSE;
8619
8620           /* Make sure that .got.plt is word-aligned.  We do this lazily
8621              for the same reason as above.  */
8622           if (!bfd_set_section_alignment (dynobj, htab->sgotplt,
8623                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
8624             return FALSE;
8625
8626           htab->splt->size += htab->plt_header_size;
8627
8628           /* On non-VxWorks targets, the first two entries in .got.plt
8629              are reserved.  */
8630           if (!htab->is_vxworks)
8631             htab->sgotplt->size
8632               += get_elf_backend_data (dynobj)->got_header_size;
8633
8634           /* On VxWorks, also allocate room for the header's
8635              .rela.plt.unloaded entries.  */
8636           if (htab->is_vxworks && !info->shared)
8637             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
8638         }
8639
8640       /* Assign the next .plt entry to this symbol.  */
8641       h->plt.offset = htab->splt->size;
8642       htab->splt->size += htab->plt_entry_size;
8643
8644       /* If the output file has no definition of the symbol, set the
8645          symbol's value to the address of the stub.  */
8646       if (!info->shared && !h->def_regular)
8647         {
8648           h->root.u.def.section = htab->splt;
8649           h->root.u.def.value = h->plt.offset;
8650           /* For VxWorks, point at the PLT load stub rather than the
8651              lazy resolution stub; this stub will become the canonical
8652              function address.  */
8653           if (htab->is_vxworks)
8654             h->root.u.def.value += 8;
8655         }
8656
8657       /* Make room for the .got.plt entry and the R_MIPS_JUMP_SLOT
8658          relocation.  */
8659       htab->sgotplt->size += MIPS_ELF_GOT_SIZE (dynobj);
8660       htab->srelplt->size += (htab->is_vxworks
8661                               ? MIPS_ELF_RELA_SIZE (dynobj)
8662                               : MIPS_ELF_REL_SIZE (dynobj));
8663
8664       /* Make room for the .rela.plt.unloaded relocations.  */
8665       if (htab->is_vxworks && !info->shared)
8666         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
8667
8668       /* All relocations against this symbol that could have been made
8669          dynamic will now refer to the PLT entry instead.  */
8670       hmips->possibly_dynamic_relocs = 0;
8671
8672       return TRUE;
8673     }
8674
8675   /* If this is a weak symbol, and there is a real definition, the
8676      processor independent code will have arranged for us to see the
8677      real definition first, and we can just use the same value.  */
8678   if (h->u.weakdef != NULL)
8679     {
8680       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
8681                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
8682       h->root.u.def.section = h->u.weakdef->root.u.def.section;
8683       h->root.u.def.value = h->u.weakdef->root.u.def.value;
8684       return TRUE;
8685     }
8686
8687   /* Otherwise, there is nothing further to do for symbols defined
8688      in regular objects.  */
8689   if (h->def_regular)
8690     return TRUE;
8691
8692   /* There's also nothing more to do if we'll convert all relocations
8693      against this symbol into dynamic relocations.  */
8694   if (!hmips->has_static_relocs)
8695     return TRUE;
8696
8697   /* We're now relying on copy relocations.  Complain if we have
8698      some that we can't convert.  */
8699   if (!htab->use_plts_and_copy_relocs || info->shared)
8700     {
8701       (*_bfd_error_handler) (_("non-dynamic relocations refer to "
8702                                "dynamic symbol %s"),
8703                              h->root.root.string);
8704       bfd_set_error (bfd_error_bad_value);
8705       return FALSE;
8706     }
8707
8708   /* We must allocate the symbol in our .dynbss section, which will
8709      become part of the .bss section of the executable.  There will be
8710      an entry for this symbol in the .dynsym section.  The dynamic
8711      object will contain position independent code, so all references
8712      from the dynamic object to this symbol will go through the global
8713      offset table.  The dynamic linker will use the .dynsym entry to
8714      determine the address it must put in the global offset table, so
8715      both the dynamic object and the regular object will refer to the
8716      same memory location for the variable.  */
8717
8718   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
8719     {
8720       if (htab->is_vxworks)
8721         htab->srelbss->size += sizeof (Elf32_External_Rela);
8722       else
8723         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8724       h->needs_copy = 1;
8725     }
8726
8727   /* All relocations against this symbol that could have been made
8728      dynamic will now refer to the local copy instead.  */
8729   hmips->possibly_dynamic_relocs = 0;
8730
8731   return _bfd_elf_adjust_dynamic_copy (h, htab->sdynbss);
8732 }
8733 \f
8734 /* This function is called after all the input files have been read,
8735    and the input sections have been assigned to output sections.  We
8736    check for any mips16 stub sections that we can discard.  */
8737
8738 bfd_boolean
8739 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
8740                                     struct bfd_link_info *info)
8741 {
8742   asection *ri;
8743   struct mips_elf_link_hash_table *htab;
8744   struct mips_htab_traverse_info hti;
8745
8746   htab = mips_elf_hash_table (info);
8747   BFD_ASSERT (htab != NULL);
8748
8749   /* The .reginfo section has a fixed size.  */
8750   ri = bfd_get_section_by_name (output_bfd, ".reginfo");
8751   if (ri != NULL)
8752     bfd_set_section_size (output_bfd, ri, sizeof (Elf32_External_RegInfo));
8753
8754   hti.info = info;
8755   hti.output_bfd = output_bfd;
8756   hti.error = FALSE;
8757   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
8758                                mips_elf_check_symbols, &hti);
8759   if (hti.error)
8760     return FALSE;
8761
8762   return TRUE;
8763 }
8764
8765 /* If the link uses a GOT, lay it out and work out its size.  */
8766
8767 static bfd_boolean
8768 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
8769 {
8770   bfd *dynobj;
8771   asection *s;
8772   struct mips_got_info *g;
8773   bfd_size_type loadable_size = 0;
8774   bfd_size_type page_gotno;
8775   bfd *sub;
8776   struct mips_elf_count_tls_arg count_tls_arg;
8777   struct mips_elf_link_hash_table *htab;
8778
8779   htab = mips_elf_hash_table (info);
8780   BFD_ASSERT (htab != NULL);
8781
8782   s = htab->sgot;
8783   if (s == NULL)
8784     return TRUE;
8785
8786   dynobj = elf_hash_table (info)->dynobj;
8787   g = htab->got_info;
8788
8789   /* Allocate room for the reserved entries.  VxWorks always reserves
8790      3 entries; other objects only reserve 2 entries.  */
8791   BFD_ASSERT (g->assigned_gotno == 0);
8792   if (htab->is_vxworks)
8793     htab->reserved_gotno = 3;
8794   else
8795     htab->reserved_gotno = 2;
8796   g->local_gotno += htab->reserved_gotno;
8797   g->assigned_gotno = htab->reserved_gotno;
8798
8799   /* Replace entries for indirect and warning symbols with entries for
8800      the target symbol.  */
8801   if (!mips_elf_resolve_final_got_entries (g))
8802     return FALSE;
8803
8804   /* Count the number of GOT symbols.  */
8805   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
8806
8807   /* Calculate the total loadable size of the output.  That
8808      will give us the maximum number of GOT_PAGE entries
8809      required.  */
8810   for (sub = info->input_bfds; sub; sub = sub->link_next)
8811     {
8812       asection *subsection;
8813
8814       for (subsection = sub->sections;
8815            subsection;
8816            subsection = subsection->next)
8817         {
8818           if ((subsection->flags & SEC_ALLOC) == 0)
8819             continue;
8820           loadable_size += ((subsection->size + 0xf)
8821                             &~ (bfd_size_type) 0xf);
8822         }
8823     }
8824
8825   if (htab->is_vxworks)
8826     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
8827        relocations against local symbols evaluate to "G", and the EABI does
8828        not include R_MIPS_GOT_PAGE.  */
8829     page_gotno = 0;
8830   else
8831     /* Assume there are two loadable segments consisting of contiguous
8832        sections.  Is 5 enough?  */
8833     page_gotno = (loadable_size >> 16) + 5;
8834
8835   /* Choose the smaller of the two estimates; both are intended to be
8836      conservative.  */
8837   if (page_gotno > g->page_gotno)
8838     page_gotno = g->page_gotno;
8839
8840   g->local_gotno += page_gotno;
8841   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8842   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8843
8844   /* We need to calculate tls_gotno for global symbols at this point
8845      instead of building it up earlier, to avoid doublecounting
8846      entries for one global symbol from multiple input files.  */
8847   count_tls_arg.info = info;
8848   count_tls_arg.needed = 0;
8849   elf_link_hash_traverse (elf_hash_table (info),
8850                           mips_elf_count_global_tls_entries,
8851                           &count_tls_arg);
8852   g->tls_gotno += count_tls_arg.needed;
8853   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8854
8855   /* VxWorks does not support multiple GOTs.  It initializes $gp to
8856      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
8857      dynamic loader.  */
8858   if (htab->is_vxworks)
8859     {
8860       /* VxWorks executables do not need a GOT.  */
8861       if (info->shared)
8862         {
8863           /* Each VxWorks GOT entry needs an explicit relocation.  */
8864           unsigned int count;
8865
8866           count = g->global_gotno + g->local_gotno - htab->reserved_gotno;
8867           if (count)
8868             mips_elf_allocate_dynamic_relocations (dynobj, info, count);
8869         }
8870     }
8871   else if (s->size > MIPS_ELF_GOT_MAX_SIZE (info))
8872     {
8873       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
8874         return FALSE;
8875     }
8876   else
8877     {
8878       struct mips_elf_count_tls_arg arg;
8879
8880       /* Set up TLS entries.  */
8881       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
8882       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, g);
8883       BFD_ASSERT (g->tls_assigned_gotno
8884                   == g->global_gotno + g->local_gotno + g->tls_gotno);
8885
8886       /* Allocate room for the TLS relocations.  */
8887       arg.info = info;
8888       arg.needed = 0;
8889       htab_traverse (g->got_entries, mips_elf_count_local_tls_relocs, &arg);
8890       elf_link_hash_traverse (elf_hash_table (info),
8891                               mips_elf_count_global_tls_relocs,
8892                               &arg);
8893       if (arg.needed)
8894         mips_elf_allocate_dynamic_relocations (dynobj, info, arg.needed);
8895     }
8896
8897   return TRUE;
8898 }
8899
8900 /* Estimate the size of the .MIPS.stubs section.  */
8901
8902 static void
8903 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
8904 {
8905   struct mips_elf_link_hash_table *htab;
8906   bfd_size_type dynsymcount;
8907
8908   htab = mips_elf_hash_table (info);
8909   BFD_ASSERT (htab != NULL);
8910
8911   if (htab->lazy_stub_count == 0)
8912     return;
8913
8914   /* IRIX rld assumes that a function stub isn't at the end of the .text
8915      section, so add a dummy entry to the end.  */
8916   htab->lazy_stub_count++;
8917
8918   /* Get a worst-case estimate of the number of dynamic symbols needed.
8919      At this point, dynsymcount does not account for section symbols
8920      and count_section_dynsyms may overestimate the number that will
8921      be needed.  */
8922   dynsymcount = (elf_hash_table (info)->dynsymcount
8923                  + count_section_dynsyms (output_bfd, info));
8924
8925   /* Determine the size of one stub entry.  */
8926   htab->function_stub_size = (dynsymcount > 0x10000
8927                               ? MIPS_FUNCTION_STUB_BIG_SIZE
8928                               : MIPS_FUNCTION_STUB_NORMAL_SIZE);
8929
8930   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
8931 }
8932
8933 /* A mips_elf_link_hash_traverse callback for which DATA points to the
8934    MIPS hash table.  If H needs a traditional MIPS lazy-binding stub,
8935    allocate an entry in the stubs section.  */
8936
8937 static bfd_boolean
8938 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void **data)
8939 {
8940   struct mips_elf_link_hash_table *htab;
8941
8942   htab = (struct mips_elf_link_hash_table *) data;
8943   if (h->needs_lazy_stub)
8944     {
8945       h->root.root.u.def.section = htab->sstubs;
8946       h->root.root.u.def.value = htab->sstubs->size;
8947       h->root.plt.offset = htab->sstubs->size;
8948       htab->sstubs->size += htab->function_stub_size;
8949     }
8950   return TRUE;
8951 }
8952
8953 /* Allocate offsets in the stubs section to each symbol that needs one.
8954    Set the final size of the .MIPS.stub section.  */
8955
8956 static void
8957 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
8958 {
8959   struct mips_elf_link_hash_table *htab;
8960
8961   htab = mips_elf_hash_table (info);
8962   BFD_ASSERT (htab != NULL);
8963
8964   if (htab->lazy_stub_count == 0)
8965     return;
8966
8967   htab->sstubs->size = 0;
8968   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, htab);
8969   htab->sstubs->size += htab->function_stub_size;
8970   BFD_ASSERT (htab->sstubs->size
8971               == htab->lazy_stub_count * htab->function_stub_size);
8972 }
8973
8974 /* Set the sizes of the dynamic sections.  */
8975
8976 bfd_boolean
8977 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
8978                                      struct bfd_link_info *info)
8979 {
8980   bfd *dynobj;
8981   asection *s, *sreldyn;
8982   bfd_boolean reltext;
8983   struct mips_elf_link_hash_table *htab;
8984
8985   htab = mips_elf_hash_table (info);
8986   BFD_ASSERT (htab != NULL);
8987   dynobj = elf_hash_table (info)->dynobj;
8988   BFD_ASSERT (dynobj != NULL);
8989
8990   if (elf_hash_table (info)->dynamic_sections_created)
8991     {
8992       /* Set the contents of the .interp section to the interpreter.  */
8993       if (info->executable)
8994         {
8995           s = bfd_get_linker_section (dynobj, ".interp");
8996           BFD_ASSERT (s != NULL);
8997           s->size
8998             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
8999           s->contents
9000             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
9001         }
9002
9003       /* Create a symbol for the PLT, if we know that we are using it.  */
9004       if (htab->splt && htab->splt->size > 0 && htab->root.hplt == NULL)
9005         {
9006           struct elf_link_hash_entry *h;
9007
9008           BFD_ASSERT (htab->use_plts_and_copy_relocs);
9009
9010           h = _bfd_elf_define_linkage_sym (dynobj, info, htab->splt,
9011                                            "_PROCEDURE_LINKAGE_TABLE_");
9012           htab->root.hplt = h;
9013           if (h == NULL)
9014             return FALSE;
9015           h->type = STT_FUNC;
9016         }
9017     }
9018
9019   /* Allocate space for global sym dynamic relocs.  */
9020   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, info);
9021
9022   mips_elf_estimate_stub_size (output_bfd, info);
9023
9024   if (!mips_elf_lay_out_got (output_bfd, info))
9025     return FALSE;
9026
9027   mips_elf_lay_out_lazy_stubs (info);
9028
9029   /* The check_relocs and adjust_dynamic_symbol entry points have
9030      determined the sizes of the various dynamic sections.  Allocate
9031      memory for them.  */
9032   reltext = FALSE;
9033   for (s = dynobj->sections; s != NULL; s = s->next)
9034     {
9035       const char *name;
9036
9037       /* It's OK to base decisions on the section name, because none
9038          of the dynobj section names depend upon the input files.  */
9039       name = bfd_get_section_name (dynobj, s);
9040
9041       if ((s->flags & SEC_LINKER_CREATED) == 0)
9042         continue;
9043
9044       if (CONST_STRNEQ (name, ".rel"))
9045         {
9046           if (s->size != 0)
9047             {
9048               const char *outname;
9049               asection *target;
9050
9051               /* If this relocation section applies to a read only
9052                  section, then we probably need a DT_TEXTREL entry.
9053                  If the relocation section is .rel(a).dyn, we always
9054                  assert a DT_TEXTREL entry rather than testing whether
9055                  there exists a relocation to a read only section or
9056                  not.  */
9057               outname = bfd_get_section_name (output_bfd,
9058                                               s->output_section);
9059               target = bfd_get_section_by_name (output_bfd, outname + 4);
9060               if ((target != NULL
9061                    && (target->flags & SEC_READONLY) != 0
9062                    && (target->flags & SEC_ALLOC) != 0)
9063                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
9064                 reltext = TRUE;
9065
9066               /* We use the reloc_count field as a counter if we need
9067                  to copy relocs into the output file.  */
9068               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
9069                 s->reloc_count = 0;
9070
9071               /* If combreloc is enabled, elf_link_sort_relocs() will
9072                  sort relocations, but in a different way than we do,
9073                  and before we're done creating relocations.  Also, it
9074                  will move them around between input sections'
9075                  relocation's contents, so our sorting would be
9076                  broken, so don't let it run.  */
9077               info->combreloc = 0;
9078             }
9079         }
9080       else if (! info->shared
9081                && ! mips_elf_hash_table (info)->use_rld_obj_head
9082                && CONST_STRNEQ (name, ".rld_map"))
9083         {
9084           /* We add a room for __rld_map.  It will be filled in by the
9085              rtld to contain a pointer to the _r_debug structure.  */
9086           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
9087         }
9088       else if (SGI_COMPAT (output_bfd)
9089                && CONST_STRNEQ (name, ".compact_rel"))
9090         s->size += mips_elf_hash_table (info)->compact_rel_size;
9091       else if (s == htab->splt)
9092         {
9093           /* If the last PLT entry has a branch delay slot, allocate
9094              room for an extra nop to fill the delay slot.  This is
9095              for CPUs without load interlocking.  */
9096           if (! LOAD_INTERLOCKS_P (output_bfd)
9097               && ! htab->is_vxworks && s->size > 0)
9098             s->size += 4;
9099         }
9100       else if (! CONST_STRNEQ (name, ".init")
9101                && s != htab->sgot
9102                && s != htab->sgotplt
9103                && s != htab->sstubs
9104                && s != htab->sdynbss)
9105         {
9106           /* It's not one of our sections, so don't allocate space.  */
9107           continue;
9108         }
9109
9110       if (s->size == 0)
9111         {
9112           s->flags |= SEC_EXCLUDE;
9113           continue;
9114         }
9115
9116       if ((s->flags & SEC_HAS_CONTENTS) == 0)
9117         continue;
9118
9119       /* Allocate memory for the section contents.  */
9120       s->contents = bfd_zalloc (dynobj, s->size);
9121       if (s->contents == NULL)
9122         {
9123           bfd_set_error (bfd_error_no_memory);
9124           return FALSE;
9125         }
9126     }
9127
9128   if (elf_hash_table (info)->dynamic_sections_created)
9129     {
9130       /* Add some entries to the .dynamic section.  We fill in the
9131          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
9132          must add the entries now so that we get the correct size for
9133          the .dynamic section.  */
9134
9135       /* SGI object has the equivalence of DT_DEBUG in the
9136          DT_MIPS_RLD_MAP entry.  This must come first because glibc
9137          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and some tools
9138          may only look at the first one they see.  */
9139       if (!info->shared
9140           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
9141         return FALSE;
9142
9143       /* The DT_DEBUG entry may be filled in by the dynamic linker and
9144          used by the debugger.  */
9145       if (info->executable
9146           && !SGI_COMPAT (output_bfd)
9147           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
9148         return FALSE;
9149
9150       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
9151         info->flags |= DF_TEXTREL;
9152
9153       if ((info->flags & DF_TEXTREL) != 0)
9154         {
9155           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
9156             return FALSE;
9157
9158           /* Clear the DF_TEXTREL flag.  It will be set again if we
9159              write out an actual text relocation; we may not, because
9160              at this point we do not know whether e.g. any .eh_frame
9161              absolute relocations have been converted to PC-relative.  */
9162           info->flags &= ~DF_TEXTREL;
9163         }
9164
9165       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
9166         return FALSE;
9167
9168       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
9169       if (htab->is_vxworks)
9170         {
9171           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
9172              use any of the DT_MIPS_* tags.  */
9173           if (sreldyn && sreldyn->size > 0)
9174             {
9175               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
9176                 return FALSE;
9177
9178               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
9179                 return FALSE;
9180
9181               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
9182                 return FALSE;
9183             }
9184         }
9185       else
9186         {
9187           if (sreldyn && sreldyn->size > 0)
9188             {
9189               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
9190                 return FALSE;
9191
9192               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
9193                 return FALSE;
9194
9195               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
9196                 return FALSE;
9197             }
9198
9199           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
9200             return FALSE;
9201
9202           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
9203             return FALSE;
9204
9205           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
9206             return FALSE;
9207
9208           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
9209             return FALSE;
9210
9211           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
9212             return FALSE;
9213
9214           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
9215             return FALSE;
9216
9217           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
9218             return FALSE;
9219
9220           if (IRIX_COMPAT (dynobj) == ict_irix5
9221               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
9222             return FALSE;
9223
9224           if (IRIX_COMPAT (dynobj) == ict_irix6
9225               && (bfd_get_section_by_name
9226                   (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
9227               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
9228             return FALSE;
9229         }
9230       if (htab->splt->size > 0)
9231         {
9232           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
9233             return FALSE;
9234
9235           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
9236             return FALSE;
9237
9238           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
9239             return FALSE;
9240
9241           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
9242             return FALSE;
9243         }
9244       if (htab->is_vxworks
9245           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
9246         return FALSE;
9247     }
9248
9249   return TRUE;
9250 }
9251 \f
9252 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
9253    Adjust its R_ADDEND field so that it is correct for the output file.
9254    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
9255    and sections respectively; both use symbol indexes.  */
9256
9257 static void
9258 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
9259                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
9260                         asection **local_sections, Elf_Internal_Rela *rel)
9261 {
9262   unsigned int r_type, r_symndx;
9263   Elf_Internal_Sym *sym;
9264   asection *sec;
9265
9266   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9267     {
9268       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9269       if (gprel16_reloc_p (r_type)
9270           || r_type == R_MIPS_GPREL32
9271           || literal_reloc_p (r_type))
9272         {
9273           rel->r_addend += _bfd_get_gp_value (input_bfd);
9274           rel->r_addend -= _bfd_get_gp_value (output_bfd);
9275         }
9276
9277       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
9278       sym = local_syms + r_symndx;
9279
9280       /* Adjust REL's addend to account for section merging.  */
9281       if (!info->relocatable)
9282         {
9283           sec = local_sections[r_symndx];
9284           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
9285         }
9286
9287       /* This would normally be done by the rela_normal code in elflink.c.  */
9288       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
9289         rel->r_addend += local_sections[r_symndx]->output_offset;
9290     }
9291 }
9292
9293 /* Handle relocations against symbols from removed linkonce sections,
9294    or sections discarded by a linker script.  We use this wrapper around
9295    RELOC_AGAINST_DISCARDED_SECTION to handle triplets of compound relocs
9296    on 64-bit ELF targets.  In this case for any relocation handled, which
9297    always be the first in a triplet, the remaining two have to be processed
9298    together with the first, even if they are R_MIPS_NONE.  It is the symbol
9299    index referred by the first reloc that applies to all the three and the
9300    remaining two never refer to an object symbol.  And it is the final
9301    relocation (the last non-null one) that determines the output field of
9302    the whole relocation so retrieve the corresponding howto structure for
9303    the relocatable field to be cleared by RELOC_AGAINST_DISCARDED_SECTION.
9304
9305    Note that RELOC_AGAINST_DISCARDED_SECTION is a macro that uses "continue"
9306    and therefore requires to be pasted in a loop.  It also defines a block
9307    and does not protect any of its arguments, hence the extra brackets.  */
9308
9309 static void
9310 mips_reloc_against_discarded_section (bfd *output_bfd,
9311                                       struct bfd_link_info *info,
9312                                       bfd *input_bfd, asection *input_section,
9313                                       Elf_Internal_Rela **rel,
9314                                       const Elf_Internal_Rela **relend,
9315                                       bfd_boolean rel_reloc,
9316                                       reloc_howto_type *howto,
9317                                       bfd_byte *contents)
9318 {
9319   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
9320   int count = bed->s->int_rels_per_ext_rel;
9321   unsigned int r_type;
9322   int i;
9323
9324   for (i = count - 1; i > 0; i--)
9325     {
9326       r_type = ELF_R_TYPE (output_bfd, (*rel)[i].r_info);
9327       if (r_type != R_MIPS_NONE)
9328         {
9329           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9330           break;
9331         }
9332     }
9333   do
9334     {
9335        RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
9336                                         (*rel), count, (*relend),
9337                                         howto, i, contents);
9338     }
9339   while (0);
9340 }
9341
9342 /* Relocate a MIPS ELF section.  */
9343
9344 bfd_boolean
9345 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
9346                                 bfd *input_bfd, asection *input_section,
9347                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
9348                                 Elf_Internal_Sym *local_syms,
9349                                 asection **local_sections)
9350 {
9351   Elf_Internal_Rela *rel;
9352   const Elf_Internal_Rela *relend;
9353   bfd_vma addend = 0;
9354   bfd_boolean use_saved_addend_p = FALSE;
9355   const struct elf_backend_data *bed;
9356
9357   bed = get_elf_backend_data (output_bfd);
9358   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
9359   for (rel = relocs; rel < relend; ++rel)
9360     {
9361       const char *name;
9362       bfd_vma value = 0;
9363       reloc_howto_type *howto;
9364       bfd_boolean cross_mode_jump_p;
9365       /* TRUE if the relocation is a RELA relocation, rather than a
9366          REL relocation.  */
9367       bfd_boolean rela_relocation_p = TRUE;
9368       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9369       const char *msg;
9370       unsigned long r_symndx;
9371       asection *sec;
9372       Elf_Internal_Shdr *symtab_hdr;
9373       struct elf_link_hash_entry *h;
9374       bfd_boolean rel_reloc;
9375
9376       rel_reloc = (NEWABI_P (input_bfd)
9377                    && mips_elf_rel_relocation_p (input_bfd, input_section,
9378                                                  relocs, rel));
9379       /* Find the relocation howto for this relocation.  */
9380       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9381
9382       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
9383       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9384       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9385         {
9386           sec = local_sections[r_symndx];
9387           h = NULL;
9388         }
9389       else
9390         {
9391           unsigned long extsymoff;
9392
9393           extsymoff = 0;
9394           if (!elf_bad_symtab (input_bfd))
9395             extsymoff = symtab_hdr->sh_info;
9396           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
9397           while (h->root.type == bfd_link_hash_indirect
9398                  || h->root.type == bfd_link_hash_warning)
9399             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9400
9401           sec = NULL;
9402           if (h->root.type == bfd_link_hash_defined
9403               || h->root.type == bfd_link_hash_defweak)
9404             sec = h->root.u.def.section;
9405         }
9406
9407       if (sec != NULL && discarded_section (sec))
9408         {
9409           mips_reloc_against_discarded_section (output_bfd, info, input_bfd,
9410                                                 input_section, &rel, &relend,
9411                                                 rel_reloc, howto, contents);
9412           continue;
9413         }
9414
9415       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
9416         {
9417           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
9418              64-bit code, but make sure all their addresses are in the
9419              lowermost or uppermost 32-bit section of the 64-bit address
9420              space.  Thus, when they use an R_MIPS_64 they mean what is
9421              usually meant by R_MIPS_32, with the exception that the
9422              stored value is sign-extended to 64 bits.  */
9423           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
9424
9425           /* On big-endian systems, we need to lie about the position
9426              of the reloc.  */
9427           if (bfd_big_endian (input_bfd))
9428             rel->r_offset += 4;
9429         }
9430
9431       if (!use_saved_addend_p)
9432         {
9433           /* If these relocations were originally of the REL variety,
9434              we must pull the addend out of the field that will be
9435              relocated.  Otherwise, we simply use the contents of the
9436              RELA relocation.  */
9437           if (mips_elf_rel_relocation_p (input_bfd, input_section,
9438                                          relocs, rel))
9439             {
9440               rela_relocation_p = FALSE;
9441               addend = mips_elf_read_rel_addend (input_bfd, rel,
9442                                                  howto, contents);
9443               if (hi16_reloc_p (r_type)
9444                   || (got16_reloc_p (r_type)
9445                       && mips_elf_local_relocation_p (input_bfd, rel,
9446                                                       local_sections)))
9447                 {
9448                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
9449                                                      contents, &addend))
9450                     {
9451                       if (h)
9452                         name = h->root.root.string;
9453                       else
9454                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9455                                                  local_syms + r_symndx,
9456                                                  sec);
9457                       (*_bfd_error_handler)
9458                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
9459                          input_bfd, input_section, name, howto->name,
9460                          rel->r_offset);
9461                     }
9462                 }
9463               else
9464                 addend <<= howto->rightshift;
9465             }
9466           else
9467             addend = rel->r_addend;
9468           mips_elf_adjust_addend (output_bfd, info, input_bfd,
9469                                   local_syms, local_sections, rel);
9470         }
9471
9472       if (info->relocatable)
9473         {
9474           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
9475               && bfd_big_endian (input_bfd))
9476             rel->r_offset -= 4;
9477
9478           if (!rela_relocation_p && rel->r_addend)
9479             {
9480               addend += rel->r_addend;
9481               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
9482                 addend = mips_elf_high (addend);
9483               else if (r_type == R_MIPS_HIGHER)
9484                 addend = mips_elf_higher (addend);
9485               else if (r_type == R_MIPS_HIGHEST)
9486                 addend = mips_elf_highest (addend);
9487               else
9488                 addend >>= howto->rightshift;
9489
9490               /* We use the source mask, rather than the destination
9491                  mask because the place to which we are writing will be
9492                  source of the addend in the final link.  */
9493               addend &= howto->src_mask;
9494
9495               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9496                 /* See the comment above about using R_MIPS_64 in the 32-bit
9497                    ABI.  Here, we need to update the addend.  It would be
9498                    possible to get away with just using the R_MIPS_32 reloc
9499                    but for endianness.  */
9500                 {
9501                   bfd_vma sign_bits;
9502                   bfd_vma low_bits;
9503                   bfd_vma high_bits;
9504
9505                   if (addend & ((bfd_vma) 1 << 31))
9506 #ifdef BFD64
9507                     sign_bits = ((bfd_vma) 1 << 32) - 1;
9508 #else
9509                     sign_bits = -1;
9510 #endif
9511                   else
9512                     sign_bits = 0;
9513
9514                   /* If we don't know that we have a 64-bit type,
9515                      do two separate stores.  */
9516                   if (bfd_big_endian (input_bfd))
9517                     {
9518                       /* Store the sign-bits (which are most significant)
9519                          first.  */
9520                       low_bits = sign_bits;
9521                       high_bits = addend;
9522                     }
9523                   else
9524                     {
9525                       low_bits = addend;
9526                       high_bits = sign_bits;
9527                     }
9528                   bfd_put_32 (input_bfd, low_bits,
9529                               contents + rel->r_offset);
9530                   bfd_put_32 (input_bfd, high_bits,
9531                               contents + rel->r_offset + 4);
9532                   continue;
9533                 }
9534
9535               if (! mips_elf_perform_relocation (info, howto, rel, addend,
9536                                                  input_bfd, input_section,
9537                                                  contents, FALSE))
9538                 return FALSE;
9539             }
9540
9541           /* Go on to the next relocation.  */
9542           continue;
9543         }
9544
9545       /* In the N32 and 64-bit ABIs there may be multiple consecutive
9546          relocations for the same offset.  In that case we are
9547          supposed to treat the output of each relocation as the addend
9548          for the next.  */
9549       if (rel + 1 < relend
9550           && rel->r_offset == rel[1].r_offset
9551           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
9552         use_saved_addend_p = TRUE;
9553       else
9554         use_saved_addend_p = FALSE;
9555
9556       /* Figure out what value we are supposed to relocate.  */
9557       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
9558                                              input_section, info, rel,
9559                                              addend, howto, local_syms,
9560                                              local_sections, &value,
9561                                              &name, &cross_mode_jump_p,
9562                                              use_saved_addend_p))
9563         {
9564         case bfd_reloc_continue:
9565           /* There's nothing to do.  */
9566           continue;
9567
9568         case bfd_reloc_undefined:
9569           /* mips_elf_calculate_relocation already called the
9570              undefined_symbol callback.  There's no real point in
9571              trying to perform the relocation at this point, so we
9572              just skip ahead to the next relocation.  */
9573           continue;
9574
9575         case bfd_reloc_notsupported:
9576           msg = _("internal error: unsupported relocation error");
9577           info->callbacks->warning
9578             (info, msg, name, input_bfd, input_section, rel->r_offset);
9579           return FALSE;
9580
9581         case bfd_reloc_overflow:
9582           if (use_saved_addend_p)
9583             /* Ignore overflow until we reach the last relocation for
9584                a given location.  */
9585             ;
9586           else
9587             {
9588               struct mips_elf_link_hash_table *htab;
9589
9590               htab = mips_elf_hash_table (info);
9591               BFD_ASSERT (htab != NULL);
9592               BFD_ASSERT (name != NULL);
9593               if (!htab->small_data_overflow_reported
9594                   && (gprel16_reloc_p (howto->type)
9595                       || literal_reloc_p (howto->type)))
9596                 {
9597                   msg = _("small-data section exceeds 64KB;"
9598                           " lower small-data size limit (see option -G)");
9599
9600                   htab->small_data_overflow_reported = TRUE;
9601                   (*info->callbacks->einfo) ("%P: %s\n", msg);
9602                 }
9603               if (! ((*info->callbacks->reloc_overflow)
9604                      (info, NULL, name, howto->name, (bfd_vma) 0,
9605                       input_bfd, input_section, rel->r_offset)))
9606                 return FALSE;
9607             }
9608           break;
9609
9610         case bfd_reloc_ok:
9611           break;
9612
9613         case bfd_reloc_outofrange:
9614           if (jal_reloc_p (howto->type))
9615             {
9616               msg = _("JALX to a non-word-aligned address");
9617               info->callbacks->warning
9618                 (info, msg, name, input_bfd, input_section, rel->r_offset);
9619               return FALSE;
9620             }
9621           /* Fall through.  */
9622
9623         default:
9624           abort ();
9625           break;
9626         }
9627
9628       /* If we've got another relocation for the address, keep going
9629          until we reach the last one.  */
9630       if (use_saved_addend_p)
9631         {
9632           addend = value;
9633           continue;
9634         }
9635
9636       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9637         /* See the comment above about using R_MIPS_64 in the 32-bit
9638            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
9639            that calculated the right value.  Now, however, we
9640            sign-extend the 32-bit result to 64-bits, and store it as a
9641            64-bit value.  We are especially generous here in that we
9642            go to extreme lengths to support this usage on systems with
9643            only a 32-bit VMA.  */
9644         {
9645           bfd_vma sign_bits;
9646           bfd_vma low_bits;
9647           bfd_vma high_bits;
9648
9649           if (value & ((bfd_vma) 1 << 31))
9650 #ifdef BFD64
9651             sign_bits = ((bfd_vma) 1 << 32) - 1;
9652 #else
9653             sign_bits = -1;
9654 #endif
9655           else
9656             sign_bits = 0;
9657
9658           /* If we don't know that we have a 64-bit type,
9659              do two separate stores.  */
9660           if (bfd_big_endian (input_bfd))
9661             {
9662               /* Undo what we did above.  */
9663               rel->r_offset -= 4;
9664               /* Store the sign-bits (which are most significant)
9665                  first.  */
9666               low_bits = sign_bits;
9667               high_bits = value;
9668             }
9669           else
9670             {
9671               low_bits = value;
9672               high_bits = sign_bits;
9673             }
9674           bfd_put_32 (input_bfd, low_bits,
9675                       contents + rel->r_offset);
9676           bfd_put_32 (input_bfd, high_bits,
9677                       contents + rel->r_offset + 4);
9678           continue;
9679         }
9680
9681       /* Actually perform the relocation.  */
9682       if (! mips_elf_perform_relocation (info, howto, rel, value,
9683                                          input_bfd, input_section,
9684                                          contents, cross_mode_jump_p))
9685         return FALSE;
9686     }
9687
9688   return TRUE;
9689 }
9690 \f
9691 /* A function that iterates over each entry in la25_stubs and fills
9692    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
9693
9694 static int
9695 mips_elf_create_la25_stub (void **slot, void *data)
9696 {
9697   struct mips_htab_traverse_info *hti;
9698   struct mips_elf_link_hash_table *htab;
9699   struct mips_elf_la25_stub *stub;
9700   asection *s;
9701   bfd_byte *loc;
9702   bfd_vma offset, target, target_high, target_low;
9703
9704   stub = (struct mips_elf_la25_stub *) *slot;
9705   hti = (struct mips_htab_traverse_info *) data;
9706   htab = mips_elf_hash_table (hti->info);
9707   BFD_ASSERT (htab != NULL);
9708
9709   /* Create the section contents, if we haven't already.  */
9710   s = stub->stub_section;
9711   loc = s->contents;
9712   if (loc == NULL)
9713     {
9714       loc = bfd_malloc (s->size);
9715       if (loc == NULL)
9716         {
9717           hti->error = TRUE;
9718           return FALSE;
9719         }
9720       s->contents = loc;
9721     }
9722
9723   /* Work out where in the section this stub should go.  */
9724   offset = stub->offset;
9725
9726   /* Work out the target address.  */
9727   target = mips_elf_get_la25_target (stub, &s);
9728   target += s->output_section->vma + s->output_offset;
9729
9730   target_high = ((target + 0x8000) >> 16) & 0xffff;
9731   target_low = (target & 0xffff);
9732
9733   if (stub->stub_section != htab->strampoline)
9734     {
9735       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
9736          of the section and write the two instructions at the end.  */
9737       memset (loc, 0, offset);
9738       loc += offset;
9739       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9740         {
9741           bfd_put_micromips_32 (hti->output_bfd,
9742                                 LA25_LUI_MICROMIPS (target_high),
9743                                 loc);
9744           bfd_put_micromips_32 (hti->output_bfd,
9745                                 LA25_ADDIU_MICROMIPS (target_low),
9746                                 loc + 4);
9747         }
9748       else
9749         {
9750           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9751           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
9752         }
9753     }
9754   else
9755     {
9756       /* This is trampoline.  */
9757       loc += offset;
9758       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9759         {
9760           bfd_put_micromips_32 (hti->output_bfd,
9761                                 LA25_LUI_MICROMIPS (target_high), loc);
9762           bfd_put_micromips_32 (hti->output_bfd,
9763                                 LA25_J_MICROMIPS (target), loc + 4);
9764           bfd_put_micromips_32 (hti->output_bfd,
9765                                 LA25_ADDIU_MICROMIPS (target_low), loc + 8);
9766           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9767         }
9768       else
9769         {
9770           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9771           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
9772           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
9773           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9774         }
9775     }
9776   return TRUE;
9777 }
9778
9779 /* If NAME is one of the special IRIX6 symbols defined by the linker,
9780    adjust it appropriately now.  */
9781
9782 static void
9783 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
9784                                       const char *name, Elf_Internal_Sym *sym)
9785 {
9786   /* The linker script takes care of providing names and values for
9787      these, but we must place them into the right sections.  */
9788   static const char* const text_section_symbols[] = {
9789     "_ftext",
9790     "_etext",
9791     "__dso_displacement",
9792     "__elf_header",
9793     "__program_header_table",
9794     NULL
9795   };
9796
9797   static const char* const data_section_symbols[] = {
9798     "_fdata",
9799     "_edata",
9800     "_end",
9801     "_fbss",
9802     NULL
9803   };
9804
9805   const char* const *p;
9806   int i;
9807
9808   for (i = 0; i < 2; ++i)
9809     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
9810          *p;
9811          ++p)
9812       if (strcmp (*p, name) == 0)
9813         {
9814           /* All of these symbols are given type STT_SECTION by the
9815              IRIX6 linker.  */
9816           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9817           sym->st_other = STO_PROTECTED;
9818
9819           /* The IRIX linker puts these symbols in special sections.  */
9820           if (i == 0)
9821             sym->st_shndx = SHN_MIPS_TEXT;
9822           else
9823             sym->st_shndx = SHN_MIPS_DATA;
9824
9825           break;
9826         }
9827 }
9828
9829 /* Finish up dynamic symbol handling.  We set the contents of various
9830    dynamic sections here.  */
9831
9832 bfd_boolean
9833 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
9834                                      struct bfd_link_info *info,
9835                                      struct elf_link_hash_entry *h,
9836                                      Elf_Internal_Sym *sym)
9837 {
9838   bfd *dynobj;
9839   asection *sgot;
9840   struct mips_got_info *g, *gg;
9841   const char *name;
9842   int idx;
9843   struct mips_elf_link_hash_table *htab;
9844   struct mips_elf_link_hash_entry *hmips;
9845
9846   htab = mips_elf_hash_table (info);
9847   BFD_ASSERT (htab != NULL);
9848   dynobj = elf_hash_table (info)->dynobj;
9849   hmips = (struct mips_elf_link_hash_entry *) h;
9850
9851   BFD_ASSERT (!htab->is_vxworks);
9852
9853   if (h->plt.offset != MINUS_ONE && hmips->no_fn_stub)
9854     {
9855       /* We've decided to create a PLT entry for this symbol.  */
9856       bfd_byte *loc;
9857       bfd_vma header_address, plt_index, got_address;
9858       bfd_vma got_address_high, got_address_low, load;
9859       const bfd_vma *plt_entry;
9860
9861       BFD_ASSERT (htab->use_plts_and_copy_relocs);
9862       BFD_ASSERT (h->dynindx != -1);
9863       BFD_ASSERT (htab->splt != NULL);
9864       BFD_ASSERT (h->plt.offset <= htab->splt->size);
9865       BFD_ASSERT (!h->def_regular);
9866
9867       /* Calculate the address of the PLT header.  */
9868       header_address = (htab->splt->output_section->vma
9869                         + htab->splt->output_offset);
9870
9871       /* Calculate the index of the entry.  */
9872       plt_index = ((h->plt.offset - htab->plt_header_size)
9873                    / htab->plt_entry_size);
9874
9875       /* Calculate the address of the .got.plt entry.  */
9876       got_address = (htab->sgotplt->output_section->vma
9877                      + htab->sgotplt->output_offset
9878                      + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9879       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
9880       got_address_low = got_address & 0xffff;
9881
9882       /* Initially point the .got.plt entry at the PLT header.  */
9883       loc = (htab->sgotplt->contents
9884              + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9885       if (ABI_64_P (output_bfd))
9886         bfd_put_64 (output_bfd, header_address, loc);
9887       else
9888         bfd_put_32 (output_bfd, header_address, loc);
9889
9890       /* Find out where the .plt entry should go.  */
9891       loc = htab->splt->contents + h->plt.offset;
9892
9893       /* Pick the load opcode.  */
9894       load = MIPS_ELF_LOAD_WORD (output_bfd);
9895
9896       /* Fill in the PLT entry itself.  */
9897       plt_entry = mips_exec_plt_entry;
9898       bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
9899       bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load, loc + 4);
9900
9901       if (! LOAD_INTERLOCKS_P (output_bfd))
9902         {
9903           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
9904           bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
9905         }
9906       else
9907         {
9908           bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
9909           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 12);
9910         }
9911
9912       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
9913       mips_elf_output_dynamic_relocation (output_bfd, htab->srelplt,
9914                                           plt_index, h->dynindx,
9915                                           R_MIPS_JUMP_SLOT, got_address);
9916
9917       /* We distinguish between PLT entries and lazy-binding stubs by
9918          giving the former an st_other value of STO_MIPS_PLT.  Set the
9919          flag and leave the value if there are any relocations in the
9920          binary where pointer equality matters.  */
9921       sym->st_shndx = SHN_UNDEF;
9922       if (h->pointer_equality_needed)
9923         sym->st_other = STO_MIPS_PLT;
9924       else
9925         sym->st_value = 0;
9926     }
9927   else if (h->plt.offset != MINUS_ONE)
9928     {
9929       /* We've decided to create a lazy-binding stub.  */
9930       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
9931
9932       /* This symbol has a stub.  Set it up.  */
9933
9934       BFD_ASSERT (h->dynindx != -1);
9935
9936       BFD_ASSERT ((htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9937                   || (h->dynindx <= 0xffff));
9938
9939       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
9940          sign extension at runtime in the stub, resulting in a negative
9941          index value.  */
9942       if (h->dynindx & ~0x7fffffff)
9943         return FALSE;
9944
9945       /* Fill the stub.  */
9946       idx = 0;
9947       bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
9948       idx += 4;
9949       bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + idx);
9950       idx += 4;
9951       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9952         {
9953           bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
9954                       stub + idx);
9955           idx += 4;
9956         }
9957       bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
9958       idx += 4;
9959
9960       /* If a large stub is not required and sign extension is not a
9961          problem, then use legacy code in the stub.  */
9962       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9963         bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff), stub + idx);
9964       else if (h->dynindx & ~0x7fff)
9965         bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff), stub + idx);
9966       else
9967         bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
9968                     stub + idx);
9969
9970       BFD_ASSERT (h->plt.offset <= htab->sstubs->size);
9971       memcpy (htab->sstubs->contents + h->plt.offset,
9972               stub, htab->function_stub_size);
9973
9974       /* Mark the symbol as undefined.  plt.offset != -1 occurs
9975          only for the referenced symbol.  */
9976       sym->st_shndx = SHN_UNDEF;
9977
9978       /* The run-time linker uses the st_value field of the symbol
9979          to reset the global offset table entry for this external
9980          to its stub address when unlinking a shared object.  */
9981       sym->st_value = (htab->sstubs->output_section->vma
9982                        + htab->sstubs->output_offset
9983                        + h->plt.offset);
9984     }
9985
9986   /* If we have a MIPS16 function with a stub, the dynamic symbol must
9987      refer to the stub, since only the stub uses the standard calling
9988      conventions.  */
9989   if (h->dynindx != -1 && hmips->fn_stub != NULL)
9990     {
9991       BFD_ASSERT (hmips->need_fn_stub);
9992       sym->st_value = (hmips->fn_stub->output_section->vma
9993                        + hmips->fn_stub->output_offset);
9994       sym->st_size = hmips->fn_stub->size;
9995       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
9996     }
9997
9998   BFD_ASSERT (h->dynindx != -1
9999               || h->forced_local);
10000
10001   sgot = htab->sgot;
10002   g = htab->got_info;
10003   BFD_ASSERT (g != NULL);
10004
10005   /* Run through the global symbol table, creating GOT entries for all
10006      the symbols that need them.  */
10007   if (hmips->global_got_area != GGA_NONE)
10008     {
10009       bfd_vma offset;
10010       bfd_vma value;
10011
10012       value = sym->st_value;
10013       offset = mips_elf_global_got_index (dynobj, output_bfd, h,
10014                                           R_MIPS_GOT16, info);
10015       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
10016     }
10017
10018   if (hmips->global_got_area != GGA_NONE && g->next)
10019     {
10020       struct mips_got_entry e, *p;
10021       bfd_vma entry;
10022       bfd_vma offset;
10023
10024       gg = g;
10025
10026       e.abfd = output_bfd;
10027       e.symndx = -1;
10028       e.d.h = hmips;
10029       e.tls_type = 0;
10030
10031       for (g = g->next; g->next != gg; g = g->next)
10032         {
10033           if (g->got_entries
10034               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
10035                                                            &e)))
10036             {
10037               offset = p->gotidx;
10038               if (info->shared
10039                   || (elf_hash_table (info)->dynamic_sections_created
10040                       && p->d.h != NULL
10041                       && p->d.h->root.def_dynamic
10042                       && !p->d.h->root.def_regular))
10043                 {
10044                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
10045                      the various compatibility problems, it's easier to mock
10046                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
10047                      mips_elf_create_dynamic_relocation to calculate the
10048                      appropriate addend.  */
10049                   Elf_Internal_Rela rel[3];
10050
10051                   memset (rel, 0, sizeof (rel));
10052                   if (ABI_64_P (output_bfd))
10053                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
10054                   else
10055                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
10056                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
10057
10058                   entry = 0;
10059                   if (! (mips_elf_create_dynamic_relocation
10060                          (output_bfd, info, rel,
10061                           e.d.h, NULL, sym->st_value, &entry, sgot)))
10062                     return FALSE;
10063                 }
10064               else
10065                 entry = sym->st_value;
10066               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
10067             }
10068         }
10069     }
10070
10071   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
10072   name = h->root.root.string;
10073   if (h == elf_hash_table (info)->hdynamic
10074       || h == elf_hash_table (info)->hgot)
10075     sym->st_shndx = SHN_ABS;
10076   else if (strcmp (name, "_DYNAMIC_LINK") == 0
10077            || strcmp (name, "_DYNAMIC_LINKING") == 0)
10078     {
10079       sym->st_shndx = SHN_ABS;
10080       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10081       sym->st_value = 1;
10082     }
10083   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
10084     {
10085       sym->st_shndx = SHN_ABS;
10086       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10087       sym->st_value = elf_gp (output_bfd);
10088     }
10089   else if (SGI_COMPAT (output_bfd))
10090     {
10091       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
10092           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
10093         {
10094           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10095           sym->st_other = STO_PROTECTED;
10096           sym->st_value = 0;
10097           sym->st_shndx = SHN_MIPS_DATA;
10098         }
10099       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
10100         {
10101           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10102           sym->st_other = STO_PROTECTED;
10103           sym->st_value = mips_elf_hash_table (info)->procedure_count;
10104           sym->st_shndx = SHN_ABS;
10105         }
10106       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
10107         {
10108           if (h->type == STT_FUNC)
10109             sym->st_shndx = SHN_MIPS_TEXT;
10110           else if (h->type == STT_OBJECT)
10111             sym->st_shndx = SHN_MIPS_DATA;
10112         }
10113     }
10114
10115   /* Emit a copy reloc, if needed.  */
10116   if (h->needs_copy)
10117     {
10118       asection *s;
10119       bfd_vma symval;
10120
10121       BFD_ASSERT (h->dynindx != -1);
10122       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10123
10124       s = mips_elf_rel_dyn_section (info, FALSE);
10125       symval = (h->root.u.def.section->output_section->vma
10126                 + h->root.u.def.section->output_offset
10127                 + h->root.u.def.value);
10128       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
10129                                           h->dynindx, R_MIPS_COPY, symval);
10130     }
10131
10132   /* Handle the IRIX6-specific symbols.  */
10133   if (IRIX_COMPAT (output_bfd) == ict_irix6)
10134     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
10135
10136   /* Keep dynamic MIPS16 symbols odd.  This allows the dynamic linker to
10137      treat MIPS16 symbols like any other.  */
10138   if (ELF_ST_IS_MIPS16 (sym->st_other))
10139     {
10140       BFD_ASSERT (sym->st_value & 1);
10141       sym->st_other -= STO_MIPS16;
10142     }
10143
10144   return TRUE;
10145 }
10146
10147 /* Likewise, for VxWorks.  */
10148
10149 bfd_boolean
10150 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
10151                                          struct bfd_link_info *info,
10152                                          struct elf_link_hash_entry *h,
10153                                          Elf_Internal_Sym *sym)
10154 {
10155   bfd *dynobj;
10156   asection *sgot;
10157   struct mips_got_info *g;
10158   struct mips_elf_link_hash_table *htab;
10159   struct mips_elf_link_hash_entry *hmips;
10160
10161   htab = mips_elf_hash_table (info);
10162   BFD_ASSERT (htab != NULL);
10163   dynobj = elf_hash_table (info)->dynobj;
10164   hmips = (struct mips_elf_link_hash_entry *) h;
10165
10166   if (h->plt.offset != (bfd_vma) -1)
10167     {
10168       bfd_byte *loc;
10169       bfd_vma plt_address, plt_index, got_address, got_offset, branch_offset;
10170       Elf_Internal_Rela rel;
10171       static const bfd_vma *plt_entry;
10172
10173       BFD_ASSERT (h->dynindx != -1);
10174       BFD_ASSERT (htab->splt != NULL);
10175       BFD_ASSERT (h->plt.offset <= htab->splt->size);
10176
10177       /* Calculate the address of the .plt entry.  */
10178       plt_address = (htab->splt->output_section->vma
10179                      + htab->splt->output_offset
10180                      + h->plt.offset);
10181
10182       /* Calculate the index of the entry.  */
10183       plt_index = ((h->plt.offset - htab->plt_header_size)
10184                    / htab->plt_entry_size);
10185
10186       /* Calculate the address of the .got.plt entry.  */
10187       got_address = (htab->sgotplt->output_section->vma
10188                      + htab->sgotplt->output_offset
10189                      + plt_index * 4);
10190
10191       /* Calculate the offset of the .got.plt entry from
10192          _GLOBAL_OFFSET_TABLE_.  */
10193       got_offset = mips_elf_gotplt_index (info, h);
10194
10195       /* Calculate the offset for the branch at the start of the PLT
10196          entry.  The branch jumps to the beginning of .plt.  */
10197       branch_offset = -(h->plt.offset / 4 + 1) & 0xffff;
10198
10199       /* Fill in the initial value of the .got.plt entry.  */
10200       bfd_put_32 (output_bfd, plt_address,
10201                   htab->sgotplt->contents + plt_index * 4);
10202
10203       /* Find out where the .plt entry should go.  */
10204       loc = htab->splt->contents + h->plt.offset;
10205
10206       if (info->shared)
10207         {
10208           plt_entry = mips_vxworks_shared_plt_entry;
10209           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10210           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10211         }
10212       else
10213         {
10214           bfd_vma got_address_high, got_address_low;
10215
10216           plt_entry = mips_vxworks_exec_plt_entry;
10217           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10218           got_address_low = got_address & 0xffff;
10219
10220           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10221           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10222           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
10223           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
10224           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10225           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10226           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10227           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10228
10229           loc = (htab->srelplt2->contents
10230                  + (plt_index * 3 + 2) * sizeof (Elf32_External_Rela));
10231
10232           /* Emit a relocation for the .got.plt entry.  */
10233           rel.r_offset = got_address;
10234           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10235           rel.r_addend = h->plt.offset;
10236           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10237
10238           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
10239           loc += sizeof (Elf32_External_Rela);
10240           rel.r_offset = plt_address + 8;
10241           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10242           rel.r_addend = got_offset;
10243           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10244
10245           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
10246           loc += sizeof (Elf32_External_Rela);
10247           rel.r_offset += 4;
10248           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10249           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10250         }
10251
10252       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10253       loc = htab->srelplt->contents + plt_index * sizeof (Elf32_External_Rela);
10254       rel.r_offset = got_address;
10255       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
10256       rel.r_addend = 0;
10257       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10258
10259       if (!h->def_regular)
10260         sym->st_shndx = SHN_UNDEF;
10261     }
10262
10263   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
10264
10265   sgot = htab->sgot;
10266   g = htab->got_info;
10267   BFD_ASSERT (g != NULL);
10268
10269   /* See if this symbol has an entry in the GOT.  */
10270   if (hmips->global_got_area != GGA_NONE)
10271     {
10272       bfd_vma offset;
10273       Elf_Internal_Rela outrel;
10274       bfd_byte *loc;
10275       asection *s;
10276
10277       /* Install the symbol value in the GOT.   */
10278       offset = mips_elf_global_got_index (dynobj, output_bfd, h,
10279                                           R_MIPS_GOT16, info);
10280       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
10281
10282       /* Add a dynamic relocation for it.  */
10283       s = mips_elf_rel_dyn_section (info, FALSE);
10284       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
10285       outrel.r_offset = (sgot->output_section->vma
10286                          + sgot->output_offset
10287                          + offset);
10288       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
10289       outrel.r_addend = 0;
10290       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
10291     }
10292
10293   /* Emit a copy reloc, if needed.  */
10294   if (h->needs_copy)
10295     {
10296       Elf_Internal_Rela rel;
10297
10298       BFD_ASSERT (h->dynindx != -1);
10299
10300       rel.r_offset = (h->root.u.def.section->output_section->vma
10301                       + h->root.u.def.section->output_offset
10302                       + h->root.u.def.value);
10303       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
10304       rel.r_addend = 0;
10305       bfd_elf32_swap_reloca_out (output_bfd, &rel,
10306                                  htab->srelbss->contents
10307                                  + (htab->srelbss->reloc_count
10308                                     * sizeof (Elf32_External_Rela)));
10309       ++htab->srelbss->reloc_count;
10310     }
10311
10312   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
10313   if (ELF_ST_IS_COMPRESSED (sym->st_other))
10314     sym->st_value &= ~1;
10315
10316   return TRUE;
10317 }
10318
10319 /* Write out a plt0 entry to the beginning of .plt.  */
10320
10321 static void
10322 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10323 {
10324   bfd_byte *loc;
10325   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
10326   static const bfd_vma *plt_entry;
10327   struct mips_elf_link_hash_table *htab;
10328
10329   htab = mips_elf_hash_table (info);
10330   BFD_ASSERT (htab != NULL);
10331
10332   if (ABI_64_P (output_bfd))
10333     plt_entry = mips_n64_exec_plt0_entry;
10334   else if (ABI_N32_P (output_bfd))
10335     plt_entry = mips_n32_exec_plt0_entry;
10336   else
10337     plt_entry = mips_o32_exec_plt0_entry;
10338
10339   /* Calculate the value of .got.plt.  */
10340   gotplt_value = (htab->sgotplt->output_section->vma
10341                   + htab->sgotplt->output_offset);
10342   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
10343   gotplt_value_low = gotplt_value & 0xffff;
10344
10345   /* The PLT sequence is not safe for N64 if .got.plt's address can
10346      not be loaded in two instructions.  */
10347   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
10348               || ~(gotplt_value | 0x7fffffff) == 0);
10349
10350   /* Install the PLT header.  */
10351   loc = htab->splt->contents;
10352   bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
10353   bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
10354   bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
10355   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10356   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10357   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10358   bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10359   bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10360 }
10361
10362 /* Install the PLT header for a VxWorks executable and finalize the
10363    contents of .rela.plt.unloaded.  */
10364
10365 static void
10366 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10367 {
10368   Elf_Internal_Rela rela;
10369   bfd_byte *loc;
10370   bfd_vma got_value, got_value_high, got_value_low, plt_address;
10371   static const bfd_vma *plt_entry;
10372   struct mips_elf_link_hash_table *htab;
10373
10374   htab = mips_elf_hash_table (info);
10375   BFD_ASSERT (htab != NULL);
10376
10377   plt_entry = mips_vxworks_exec_plt0_entry;
10378
10379   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
10380   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
10381                + htab->root.hgot->root.u.def.section->output_offset
10382                + htab->root.hgot->root.u.def.value);
10383
10384   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
10385   got_value_low = got_value & 0xffff;
10386
10387   /* Calculate the address of the PLT header.  */
10388   plt_address = htab->splt->output_section->vma + htab->splt->output_offset;
10389
10390   /* Install the PLT header.  */
10391   loc = htab->splt->contents;
10392   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
10393   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
10394   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
10395   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10396   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10397   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10398
10399   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
10400   loc = htab->srelplt2->contents;
10401   rela.r_offset = plt_address;
10402   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10403   rela.r_addend = 0;
10404   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10405   loc += sizeof (Elf32_External_Rela);
10406
10407   /* Output the relocation for the following addiu of
10408      %lo(_GLOBAL_OFFSET_TABLE_).  */
10409   rela.r_offset += 4;
10410   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10411   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10412   loc += sizeof (Elf32_External_Rela);
10413
10414   /* Fix up the remaining relocations.  They may have the wrong
10415      symbol index for _G_O_T_ or _P_L_T_ depending on the order
10416      in which symbols were output.  */
10417   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
10418     {
10419       Elf_Internal_Rela rel;
10420
10421       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10422       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10423       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10424       loc += sizeof (Elf32_External_Rela);
10425
10426       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10427       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10428       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10429       loc += sizeof (Elf32_External_Rela);
10430
10431       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10432       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10433       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10434       loc += sizeof (Elf32_External_Rela);
10435     }
10436 }
10437
10438 /* Install the PLT header for a VxWorks shared library.  */
10439
10440 static void
10441 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
10442 {
10443   unsigned int i;
10444   struct mips_elf_link_hash_table *htab;
10445
10446   htab = mips_elf_hash_table (info);
10447   BFD_ASSERT (htab != NULL);
10448
10449   /* We just need to copy the entry byte-by-byte.  */
10450   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
10451     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
10452                 htab->splt->contents + i * 4);
10453 }
10454
10455 /* Finish up the dynamic sections.  */
10456
10457 bfd_boolean
10458 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
10459                                        struct bfd_link_info *info)
10460 {
10461   bfd *dynobj;
10462   asection *sdyn;
10463   asection *sgot;
10464   struct mips_got_info *gg, *g;
10465   struct mips_elf_link_hash_table *htab;
10466
10467   htab = mips_elf_hash_table (info);
10468   BFD_ASSERT (htab != NULL);
10469
10470   dynobj = elf_hash_table (info)->dynobj;
10471
10472   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
10473
10474   sgot = htab->sgot;
10475   gg = htab->got_info;
10476
10477   if (elf_hash_table (info)->dynamic_sections_created)
10478     {
10479       bfd_byte *b;
10480       int dyn_to_skip = 0, dyn_skipped = 0;
10481
10482       BFD_ASSERT (sdyn != NULL);
10483       BFD_ASSERT (gg != NULL);
10484
10485       g = mips_elf_got_for_ibfd (gg, output_bfd);
10486       BFD_ASSERT (g != NULL);
10487
10488       for (b = sdyn->contents;
10489            b < sdyn->contents + sdyn->size;
10490            b += MIPS_ELF_DYN_SIZE (dynobj))
10491         {
10492           Elf_Internal_Dyn dyn;
10493           const char *name;
10494           size_t elemsize;
10495           asection *s;
10496           bfd_boolean swap_out_p;
10497
10498           /* Read in the current dynamic entry.  */
10499           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10500
10501           /* Assume that we're going to modify it and write it out.  */
10502           swap_out_p = TRUE;
10503
10504           switch (dyn.d_tag)
10505             {
10506             case DT_RELENT:
10507               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
10508               break;
10509
10510             case DT_RELAENT:
10511               BFD_ASSERT (htab->is_vxworks);
10512               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
10513               break;
10514
10515             case DT_STRSZ:
10516               /* Rewrite DT_STRSZ.  */
10517               dyn.d_un.d_val =
10518                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
10519               break;
10520
10521             case DT_PLTGOT:
10522               s = htab->sgot;
10523               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10524               break;
10525
10526             case DT_MIPS_PLTGOT:
10527               s = htab->sgotplt;
10528               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10529               break;
10530
10531             case DT_MIPS_RLD_VERSION:
10532               dyn.d_un.d_val = 1; /* XXX */
10533               break;
10534
10535             case DT_MIPS_FLAGS:
10536               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
10537               break;
10538
10539             case DT_MIPS_TIME_STAMP:
10540               {
10541                 time_t t;
10542                 time (&t);
10543                 dyn.d_un.d_val = t;
10544               }
10545               break;
10546
10547             case DT_MIPS_ICHECKSUM:
10548               /* XXX FIXME: */
10549               swap_out_p = FALSE;
10550               break;
10551
10552             case DT_MIPS_IVERSION:
10553               /* XXX FIXME: */
10554               swap_out_p = FALSE;
10555               break;
10556
10557             case DT_MIPS_BASE_ADDRESS:
10558               s = output_bfd->sections;
10559               BFD_ASSERT (s != NULL);
10560               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
10561               break;
10562
10563             case DT_MIPS_LOCAL_GOTNO:
10564               dyn.d_un.d_val = g->local_gotno;
10565               break;
10566
10567             case DT_MIPS_UNREFEXTNO:
10568               /* The index into the dynamic symbol table which is the
10569                  entry of the first external symbol that is not
10570                  referenced within the same object.  */
10571               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
10572               break;
10573
10574             case DT_MIPS_GOTSYM:
10575               if (htab->global_gotsym)
10576                 {
10577                   dyn.d_un.d_val = htab->global_gotsym->dynindx;
10578                   break;
10579                 }
10580               /* In case if we don't have global got symbols we default
10581                  to setting DT_MIPS_GOTSYM to the same value as
10582                  DT_MIPS_SYMTABNO, so we just fall through.  */
10583
10584             case DT_MIPS_SYMTABNO:
10585               name = ".dynsym";
10586               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
10587               s = bfd_get_section_by_name (output_bfd, name);
10588               BFD_ASSERT (s != NULL);
10589
10590               dyn.d_un.d_val = s->size / elemsize;
10591               break;
10592
10593             case DT_MIPS_HIPAGENO:
10594               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
10595               break;
10596
10597             case DT_MIPS_RLD_MAP:
10598               {
10599                 struct elf_link_hash_entry *h;
10600                 h = mips_elf_hash_table (info)->rld_symbol;
10601                 if (!h)
10602                   {
10603                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10604                     swap_out_p = FALSE;
10605                     break;
10606                   }
10607                 s = h->root.u.def.section;
10608                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
10609                                   + h->root.u.def.value);
10610               }
10611               break;
10612
10613             case DT_MIPS_OPTIONS:
10614               s = (bfd_get_section_by_name
10615                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
10616               dyn.d_un.d_ptr = s->vma;
10617               break;
10618
10619             case DT_RELASZ:
10620               BFD_ASSERT (htab->is_vxworks);
10621               /* The count does not include the JUMP_SLOT relocations.  */
10622               if (htab->srelplt)
10623                 dyn.d_un.d_val -= htab->srelplt->size;
10624               break;
10625
10626             case DT_PLTREL:
10627               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10628               if (htab->is_vxworks)
10629                 dyn.d_un.d_val = DT_RELA;
10630               else
10631                 dyn.d_un.d_val = DT_REL;
10632               break;
10633
10634             case DT_PLTRELSZ:
10635               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10636               dyn.d_un.d_val = htab->srelplt->size;
10637               break;
10638
10639             case DT_JMPREL:
10640               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10641               dyn.d_un.d_ptr = (htab->srelplt->output_section->vma
10642                                 + htab->srelplt->output_offset);
10643               break;
10644
10645             case DT_TEXTREL:
10646               /* If we didn't need any text relocations after all, delete
10647                  the dynamic tag.  */
10648               if (!(info->flags & DF_TEXTREL))
10649                 {
10650                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10651                   swap_out_p = FALSE;
10652                 }
10653               break;
10654
10655             case DT_FLAGS:
10656               /* If we didn't need any text relocations after all, clear
10657                  DF_TEXTREL from DT_FLAGS.  */
10658               if (!(info->flags & DF_TEXTREL))
10659                 dyn.d_un.d_val &= ~DF_TEXTREL;
10660               else
10661                 swap_out_p = FALSE;
10662               break;
10663
10664             default:
10665               swap_out_p = FALSE;
10666               if (htab->is_vxworks
10667                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
10668                 swap_out_p = TRUE;
10669               break;
10670             }
10671
10672           if (swap_out_p || dyn_skipped)
10673             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10674               (dynobj, &dyn, b - dyn_skipped);
10675
10676           if (dyn_to_skip)
10677             {
10678               dyn_skipped += dyn_to_skip;
10679               dyn_to_skip = 0;
10680             }
10681         }
10682
10683       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
10684       if (dyn_skipped > 0)
10685         memset (b - dyn_skipped, 0, dyn_skipped);
10686     }
10687
10688   if (sgot != NULL && sgot->size > 0
10689       && !bfd_is_abs_section (sgot->output_section))
10690     {
10691       if (htab->is_vxworks)
10692         {
10693           /* The first entry of the global offset table points to the
10694              ".dynamic" section.  The second is initialized by the
10695              loader and contains the shared library identifier.
10696              The third is also initialized by the loader and points
10697              to the lazy resolution stub.  */
10698           MIPS_ELF_PUT_WORD (output_bfd,
10699                              sdyn->output_offset + sdyn->output_section->vma,
10700                              sgot->contents);
10701           MIPS_ELF_PUT_WORD (output_bfd, 0,
10702                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10703           MIPS_ELF_PUT_WORD (output_bfd, 0,
10704                              sgot->contents
10705                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
10706         }
10707       else
10708         {
10709           /* The first entry of the global offset table will be filled at
10710              runtime. The second entry will be used by some runtime loaders.
10711              This isn't the case of IRIX rld.  */
10712           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
10713           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10714                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10715         }
10716
10717       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
10718          = MIPS_ELF_GOT_SIZE (output_bfd);
10719     }
10720
10721   /* Generate dynamic relocations for the non-primary gots.  */
10722   if (gg != NULL && gg->next)
10723     {
10724       Elf_Internal_Rela rel[3];
10725       bfd_vma addend = 0;
10726
10727       memset (rel, 0, sizeof (rel));
10728       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
10729
10730       for (g = gg->next; g->next != gg; g = g->next)
10731         {
10732           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
10733             + g->next->tls_gotno;
10734
10735           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
10736                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10737           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10738                              sgot->contents
10739                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10740
10741           if (! info->shared)
10742             continue;
10743
10744           while (got_index < g->assigned_gotno)
10745             {
10746               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
10747                 = got_index++ * MIPS_ELF_GOT_SIZE (output_bfd);
10748               if (!(mips_elf_create_dynamic_relocation
10749                     (output_bfd, info, rel, NULL,
10750                      bfd_abs_section_ptr,
10751                      0, &addend, sgot)))
10752                 return FALSE;
10753               BFD_ASSERT (addend == 0);
10754             }
10755         }
10756     }
10757
10758   /* The generation of dynamic relocations for the non-primary gots
10759      adds more dynamic relocations.  We cannot count them until
10760      here.  */
10761
10762   if (elf_hash_table (info)->dynamic_sections_created)
10763     {
10764       bfd_byte *b;
10765       bfd_boolean swap_out_p;
10766
10767       BFD_ASSERT (sdyn != NULL);
10768
10769       for (b = sdyn->contents;
10770            b < sdyn->contents + sdyn->size;
10771            b += MIPS_ELF_DYN_SIZE (dynobj))
10772         {
10773           Elf_Internal_Dyn dyn;
10774           asection *s;
10775
10776           /* Read in the current dynamic entry.  */
10777           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10778
10779           /* Assume that we're going to modify it and write it out.  */
10780           swap_out_p = TRUE;
10781
10782           switch (dyn.d_tag)
10783             {
10784             case DT_RELSZ:
10785               /* Reduce DT_RELSZ to account for any relocations we
10786                  decided not to make.  This is for the n64 irix rld,
10787                  which doesn't seem to apply any relocations if there
10788                  are trailing null entries.  */
10789               s = mips_elf_rel_dyn_section (info, FALSE);
10790               dyn.d_un.d_val = (s->reloc_count
10791                                 * (ABI_64_P (output_bfd)
10792                                    ? sizeof (Elf64_Mips_External_Rel)
10793                                    : sizeof (Elf32_External_Rel)));
10794               /* Adjust the section size too.  Tools like the prelinker
10795                  can reasonably expect the values to the same.  */
10796               elf_section_data (s->output_section)->this_hdr.sh_size
10797                 = dyn.d_un.d_val;
10798               break;
10799
10800             default:
10801               swap_out_p = FALSE;
10802               break;
10803             }
10804
10805           if (swap_out_p)
10806             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10807               (dynobj, &dyn, b);
10808         }
10809     }
10810
10811   {
10812     asection *s;
10813     Elf32_compact_rel cpt;
10814
10815     if (SGI_COMPAT (output_bfd))
10816       {
10817         /* Write .compact_rel section out.  */
10818         s = bfd_get_linker_section (dynobj, ".compact_rel");
10819         if (s != NULL)
10820           {
10821             cpt.id1 = 1;
10822             cpt.num = s->reloc_count;
10823             cpt.id2 = 2;
10824             cpt.offset = (s->output_section->filepos
10825                           + sizeof (Elf32_External_compact_rel));
10826             cpt.reserved0 = 0;
10827             cpt.reserved1 = 0;
10828             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
10829                                             ((Elf32_External_compact_rel *)
10830                                              s->contents));
10831
10832             /* Clean up a dummy stub function entry in .text.  */
10833             if (htab->sstubs != NULL)
10834               {
10835                 file_ptr dummy_offset;
10836
10837                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
10838                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
10839                 memset (htab->sstubs->contents + dummy_offset, 0,
10840                         htab->function_stub_size);
10841               }
10842           }
10843       }
10844
10845     /* The psABI says that the dynamic relocations must be sorted in
10846        increasing order of r_symndx.  The VxWorks EABI doesn't require
10847        this, and because the code below handles REL rather than RELA
10848        relocations, using it for VxWorks would be outright harmful.  */
10849     if (!htab->is_vxworks)
10850       {
10851         s = mips_elf_rel_dyn_section (info, FALSE);
10852         if (s != NULL
10853             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
10854           {
10855             reldyn_sorting_bfd = output_bfd;
10856
10857             if (ABI_64_P (output_bfd))
10858               qsort ((Elf64_External_Rel *) s->contents + 1,
10859                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
10860                      sort_dynamic_relocs_64);
10861             else
10862               qsort ((Elf32_External_Rel *) s->contents + 1,
10863                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
10864                      sort_dynamic_relocs);
10865           }
10866       }
10867   }
10868
10869   if (htab->splt && htab->splt->size > 0)
10870     {
10871       if (htab->is_vxworks)
10872         {
10873           if (info->shared)
10874             mips_vxworks_finish_shared_plt (output_bfd, info);
10875           else
10876             mips_vxworks_finish_exec_plt (output_bfd, info);
10877         }
10878       else
10879         {
10880           BFD_ASSERT (!info->shared);
10881           mips_finish_exec_plt (output_bfd, info);
10882         }
10883     }
10884   return TRUE;
10885 }
10886
10887
10888 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
10889
10890 static void
10891 mips_set_isa_flags (bfd *abfd)
10892 {
10893   flagword val;
10894
10895   switch (bfd_get_mach (abfd))
10896     {
10897     default:
10898     case bfd_mach_mips3000:
10899       val = E_MIPS_ARCH_1;
10900       break;
10901
10902     case bfd_mach_mips3900:
10903       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
10904       break;
10905
10906     case bfd_mach_mips6000:
10907       val = E_MIPS_ARCH_2;
10908       break;
10909
10910     case bfd_mach_mips4000:
10911     case bfd_mach_mips4300:
10912     case bfd_mach_mips4400:
10913     case bfd_mach_mips4600:
10914       val = E_MIPS_ARCH_3;
10915       break;
10916
10917     case bfd_mach_mips4010:
10918       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
10919       break;
10920
10921     case bfd_mach_mips4100:
10922       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
10923       break;
10924
10925     case bfd_mach_mips4111:
10926       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
10927       break;
10928
10929     case bfd_mach_mips4120:
10930       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
10931       break;
10932
10933     case bfd_mach_mips4650:
10934       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
10935       break;
10936
10937     case bfd_mach_mips5400:
10938       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
10939       break;
10940
10941     case bfd_mach_mips5500:
10942       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
10943       break;
10944
10945     case bfd_mach_mips5900:
10946       val = E_MIPS_ARCH_3 | E_MIPS_MACH_5900;
10947       break;
10948
10949     case bfd_mach_mips9000:
10950       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
10951       break;
10952
10953     case bfd_mach_mips5000:
10954     case bfd_mach_mips7000:
10955     case bfd_mach_mips8000:
10956     case bfd_mach_mips10000:
10957     case bfd_mach_mips12000:
10958     case bfd_mach_mips14000:
10959     case bfd_mach_mips16000:
10960       val = E_MIPS_ARCH_4;
10961       break;
10962
10963     case bfd_mach_mips5:
10964       val = E_MIPS_ARCH_5;
10965       break;
10966
10967     case bfd_mach_mips_loongson_2e:
10968       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
10969       break;
10970
10971     case bfd_mach_mips_loongson_2f:
10972       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
10973       break;
10974
10975     case bfd_mach_mips_sb1:
10976       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
10977       break;
10978
10979     case bfd_mach_mips_loongson_3a:
10980       val = E_MIPS_ARCH_64 | E_MIPS_MACH_LS3A;
10981       break;
10982
10983     case bfd_mach_mips_octeon:
10984     case bfd_mach_mips_octeonp:
10985       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
10986       break;
10987
10988     case bfd_mach_mips_xlr:
10989       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
10990       break;
10991
10992     case bfd_mach_mips_octeon2:
10993       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
10994       break;
10995
10996     case bfd_mach_mipsisa32:
10997       val = E_MIPS_ARCH_32;
10998       break;
10999
11000     case bfd_mach_mipsisa64:
11001       val = E_MIPS_ARCH_64;
11002       break;
11003
11004     case bfd_mach_mipsisa32r2:
11005       val = E_MIPS_ARCH_32R2;
11006       break;
11007
11008     case bfd_mach_mipsisa64r2:
11009       val = E_MIPS_ARCH_64R2;
11010       break;
11011     }
11012   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
11013   elf_elfheader (abfd)->e_flags |= val;
11014
11015 }
11016
11017
11018 /* The final processing done just before writing out a MIPS ELF object
11019    file.  This gets the MIPS architecture right based on the machine
11020    number.  This is used by both the 32-bit and the 64-bit ABI.  */
11021
11022 void
11023 _bfd_mips_elf_final_write_processing (bfd *abfd,
11024                                       bfd_boolean linker ATTRIBUTE_UNUSED)
11025 {
11026   unsigned int i;
11027   Elf_Internal_Shdr **hdrpp;
11028   const char *name;
11029   asection *sec;
11030
11031   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
11032      is nonzero.  This is for compatibility with old objects, which used
11033      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
11034   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
11035     mips_set_isa_flags (abfd);
11036
11037   /* Set the sh_info field for .gptab sections and other appropriate
11038      info for each special section.  */
11039   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
11040        i < elf_numsections (abfd);
11041        i++, hdrpp++)
11042     {
11043       switch ((*hdrpp)->sh_type)
11044         {
11045         case SHT_MIPS_MSYM:
11046         case SHT_MIPS_LIBLIST:
11047           sec = bfd_get_section_by_name (abfd, ".dynstr");
11048           if (sec != NULL)
11049             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11050           break;
11051
11052         case SHT_MIPS_GPTAB:
11053           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11054           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11055           BFD_ASSERT (name != NULL
11056                       && CONST_STRNEQ (name, ".gptab."));
11057           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
11058           BFD_ASSERT (sec != NULL);
11059           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11060           break;
11061
11062         case SHT_MIPS_CONTENT:
11063           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11064           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11065           BFD_ASSERT (name != NULL
11066                       && CONST_STRNEQ (name, ".MIPS.content"));
11067           sec = bfd_get_section_by_name (abfd,
11068                                          name + sizeof ".MIPS.content" - 1);
11069           BFD_ASSERT (sec != NULL);
11070           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11071           break;
11072
11073         case SHT_MIPS_SYMBOL_LIB:
11074           sec = bfd_get_section_by_name (abfd, ".dynsym");
11075           if (sec != NULL)
11076             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11077           sec = bfd_get_section_by_name (abfd, ".liblist");
11078           if (sec != NULL)
11079             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11080           break;
11081
11082         case SHT_MIPS_EVENTS:
11083           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11084           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11085           BFD_ASSERT (name != NULL);
11086           if (CONST_STRNEQ (name, ".MIPS.events"))
11087             sec = bfd_get_section_by_name (abfd,
11088                                            name + sizeof ".MIPS.events" - 1);
11089           else
11090             {
11091               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
11092               sec = bfd_get_section_by_name (abfd,
11093                                              (name
11094                                               + sizeof ".MIPS.post_rel" - 1));
11095             }
11096           BFD_ASSERT (sec != NULL);
11097           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11098           break;
11099
11100         }
11101     }
11102 }
11103 \f
11104 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
11105    segments.  */
11106
11107 int
11108 _bfd_mips_elf_additional_program_headers (bfd *abfd,
11109                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
11110 {
11111   asection *s;
11112   int ret = 0;
11113
11114   /* See if we need a PT_MIPS_REGINFO segment.  */
11115   s = bfd_get_section_by_name (abfd, ".reginfo");
11116   if (s && (s->flags & SEC_LOAD))
11117     ++ret;
11118
11119   /* See if we need a PT_MIPS_OPTIONS segment.  */
11120   if (IRIX_COMPAT (abfd) == ict_irix6
11121       && bfd_get_section_by_name (abfd,
11122                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
11123     ++ret;
11124
11125   /* See if we need a PT_MIPS_RTPROC segment.  */
11126   if (IRIX_COMPAT (abfd) == ict_irix5
11127       && bfd_get_section_by_name (abfd, ".dynamic")
11128       && bfd_get_section_by_name (abfd, ".mdebug"))
11129     ++ret;
11130
11131   /* Allocate a PT_NULL header in dynamic objects.  See
11132      _bfd_mips_elf_modify_segment_map for details.  */
11133   if (!SGI_COMPAT (abfd)
11134       && bfd_get_section_by_name (abfd, ".dynamic"))
11135     ++ret;
11136
11137   return ret;
11138 }
11139
11140 /* Modify the segment map for an IRIX5 executable.  */
11141
11142 bfd_boolean
11143 _bfd_mips_elf_modify_segment_map (bfd *abfd,
11144                                   struct bfd_link_info *info)
11145 {
11146   asection *s;
11147   struct elf_segment_map *m, **pm;
11148   bfd_size_type amt;
11149
11150   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
11151      segment.  */
11152   s = bfd_get_section_by_name (abfd, ".reginfo");
11153   if (s != NULL && (s->flags & SEC_LOAD) != 0)
11154     {
11155       for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11156         if (m->p_type == PT_MIPS_REGINFO)
11157           break;
11158       if (m == NULL)
11159         {
11160           amt = sizeof *m;
11161           m = bfd_zalloc (abfd, amt);
11162           if (m == NULL)
11163             return FALSE;
11164
11165           m->p_type = PT_MIPS_REGINFO;
11166           m->count = 1;
11167           m->sections[0] = s;
11168
11169           /* We want to put it after the PHDR and INTERP segments.  */
11170           pm = &elf_tdata (abfd)->segment_map;
11171           while (*pm != NULL
11172                  && ((*pm)->p_type == PT_PHDR
11173                      || (*pm)->p_type == PT_INTERP))
11174             pm = &(*pm)->next;
11175
11176           m->next = *pm;
11177           *pm = m;
11178         }
11179     }
11180
11181   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
11182      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
11183      PT_MIPS_OPTIONS segment immediately following the program header
11184      table.  */
11185   if (NEWABI_P (abfd)
11186       /* On non-IRIX6 new abi, we'll have already created a segment
11187          for this section, so don't create another.  I'm not sure this
11188          is not also the case for IRIX 6, but I can't test it right
11189          now.  */
11190       && IRIX_COMPAT (abfd) == ict_irix6)
11191     {
11192       for (s = abfd->sections; s; s = s->next)
11193         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
11194           break;
11195
11196       if (s)
11197         {
11198           struct elf_segment_map *options_segment;
11199
11200           pm = &elf_tdata (abfd)->segment_map;
11201           while (*pm != NULL
11202                  && ((*pm)->p_type == PT_PHDR
11203                      || (*pm)->p_type == PT_INTERP))
11204             pm = &(*pm)->next;
11205
11206           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
11207             {
11208               amt = sizeof (struct elf_segment_map);
11209               options_segment = bfd_zalloc (abfd, amt);
11210               options_segment->next = *pm;
11211               options_segment->p_type = PT_MIPS_OPTIONS;
11212               options_segment->p_flags = PF_R;
11213               options_segment->p_flags_valid = TRUE;
11214               options_segment->count = 1;
11215               options_segment->sections[0] = s;
11216               *pm = options_segment;
11217             }
11218         }
11219     }
11220   else
11221     {
11222       if (IRIX_COMPAT (abfd) == ict_irix5)
11223         {
11224           /* If there are .dynamic and .mdebug sections, we make a room
11225              for the RTPROC header.  FIXME: Rewrite without section names.  */
11226           if (bfd_get_section_by_name (abfd, ".interp") == NULL
11227               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
11228               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
11229             {
11230               for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11231                 if (m->p_type == PT_MIPS_RTPROC)
11232                   break;
11233               if (m == NULL)
11234                 {
11235                   amt = sizeof *m;
11236                   m = bfd_zalloc (abfd, amt);
11237                   if (m == NULL)
11238                     return FALSE;
11239
11240                   m->p_type = PT_MIPS_RTPROC;
11241
11242                   s = bfd_get_section_by_name (abfd, ".rtproc");
11243                   if (s == NULL)
11244                     {
11245                       m->count = 0;
11246                       m->p_flags = 0;
11247                       m->p_flags_valid = 1;
11248                     }
11249                   else
11250                     {
11251                       m->count = 1;
11252                       m->sections[0] = s;
11253                     }
11254
11255                   /* We want to put it after the DYNAMIC segment.  */
11256                   pm = &elf_tdata (abfd)->segment_map;
11257                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
11258                     pm = &(*pm)->next;
11259                   if (*pm != NULL)
11260                     pm = &(*pm)->next;
11261
11262                   m->next = *pm;
11263                   *pm = m;
11264                 }
11265             }
11266         }
11267       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
11268          .dynstr, .dynsym, and .hash sections, and everything in
11269          between.  */
11270       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL;
11271            pm = &(*pm)->next)
11272         if ((*pm)->p_type == PT_DYNAMIC)
11273           break;
11274       m = *pm;
11275       if (m != NULL && IRIX_COMPAT (abfd) == ict_none)
11276         {
11277           /* For a normal mips executable the permissions for the PT_DYNAMIC
11278              segment are read, write and execute. We do that here since
11279              the code in elf.c sets only the read permission. This matters
11280              sometimes for the dynamic linker.  */
11281           if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
11282             {
11283               m->p_flags = PF_R | PF_W | PF_X;
11284               m->p_flags_valid = 1;
11285             }
11286         }
11287       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
11288          glibc's dynamic linker has traditionally derived the number of
11289          tags from the p_filesz field, and sometimes allocates stack
11290          arrays of that size.  An overly-big PT_DYNAMIC segment can
11291          be actively harmful in such cases.  Making PT_DYNAMIC contain
11292          other sections can also make life hard for the prelinker,
11293          which might move one of the other sections to a different
11294          PT_LOAD segment.  */
11295       if (SGI_COMPAT (abfd)
11296           && m != NULL
11297           && m->count == 1
11298           && strcmp (m->sections[0]->name, ".dynamic") == 0)
11299         {
11300           static const char *sec_names[] =
11301           {
11302             ".dynamic", ".dynstr", ".dynsym", ".hash"
11303           };
11304           bfd_vma low, high;
11305           unsigned int i, c;
11306           struct elf_segment_map *n;
11307
11308           low = ~(bfd_vma) 0;
11309           high = 0;
11310           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
11311             {
11312               s = bfd_get_section_by_name (abfd, sec_names[i]);
11313               if (s != NULL && (s->flags & SEC_LOAD) != 0)
11314                 {
11315                   bfd_size_type sz;
11316
11317                   if (low > s->vma)
11318                     low = s->vma;
11319                   sz = s->size;
11320                   if (high < s->vma + sz)
11321                     high = s->vma + sz;
11322                 }
11323             }
11324
11325           c = 0;
11326           for (s = abfd->sections; s != NULL; s = s->next)
11327             if ((s->flags & SEC_LOAD) != 0
11328                 && s->vma >= low
11329                 && s->vma + s->size <= high)
11330               ++c;
11331
11332           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
11333           n = bfd_zalloc (abfd, amt);
11334           if (n == NULL)
11335             return FALSE;
11336           *n = *m;
11337           n->count = c;
11338
11339           i = 0;
11340           for (s = abfd->sections; s != NULL; s = s->next)
11341             {
11342               if ((s->flags & SEC_LOAD) != 0
11343                   && s->vma >= low
11344                   && s->vma + s->size <= high)
11345                 {
11346                   n->sections[i] = s;
11347                   ++i;
11348                 }
11349             }
11350
11351           *pm = n;
11352         }
11353     }
11354
11355   /* Allocate a spare program header in dynamic objects so that tools
11356      like the prelinker can add an extra PT_LOAD entry.
11357
11358      If the prelinker needs to make room for a new PT_LOAD entry, its
11359      standard procedure is to move the first (read-only) sections into
11360      the new (writable) segment.  However, the MIPS ABI requires
11361      .dynamic to be in a read-only segment, and the section will often
11362      start within sizeof (ElfNN_Phdr) bytes of the last program header.
11363
11364      Although the prelinker could in principle move .dynamic to a
11365      writable segment, it seems better to allocate a spare program
11366      header instead, and avoid the need to move any sections.
11367      There is a long tradition of allocating spare dynamic tags,
11368      so allocating a spare program header seems like a natural
11369      extension.
11370
11371      If INFO is NULL, we may be copying an already prelinked binary
11372      with objcopy or strip, so do not add this header.  */
11373   if (info != NULL
11374       && !SGI_COMPAT (abfd)
11375       && bfd_get_section_by_name (abfd, ".dynamic"))
11376     {
11377       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL; pm = &(*pm)->next)
11378         if ((*pm)->p_type == PT_NULL)
11379           break;
11380       if (*pm == NULL)
11381         {
11382           m = bfd_zalloc (abfd, sizeof (*m));
11383           if (m == NULL)
11384             return FALSE;
11385
11386           m->p_type = PT_NULL;
11387           *pm = m;
11388         }
11389     }
11390
11391   return TRUE;
11392 }
11393 \f
11394 /* Return the section that should be marked against GC for a given
11395    relocation.  */
11396
11397 asection *
11398 _bfd_mips_elf_gc_mark_hook (asection *sec,
11399                             struct bfd_link_info *info,
11400                             Elf_Internal_Rela *rel,
11401                             struct elf_link_hash_entry *h,
11402                             Elf_Internal_Sym *sym)
11403 {
11404   /* ??? Do mips16 stub sections need to be handled special?  */
11405
11406   if (h != NULL)
11407     switch (ELF_R_TYPE (sec->owner, rel->r_info))
11408       {
11409       case R_MIPS_GNU_VTINHERIT:
11410       case R_MIPS_GNU_VTENTRY:
11411         return NULL;
11412       }
11413
11414   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
11415 }
11416
11417 /* Update the got entry reference counts for the section being removed.  */
11418
11419 bfd_boolean
11420 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
11421                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
11422                              asection *sec ATTRIBUTE_UNUSED,
11423                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
11424 {
11425 #if 0
11426   Elf_Internal_Shdr *symtab_hdr;
11427   struct elf_link_hash_entry **sym_hashes;
11428   bfd_signed_vma *local_got_refcounts;
11429   const Elf_Internal_Rela *rel, *relend;
11430   unsigned long r_symndx;
11431   struct elf_link_hash_entry *h;
11432
11433   if (info->relocatable)
11434     return TRUE;
11435
11436   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11437   sym_hashes = elf_sym_hashes (abfd);
11438   local_got_refcounts = elf_local_got_refcounts (abfd);
11439
11440   relend = relocs + sec->reloc_count;
11441   for (rel = relocs; rel < relend; rel++)
11442     switch (ELF_R_TYPE (abfd, rel->r_info))
11443       {
11444       case R_MIPS16_GOT16:
11445       case R_MIPS16_CALL16:
11446       case R_MIPS_GOT16:
11447       case R_MIPS_CALL16:
11448       case R_MIPS_CALL_HI16:
11449       case R_MIPS_CALL_LO16:
11450       case R_MIPS_GOT_HI16:
11451       case R_MIPS_GOT_LO16:
11452       case R_MIPS_GOT_DISP:
11453       case R_MIPS_GOT_PAGE:
11454       case R_MIPS_GOT_OFST:
11455       case R_MICROMIPS_GOT16:
11456       case R_MICROMIPS_CALL16:
11457       case R_MICROMIPS_CALL_HI16:
11458       case R_MICROMIPS_CALL_LO16:
11459       case R_MICROMIPS_GOT_HI16:
11460       case R_MICROMIPS_GOT_LO16:
11461       case R_MICROMIPS_GOT_DISP:
11462       case R_MICROMIPS_GOT_PAGE:
11463       case R_MICROMIPS_GOT_OFST:
11464         /* ??? It would seem that the existing MIPS code does no sort
11465            of reference counting or whatnot on its GOT and PLT entries,
11466            so it is not possible to garbage collect them at this time.  */
11467         break;
11468
11469       default:
11470         break;
11471       }
11472 #endif
11473
11474   return TRUE;
11475 }
11476 \f
11477 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
11478    hiding the old indirect symbol.  Process additional relocation
11479    information.  Also called for weakdefs, in which case we just let
11480    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
11481
11482 void
11483 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
11484                                     struct elf_link_hash_entry *dir,
11485                                     struct elf_link_hash_entry *ind)
11486 {
11487   struct mips_elf_link_hash_entry *dirmips, *indmips;
11488
11489   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
11490
11491   dirmips = (struct mips_elf_link_hash_entry *) dir;
11492   indmips = (struct mips_elf_link_hash_entry *) ind;
11493   /* Any absolute non-dynamic relocations against an indirect or weak
11494      definition will be against the target symbol.  */
11495   if (indmips->has_static_relocs)
11496     dirmips->has_static_relocs = TRUE;
11497
11498   if (ind->root.type != bfd_link_hash_indirect)
11499     return;
11500
11501   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
11502   if (indmips->readonly_reloc)
11503     dirmips->readonly_reloc = TRUE;
11504   if (indmips->no_fn_stub)
11505     dirmips->no_fn_stub = TRUE;
11506   if (indmips->fn_stub)
11507     {
11508       dirmips->fn_stub = indmips->fn_stub;
11509       indmips->fn_stub = NULL;
11510     }
11511   if (indmips->need_fn_stub)
11512     {
11513       dirmips->need_fn_stub = TRUE;
11514       indmips->need_fn_stub = FALSE;
11515     }
11516   if (indmips->call_stub)
11517     {
11518       dirmips->call_stub = indmips->call_stub;
11519       indmips->call_stub = NULL;
11520     }
11521   if (indmips->call_fp_stub)
11522     {
11523       dirmips->call_fp_stub = indmips->call_fp_stub;
11524       indmips->call_fp_stub = NULL;
11525     }
11526   if (indmips->global_got_area < dirmips->global_got_area)
11527     dirmips->global_got_area = indmips->global_got_area;
11528   if (indmips->global_got_area < GGA_NONE)
11529     indmips->global_got_area = GGA_NONE;
11530   if (indmips->has_nonpic_branches)
11531     dirmips->has_nonpic_branches = TRUE;
11532
11533   if (dirmips->tls_ie_type == 0)
11534     dirmips->tls_ie_type = indmips->tls_ie_type;
11535   if (dirmips->tls_gd_type == 0)
11536     dirmips->tls_gd_type = indmips->tls_gd_type;
11537 }
11538 \f
11539 #define PDR_SIZE 32
11540
11541 bfd_boolean
11542 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
11543                             struct bfd_link_info *info)
11544 {
11545   asection *o;
11546   bfd_boolean ret = FALSE;
11547   unsigned char *tdata;
11548   size_t i, skip;
11549
11550   o = bfd_get_section_by_name (abfd, ".pdr");
11551   if (! o)
11552     return FALSE;
11553   if (o->size == 0)
11554     return FALSE;
11555   if (o->size % PDR_SIZE != 0)
11556     return FALSE;
11557   if (o->output_section != NULL
11558       && bfd_is_abs_section (o->output_section))
11559     return FALSE;
11560
11561   tdata = bfd_zmalloc (o->size / PDR_SIZE);
11562   if (! tdata)
11563     return FALSE;
11564
11565   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
11566                                             info->keep_memory);
11567   if (!cookie->rels)
11568     {
11569       free (tdata);
11570       return FALSE;
11571     }
11572
11573   cookie->rel = cookie->rels;
11574   cookie->relend = cookie->rels + o->reloc_count;
11575
11576   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
11577     {
11578       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
11579         {
11580           tdata[i] = 1;
11581           skip ++;
11582         }
11583     }
11584
11585   if (skip != 0)
11586     {
11587       mips_elf_section_data (o)->u.tdata = tdata;
11588       o->size -= skip * PDR_SIZE;
11589       ret = TRUE;
11590     }
11591   else
11592     free (tdata);
11593
11594   if (! info->keep_memory)
11595     free (cookie->rels);
11596
11597   return ret;
11598 }
11599
11600 bfd_boolean
11601 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
11602 {
11603   if (strcmp (sec->name, ".pdr") == 0)
11604     return TRUE;
11605   return FALSE;
11606 }
11607
11608 bfd_boolean
11609 _bfd_mips_elf_write_section (bfd *output_bfd,
11610                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
11611                              asection *sec, bfd_byte *contents)
11612 {
11613   bfd_byte *to, *from, *end;
11614   int i;
11615
11616   if (strcmp (sec->name, ".pdr") != 0)
11617     return FALSE;
11618
11619   if (mips_elf_section_data (sec)->u.tdata == NULL)
11620     return FALSE;
11621
11622   to = contents;
11623   end = contents + sec->size;
11624   for (from = contents, i = 0;
11625        from < end;
11626        from += PDR_SIZE, i++)
11627     {
11628       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
11629         continue;
11630       if (to != from)
11631         memcpy (to, from, PDR_SIZE);
11632       to += PDR_SIZE;
11633     }
11634   bfd_set_section_contents (output_bfd, sec->output_section, contents,
11635                             sec->output_offset, sec->size);
11636   return TRUE;
11637 }
11638 \f
11639 /* microMIPS code retains local labels for linker relaxation.  Omit them
11640    from output by default for clarity.  */
11641
11642 bfd_boolean
11643 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
11644 {
11645   return _bfd_elf_is_local_label_name (abfd, sym->name);
11646 }
11647
11648 /* MIPS ELF uses a special find_nearest_line routine in order the
11649    handle the ECOFF debugging information.  */
11650
11651 struct mips_elf_find_line
11652 {
11653   struct ecoff_debug_info d;
11654   struct ecoff_find_line i;
11655 };
11656
11657 bfd_boolean
11658 _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section,
11659                                  asymbol **symbols, bfd_vma offset,
11660                                  const char **filename_ptr,
11661                                  const char **functionname_ptr,
11662                                  unsigned int *line_ptr)
11663 {
11664   asection *msec;
11665
11666   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
11667                                      filename_ptr, functionname_ptr,
11668                                      line_ptr))
11669     return TRUE;
11670
11671   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
11672                                      section, symbols, offset,
11673                                      filename_ptr, functionname_ptr,
11674                                      line_ptr, NULL, ABI_64_P (abfd) ? 8 : 0,
11675                                      &elf_tdata (abfd)->dwarf2_find_line_info))
11676     return TRUE;
11677
11678   msec = bfd_get_section_by_name (abfd, ".mdebug");
11679   if (msec != NULL)
11680     {
11681       flagword origflags;
11682       struct mips_elf_find_line *fi;
11683       const struct ecoff_debug_swap * const swap =
11684         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
11685
11686       /* If we are called during a link, mips_elf_final_link may have
11687          cleared the SEC_HAS_CONTENTS field.  We force it back on here
11688          if appropriate (which it normally will be).  */
11689       origflags = msec->flags;
11690       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
11691         msec->flags |= SEC_HAS_CONTENTS;
11692
11693       fi = elf_tdata (abfd)->find_line_info;
11694       if (fi == NULL)
11695         {
11696           bfd_size_type external_fdr_size;
11697           char *fraw_src;
11698           char *fraw_end;
11699           struct fdr *fdr_ptr;
11700           bfd_size_type amt = sizeof (struct mips_elf_find_line);
11701
11702           fi = bfd_zalloc (abfd, amt);
11703           if (fi == NULL)
11704             {
11705               msec->flags = origflags;
11706               return FALSE;
11707             }
11708
11709           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
11710             {
11711               msec->flags = origflags;
11712               return FALSE;
11713             }
11714
11715           /* Swap in the FDR information.  */
11716           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
11717           fi->d.fdr = bfd_alloc (abfd, amt);
11718           if (fi->d.fdr == NULL)
11719             {
11720               msec->flags = origflags;
11721               return FALSE;
11722             }
11723           external_fdr_size = swap->external_fdr_size;
11724           fdr_ptr = fi->d.fdr;
11725           fraw_src = (char *) fi->d.external_fdr;
11726           fraw_end = (fraw_src
11727                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
11728           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
11729             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
11730
11731           elf_tdata (abfd)->find_line_info = fi;
11732
11733           /* Note that we don't bother to ever free this information.
11734              find_nearest_line is either called all the time, as in
11735              objdump -l, so the information should be saved, or it is
11736              rarely called, as in ld error messages, so the memory
11737              wasted is unimportant.  Still, it would probably be a
11738              good idea for free_cached_info to throw it away.  */
11739         }
11740
11741       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
11742                                   &fi->i, filename_ptr, functionname_ptr,
11743                                   line_ptr))
11744         {
11745           msec->flags = origflags;
11746           return TRUE;
11747         }
11748
11749       msec->flags = origflags;
11750     }
11751
11752   /* Fall back on the generic ELF find_nearest_line routine.  */
11753
11754   return _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
11755                                      filename_ptr, functionname_ptr,
11756                                      line_ptr);
11757 }
11758
11759 bfd_boolean
11760 _bfd_mips_elf_find_inliner_info (bfd *abfd,
11761                                  const char **filename_ptr,
11762                                  const char **functionname_ptr,
11763                                  unsigned int *line_ptr)
11764 {
11765   bfd_boolean found;
11766   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
11767                                          functionname_ptr, line_ptr,
11768                                          & elf_tdata (abfd)->dwarf2_find_line_info);
11769   return found;
11770 }
11771
11772 \f
11773 /* When are writing out the .options or .MIPS.options section,
11774    remember the bytes we are writing out, so that we can install the
11775    GP value in the section_processing routine.  */
11776
11777 bfd_boolean
11778 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
11779                                     const void *location,
11780                                     file_ptr offset, bfd_size_type count)
11781 {
11782   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
11783     {
11784       bfd_byte *c;
11785
11786       if (elf_section_data (section) == NULL)
11787         {
11788           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
11789           section->used_by_bfd = bfd_zalloc (abfd, amt);
11790           if (elf_section_data (section) == NULL)
11791             return FALSE;
11792         }
11793       c = mips_elf_section_data (section)->u.tdata;
11794       if (c == NULL)
11795         {
11796           c = bfd_zalloc (abfd, section->size);
11797           if (c == NULL)
11798             return FALSE;
11799           mips_elf_section_data (section)->u.tdata = c;
11800         }
11801
11802       memcpy (c + offset, location, count);
11803     }
11804
11805   return _bfd_elf_set_section_contents (abfd, section, location, offset,
11806                                         count);
11807 }
11808
11809 /* This is almost identical to bfd_generic_get_... except that some
11810    MIPS relocations need to be handled specially.  Sigh.  */
11811
11812 bfd_byte *
11813 _bfd_elf_mips_get_relocated_section_contents
11814   (bfd *abfd,
11815    struct bfd_link_info *link_info,
11816    struct bfd_link_order *link_order,
11817    bfd_byte *data,
11818    bfd_boolean relocatable,
11819    asymbol **symbols)
11820 {
11821   /* Get enough memory to hold the stuff */
11822   bfd *input_bfd = link_order->u.indirect.section->owner;
11823   asection *input_section = link_order->u.indirect.section;
11824   bfd_size_type sz;
11825
11826   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
11827   arelent **reloc_vector = NULL;
11828   long reloc_count;
11829
11830   if (reloc_size < 0)
11831     goto error_return;
11832
11833   reloc_vector = bfd_malloc (reloc_size);
11834   if (reloc_vector == NULL && reloc_size != 0)
11835     goto error_return;
11836
11837   /* read in the section */
11838   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
11839   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
11840     goto error_return;
11841
11842   reloc_count = bfd_canonicalize_reloc (input_bfd,
11843                                         input_section,
11844                                         reloc_vector,
11845                                         symbols);
11846   if (reloc_count < 0)
11847     goto error_return;
11848
11849   if (reloc_count > 0)
11850     {
11851       arelent **parent;
11852       /* for mips */
11853       int gp_found;
11854       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
11855
11856       {
11857         struct bfd_hash_entry *h;
11858         struct bfd_link_hash_entry *lh;
11859         /* Skip all this stuff if we aren't mixing formats.  */
11860         if (abfd && input_bfd
11861             && abfd->xvec == input_bfd->xvec)
11862           lh = 0;
11863         else
11864           {
11865             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
11866             lh = (struct bfd_link_hash_entry *) h;
11867           }
11868       lookup:
11869         if (lh)
11870           {
11871             switch (lh->type)
11872               {
11873               case bfd_link_hash_undefined:
11874               case bfd_link_hash_undefweak:
11875               case bfd_link_hash_common:
11876                 gp_found = 0;
11877                 break;
11878               case bfd_link_hash_defined:
11879               case bfd_link_hash_defweak:
11880                 gp_found = 1;
11881                 gp = lh->u.def.value;
11882                 break;
11883               case bfd_link_hash_indirect:
11884               case bfd_link_hash_warning:
11885                 lh = lh->u.i.link;
11886                 /* @@FIXME  ignoring warning for now */
11887                 goto lookup;
11888               case bfd_link_hash_new:
11889               default:
11890                 abort ();
11891               }
11892           }
11893         else
11894           gp_found = 0;
11895       }
11896       /* end mips */
11897       for (parent = reloc_vector; *parent != NULL; parent++)
11898         {
11899           char *error_message = NULL;
11900           bfd_reloc_status_type r;
11901
11902           /* Specific to MIPS: Deal with relocation types that require
11903              knowing the gp of the output bfd.  */
11904           asymbol *sym = *(*parent)->sym_ptr_ptr;
11905
11906           /* If we've managed to find the gp and have a special
11907              function for the relocation then go ahead, else default
11908              to the generic handling.  */
11909           if (gp_found
11910               && (*parent)->howto->special_function
11911               == _bfd_mips_elf32_gprel16_reloc)
11912             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
11913                                                input_section, relocatable,
11914                                                data, gp);
11915           else
11916             r = bfd_perform_relocation (input_bfd, *parent, data,
11917                                         input_section,
11918                                         relocatable ? abfd : NULL,
11919                                         &error_message);
11920
11921           if (relocatable)
11922             {
11923               asection *os = input_section->output_section;
11924
11925               /* A partial link, so keep the relocs */
11926               os->orelocation[os->reloc_count] = *parent;
11927               os->reloc_count++;
11928             }
11929
11930           if (r != bfd_reloc_ok)
11931             {
11932               switch (r)
11933                 {
11934                 case bfd_reloc_undefined:
11935                   if (!((*link_info->callbacks->undefined_symbol)
11936                         (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11937                          input_bfd, input_section, (*parent)->address, TRUE)))
11938                     goto error_return;
11939                   break;
11940                 case bfd_reloc_dangerous:
11941                   BFD_ASSERT (error_message != NULL);
11942                   if (!((*link_info->callbacks->reloc_dangerous)
11943                         (link_info, error_message, input_bfd, input_section,
11944                          (*parent)->address)))
11945                     goto error_return;
11946                   break;
11947                 case bfd_reloc_overflow:
11948                   if (!((*link_info->callbacks->reloc_overflow)
11949                         (link_info, NULL,
11950                          bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11951                          (*parent)->howto->name, (*parent)->addend,
11952                          input_bfd, input_section, (*parent)->address)))
11953                     goto error_return;
11954                   break;
11955                 case bfd_reloc_outofrange:
11956                 default:
11957                   abort ();
11958                   break;
11959                 }
11960
11961             }
11962         }
11963     }
11964   if (reloc_vector != NULL)
11965     free (reloc_vector);
11966   return data;
11967
11968 error_return:
11969   if (reloc_vector != NULL)
11970     free (reloc_vector);
11971   return NULL;
11972 }
11973 \f
11974 static bfd_boolean
11975 mips_elf_relax_delete_bytes (bfd *abfd,
11976                              asection *sec, bfd_vma addr, int count)
11977 {
11978   Elf_Internal_Shdr *symtab_hdr;
11979   unsigned int sec_shndx;
11980   bfd_byte *contents;
11981   Elf_Internal_Rela *irel, *irelend;
11982   Elf_Internal_Sym *isym;
11983   Elf_Internal_Sym *isymend;
11984   struct elf_link_hash_entry **sym_hashes;
11985   struct elf_link_hash_entry **end_hashes;
11986   struct elf_link_hash_entry **start_hashes;
11987   unsigned int symcount;
11988
11989   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
11990   contents = elf_section_data (sec)->this_hdr.contents;
11991
11992   irel = elf_section_data (sec)->relocs;
11993   irelend = irel + sec->reloc_count;
11994
11995   /* Actually delete the bytes.  */
11996   memmove (contents + addr, contents + addr + count,
11997            (size_t) (sec->size - addr - count));
11998   sec->size -= count;
11999
12000   /* Adjust all the relocs.  */
12001   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
12002     {
12003       /* Get the new reloc address.  */
12004       if (irel->r_offset > addr)
12005         irel->r_offset -= count;
12006     }
12007
12008   BFD_ASSERT (addr % 2 == 0);
12009   BFD_ASSERT (count % 2 == 0);
12010
12011   /* Adjust the local symbols defined in this section.  */
12012   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12013   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
12014   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
12015     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
12016       isym->st_value -= count;
12017
12018   /* Now adjust the global symbols defined in this section.  */
12019   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
12020               - symtab_hdr->sh_info);
12021   sym_hashes = start_hashes = elf_sym_hashes (abfd);
12022   end_hashes = sym_hashes + symcount;
12023
12024   for (; sym_hashes < end_hashes; sym_hashes++)
12025     {
12026       struct elf_link_hash_entry *sym_hash = *sym_hashes;
12027
12028       if ((sym_hash->root.type == bfd_link_hash_defined
12029            || sym_hash->root.type == bfd_link_hash_defweak)
12030           && sym_hash->root.u.def.section == sec)
12031         {
12032           bfd_vma value = sym_hash->root.u.def.value;
12033
12034           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
12035             value &= MINUS_TWO;
12036           if (value > addr)
12037             sym_hash->root.u.def.value -= count;
12038         }
12039     }
12040
12041   return TRUE;
12042 }
12043
12044
12045 /* Opcodes needed for microMIPS relaxation as found in
12046    opcodes/micromips-opc.c.  */
12047
12048 struct opcode_descriptor {
12049   unsigned long match;
12050   unsigned long mask;
12051 };
12052
12053 /* The $ra register aka $31.  */
12054
12055 #define RA 31
12056
12057 /* 32-bit instruction format register fields.  */
12058
12059 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
12060 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
12061
12062 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
12063
12064 #define OP16_VALID_REG(r) \
12065   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
12066
12067
12068 /* 32-bit and 16-bit branches.  */
12069
12070 static const struct opcode_descriptor b_insns_32[] = {
12071   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
12072   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
12073   { 0, 0 }  /* End marker for find_match().  */
12074 };
12075
12076 static const struct opcode_descriptor bc_insn_32 =
12077   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
12078
12079 static const struct opcode_descriptor bz_insn_32 =
12080   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
12081
12082 static const struct opcode_descriptor bzal_insn_32 =
12083   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
12084
12085 static const struct opcode_descriptor beq_insn_32 =
12086   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
12087
12088 static const struct opcode_descriptor b_insn_16 =
12089   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
12090
12091 static const struct opcode_descriptor bz_insn_16 =
12092   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
12093
12094
12095 /* 32-bit and 16-bit branch EQ and NE zero.  */
12096
12097 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
12098    eq and second the ne.  This convention is used when replacing a
12099    32-bit BEQ/BNE with the 16-bit version.  */
12100
12101 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
12102
12103 static const struct opcode_descriptor bz_rs_insns_32[] = {
12104   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
12105   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
12106   { 0, 0 }  /* End marker for find_match().  */
12107 };
12108
12109 static const struct opcode_descriptor bz_rt_insns_32[] = {
12110   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
12111   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
12112   { 0, 0 }  /* End marker for find_match().  */
12113 };
12114
12115 static const struct opcode_descriptor bzc_insns_32[] = {
12116   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
12117   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
12118   { 0, 0 }  /* End marker for find_match().  */
12119 };
12120
12121 static const struct opcode_descriptor bz_insns_16[] = {
12122   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
12123   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
12124   { 0, 0 }  /* End marker for find_match().  */
12125 };
12126
12127 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
12128
12129 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0x17) + 2)
12130 #define BZ16_REG_FIELD(r) \
12131   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 7)
12132
12133
12134 /* 32-bit instructions with a delay slot.  */
12135
12136 static const struct opcode_descriptor jal_insn_32_bd16 =
12137   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
12138
12139 static const struct opcode_descriptor jal_insn_32_bd32 =
12140   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
12141
12142 static const struct opcode_descriptor jal_x_insn_32_bd32 =
12143   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
12144
12145 static const struct opcode_descriptor j_insn_32 =
12146   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
12147
12148 static const struct opcode_descriptor jalr_insn_32 =
12149   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
12150
12151 /* This table can be compacted, because no opcode replacement is made.  */
12152
12153 static const struct opcode_descriptor ds_insns_32_bd16[] = {
12154   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
12155
12156   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
12157   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
12158
12159   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
12160   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
12161   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
12162   { 0, 0 }  /* End marker for find_match().  */
12163 };
12164
12165 /* This table can be compacted, because no opcode replacement is made.  */
12166
12167 static const struct opcode_descriptor ds_insns_32_bd32[] = {
12168   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
12169
12170   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
12171   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
12172   { 0, 0 }  /* End marker for find_match().  */
12173 };
12174
12175
12176 /* 16-bit instructions with a delay slot.  */
12177
12178 static const struct opcode_descriptor jalr_insn_16_bd16 =
12179   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
12180
12181 static const struct opcode_descriptor jalr_insn_16_bd32 =
12182   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
12183
12184 static const struct opcode_descriptor jr_insn_16 =
12185   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
12186
12187 #define JR16_REG(opcode) ((opcode) & 0x1f)
12188
12189 /* This table can be compacted, because no opcode replacement is made.  */
12190
12191 static const struct opcode_descriptor ds_insns_16_bd16[] = {
12192   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
12193
12194   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
12195   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
12196   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
12197   { 0, 0 }  /* End marker for find_match().  */
12198 };
12199
12200
12201 /* LUI instruction.  */
12202
12203 static const struct opcode_descriptor lui_insn =
12204  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
12205
12206
12207 /* ADDIU instruction.  */
12208
12209 static const struct opcode_descriptor addiu_insn =
12210   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
12211
12212 static const struct opcode_descriptor addiupc_insn =
12213   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
12214
12215 #define ADDIUPC_REG_FIELD(r) \
12216   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
12217
12218
12219 /* Relaxable instructions in a JAL delay slot: MOVE.  */
12220
12221 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
12222    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
12223 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
12224 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
12225
12226 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
12227 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
12228
12229 static const struct opcode_descriptor move_insns_32[] = {
12230   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
12231   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
12232   { 0, 0 }  /* End marker for find_match().  */
12233 };
12234
12235 static const struct opcode_descriptor move_insn_16 =
12236   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
12237
12238
12239 /* NOP instructions.  */
12240
12241 static const struct opcode_descriptor nop_insn_32 =
12242   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
12243
12244 static const struct opcode_descriptor nop_insn_16 =
12245   { /* "nop",   "",             */ 0x0c00,     0xffff };
12246
12247
12248 /* Instruction match support.  */
12249
12250 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
12251
12252 static int
12253 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
12254 {
12255   unsigned long indx;
12256
12257   for (indx = 0; insn[indx].mask != 0; indx++)
12258     if (MATCH (opcode, insn[indx]))
12259       return indx;
12260
12261   return -1;
12262 }
12263
12264
12265 /* Branch and delay slot decoding support.  */
12266
12267 /* If PTR points to what *might* be a 16-bit branch or jump, then
12268    return the minimum length of its delay slot, otherwise return 0.
12269    Non-zero results are not definitive as we might be checking against
12270    the second half of another instruction.  */
12271
12272 static int
12273 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
12274 {
12275   unsigned long opcode;
12276   int bdsize;
12277
12278   opcode = bfd_get_16 (abfd, ptr);
12279   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
12280     /* 16-bit branch/jump with a 32-bit delay slot.  */
12281     bdsize = 4;
12282   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
12283            || find_match (opcode, ds_insns_16_bd16) >= 0)
12284     /* 16-bit branch/jump with a 16-bit delay slot.  */
12285     bdsize = 2;
12286   else
12287     /* No delay slot.  */
12288     bdsize = 0;
12289
12290   return bdsize;
12291 }
12292
12293 /* If PTR points to what *might* be a 32-bit branch or jump, then
12294    return the minimum length of its delay slot, otherwise return 0.
12295    Non-zero results are not definitive as we might be checking against
12296    the second half of another instruction.  */
12297
12298 static int
12299 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
12300 {
12301   unsigned long opcode;
12302   int bdsize;
12303
12304   opcode = bfd_get_micromips_32 (abfd, ptr);
12305   if (find_match (opcode, ds_insns_32_bd32) >= 0)
12306     /* 32-bit branch/jump with a 32-bit delay slot.  */
12307     bdsize = 4;
12308   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
12309     /* 32-bit branch/jump with a 16-bit delay slot.  */
12310     bdsize = 2;
12311   else
12312     /* No delay slot.  */
12313     bdsize = 0;
12314
12315   return bdsize;
12316 }
12317
12318 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
12319    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
12320
12321 static bfd_boolean
12322 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12323 {
12324   unsigned long opcode;
12325
12326   opcode = bfd_get_16 (abfd, ptr);
12327   if (MATCH (opcode, b_insn_16)
12328                                                 /* B16  */
12329       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
12330                                                 /* JR16  */
12331       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
12332                                                 /* BEQZ16, BNEZ16  */
12333       || (MATCH (opcode, jalr_insn_16_bd32)
12334                                                 /* JALR16  */
12335           && reg != JR16_REG (opcode) && reg != RA))
12336     return TRUE;
12337
12338   return FALSE;
12339 }
12340
12341 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
12342    then return TRUE, otherwise FALSE.  */
12343
12344 static bfd_boolean
12345 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12346 {
12347   unsigned long opcode;
12348
12349   opcode = bfd_get_micromips_32 (abfd, ptr);
12350   if (MATCH (opcode, j_insn_32)
12351                                                 /* J  */
12352       || MATCH (opcode, bc_insn_32)
12353                                                 /* BC1F, BC1T, BC2F, BC2T  */
12354       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
12355                                                 /* JAL, JALX  */
12356       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
12357                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
12358       || (MATCH (opcode, bzal_insn_32)
12359                                                 /* BGEZAL, BLTZAL  */
12360           && reg != OP32_SREG (opcode) && reg != RA)
12361       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
12362                                                 /* JALR, JALR.HB, BEQ, BNE  */
12363           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
12364     return TRUE;
12365
12366   return FALSE;
12367 }
12368
12369 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
12370    IRELEND) at OFFSET indicate that there must be a compact branch there,
12371    then return TRUE, otherwise FALSE.  */
12372
12373 static bfd_boolean
12374 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
12375                      const Elf_Internal_Rela *internal_relocs,
12376                      const Elf_Internal_Rela *irelend)
12377 {
12378   const Elf_Internal_Rela *irel;
12379   unsigned long opcode;
12380
12381   opcode = bfd_get_micromips_32 (abfd, ptr);
12382   if (find_match (opcode, bzc_insns_32) < 0)
12383     return FALSE;
12384
12385   for (irel = internal_relocs; irel < irelend; irel++)
12386     if (irel->r_offset == offset
12387         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
12388       return TRUE;
12389
12390   return FALSE;
12391 }
12392
12393 /* Bitsize checking.  */
12394 #define IS_BITSIZE(val, N)                                              \
12395   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
12396     - (1ULL << ((N) - 1))) == (val))
12397
12398 \f
12399 bfd_boolean
12400 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
12401                              struct bfd_link_info *link_info,
12402                              bfd_boolean *again)
12403 {
12404   Elf_Internal_Shdr *symtab_hdr;
12405   Elf_Internal_Rela *internal_relocs;
12406   Elf_Internal_Rela *irel, *irelend;
12407   bfd_byte *contents = NULL;
12408   Elf_Internal_Sym *isymbuf = NULL;
12409
12410   /* Assume nothing changes.  */
12411   *again = FALSE;
12412
12413   /* We don't have to do anything for a relocatable link, if
12414      this section does not have relocs, or if this is not a
12415      code section.  */
12416
12417   if (link_info->relocatable
12418       || (sec->flags & SEC_RELOC) == 0
12419       || sec->reloc_count == 0
12420       || (sec->flags & SEC_CODE) == 0)
12421     return TRUE;
12422
12423   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12424
12425   /* Get a copy of the native relocations.  */
12426   internal_relocs = (_bfd_elf_link_read_relocs
12427                      (abfd, sec, NULL, (Elf_Internal_Rela *) NULL,
12428                       link_info->keep_memory));
12429   if (internal_relocs == NULL)
12430     goto error_return;
12431
12432   /* Walk through them looking for relaxing opportunities.  */
12433   irelend = internal_relocs + sec->reloc_count;
12434   for (irel = internal_relocs; irel < irelend; irel++)
12435     {
12436       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
12437       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
12438       bfd_boolean target_is_micromips_code_p;
12439       unsigned long opcode;
12440       bfd_vma symval;
12441       bfd_vma pcrval;
12442       bfd_byte *ptr;
12443       int fndopc;
12444
12445       /* The number of bytes to delete for relaxation and from where
12446          to delete these bytes starting at irel->r_offset.  */
12447       int delcnt = 0;
12448       int deloff = 0;
12449
12450       /* If this isn't something that can be relaxed, then ignore
12451          this reloc.  */
12452       if (r_type != R_MICROMIPS_HI16
12453           && r_type != R_MICROMIPS_PC16_S1
12454           && r_type != R_MICROMIPS_26_S1)
12455         continue;
12456
12457       /* Get the section contents if we haven't done so already.  */
12458       if (contents == NULL)
12459         {
12460           /* Get cached copy if it exists.  */
12461           if (elf_section_data (sec)->this_hdr.contents != NULL)
12462             contents = elf_section_data (sec)->this_hdr.contents;
12463           /* Go get them off disk.  */
12464           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
12465             goto error_return;
12466         }
12467       ptr = contents + irel->r_offset;
12468
12469       /* Read this BFD's local symbols if we haven't done so already.  */
12470       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
12471         {
12472           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
12473           if (isymbuf == NULL)
12474             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12475                                             symtab_hdr->sh_info, 0,
12476                                             NULL, NULL, NULL);
12477           if (isymbuf == NULL)
12478             goto error_return;
12479         }
12480
12481       /* Get the value of the symbol referred to by the reloc.  */
12482       if (r_symndx < symtab_hdr->sh_info)
12483         {
12484           /* A local symbol.  */
12485           Elf_Internal_Sym *isym;
12486           asection *sym_sec;
12487
12488           isym = isymbuf + r_symndx;
12489           if (isym->st_shndx == SHN_UNDEF)
12490             sym_sec = bfd_und_section_ptr;
12491           else if (isym->st_shndx == SHN_ABS)
12492             sym_sec = bfd_abs_section_ptr;
12493           else if (isym->st_shndx == SHN_COMMON)
12494             sym_sec = bfd_com_section_ptr;
12495           else
12496             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
12497           symval = (isym->st_value
12498                     + sym_sec->output_section->vma
12499                     + sym_sec->output_offset);
12500           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
12501         }
12502       else
12503         {
12504           unsigned long indx;
12505           struct elf_link_hash_entry *h;
12506
12507           /* An external symbol.  */
12508           indx = r_symndx - symtab_hdr->sh_info;
12509           h = elf_sym_hashes (abfd)[indx];
12510           BFD_ASSERT (h != NULL);
12511
12512           if (h->root.type != bfd_link_hash_defined
12513               && h->root.type != bfd_link_hash_defweak)
12514             /* This appears to be a reference to an undefined
12515                symbol.  Just ignore it -- it will be caught by the
12516                regular reloc processing.  */
12517             continue;
12518
12519           symval = (h->root.u.def.value
12520                     + h->root.u.def.section->output_section->vma
12521                     + h->root.u.def.section->output_offset);
12522           target_is_micromips_code_p = (!h->needs_plt
12523                                         && ELF_ST_IS_MICROMIPS (h->other));
12524         }
12525
12526
12527       /* For simplicity of coding, we are going to modify the
12528          section contents, the section relocs, and the BFD symbol
12529          table.  We must tell the rest of the code not to free up this
12530          information.  It would be possible to instead create a table
12531          of changes which have to be made, as is done in coff-mips.c;
12532          that would be more work, but would require less memory when
12533          the linker is run.  */
12534
12535       /* Only 32-bit instructions relaxed.  */
12536       if (irel->r_offset + 4 > sec->size)
12537         continue;
12538
12539       opcode = bfd_get_micromips_32 (abfd, ptr);
12540
12541       /* This is the pc-relative distance from the instruction the
12542          relocation is applied to, to the symbol referred.  */
12543       pcrval = (symval
12544                 - (sec->output_section->vma + sec->output_offset)
12545                 - irel->r_offset);
12546
12547       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
12548          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
12549          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
12550
12551            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
12552
12553          where pcrval has first to be adjusted to apply against the LO16
12554          location (we make the adjustment later on, when we have figured
12555          out the offset).  */
12556       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
12557         {
12558           bfd_boolean bzc = FALSE;
12559           unsigned long nextopc;
12560           unsigned long reg;
12561           bfd_vma offset;
12562
12563           /* Give up if the previous reloc was a HI16 against this symbol
12564              too.  */
12565           if (irel > internal_relocs
12566               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
12567               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
12568             continue;
12569
12570           /* Or if the next reloc is not a LO16 against this symbol.  */
12571           if (irel + 1 >= irelend
12572               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
12573               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
12574             continue;
12575
12576           /* Or if the second next reloc is a LO16 against this symbol too.  */
12577           if (irel + 2 >= irelend
12578               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
12579               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
12580             continue;
12581
12582           /* See if the LUI instruction *might* be in a branch delay slot.
12583              We check whether what looks like a 16-bit branch or jump is
12584              actually an immediate argument to a compact branch, and let
12585              it through if so.  */
12586           if (irel->r_offset >= 2
12587               && check_br16_dslot (abfd, ptr - 2)
12588               && !(irel->r_offset >= 4
12589                    && (bzc = check_relocated_bzc (abfd,
12590                                                   ptr - 4, irel->r_offset - 4,
12591                                                   internal_relocs, irelend))))
12592             continue;
12593           if (irel->r_offset >= 4
12594               && !bzc
12595               && check_br32_dslot (abfd, ptr - 4))
12596             continue;
12597
12598           reg = OP32_SREG (opcode);
12599
12600           /* We only relax adjacent instructions or ones separated with
12601              a branch or jump that has a delay slot.  The branch or jump
12602              must not fiddle with the register used to hold the address.
12603              Subtract 4 for the LUI itself.  */
12604           offset = irel[1].r_offset - irel[0].r_offset;
12605           switch (offset - 4)
12606             {
12607             case 0:
12608               break;
12609             case 2:
12610               if (check_br16 (abfd, ptr + 4, reg))
12611                 break;
12612               continue;
12613             case 4:
12614               if (check_br32 (abfd, ptr + 4, reg))
12615                 break;
12616               continue;
12617             default:
12618               continue;
12619             }
12620
12621           nextopc = bfd_get_micromips_32 (abfd, contents + irel[1].r_offset);
12622
12623           /* Give up unless the same register is used with both
12624              relocations.  */
12625           if (OP32_SREG (nextopc) != reg)
12626             continue;
12627
12628           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
12629              and rounding up to take masking of the two LSBs into account.  */
12630           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
12631
12632           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
12633           if (IS_BITSIZE (symval, 16))
12634             {
12635               /* Fix the relocation's type.  */
12636               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
12637
12638               /* Instructions using R_MICROMIPS_LO16 have the base or
12639                  source register in bits 20:16.  This register becomes $0
12640                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
12641               nextopc &= ~0x001f0000;
12642               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
12643                           contents + irel[1].r_offset);
12644             }
12645
12646           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
12647              We add 4 to take LUI deletion into account while checking
12648              the PC-relative distance.  */
12649           else if (symval % 4 == 0
12650                    && IS_BITSIZE (pcrval + 4, 25)
12651                    && MATCH (nextopc, addiu_insn)
12652                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
12653                    && OP16_VALID_REG (OP32_TREG (nextopc)))
12654             {
12655               /* Fix the relocation's type.  */
12656               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
12657
12658               /* Replace ADDIU with the ADDIUPC version.  */
12659               nextopc = (addiupc_insn.match
12660                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
12661
12662               bfd_put_micromips_32 (abfd, nextopc,
12663                                     contents + irel[1].r_offset);
12664             }
12665
12666           /* Can't do anything, give up, sigh...  */
12667           else
12668             continue;
12669
12670           /* Fix the relocation's type.  */
12671           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
12672
12673           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
12674           delcnt = 4;
12675           deloff = 0;
12676         }
12677
12678       /* Compact branch relaxation -- due to the multitude of macros
12679          employed by the compiler/assembler, compact branches are not
12680          always generated.  Obviously, this can/will be fixed elsewhere,
12681          but there is no drawback in double checking it here.  */
12682       else if (r_type == R_MICROMIPS_PC16_S1
12683                && irel->r_offset + 5 < sec->size
12684                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12685                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
12686                && MATCH (bfd_get_16 (abfd, ptr + 4), nop_insn_16))
12687         {
12688           unsigned long reg;
12689
12690           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12691
12692           /* Replace BEQZ/BNEZ with the compact version.  */
12693           opcode = (bzc_insns_32[fndopc].match
12694                     | BZC32_REG_FIELD (reg)
12695                     | (opcode & 0xffff));               /* Addend value.  */
12696
12697           bfd_put_micromips_32 (abfd, opcode, ptr);
12698
12699           /* Delete the 16-bit delay slot NOP: two bytes from
12700              irel->offset + 4.  */
12701           delcnt = 2;
12702           deloff = 4;
12703         }
12704
12705       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
12706          to check the distance from the next instruction, so subtract 2.  */
12707       else if (r_type == R_MICROMIPS_PC16_S1
12708                && IS_BITSIZE (pcrval - 2, 11)
12709                && find_match (opcode, b_insns_32) >= 0)
12710         {
12711           /* Fix the relocation's type.  */
12712           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
12713
12714           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12715           bfd_put_16 (abfd,
12716                       (b_insn_16.match
12717                        | (opcode & 0x3ff)),             /* Addend value.  */
12718                       ptr);
12719
12720           /* Delete 2 bytes from irel->r_offset + 2.  */
12721           delcnt = 2;
12722           deloff = 2;
12723         }
12724
12725       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
12726          to check the distance from the next instruction, so subtract 2.  */
12727       else if (r_type == R_MICROMIPS_PC16_S1
12728                && IS_BITSIZE (pcrval - 2, 8)
12729                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12730                     && OP16_VALID_REG (OP32_SREG (opcode)))
12731                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
12732                        && OP16_VALID_REG (OP32_TREG (opcode)))))
12733         {
12734           unsigned long reg;
12735
12736           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12737
12738           /* Fix the relocation's type.  */
12739           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
12740
12741           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12742           bfd_put_16 (abfd,
12743                       (bz_insns_16[fndopc].match
12744                        | BZ16_REG_FIELD (reg)
12745                        | (opcode & 0x7f)),              /* Addend value.  */
12746                       ptr);
12747
12748           /* Delete 2 bytes from irel->r_offset + 2.  */
12749           delcnt = 2;
12750           deloff = 2;
12751         }
12752
12753       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
12754       else if (r_type == R_MICROMIPS_26_S1
12755                && target_is_micromips_code_p
12756                && irel->r_offset + 7 < sec->size
12757                && MATCH (opcode, jal_insn_32_bd32))
12758         {
12759           unsigned long n32opc;
12760           bfd_boolean relaxed = FALSE;
12761
12762           n32opc = bfd_get_micromips_32 (abfd, ptr + 4);
12763
12764           if (MATCH (n32opc, nop_insn_32))
12765             {
12766               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
12767               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
12768
12769               relaxed = TRUE;
12770             }
12771           else if (find_match (n32opc, move_insns_32) >= 0)
12772             {
12773               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
12774               bfd_put_16 (abfd,
12775                           (move_insn_16.match
12776                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
12777                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
12778                           ptr + 4);
12779
12780               relaxed = TRUE;
12781             }
12782           /* Other 32-bit instructions relaxable to 16-bit
12783              instructions will be handled here later.  */
12784
12785           if (relaxed)
12786             {
12787               /* JAL with 32-bit delay slot that is changed to a JALS
12788                  with 16-bit delay slot.  */
12789               bfd_put_micromips_32 (abfd, jal_insn_32_bd16.match, ptr);
12790
12791               /* Delete 2 bytes from irel->r_offset + 6.  */
12792               delcnt = 2;
12793               deloff = 6;
12794             }
12795         }
12796
12797       if (delcnt != 0)
12798         {
12799           /* Note that we've changed the relocs, section contents, etc.  */
12800           elf_section_data (sec)->relocs = internal_relocs;
12801           elf_section_data (sec)->this_hdr.contents = contents;
12802           symtab_hdr->contents = (unsigned char *) isymbuf;
12803
12804           /* Delete bytes depending on the delcnt and deloff.  */
12805           if (!mips_elf_relax_delete_bytes (abfd, sec,
12806                                             irel->r_offset + deloff, delcnt))
12807             goto error_return;
12808
12809           /* That will change things, so we should relax again.
12810              Note that this is not required, and it may be slow.  */
12811           *again = TRUE;
12812         }
12813     }
12814
12815   if (isymbuf != NULL
12816       && symtab_hdr->contents != (unsigned char *) isymbuf)
12817     {
12818       if (! link_info->keep_memory)
12819         free (isymbuf);
12820       else
12821         {
12822           /* Cache the symbols for elf_link_input_bfd.  */
12823           symtab_hdr->contents = (unsigned char *) isymbuf;
12824         }
12825     }
12826
12827   if (contents != NULL
12828       && elf_section_data (sec)->this_hdr.contents != contents)
12829     {
12830       if (! link_info->keep_memory)
12831         free (contents);
12832       else
12833         {
12834           /* Cache the section contents for elf_link_input_bfd.  */
12835           elf_section_data (sec)->this_hdr.contents = contents;
12836         }
12837     }
12838
12839   if (internal_relocs != NULL
12840       && elf_section_data (sec)->relocs != internal_relocs)
12841     free (internal_relocs);
12842
12843   return TRUE;
12844
12845  error_return:
12846   if (isymbuf != NULL
12847       && symtab_hdr->contents != (unsigned char *) isymbuf)
12848     free (isymbuf);
12849   if (contents != NULL
12850       && elf_section_data (sec)->this_hdr.contents != contents)
12851     free (contents);
12852   if (internal_relocs != NULL
12853       && elf_section_data (sec)->relocs != internal_relocs)
12854     free (internal_relocs);
12855
12856   return FALSE;
12857 }
12858 \f
12859 /* Create a MIPS ELF linker hash table.  */
12860
12861 struct bfd_link_hash_table *
12862 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
12863 {
12864   struct mips_elf_link_hash_table *ret;
12865   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
12866
12867   ret = bfd_zmalloc (amt);
12868   if (ret == NULL)
12869     return NULL;
12870
12871   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
12872                                       mips_elf_link_hash_newfunc,
12873                                       sizeof (struct mips_elf_link_hash_entry),
12874                                       MIPS_ELF_DATA))
12875     {
12876       free (ret);
12877       return NULL;
12878     }
12879
12880   return &ret->root.root;
12881 }
12882
12883 /* Likewise, but indicate that the target is VxWorks.  */
12884
12885 struct bfd_link_hash_table *
12886 _bfd_mips_vxworks_link_hash_table_create (bfd *abfd)
12887 {
12888   struct bfd_link_hash_table *ret;
12889
12890   ret = _bfd_mips_elf_link_hash_table_create (abfd);
12891   if (ret)
12892     {
12893       struct mips_elf_link_hash_table *htab;
12894
12895       htab = (struct mips_elf_link_hash_table *) ret;
12896       htab->use_plts_and_copy_relocs = TRUE;
12897       htab->is_vxworks = TRUE;
12898     }
12899   return ret;
12900 }
12901
12902 /* A function that the linker calls if we are allowed to use PLTs
12903    and copy relocs.  */
12904
12905 void
12906 _bfd_mips_elf_use_plts_and_copy_relocs (struct bfd_link_info *info)
12907 {
12908   mips_elf_hash_table (info)->use_plts_and_copy_relocs = TRUE;
12909 }
12910 \f
12911 /* We need to use a special link routine to handle the .reginfo and
12912    the .mdebug sections.  We need to merge all instances of these
12913    sections together, not write them all out sequentially.  */
12914
12915 bfd_boolean
12916 _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info)
12917 {
12918   asection *o;
12919   struct bfd_link_order *p;
12920   asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec;
12921   asection *rtproc_sec;
12922   Elf32_RegInfo reginfo;
12923   struct ecoff_debug_info debug;
12924   struct mips_htab_traverse_info hti;
12925   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12926   const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap;
12927   HDRR *symhdr = &debug.symbolic_header;
12928   void *mdebug_handle = NULL;
12929   asection *s;
12930   EXTR esym;
12931   unsigned int i;
12932   bfd_size_type amt;
12933   struct mips_elf_link_hash_table *htab;
12934
12935   static const char * const secname[] =
12936   {
12937     ".text", ".init", ".fini", ".data",
12938     ".rodata", ".sdata", ".sbss", ".bss"
12939   };
12940   static const int sc[] =
12941   {
12942     scText, scInit, scFini, scData,
12943     scRData, scSData, scSBss, scBss
12944   };
12945
12946   /* Sort the dynamic symbols so that those with GOT entries come after
12947      those without.  */
12948   htab = mips_elf_hash_table (info);
12949   BFD_ASSERT (htab != NULL);
12950
12951   if (!mips_elf_sort_hash_table (abfd, info))
12952     return FALSE;
12953
12954   /* Create any scheduled LA25 stubs.  */
12955   hti.info = info;
12956   hti.output_bfd = abfd;
12957   hti.error = FALSE;
12958   htab_traverse (htab->la25_stubs, mips_elf_create_la25_stub, &hti);
12959   if (hti.error)
12960     return FALSE;
12961
12962   /* Get a value for the GP register.  */
12963   if (elf_gp (abfd) == 0)
12964     {
12965       struct bfd_link_hash_entry *h;
12966
12967       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
12968       if (h != NULL && h->type == bfd_link_hash_defined)
12969         elf_gp (abfd) = (h->u.def.value
12970                          + h->u.def.section->output_section->vma
12971                          + h->u.def.section->output_offset);
12972       else if (htab->is_vxworks
12973                && (h = bfd_link_hash_lookup (info->hash,
12974                                              "_GLOBAL_OFFSET_TABLE_",
12975                                              FALSE, FALSE, TRUE))
12976                && h->type == bfd_link_hash_defined)
12977         elf_gp (abfd) = (h->u.def.section->output_section->vma
12978                          + h->u.def.section->output_offset
12979                          + h->u.def.value);
12980       else if (info->relocatable)
12981         {
12982           bfd_vma lo = MINUS_ONE;
12983
12984           /* Find the GP-relative section with the lowest offset.  */
12985           for (o = abfd->sections; o != NULL; o = o->next)
12986             if (o->vma < lo
12987                 && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL))
12988               lo = o->vma;
12989
12990           /* And calculate GP relative to that.  */
12991           elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (info);
12992         }
12993       else
12994         {
12995           /* If the relocate_section function needs to do a reloc
12996              involving the GP value, it should make a reloc_dangerous
12997              callback to warn that GP is not defined.  */
12998         }
12999     }
13000
13001   /* Go through the sections and collect the .reginfo and .mdebug
13002      information.  */
13003   reginfo_sec = NULL;
13004   mdebug_sec = NULL;
13005   gptab_data_sec = NULL;
13006   gptab_bss_sec = NULL;
13007   for (o = abfd->sections; o != NULL; o = o->next)
13008     {
13009       if (strcmp (o->name, ".reginfo") == 0)
13010         {
13011           memset (&reginfo, 0, sizeof reginfo);
13012
13013           /* We have found the .reginfo section in the output file.
13014              Look through all the link_orders comprising it and merge
13015              the information together.  */
13016           for (p = o->map_head.link_order; p != NULL; p = p->next)
13017             {
13018               asection *input_section;
13019               bfd *input_bfd;
13020               Elf32_External_RegInfo ext;
13021               Elf32_RegInfo sub;
13022
13023               if (p->type != bfd_indirect_link_order)
13024                 {
13025                   if (p->type == bfd_data_link_order)
13026                     continue;
13027                   abort ();
13028                 }
13029
13030               input_section = p->u.indirect.section;
13031               input_bfd = input_section->owner;
13032
13033               if (! bfd_get_section_contents (input_bfd, input_section,
13034                                               &ext, 0, sizeof ext))
13035                 return FALSE;
13036
13037               bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub);
13038
13039               reginfo.ri_gprmask |= sub.ri_gprmask;
13040               reginfo.ri_cprmask[0] |= sub.ri_cprmask[0];
13041               reginfo.ri_cprmask[1] |= sub.ri_cprmask[1];
13042               reginfo.ri_cprmask[2] |= sub.ri_cprmask[2];
13043               reginfo.ri_cprmask[3] |= sub.ri_cprmask[3];
13044
13045               /* ri_gp_value is set by the function
13046                  mips_elf32_section_processing when the section is
13047                  finally written out.  */
13048
13049               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13050                  elf_link_input_bfd ignores this section.  */
13051               input_section->flags &= ~SEC_HAS_CONTENTS;
13052             }
13053
13054           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
13055           BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo));
13056
13057           /* Skip this section later on (I don't think this currently
13058              matters, but someday it might).  */
13059           o->map_head.link_order = NULL;
13060
13061           reginfo_sec = o;
13062         }
13063
13064       if (strcmp (o->name, ".mdebug") == 0)
13065         {
13066           struct extsym_info einfo;
13067           bfd_vma last;
13068
13069           /* We have found the .mdebug section in the output file.
13070              Look through all the link_orders comprising it and merge
13071              the information together.  */
13072           symhdr->magic = swap->sym_magic;
13073           /* FIXME: What should the version stamp be?  */
13074           symhdr->vstamp = 0;
13075           symhdr->ilineMax = 0;
13076           symhdr->cbLine = 0;
13077           symhdr->idnMax = 0;
13078           symhdr->ipdMax = 0;
13079           symhdr->isymMax = 0;
13080           symhdr->ioptMax = 0;
13081           symhdr->iauxMax = 0;
13082           symhdr->issMax = 0;
13083           symhdr->issExtMax = 0;
13084           symhdr->ifdMax = 0;
13085           symhdr->crfd = 0;
13086           symhdr->iextMax = 0;
13087
13088           /* We accumulate the debugging information itself in the
13089              debug_info structure.  */
13090           debug.line = NULL;
13091           debug.external_dnr = NULL;
13092           debug.external_pdr = NULL;
13093           debug.external_sym = NULL;
13094           debug.external_opt = NULL;
13095           debug.external_aux = NULL;
13096           debug.ss = NULL;
13097           debug.ssext = debug.ssext_end = NULL;
13098           debug.external_fdr = NULL;
13099           debug.external_rfd = NULL;
13100           debug.external_ext = debug.external_ext_end = NULL;
13101
13102           mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info);
13103           if (mdebug_handle == NULL)
13104             return FALSE;
13105
13106           esym.jmptbl = 0;
13107           esym.cobol_main = 0;
13108           esym.weakext = 0;
13109           esym.reserved = 0;
13110           esym.ifd = ifdNil;
13111           esym.asym.iss = issNil;
13112           esym.asym.st = stLocal;
13113           esym.asym.reserved = 0;
13114           esym.asym.index = indexNil;
13115           last = 0;
13116           for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++)
13117             {
13118               esym.asym.sc = sc[i];
13119               s = bfd_get_section_by_name (abfd, secname[i]);
13120               if (s != NULL)
13121                 {
13122                   esym.asym.value = s->vma;
13123                   last = s->vma + s->size;
13124                 }
13125               else
13126                 esym.asym.value = last;
13127               if (!bfd_ecoff_debug_one_external (abfd, &debug, swap,
13128                                                  secname[i], &esym))
13129                 return FALSE;
13130             }
13131
13132           for (p = o->map_head.link_order; p != NULL; p = p->next)
13133             {
13134               asection *input_section;
13135               bfd *input_bfd;
13136               const struct ecoff_debug_swap *input_swap;
13137               struct ecoff_debug_info input_debug;
13138               char *eraw_src;
13139               char *eraw_end;
13140
13141               if (p->type != bfd_indirect_link_order)
13142                 {
13143                   if (p->type == bfd_data_link_order)
13144                     continue;
13145                   abort ();
13146                 }
13147
13148               input_section = p->u.indirect.section;
13149               input_bfd = input_section->owner;
13150
13151               if (!is_mips_elf (input_bfd))
13152                 {
13153                   /* I don't know what a non MIPS ELF bfd would be
13154                      doing with a .mdebug section, but I don't really
13155                      want to deal with it.  */
13156                   continue;
13157                 }
13158
13159               input_swap = (get_elf_backend_data (input_bfd)
13160                             ->elf_backend_ecoff_debug_swap);
13161
13162               BFD_ASSERT (p->size == input_section->size);
13163
13164               /* The ECOFF linking code expects that we have already
13165                  read in the debugging information and set up an
13166                  ecoff_debug_info structure, so we do that now.  */
13167               if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section,
13168                                                    &input_debug))
13169                 return FALSE;
13170
13171               if (! (bfd_ecoff_debug_accumulate
13172                      (mdebug_handle, abfd, &debug, swap, input_bfd,
13173                       &input_debug, input_swap, info)))
13174                 return FALSE;
13175
13176               /* Loop through the external symbols.  For each one with
13177                  interesting information, try to find the symbol in
13178                  the linker global hash table and save the information
13179                  for the output external symbols.  */
13180               eraw_src = input_debug.external_ext;
13181               eraw_end = (eraw_src
13182                           + (input_debug.symbolic_header.iextMax
13183                              * input_swap->external_ext_size));
13184               for (;
13185                    eraw_src < eraw_end;
13186                    eraw_src += input_swap->external_ext_size)
13187                 {
13188                   EXTR ext;
13189                   const char *name;
13190                   struct mips_elf_link_hash_entry *h;
13191
13192                   (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext);
13193                   if (ext.asym.sc == scNil
13194                       || ext.asym.sc == scUndefined
13195                       || ext.asym.sc == scSUndefined)
13196                     continue;
13197
13198                   name = input_debug.ssext + ext.asym.iss;
13199                   h = mips_elf_link_hash_lookup (mips_elf_hash_table (info),
13200                                                  name, FALSE, FALSE, TRUE);
13201                   if (h == NULL || h->esym.ifd != -2)
13202                     continue;
13203
13204                   if (ext.ifd != -1)
13205                     {
13206                       BFD_ASSERT (ext.ifd
13207                                   < input_debug.symbolic_header.ifdMax);
13208                       ext.ifd = input_debug.ifdmap[ext.ifd];
13209                     }
13210
13211                   h->esym = ext;
13212                 }
13213
13214               /* Free up the information we just read.  */
13215               free (input_debug.line);
13216               free (input_debug.external_dnr);
13217               free (input_debug.external_pdr);
13218               free (input_debug.external_sym);
13219               free (input_debug.external_opt);
13220               free (input_debug.external_aux);
13221               free (input_debug.ss);
13222               free (input_debug.ssext);
13223               free (input_debug.external_fdr);
13224               free (input_debug.external_rfd);
13225               free (input_debug.external_ext);
13226
13227               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13228                  elf_link_input_bfd ignores this section.  */
13229               input_section->flags &= ~SEC_HAS_CONTENTS;
13230             }
13231
13232           if (SGI_COMPAT (abfd) && info->shared)
13233             {
13234               /* Create .rtproc section.  */
13235               rtproc_sec = bfd_get_linker_section (abfd, ".rtproc");
13236               if (rtproc_sec == NULL)
13237                 {
13238                   flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
13239                                     | SEC_LINKER_CREATED | SEC_READONLY);
13240
13241                   rtproc_sec = bfd_make_section_anyway_with_flags (abfd,
13242                                                                    ".rtproc",
13243                                                                    flags);
13244                   if (rtproc_sec == NULL
13245                       || ! bfd_set_section_alignment (abfd, rtproc_sec, 4))
13246                     return FALSE;
13247                 }
13248
13249               if (! mips_elf_create_procedure_table (mdebug_handle, abfd,
13250                                                      info, rtproc_sec,
13251                                                      &debug))
13252                 return FALSE;
13253             }
13254
13255           /* Build the external symbol information.  */
13256           einfo.abfd = abfd;
13257           einfo.info = info;
13258           einfo.debug = &debug;
13259           einfo.swap = swap;
13260           einfo.failed = FALSE;
13261           mips_elf_link_hash_traverse (mips_elf_hash_table (info),
13262                                        mips_elf_output_extsym, &einfo);
13263           if (einfo.failed)
13264             return FALSE;
13265
13266           /* Set the size of the .mdebug section.  */
13267           o->size = bfd_ecoff_debug_size (abfd, &debug, swap);
13268
13269           /* Skip this section later on (I don't think this currently
13270              matters, but someday it might).  */
13271           o->map_head.link_order = NULL;
13272
13273           mdebug_sec = o;
13274         }
13275
13276       if (CONST_STRNEQ (o->name, ".gptab."))
13277         {
13278           const char *subname;
13279           unsigned int c;
13280           Elf32_gptab *tab;
13281           Elf32_External_gptab *ext_tab;
13282           unsigned int j;
13283
13284           /* The .gptab.sdata and .gptab.sbss sections hold
13285              information describing how the small data area would
13286              change depending upon the -G switch.  These sections
13287              not used in executables files.  */
13288           if (! info->relocatable)
13289             {
13290               for (p = o->map_head.link_order; p != NULL; p = p->next)
13291                 {
13292                   asection *input_section;
13293
13294                   if (p->type != bfd_indirect_link_order)
13295                     {
13296                       if (p->type == bfd_data_link_order)
13297                         continue;
13298                       abort ();
13299                     }
13300
13301                   input_section = p->u.indirect.section;
13302
13303                   /* Hack: reset the SEC_HAS_CONTENTS flag so that
13304                      elf_link_input_bfd ignores this section.  */
13305                   input_section->flags &= ~SEC_HAS_CONTENTS;
13306                 }
13307
13308               /* Skip this section later on (I don't think this
13309                  currently matters, but someday it might).  */
13310               o->map_head.link_order = NULL;
13311
13312               /* Really remove the section.  */
13313               bfd_section_list_remove (abfd, o);
13314               --abfd->section_count;
13315
13316               continue;
13317             }
13318
13319           /* There is one gptab for initialized data, and one for
13320              uninitialized data.  */
13321           if (strcmp (o->name, ".gptab.sdata") == 0)
13322             gptab_data_sec = o;
13323           else if (strcmp (o->name, ".gptab.sbss") == 0)
13324             gptab_bss_sec = o;
13325           else
13326             {
13327               (*_bfd_error_handler)
13328                 (_("%s: illegal section name `%s'"),
13329                  bfd_get_filename (abfd), o->name);
13330               bfd_set_error (bfd_error_nonrepresentable_section);
13331               return FALSE;
13332             }
13333
13334           /* The linker script always combines .gptab.data and
13335              .gptab.sdata into .gptab.sdata, and likewise for
13336              .gptab.bss and .gptab.sbss.  It is possible that there is
13337              no .sdata or .sbss section in the output file, in which
13338              case we must change the name of the output section.  */
13339           subname = o->name + sizeof ".gptab" - 1;
13340           if (bfd_get_section_by_name (abfd, subname) == NULL)
13341             {
13342               if (o == gptab_data_sec)
13343                 o->name = ".gptab.data";
13344               else
13345                 o->name = ".gptab.bss";
13346               subname = o->name + sizeof ".gptab" - 1;
13347               BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL);
13348             }
13349
13350           /* Set up the first entry.  */
13351           c = 1;
13352           amt = c * sizeof (Elf32_gptab);
13353           tab = bfd_malloc (amt);
13354           if (tab == NULL)
13355             return FALSE;
13356           tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd);
13357           tab[0].gt_header.gt_unused = 0;
13358
13359           /* Combine the input sections.  */
13360           for (p = o->map_head.link_order; p != NULL; p = p->next)
13361             {
13362               asection *input_section;
13363               bfd *input_bfd;
13364               bfd_size_type size;
13365               unsigned long last;
13366               bfd_size_type gpentry;
13367
13368               if (p->type != bfd_indirect_link_order)
13369                 {
13370                   if (p->type == bfd_data_link_order)
13371                     continue;
13372                   abort ();
13373                 }
13374
13375               input_section = p->u.indirect.section;
13376               input_bfd = input_section->owner;
13377
13378               /* Combine the gptab entries for this input section one
13379                  by one.  We know that the input gptab entries are
13380                  sorted by ascending -G value.  */
13381               size = input_section->size;
13382               last = 0;
13383               for (gpentry = sizeof (Elf32_External_gptab);
13384                    gpentry < size;
13385                    gpentry += sizeof (Elf32_External_gptab))
13386                 {
13387                   Elf32_External_gptab ext_gptab;
13388                   Elf32_gptab int_gptab;
13389                   unsigned long val;
13390                   unsigned long add;
13391                   bfd_boolean exact;
13392                   unsigned int look;
13393
13394                   if (! (bfd_get_section_contents
13395                          (input_bfd, input_section, &ext_gptab, gpentry,
13396                           sizeof (Elf32_External_gptab))))
13397                     {
13398                       free (tab);
13399                       return FALSE;
13400                     }
13401
13402                   bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab,
13403                                                 &int_gptab);
13404                   val = int_gptab.gt_entry.gt_g_value;
13405                   add = int_gptab.gt_entry.gt_bytes - last;
13406
13407                   exact = FALSE;
13408                   for (look = 1; look < c; look++)
13409                     {
13410                       if (tab[look].gt_entry.gt_g_value >= val)
13411                         tab[look].gt_entry.gt_bytes += add;
13412
13413                       if (tab[look].gt_entry.gt_g_value == val)
13414                         exact = TRUE;
13415                     }
13416
13417                   if (! exact)
13418                     {
13419                       Elf32_gptab *new_tab;
13420                       unsigned int max;
13421
13422                       /* We need a new table entry.  */
13423                       amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab);
13424                       new_tab = bfd_realloc (tab, amt);
13425                       if (new_tab == NULL)
13426                         {
13427                           free (tab);
13428                           return FALSE;
13429                         }
13430                       tab = new_tab;
13431                       tab[c].gt_entry.gt_g_value = val;
13432                       tab[c].gt_entry.gt_bytes = add;
13433
13434                       /* Merge in the size for the next smallest -G
13435                          value, since that will be implied by this new
13436                          value.  */
13437                       max = 0;
13438                       for (look = 1; look < c; look++)
13439                         {
13440                           if (tab[look].gt_entry.gt_g_value < val
13441                               && (max == 0
13442                                   || (tab[look].gt_entry.gt_g_value
13443                                       > tab[max].gt_entry.gt_g_value)))
13444                             max = look;
13445                         }
13446                       if (max != 0)
13447                         tab[c].gt_entry.gt_bytes +=
13448                           tab[max].gt_entry.gt_bytes;
13449
13450                       ++c;
13451                     }
13452
13453                   last = int_gptab.gt_entry.gt_bytes;
13454                 }
13455
13456               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13457                  elf_link_input_bfd ignores this section.  */
13458               input_section->flags &= ~SEC_HAS_CONTENTS;
13459             }
13460
13461           /* The table must be sorted by -G value.  */
13462           if (c > 2)
13463             qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare);
13464
13465           /* Swap out the table.  */
13466           amt = (bfd_size_type) c * sizeof (Elf32_External_gptab);
13467           ext_tab = bfd_alloc (abfd, amt);
13468           if (ext_tab == NULL)
13469             {
13470               free (tab);
13471               return FALSE;
13472             }
13473
13474           for (j = 0; j < c; j++)
13475             bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j);
13476           free (tab);
13477
13478           o->size = c * sizeof (Elf32_External_gptab);
13479           o->contents = (bfd_byte *) ext_tab;
13480
13481           /* Skip this section later on (I don't think this currently
13482              matters, but someday it might).  */
13483           o->map_head.link_order = NULL;
13484         }
13485     }
13486
13487   /* Invoke the regular ELF backend linker to do all the work.  */
13488   if (!bfd_elf_final_link (abfd, info))
13489     return FALSE;
13490
13491   /* Now write out the computed sections.  */
13492
13493   if (reginfo_sec != NULL)
13494     {
13495       Elf32_External_RegInfo ext;
13496
13497       bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext);
13498       if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext))
13499         return FALSE;
13500     }
13501
13502   if (mdebug_sec != NULL)
13503     {
13504       BFD_ASSERT (abfd->output_has_begun);
13505       if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug,
13506                                                swap, info,
13507                                                mdebug_sec->filepos))
13508         return FALSE;
13509
13510       bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info);
13511     }
13512
13513   if (gptab_data_sec != NULL)
13514     {
13515       if (! bfd_set_section_contents (abfd, gptab_data_sec,
13516                                       gptab_data_sec->contents,
13517                                       0, gptab_data_sec->size))
13518         return FALSE;
13519     }
13520
13521   if (gptab_bss_sec != NULL)
13522     {
13523       if (! bfd_set_section_contents (abfd, gptab_bss_sec,
13524                                       gptab_bss_sec->contents,
13525                                       0, gptab_bss_sec->size))
13526         return FALSE;
13527     }
13528
13529   if (SGI_COMPAT (abfd))
13530     {
13531       rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
13532       if (rtproc_sec != NULL)
13533         {
13534           if (! bfd_set_section_contents (abfd, rtproc_sec,
13535                                           rtproc_sec->contents,
13536                                           0, rtproc_sec->size))
13537             return FALSE;
13538         }
13539     }
13540
13541   return TRUE;
13542 }
13543 \f
13544 /* Structure for saying that BFD machine EXTENSION extends BASE.  */
13545
13546 struct mips_mach_extension {
13547   unsigned long extension, base;
13548 };
13549
13550
13551 /* An array describing how BFD machines relate to one another.  The entries
13552    are ordered topologically with MIPS I extensions listed last.  */
13553
13554 static const struct mips_mach_extension mips_mach_extensions[] = {
13555   /* MIPS64r2 extensions.  */
13556   { bfd_mach_mips_octeon2, bfd_mach_mips_octeonp },
13557   { bfd_mach_mips_octeonp, bfd_mach_mips_octeon },
13558   { bfd_mach_mips_octeon, bfd_mach_mipsisa64r2 },
13559
13560   /* MIPS64 extensions.  */
13561   { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 },
13562   { bfd_mach_mips_sb1, bfd_mach_mipsisa64 },
13563   { bfd_mach_mips_xlr, bfd_mach_mipsisa64 },
13564   { bfd_mach_mips_loongson_3a, bfd_mach_mipsisa64 },
13565
13566   /* MIPS V extensions.  */
13567   { bfd_mach_mipsisa64, bfd_mach_mips5 },
13568
13569   /* R10000 extensions.  */
13570   { bfd_mach_mips12000, bfd_mach_mips10000 },
13571   { bfd_mach_mips14000, bfd_mach_mips10000 },
13572   { bfd_mach_mips16000, bfd_mach_mips10000 },
13573
13574   /* R5000 extensions.  Note: the vr5500 ISA is an extension of the core
13575      vr5400 ISA, but doesn't include the multimedia stuff.  It seems
13576      better to allow vr5400 and vr5500 code to be merged anyway, since
13577      many libraries will just use the core ISA.  Perhaps we could add
13578      some sort of ASE flag if this ever proves a problem.  */
13579   { bfd_mach_mips5500, bfd_mach_mips5400 },
13580   { bfd_mach_mips5400, bfd_mach_mips5000 },
13581
13582   /* MIPS IV extensions.  */
13583   { bfd_mach_mips5, bfd_mach_mips8000 },
13584   { bfd_mach_mips10000, bfd_mach_mips8000 },
13585   { bfd_mach_mips5000, bfd_mach_mips8000 },
13586   { bfd_mach_mips7000, bfd_mach_mips8000 },
13587   { bfd_mach_mips9000, bfd_mach_mips8000 },
13588
13589   /* VR4100 extensions.  */
13590   { bfd_mach_mips4120, bfd_mach_mips4100 },
13591   { bfd_mach_mips4111, bfd_mach_mips4100 },
13592
13593   /* MIPS III extensions.  */
13594   { bfd_mach_mips_loongson_2e, bfd_mach_mips4000 },
13595   { bfd_mach_mips_loongson_2f, bfd_mach_mips4000 },
13596   { bfd_mach_mips8000, bfd_mach_mips4000 },
13597   { bfd_mach_mips4650, bfd_mach_mips4000 },
13598   { bfd_mach_mips4600, bfd_mach_mips4000 },
13599   { bfd_mach_mips4400, bfd_mach_mips4000 },
13600   { bfd_mach_mips4300, bfd_mach_mips4000 },
13601   { bfd_mach_mips4100, bfd_mach_mips4000 },
13602   { bfd_mach_mips4010, bfd_mach_mips4000 },
13603   { bfd_mach_mips5900, bfd_mach_mips4000 },
13604
13605   /* MIPS32 extensions.  */
13606   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
13607
13608   /* MIPS II extensions.  */
13609   { bfd_mach_mips4000, bfd_mach_mips6000 },
13610   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
13611
13612   /* MIPS I extensions.  */
13613   { bfd_mach_mips6000, bfd_mach_mips3000 },
13614   { bfd_mach_mips3900, bfd_mach_mips3000 }
13615 };
13616
13617
13618 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
13619
13620 static bfd_boolean
13621 mips_mach_extends_p (unsigned long base, unsigned long extension)
13622 {
13623   size_t i;
13624
13625   if (extension == base)
13626     return TRUE;
13627
13628   if (base == bfd_mach_mipsisa32
13629       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
13630     return TRUE;
13631
13632   if (base == bfd_mach_mipsisa32r2
13633       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
13634     return TRUE;
13635
13636   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
13637     if (extension == mips_mach_extensions[i].extension)
13638       {
13639         extension = mips_mach_extensions[i].base;
13640         if (extension == base)
13641           return TRUE;
13642       }
13643
13644   return FALSE;
13645 }
13646
13647
13648 /* Return true if the given ELF header flags describe a 32-bit binary.  */
13649
13650 static bfd_boolean
13651 mips_32bit_flags_p (flagword flags)
13652 {
13653   return ((flags & EF_MIPS_32BITMODE) != 0
13654           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
13655           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
13656           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
13657           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
13658           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
13659           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2);
13660 }
13661
13662
13663 /* Merge object attributes from IBFD into OBFD.  Raise an error if
13664    there are conflicting attributes.  */
13665 static bfd_boolean
13666 mips_elf_merge_obj_attributes (bfd *ibfd, bfd *obfd)
13667 {
13668   obj_attribute *in_attr;
13669   obj_attribute *out_attr;
13670   bfd *abi_fp_bfd;
13671
13672   abi_fp_bfd = mips_elf_tdata (obfd)->abi_fp_bfd;
13673   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
13674   if (!abi_fp_bfd && in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13675     mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
13676
13677   if (!elf_known_obj_attributes_proc (obfd)[0].i)
13678     {
13679       /* This is the first object.  Copy the attributes.  */
13680       _bfd_elf_copy_obj_attributes (ibfd, obfd);
13681
13682       /* Use the Tag_null value to indicate the attributes have been
13683          initialized.  */
13684       elf_known_obj_attributes_proc (obfd)[0].i = 1;
13685
13686       return TRUE;
13687     }
13688
13689   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
13690      non-conflicting ones.  */
13691   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
13692   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
13693     {
13694       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
13695       if (out_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
13696         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
13697       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13698         switch (out_attr[Tag_GNU_MIPS_ABI_FP].i)
13699           {
13700           case 1:
13701             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13702               {
13703               case 2:
13704                 _bfd_error_handler
13705                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13706                    obfd, abi_fp_bfd, ibfd, "-mdouble-float", "-msingle-float");
13707                 break;
13708
13709               case 3:
13710                 _bfd_error_handler
13711                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13712                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13713                 break;
13714
13715               case 4:
13716                 _bfd_error_handler
13717                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13718                    obfd, abi_fp_bfd, ibfd,
13719                    "-mdouble-float", "-mips32r2 -mfp64");
13720                 break;
13721
13722               default:
13723                 _bfd_error_handler
13724                   (_("Warning: %B uses %s (set by %B), "
13725                      "%B uses unknown floating point ABI %d"),
13726                    obfd, abi_fp_bfd, ibfd,
13727                    "-mdouble-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13728                 break;
13729               }
13730             break;
13731
13732           case 2:
13733             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13734               {
13735               case 1:
13736                 _bfd_error_handler
13737                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13738                    obfd, abi_fp_bfd, ibfd, "-msingle-float", "-mdouble-float");
13739                 break;
13740
13741               case 3:
13742                 _bfd_error_handler
13743                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13744                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13745                 break;
13746
13747               case 4:
13748                 _bfd_error_handler
13749                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13750                    obfd, abi_fp_bfd, ibfd,
13751                    "-msingle-float", "-mips32r2 -mfp64");
13752                 break;
13753
13754               default:
13755                 _bfd_error_handler
13756                   (_("Warning: %B uses %s (set by %B), "
13757                      "%B uses unknown floating point ABI %d"),
13758                    obfd, abi_fp_bfd, ibfd,
13759                    "-msingle-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13760                 break;
13761               }
13762             break;
13763
13764           case 3:
13765             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13766               {
13767               case 1:
13768               case 2:
13769               case 4:
13770                 _bfd_error_handler
13771                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13772                    obfd, abi_fp_bfd, ibfd, "-msoft-float", "-mhard-float");
13773                 break;
13774
13775               default:
13776                 _bfd_error_handler
13777                   (_("Warning: %B uses %s (set by %B), "
13778                      "%B uses unknown floating point ABI %d"),
13779                    obfd, abi_fp_bfd, ibfd,
13780                    "-msoft-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13781                 break;
13782               }
13783             break;
13784
13785           case 4:
13786             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13787               {
13788               case 1:
13789                 _bfd_error_handler
13790                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13791                    obfd, abi_fp_bfd, ibfd,
13792                    "-mips32r2 -mfp64", "-mdouble-float");
13793                 break;
13794
13795               case 2:
13796                 _bfd_error_handler
13797                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13798                    obfd, abi_fp_bfd, ibfd,
13799                    "-mips32r2 -mfp64", "-msingle-float");
13800                 break;
13801
13802               case 3:
13803                 _bfd_error_handler
13804                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13805                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13806                 break;
13807
13808               default:
13809                 _bfd_error_handler
13810                   (_("Warning: %B uses %s (set by %B), "
13811                      "%B uses unknown floating point ABI %d"),
13812                    obfd, abi_fp_bfd, ibfd,
13813                    "-mips32r2 -mfp64", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13814                 break;
13815               }
13816             break;
13817
13818           default:
13819             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13820               {
13821               case 1:
13822                 _bfd_error_handler
13823                   (_("Warning: %B uses unknown floating point ABI %d "
13824                      "(set by %B), %B uses %s"),
13825                    obfd, abi_fp_bfd, ibfd,
13826                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mdouble-float");
13827                 break;
13828
13829               case 2:
13830                 _bfd_error_handler
13831                   (_("Warning: %B uses unknown floating point ABI %d "
13832                      "(set by %B), %B uses %s"),
13833                    obfd, abi_fp_bfd, ibfd,
13834                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msingle-float");
13835                 break;
13836
13837               case 3:
13838                 _bfd_error_handler
13839                   (_("Warning: %B uses unknown floating point ABI %d "
13840                      "(set by %B), %B uses %s"),
13841                    obfd, abi_fp_bfd, ibfd,
13842                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msoft-float");
13843                 break;
13844
13845               case 4:
13846                 _bfd_error_handler
13847                   (_("Warning: %B uses unknown floating point ABI %d "
13848                      "(set by %B), %B uses %s"),
13849                    obfd, abi_fp_bfd, ibfd,
13850                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mips32r2 -mfp64");
13851                 break;
13852
13853               default:
13854                 _bfd_error_handler
13855                   (_("Warning: %B uses unknown floating point ABI %d "
13856                      "(set by %B), %B uses unknown floating point ABI %d"),
13857                    obfd, abi_fp_bfd, ibfd,
13858                    out_attr[Tag_GNU_MIPS_ABI_FP].i,
13859                    in_attr[Tag_GNU_MIPS_ABI_FP].i);
13860                 break;
13861               }
13862             break;
13863           }
13864     }
13865
13866   /* Merge Tag_compatibility attributes and any common GNU ones.  */
13867   _bfd_elf_merge_object_attributes (ibfd, obfd);
13868
13869   return TRUE;
13870 }
13871
13872 /* Merge backend specific data from an object file to the output
13873    object file when linking.  */
13874
13875 bfd_boolean
13876 _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
13877 {
13878   flagword old_flags;
13879   flagword new_flags;
13880   bfd_boolean ok;
13881   bfd_boolean null_input_bfd = TRUE;
13882   asection *sec;
13883
13884   /* Check if we have the same endianness.  */
13885   if (! _bfd_generic_verify_endian_match (ibfd, obfd))
13886     {
13887       (*_bfd_error_handler)
13888         (_("%B: endianness incompatible with that of the selected emulation"),
13889          ibfd);
13890       return FALSE;
13891     }
13892
13893   if (!is_mips_elf (ibfd) || !is_mips_elf (obfd))
13894     return TRUE;
13895
13896   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
13897     {
13898       (*_bfd_error_handler)
13899         (_("%B: ABI is incompatible with that of the selected emulation"),
13900          ibfd);
13901       return FALSE;
13902     }
13903
13904   if (!mips_elf_merge_obj_attributes (ibfd, obfd))
13905     return FALSE;
13906
13907   new_flags = elf_elfheader (ibfd)->e_flags;
13908   elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER;
13909   old_flags = elf_elfheader (obfd)->e_flags;
13910
13911   if (! elf_flags_init (obfd))
13912     {
13913       elf_flags_init (obfd) = TRUE;
13914       elf_elfheader (obfd)->e_flags = new_flags;
13915       elf_elfheader (obfd)->e_ident[EI_CLASS]
13916         = elf_elfheader (ibfd)->e_ident[EI_CLASS];
13917
13918       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
13919           && (bfd_get_arch_info (obfd)->the_default
13920               || mips_mach_extends_p (bfd_get_mach (obfd),
13921                                       bfd_get_mach (ibfd))))
13922         {
13923           if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
13924                                    bfd_get_mach (ibfd)))
13925             return FALSE;
13926         }
13927
13928       return TRUE;
13929     }
13930
13931   /* Check flag compatibility.  */
13932
13933   new_flags &= ~EF_MIPS_NOREORDER;
13934   old_flags &= ~EF_MIPS_NOREORDER;
13935
13936   /* Some IRIX 6 BSD-compatibility objects have this bit set.  It
13937      doesn't seem to matter.  */
13938   new_flags &= ~EF_MIPS_XGOT;
13939   old_flags &= ~EF_MIPS_XGOT;
13940
13941   /* MIPSpro generates ucode info in n64 objects.  Again, we should
13942      just be able to ignore this.  */
13943   new_flags &= ~EF_MIPS_UCODE;
13944   old_flags &= ~EF_MIPS_UCODE;
13945
13946   /* DSOs should only be linked with CPIC code.  */
13947   if ((ibfd->flags & DYNAMIC) != 0)
13948     new_flags |= EF_MIPS_PIC | EF_MIPS_CPIC;
13949
13950   if (new_flags == old_flags)
13951     return TRUE;
13952
13953   /* Check to see if the input BFD actually contains any sections.
13954      If not, its flags may not have been initialised either, but it cannot
13955      actually cause any incompatibility.  */
13956   for (sec = ibfd->sections; sec != NULL; sec = sec->next)
13957     {
13958       /* Ignore synthetic sections and empty .text, .data and .bss sections
13959          which are automatically generated by gas.  Also ignore fake
13960          (s)common sections, since merely defining a common symbol does
13961          not affect compatibility.  */
13962       if ((sec->flags & SEC_IS_COMMON) == 0
13963           && strcmp (sec->name, ".reginfo")
13964           && strcmp (sec->name, ".mdebug")
13965           && (sec->size != 0
13966               || (strcmp (sec->name, ".text")
13967                   && strcmp (sec->name, ".data")
13968                   && strcmp (sec->name, ".bss"))))
13969         {
13970           null_input_bfd = FALSE;
13971           break;
13972         }
13973     }
13974   if (null_input_bfd)
13975     return TRUE;
13976
13977   ok = TRUE;
13978
13979   if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)
13980       != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0))
13981     {
13982       (*_bfd_error_handler)
13983         (_("%B: warning: linking abicalls files with non-abicalls files"),
13984          ibfd);
13985       ok = TRUE;
13986     }
13987
13988   if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC))
13989     elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC;
13990   if (! (new_flags & EF_MIPS_PIC))
13991     elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC;
13992
13993   new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13994   old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13995
13996   /* Compare the ISAs.  */
13997   if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags))
13998     {
13999       (*_bfd_error_handler)
14000         (_("%B: linking 32-bit code with 64-bit code"),
14001          ibfd);
14002       ok = FALSE;
14003     }
14004   else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd)))
14005     {
14006       /* OBFD's ISA isn't the same as, or an extension of, IBFD's.  */
14007       if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd)))
14008         {
14009           /* Copy the architecture info from IBFD to OBFD.  Also copy
14010              the 32-bit flag (if set) so that we continue to recognise
14011              OBFD as a 32-bit binary.  */
14012           bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd));
14013           elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
14014           elf_elfheader (obfd)->e_flags
14015             |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14016
14017           /* Copy across the ABI flags if OBFD doesn't use them
14018              and if that was what caused us to treat IBFD as 32-bit.  */
14019           if ((old_flags & EF_MIPS_ABI) == 0
14020               && mips_32bit_flags_p (new_flags)
14021               && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI))
14022             elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI;
14023         }
14024       else
14025         {
14026           /* The ISAs aren't compatible.  */
14027           (*_bfd_error_handler)
14028             (_("%B: linking %s module with previous %s modules"),
14029              ibfd,
14030              bfd_printable_name (ibfd),
14031              bfd_printable_name (obfd));
14032           ok = FALSE;
14033         }
14034     }
14035
14036   new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14037   old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
14038
14039   /* Compare ABIs.  The 64-bit ABI does not use EF_MIPS_ABI.  But, it
14040      does set EI_CLASS differently from any 32-bit ABI.  */
14041   if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI)
14042       || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14043           != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14044     {
14045       /* Only error if both are set (to different values).  */
14046       if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI))
14047           || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14048               != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14049         {
14050           (*_bfd_error_handler)
14051             (_("%B: ABI mismatch: linking %s module with previous %s modules"),
14052              ibfd,
14053              elf_mips_abi_name (ibfd),
14054              elf_mips_abi_name (obfd));
14055           ok = FALSE;
14056         }
14057       new_flags &= ~EF_MIPS_ABI;
14058       old_flags &= ~EF_MIPS_ABI;
14059     }
14060
14061   /* Compare ASEs.  Forbid linking MIPS16 and microMIPS ASE modules together
14062      and allow arbitrary mixing of the remaining ASEs (retain the union).  */
14063   if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE))
14064     {
14065       int old_micro = old_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14066       int new_micro = new_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14067       int old_m16 = old_flags & EF_MIPS_ARCH_ASE_M16;
14068       int new_m16 = new_flags & EF_MIPS_ARCH_ASE_M16;
14069       int micro_mis = old_m16 && new_micro;
14070       int m16_mis = old_micro && new_m16;
14071
14072       if (m16_mis || micro_mis)
14073         {
14074           (*_bfd_error_handler)
14075             (_("%B: ASE mismatch: linking %s module with previous %s modules"),
14076              ibfd,
14077              m16_mis ? "MIPS16" : "microMIPS",
14078              m16_mis ? "microMIPS" : "MIPS16");
14079           ok = FALSE;
14080         }
14081
14082       elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE;
14083
14084       new_flags &= ~ EF_MIPS_ARCH_ASE;
14085       old_flags &= ~ EF_MIPS_ARCH_ASE;
14086     }
14087
14088   /* Warn about any other mismatches */
14089   if (new_flags != old_flags)
14090     {
14091       (*_bfd_error_handler)
14092         (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"),
14093          ibfd, (unsigned long) new_flags,
14094          (unsigned long) old_flags);
14095       ok = FALSE;
14096     }
14097
14098   if (! ok)
14099     {
14100       bfd_set_error (bfd_error_bad_value);
14101       return FALSE;
14102     }
14103
14104   return TRUE;
14105 }
14106
14107 /* Function to keep MIPS specific file flags like as EF_MIPS_PIC.  */
14108
14109 bfd_boolean
14110 _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags)
14111 {
14112   BFD_ASSERT (!elf_flags_init (abfd)
14113               || elf_elfheader (abfd)->e_flags == flags);
14114
14115   elf_elfheader (abfd)->e_flags = flags;
14116   elf_flags_init (abfd) = TRUE;
14117   return TRUE;
14118 }
14119
14120 char *
14121 _bfd_mips_elf_get_target_dtag (bfd_vma dtag)
14122 {
14123   switch (dtag)
14124     {
14125     default: return "";
14126     case DT_MIPS_RLD_VERSION:
14127       return "MIPS_RLD_VERSION";
14128     case DT_MIPS_TIME_STAMP:
14129       return "MIPS_TIME_STAMP";
14130     case DT_MIPS_ICHECKSUM:
14131       return "MIPS_ICHECKSUM";
14132     case DT_MIPS_IVERSION:
14133       return "MIPS_IVERSION";
14134     case DT_MIPS_FLAGS:
14135       return "MIPS_FLAGS";
14136     case DT_MIPS_BASE_ADDRESS:
14137       return "MIPS_BASE_ADDRESS";
14138     case DT_MIPS_MSYM:
14139       return "MIPS_MSYM";
14140     case DT_MIPS_CONFLICT:
14141       return "MIPS_CONFLICT";
14142     case DT_MIPS_LIBLIST:
14143       return "MIPS_LIBLIST";
14144     case DT_MIPS_LOCAL_GOTNO:
14145       return "MIPS_LOCAL_GOTNO";
14146     case DT_MIPS_CONFLICTNO:
14147       return "MIPS_CONFLICTNO";
14148     case DT_MIPS_LIBLISTNO:
14149       return "MIPS_LIBLISTNO";
14150     case DT_MIPS_SYMTABNO:
14151       return "MIPS_SYMTABNO";
14152     case DT_MIPS_UNREFEXTNO:
14153       return "MIPS_UNREFEXTNO";
14154     case DT_MIPS_GOTSYM:
14155       return "MIPS_GOTSYM";
14156     case DT_MIPS_HIPAGENO:
14157       return "MIPS_HIPAGENO";
14158     case DT_MIPS_RLD_MAP:
14159       return "MIPS_RLD_MAP";
14160     case DT_MIPS_DELTA_CLASS:
14161       return "MIPS_DELTA_CLASS";
14162     case DT_MIPS_DELTA_CLASS_NO:
14163       return "MIPS_DELTA_CLASS_NO";
14164     case DT_MIPS_DELTA_INSTANCE:
14165       return "MIPS_DELTA_INSTANCE";
14166     case DT_MIPS_DELTA_INSTANCE_NO:
14167       return "MIPS_DELTA_INSTANCE_NO";
14168     case DT_MIPS_DELTA_RELOC:
14169       return "MIPS_DELTA_RELOC";
14170     case DT_MIPS_DELTA_RELOC_NO:
14171       return "MIPS_DELTA_RELOC_NO";
14172     case DT_MIPS_DELTA_SYM:
14173       return "MIPS_DELTA_SYM";
14174     case DT_MIPS_DELTA_SYM_NO:
14175       return "MIPS_DELTA_SYM_NO";
14176     case DT_MIPS_DELTA_CLASSSYM:
14177       return "MIPS_DELTA_CLASSSYM";
14178     case DT_MIPS_DELTA_CLASSSYM_NO:
14179       return "MIPS_DELTA_CLASSSYM_NO";
14180     case DT_MIPS_CXX_FLAGS:
14181       return "MIPS_CXX_FLAGS";
14182     case DT_MIPS_PIXIE_INIT:
14183       return "MIPS_PIXIE_INIT";
14184     case DT_MIPS_SYMBOL_LIB:
14185       return "MIPS_SYMBOL_LIB";
14186     case DT_MIPS_LOCALPAGE_GOTIDX:
14187       return "MIPS_LOCALPAGE_GOTIDX";
14188     case DT_MIPS_LOCAL_GOTIDX:
14189       return "MIPS_LOCAL_GOTIDX";
14190     case DT_MIPS_HIDDEN_GOTIDX:
14191       return "MIPS_HIDDEN_GOTIDX";
14192     case DT_MIPS_PROTECTED_GOTIDX:
14193       return "MIPS_PROTECTED_GOT_IDX";
14194     case DT_MIPS_OPTIONS:
14195       return "MIPS_OPTIONS";
14196     case DT_MIPS_INTERFACE:
14197       return "MIPS_INTERFACE";
14198     case DT_MIPS_DYNSTR_ALIGN:
14199       return "DT_MIPS_DYNSTR_ALIGN";
14200     case DT_MIPS_INTERFACE_SIZE:
14201       return "DT_MIPS_INTERFACE_SIZE";
14202     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
14203       return "DT_MIPS_RLD_TEXT_RESOLVE_ADDR";
14204     case DT_MIPS_PERF_SUFFIX:
14205       return "DT_MIPS_PERF_SUFFIX";
14206     case DT_MIPS_COMPACT_SIZE:
14207       return "DT_MIPS_COMPACT_SIZE";
14208     case DT_MIPS_GP_VALUE:
14209       return "DT_MIPS_GP_VALUE";
14210     case DT_MIPS_AUX_DYNAMIC:
14211       return "DT_MIPS_AUX_DYNAMIC";
14212     case DT_MIPS_PLTGOT:
14213       return "DT_MIPS_PLTGOT";
14214     case DT_MIPS_RWPLT:
14215       return "DT_MIPS_RWPLT";
14216     }
14217 }
14218
14219 bfd_boolean
14220 _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr)
14221 {
14222   FILE *file = ptr;
14223
14224   BFD_ASSERT (abfd != NULL && ptr != NULL);
14225
14226   /* Print normal ELF private data.  */
14227   _bfd_elf_print_private_bfd_data (abfd, ptr);
14228
14229   /* xgettext:c-format */
14230   fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
14231
14232   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
14233     fprintf (file, _(" [abi=O32]"));
14234   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64)
14235     fprintf (file, _(" [abi=O64]"));
14236   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32)
14237     fprintf (file, _(" [abi=EABI32]"));
14238   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
14239     fprintf (file, _(" [abi=EABI64]"));
14240   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI))
14241     fprintf (file, _(" [abi unknown]"));
14242   else if (ABI_N32_P (abfd))
14243     fprintf (file, _(" [abi=N32]"));
14244   else if (ABI_64_P (abfd))
14245     fprintf (file, _(" [abi=64]"));
14246   else
14247     fprintf (file, _(" [no abi set]"));
14248
14249   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1)
14250     fprintf (file, " [mips1]");
14251   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2)
14252     fprintf (file, " [mips2]");
14253   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3)
14254     fprintf (file, " [mips3]");
14255   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4)
14256     fprintf (file, " [mips4]");
14257   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5)
14258     fprintf (file, " [mips5]");
14259   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32)
14260     fprintf (file, " [mips32]");
14261   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64)
14262     fprintf (file, " [mips64]");
14263   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2)
14264     fprintf (file, " [mips32r2]");
14265   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2)
14266     fprintf (file, " [mips64r2]");
14267   else
14268     fprintf (file, _(" [unknown ISA]"));
14269
14270   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
14271     fprintf (file, " [mdmx]");
14272
14273   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
14274     fprintf (file, " [mips16]");
14275
14276   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
14277     fprintf (file, " [micromips]");
14278
14279   if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE)
14280     fprintf (file, " [32bitmode]");
14281   else
14282     fprintf (file, _(" [not 32bitmode]"));
14283
14284   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NOREORDER)
14285     fprintf (file, " [noreorder]");
14286
14287   if (elf_elfheader (abfd)->e_flags & EF_MIPS_PIC)
14288     fprintf (file, " [PIC]");
14289
14290   if (elf_elfheader (abfd)->e_flags & EF_MIPS_CPIC)
14291     fprintf (file, " [CPIC]");
14292
14293   if (elf_elfheader (abfd)->e_flags & EF_MIPS_XGOT)
14294     fprintf (file, " [XGOT]");
14295
14296   if (elf_elfheader (abfd)->e_flags & EF_MIPS_UCODE)
14297     fprintf (file, " [UCODE]");
14298
14299   fputc ('\n', file);
14300
14301   return TRUE;
14302 }
14303
14304 const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] =
14305 {
14306   { STRING_COMMA_LEN (".lit4"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14307   { STRING_COMMA_LEN (".lit8"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14308   { STRING_COMMA_LEN (".mdebug"), 0, SHT_MIPS_DEBUG, 0 },
14309   { STRING_COMMA_LEN (".sbss"),  -2, SHT_NOBITS,     SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14310   { STRING_COMMA_LEN (".sdata"), -2, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14311   { STRING_COMMA_LEN (".ucode"),  0, SHT_MIPS_UCODE, 0 },
14312   { NULL,                     0,  0, 0,              0 }
14313 };
14314
14315 /* Merge non visibility st_other attributes.  Ensure that the
14316    STO_OPTIONAL flag is copied into h->other, even if this is not a
14317    definiton of the symbol.  */
14318 void
14319 _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
14320                                       const Elf_Internal_Sym *isym,
14321                                       bfd_boolean definition,
14322                                       bfd_boolean dynamic ATTRIBUTE_UNUSED)
14323 {
14324   if ((isym->st_other & ~ELF_ST_VISIBILITY (-1)) != 0)
14325     {
14326       unsigned char other;
14327
14328       other = (definition ? isym->st_other : h->other);
14329       other &= ~ELF_ST_VISIBILITY (-1);
14330       h->other = other | ELF_ST_VISIBILITY (h->other);
14331     }
14332
14333   if (!definition
14334       && ELF_MIPS_IS_OPTIONAL (isym->st_other))
14335     h->other |= STO_OPTIONAL;
14336 }
14337
14338 /* Decide whether an undefined symbol is special and can be ignored.
14339    This is the case for OPTIONAL symbols on IRIX.  */
14340 bfd_boolean
14341 _bfd_mips_elf_ignore_undef_symbol (struct elf_link_hash_entry *h)
14342 {
14343   return ELF_MIPS_IS_OPTIONAL (h->other) ? TRUE : FALSE;
14344 }
14345
14346 bfd_boolean
14347 _bfd_mips_elf_common_definition (Elf_Internal_Sym *sym)
14348 {
14349   return (sym->st_shndx == SHN_COMMON
14350           || sym->st_shndx == SHN_MIPS_ACOMMON
14351           || sym->st_shndx == SHN_MIPS_SCOMMON);
14352 }
14353
14354 /* Return address for Ith PLT stub in section PLT, for relocation REL
14355    or (bfd_vma) -1 if it should not be included.  */
14356
14357 bfd_vma
14358 _bfd_mips_elf_plt_sym_val (bfd_vma i, const asection *plt,
14359                            const arelent *rel ATTRIBUTE_UNUSED)
14360 {
14361   return (plt->vma
14362           + 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry)
14363           + i * 4 * ARRAY_SIZE (mips_exec_plt_entry));
14364 }
14365
14366 void
14367 _bfd_mips_post_process_headers (bfd *abfd, struct bfd_link_info *link_info)
14368 {
14369   struct mips_elf_link_hash_table *htab;
14370   Elf_Internal_Ehdr *i_ehdrp;
14371
14372   i_ehdrp = elf_elfheader (abfd);
14373   if (link_info)
14374     {
14375       htab = mips_elf_hash_table (link_info);
14376       BFD_ASSERT (htab != NULL);
14377
14378       if (htab->use_plts_and_copy_relocs && !htab->is_vxworks)
14379         i_ehdrp->e_ident[EI_ABIVERSION] = 1;
14380     }
14381 }