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 /* Types of TLS GOT entry.  */
51 enum mips_got_tls_type {
52   GOT_TLS_NONE,
53   GOT_TLS_GD,
54   GOT_TLS_LDM,
55   GOT_TLS_IE
56 };
57
58 /* This structure is used to hold information about one GOT entry.
59    There are four types of entry:
60
61       (1) an absolute address
62             requires: abfd == NULL
63             fields: d.address
64
65       (2) a SYMBOL + OFFSET address, where SYMBOL is local to an input bfd
66             requires: abfd != NULL, symndx >= 0, tls_type != GOT_TLS_LDM
67             fields: abfd, symndx, d.addend, tls_type
68
69       (3) a SYMBOL address, where SYMBOL is not local to an input bfd
70             requires: abfd != NULL, symndx == -1
71             fields: d.h, tls_type
72
73       (4) a TLS LDM slot
74             requires: abfd != NULL, symndx == 0, tls_type == GOT_TLS_LDM
75             fields: none; there's only one of these per GOT.  */
76 struct mips_got_entry
77 {
78   /* One input bfd that needs the GOT entry.  */
79   bfd *abfd;
80   /* The index of the symbol, as stored in the relocation r_info, if
81      we have a local symbol; -1 otherwise.  */
82   long symndx;
83   union
84   {
85     /* If abfd == NULL, an address that must be stored in the got.  */
86     bfd_vma address;
87     /* If abfd != NULL && symndx != -1, the addend of the relocation
88        that should be added to the symbol value.  */
89     bfd_vma addend;
90     /* If abfd != NULL && symndx == -1, the hash table entry
91        corresponding to a symbol in the GOT.  The symbol's entry
92        is in the local area if h->global_got_area is GGA_NONE,
93        otherwise it is in the global area.  */
94     struct mips_elf_link_hash_entry *h;
95   } d;
96
97   /* The TLS type of this GOT entry.  An LDM GOT entry will be a local
98      symbol entry with r_symndx == 0.  */
99   unsigned char tls_type;
100
101   /* True if we have filled in the GOT contents for a TLS entry,
102      and created the associated relocations.  */
103   unsigned char tls_initialized;
104
105   /* The offset from the beginning of the .got section to the entry
106      corresponding to this symbol+addend.  If it's a global symbol
107      whose offset is yet to be decided, it's going to be -1.  */
108   long gotidx;
109 };
110
111 /* This structure represents a GOT page reference from an input bfd.
112    Each instance represents a symbol + ADDEND, where the representation
113    of the symbol depends on whether it is local to the input bfd.
114    If it is, then SYMNDX >= 0, and the symbol has index SYMNDX in U.ABFD.
115    Otherwise, SYMNDX < 0 and U.H points to the symbol's hash table entry.
116
117    Page references with SYMNDX >= 0 always become page references
118    in the output.  Page references with SYMNDX < 0 only become page
119    references if the symbol binds locally; in other cases, the page
120    reference decays to a global GOT reference.  */
121 struct mips_got_page_ref
122 {
123   long symndx;
124   union
125   {
126     struct mips_elf_link_hash_entry *h;
127     bfd *abfd;
128   } u;
129   bfd_vma addend;
130 };
131
132 /* This structure describes a range of addends: [MIN_ADDEND, MAX_ADDEND].
133    The structures form a non-overlapping list that is sorted by increasing
134    MIN_ADDEND.  */
135 struct mips_got_page_range
136 {
137   struct mips_got_page_range *next;
138   bfd_signed_vma min_addend;
139   bfd_signed_vma max_addend;
140 };
141
142 /* This structure describes the range of addends that are applied to page
143    relocations against a given section.  */
144 struct mips_got_page_entry
145 {
146   /* The section that these entries are based on.  */
147   asection *sec;
148   /* The ranges for this page entry.  */
149   struct mips_got_page_range *ranges;
150   /* The maximum number of page entries needed for RANGES.  */
151   bfd_vma num_pages;
152 };
153
154 /* This structure is used to hold .got information when linking.  */
155
156 struct mips_got_info
157 {
158   /* The number of global .got entries.  */
159   unsigned int global_gotno;
160   /* The number of global .got entries that are in the GGA_RELOC_ONLY area.  */
161   unsigned int reloc_only_gotno;
162   /* The number of .got slots used for TLS.  */
163   unsigned int tls_gotno;
164   /* The first unused TLS .got entry.  Used only during
165      mips_elf_initialize_tls_index.  */
166   unsigned int tls_assigned_gotno;
167   /* The number of local .got entries, eventually including page entries.  */
168   unsigned int local_gotno;
169   /* The maximum number of page entries needed.  */
170   unsigned int page_gotno;
171   /* The number of relocations needed for the GOT entries.  */
172   unsigned int relocs;
173   /* The number of local .got entries we have used.  */
174   unsigned int assigned_gotno;
175   /* A hash table holding members of the got.  */
176   struct htab *got_entries;
177   /* A hash table holding mips_got_page_ref structures.  */
178   struct htab *got_page_refs;
179   /* A hash table of mips_got_page_entry structures.  */
180   struct htab *got_page_entries;
181   /* In multi-got links, a pointer to the next got (err, rather, most
182      of the time, it points to the previous got).  */
183   struct mips_got_info *next;
184 };
185
186 /* Structure passed when merging bfds' gots.  */
187
188 struct mips_elf_got_per_bfd_arg
189 {
190   /* The output bfd.  */
191   bfd *obfd;
192   /* The link information.  */
193   struct bfd_link_info *info;
194   /* A pointer to the primary got, i.e., the one that's going to get
195      the implicit relocations from DT_MIPS_LOCAL_GOTNO and
196      DT_MIPS_GOTSYM.  */
197   struct mips_got_info *primary;
198   /* A non-primary got we're trying to merge with other input bfd's
199      gots.  */
200   struct mips_got_info *current;
201   /* The maximum number of got entries that can be addressed with a
202      16-bit offset.  */
203   unsigned int max_count;
204   /* The maximum number of page entries needed by each got.  */
205   unsigned int max_pages;
206   /* The total number of global entries which will live in the
207      primary got and be automatically relocated.  This includes
208      those not referenced by the primary GOT but included in
209      the "master" GOT.  */
210   unsigned int global_count;
211 };
212
213 /* A structure used to pass information to htab_traverse callbacks
214    when laying out the GOT.  */
215
216 struct mips_elf_traverse_got_arg
217 {
218   struct bfd_link_info *info;
219   struct mips_got_info *g;
220   int value;
221 };
222
223 struct _mips_elf_section_data
224 {
225   struct bfd_elf_section_data elf;
226   union
227   {
228     bfd_byte *tdata;
229   } u;
230 };
231
232 #define mips_elf_section_data(sec) \
233   ((struct _mips_elf_section_data *) elf_section_data (sec))
234
235 #define is_mips_elf(bfd)                                \
236   (bfd_get_flavour (bfd) == bfd_target_elf_flavour      \
237    && elf_tdata (bfd) != NULL                           \
238    && elf_object_id (bfd) == MIPS_ELF_DATA)
239
240 /* The ABI says that every symbol used by dynamic relocations must have
241    a global GOT entry.  Among other things, this provides the dynamic
242    linker with a free, directly-indexed cache.  The GOT can therefore
243    contain symbols that are not referenced by GOT relocations themselves
244    (in other words, it may have symbols that are not referenced by things
245    like R_MIPS_GOT16 and R_MIPS_GOT_PAGE).
246
247    GOT relocations are less likely to overflow if we put the associated
248    GOT entries towards the beginning.  We therefore divide the global
249    GOT entries into two areas: "normal" and "reloc-only".  Entries in
250    the first area can be used for both dynamic relocations and GP-relative
251    accesses, while those in the "reloc-only" area are for dynamic
252    relocations only.
253
254    These GGA_* ("Global GOT Area") values are organised so that lower
255    values are more general than higher values.  Also, non-GGA_NONE
256    values are ordered by the position of the area in the GOT.  */
257 #define GGA_NORMAL 0
258 #define GGA_RELOC_ONLY 1
259 #define GGA_NONE 2
260
261 /* Information about a non-PIC interface to a PIC function.  There are
262    two ways of creating these interfaces.  The first is to add:
263
264         lui     $25,%hi(func)
265         addiu   $25,$25,%lo(func)
266
267    immediately before a PIC function "func".  The second is to add:
268
269         lui     $25,%hi(func)
270         j       func
271         addiu   $25,$25,%lo(func)
272
273    to a separate trampoline section.
274
275    Stubs of the first kind go in a new section immediately before the
276    target function.  Stubs of the second kind go in a single section
277    pointed to by the hash table's "strampoline" field.  */
278 struct mips_elf_la25_stub {
279   /* The generated section that contains this stub.  */
280   asection *stub_section;
281
282   /* The offset of the stub from the start of STUB_SECTION.  */
283   bfd_vma offset;
284
285   /* One symbol for the original function.  Its location is available
286      in H->root.root.u.def.  */
287   struct mips_elf_link_hash_entry *h;
288 };
289
290 /* Macros for populating a mips_elf_la25_stub.  */
291
292 #define LA25_LUI(VAL) (0x3c190000 | (VAL))      /* lui t9,VAL */
293 #define LA25_J(VAL) (0x08000000 | (((VAL) >> 2) & 0x3ffffff)) /* j VAL */
294 #define LA25_ADDIU(VAL) (0x27390000 | (VAL))    /* addiu t9,t9,VAL */
295 #define LA25_LUI_MICROMIPS(VAL)                                         \
296   (0x41b90000 | (VAL))                          /* lui t9,VAL */
297 #define LA25_J_MICROMIPS(VAL)                                           \
298   (0xd4000000 | (((VAL) >> 1) & 0x3ffffff))     /* j VAL */
299 #define LA25_ADDIU_MICROMIPS(VAL)                                       \
300   (0x33390000 | (VAL))                          /* addiu t9,t9,VAL */
301
302 /* This structure is passed to mips_elf_sort_hash_table_f when sorting
303    the dynamic symbols.  */
304
305 struct mips_elf_hash_sort_data
306 {
307   /* The symbol in the global GOT with the lowest dynamic symbol table
308      index.  */
309   struct elf_link_hash_entry *low;
310   /* The least dynamic symbol table index corresponding to a non-TLS
311      symbol with a GOT entry.  */
312   long min_got_dynindx;
313   /* The greatest dynamic symbol table index corresponding to a symbol
314      with a GOT entry that is not referenced (e.g., a dynamic symbol
315      with dynamic relocations pointing to it from non-primary GOTs).  */
316   long max_unref_got_dynindx;
317   /* The greatest dynamic symbol table index not corresponding to a
318      symbol without a GOT entry.  */
319   long max_non_got_dynindx;
320 };
321
322 /* The MIPS ELF linker needs additional information for each symbol in
323    the global hash table.  */
324
325 struct mips_elf_link_hash_entry
326 {
327   struct elf_link_hash_entry root;
328
329   /* External symbol information.  */
330   EXTR esym;
331
332   /* The la25 stub we have created for ths symbol, if any.  */
333   struct mips_elf_la25_stub *la25_stub;
334
335   /* Number of R_MIPS_32, R_MIPS_REL32, or R_MIPS_64 relocs against
336      this symbol.  */
337   unsigned int possibly_dynamic_relocs;
338
339   /* If there is a stub that 32 bit functions should use to call this
340      16 bit function, this points to the section containing the stub.  */
341   asection *fn_stub;
342
343   /* If there is a stub that 16 bit functions should use to call this
344      32 bit function, this points to the section containing the stub.  */
345   asection *call_stub;
346
347   /* This is like the call_stub field, but it is used if the function
348      being called returns a floating point value.  */
349   asection *call_fp_stub;
350
351   /* The highest GGA_* value that satisfies all references to this symbol.  */
352   unsigned int global_got_area : 2;
353
354   /* True if all GOT relocations against this symbol are for calls.  This is
355      a looser condition than no_fn_stub below, because there may be other
356      non-call non-GOT relocations against the symbol.  */
357   unsigned int got_only_for_calls : 1;
358
359   /* True if one of the relocations described by possibly_dynamic_relocs
360      is against a readonly section.  */
361   unsigned int readonly_reloc : 1;
362
363   /* True if there is a relocation against this symbol that must be
364      resolved by the static linker (in other words, if the relocation
365      cannot possibly be made dynamic).  */
366   unsigned int has_static_relocs : 1;
367
368   /* True if we must not create a .MIPS.stubs entry for this symbol.
369      This is set, for example, if there are relocations related to
370      taking the function's address, i.e. any but R_MIPS_CALL*16 ones.
371      See "MIPS ABI Supplement, 3rd Edition", p. 4-20.  */
372   unsigned int no_fn_stub : 1;
373
374   /* Whether we need the fn_stub; this is true if this symbol appears
375      in any relocs other than a 16 bit call.  */
376   unsigned int need_fn_stub : 1;
377
378   /* True if this symbol is referenced by branch relocations from
379      any non-PIC input file.  This is used to determine whether an
380      la25 stub is required.  */
381   unsigned int has_nonpic_branches : 1;
382
383   /* Does this symbol need a traditional MIPS lazy-binding stub
384      (as opposed to a PLT entry)?  */
385   unsigned int needs_lazy_stub : 1;
386 };
387
388 /* MIPS ELF linker hash table.  */
389
390 struct mips_elf_link_hash_table
391 {
392   struct elf_link_hash_table root;
393
394   /* The number of .rtproc entries.  */
395   bfd_size_type procedure_count;
396
397   /* The size of the .compact_rel section (if SGI_COMPAT).  */
398   bfd_size_type compact_rel_size;
399
400   /* This flag indicates that the value of DT_MIPS_RLD_MAP dynamic entry
401      is set to the address of __rld_obj_head as in IRIX5 and IRIX6.  */
402   bfd_boolean use_rld_obj_head;
403
404   /* The  __rld_map or __rld_obj_head symbol. */
405   struct elf_link_hash_entry *rld_symbol;
406
407   /* This is set if we see any mips16 stub sections.  */
408   bfd_boolean mips16_stubs_seen;
409
410   /* True if we can generate copy relocs and PLTs.  */
411   bfd_boolean use_plts_and_copy_relocs;
412
413   /* True if we're generating code for VxWorks.  */
414   bfd_boolean is_vxworks;
415
416   /* True if we already reported the small-data section overflow.  */
417   bfd_boolean small_data_overflow_reported;
418
419   /* Shortcuts to some dynamic sections, or NULL if they are not
420      being used.  */
421   asection *srelbss;
422   asection *sdynbss;
423   asection *srelplt;
424   asection *srelplt2;
425   asection *sgotplt;
426   asection *splt;
427   asection *sstubs;
428   asection *sgot;
429
430   /* The master GOT information.  */
431   struct mips_got_info *got_info;
432
433   /* The global symbol in the GOT with the lowest index in the dynamic
434      symbol table.  */
435   struct elf_link_hash_entry *global_gotsym;
436
437   /* The size of the PLT header in bytes.  */
438   bfd_vma plt_header_size;
439
440   /* The size of a PLT entry in bytes.  */
441   bfd_vma plt_entry_size;
442
443   /* The number of functions that need a lazy-binding stub.  */
444   bfd_vma lazy_stub_count;
445
446   /* The size of a function stub entry in bytes.  */
447   bfd_vma function_stub_size;
448
449   /* The number of reserved entries at the beginning of the GOT.  */
450   unsigned int reserved_gotno;
451
452   /* The section used for mips_elf_la25_stub trampolines.
453      See the comment above that structure for details.  */
454   asection *strampoline;
455
456   /* A table of mips_elf_la25_stubs, indexed by (input_section, offset)
457      pairs.  */
458   htab_t la25_stubs;
459
460   /* A function FN (NAME, IS, OS) that creates a new input section
461      called NAME and links it to output section OS.  If IS is nonnull,
462      the new section should go immediately before it, otherwise it
463      should go at the (current) beginning of OS.
464
465      The function returns the new section on success, otherwise it
466      returns null.  */
467   asection *(*add_stub_section) (const char *, asection *, asection *);
468
469   /* Small local sym cache.  */
470   struct sym_cache sym_cache;
471 };
472
473 /* Get the MIPS ELF linker hash table from a link_info structure.  */
474
475 #define mips_elf_hash_table(p) \
476   (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \
477   == MIPS_ELF_DATA ? ((struct mips_elf_link_hash_table *) ((p)->hash)) : NULL)
478
479 /* A structure used to communicate with htab_traverse callbacks.  */
480 struct mips_htab_traverse_info
481 {
482   /* The usual link-wide information.  */
483   struct bfd_link_info *info;
484   bfd *output_bfd;
485
486   /* Starts off FALSE and is set to TRUE if the link should be aborted.  */
487   bfd_boolean error;
488 };
489
490 /* MIPS ELF private object data.  */
491
492 struct mips_elf_obj_tdata
493 {
494   /* Generic ELF private object data.  */
495   struct elf_obj_tdata root;
496
497   /* Input BFD providing Tag_GNU_MIPS_ABI_FP attribute for output.  */
498   bfd *abi_fp_bfd;
499
500   /* The GOT requirements of input bfds.  */
501   struct mips_got_info *got;
502 };
503
504 /* Get MIPS ELF private object data from BFD's tdata.  */
505
506 #define mips_elf_tdata(bfd) \
507   ((struct mips_elf_obj_tdata *) (bfd)->tdata.any)
508
509 #define TLS_RELOC_P(r_type) \
510   (r_type == R_MIPS_TLS_DTPMOD32                \
511    || r_type == R_MIPS_TLS_DTPMOD64             \
512    || r_type == R_MIPS_TLS_DTPREL32             \
513    || r_type == R_MIPS_TLS_DTPREL64             \
514    || r_type == R_MIPS_TLS_GD                   \
515    || r_type == R_MIPS_TLS_LDM                  \
516    || r_type == R_MIPS_TLS_DTPREL_HI16          \
517    || r_type == R_MIPS_TLS_DTPREL_LO16          \
518    || r_type == R_MIPS_TLS_GOTTPREL             \
519    || r_type == R_MIPS_TLS_TPREL32              \
520    || r_type == R_MIPS_TLS_TPREL64              \
521    || r_type == R_MIPS_TLS_TPREL_HI16           \
522    || r_type == R_MIPS_TLS_TPREL_LO16           \
523    || r_type == R_MIPS16_TLS_GD                 \
524    || r_type == R_MIPS16_TLS_LDM                \
525    || r_type == R_MIPS16_TLS_DTPREL_HI16        \
526    || r_type == R_MIPS16_TLS_DTPREL_LO16        \
527    || r_type == R_MIPS16_TLS_GOTTPREL           \
528    || r_type == R_MIPS16_TLS_TPREL_HI16         \
529    || r_type == R_MIPS16_TLS_TPREL_LO16         \
530    || r_type == R_MICROMIPS_TLS_GD              \
531    || r_type == R_MICROMIPS_TLS_LDM             \
532    || r_type == R_MICROMIPS_TLS_DTPREL_HI16     \
533    || r_type == R_MICROMIPS_TLS_DTPREL_LO16     \
534    || r_type == R_MICROMIPS_TLS_GOTTPREL        \
535    || r_type == R_MICROMIPS_TLS_TPREL_HI16      \
536    || r_type == R_MICROMIPS_TLS_TPREL_LO16)
537
538 /* Structure used to pass information to mips_elf_output_extsym.  */
539
540 struct extsym_info
541 {
542   bfd *abfd;
543   struct bfd_link_info *info;
544   struct ecoff_debug_info *debug;
545   const struct ecoff_debug_swap *swap;
546   bfd_boolean failed;
547 };
548
549 /* The names of the runtime procedure table symbols used on IRIX5.  */
550
551 static const char * const mips_elf_dynsym_rtproc_names[] =
552 {
553   "_procedure_table",
554   "_procedure_string_table",
555   "_procedure_table_size",
556   NULL
557 };
558
559 /* These structures are used to generate the .compact_rel section on
560    IRIX5.  */
561
562 typedef struct
563 {
564   unsigned long id1;            /* Always one?  */
565   unsigned long num;            /* Number of compact relocation entries.  */
566   unsigned long id2;            /* Always two?  */
567   unsigned long offset;         /* The file offset of the first relocation.  */
568   unsigned long reserved0;      /* Zero?  */
569   unsigned long reserved1;      /* Zero?  */
570 } Elf32_compact_rel;
571
572 typedef struct
573 {
574   bfd_byte id1[4];
575   bfd_byte num[4];
576   bfd_byte id2[4];
577   bfd_byte offset[4];
578   bfd_byte reserved0[4];
579   bfd_byte reserved1[4];
580 } Elf32_External_compact_rel;
581
582 typedef struct
583 {
584   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
585   unsigned int rtype : 4;       /* Relocation types. See below.  */
586   unsigned int dist2to : 8;
587   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
588   unsigned long konst;          /* KONST field. See below.  */
589   unsigned long vaddr;          /* VADDR to be relocated.  */
590 } Elf32_crinfo;
591
592 typedef struct
593 {
594   unsigned int ctype : 1;       /* 1: long 0: short format. See below.  */
595   unsigned int rtype : 4;       /* Relocation types. See below.  */
596   unsigned int dist2to : 8;
597   unsigned int relvaddr : 19;   /* (VADDR - vaddr of the previous entry)/ 4 */
598   unsigned long konst;          /* KONST field. See below.  */
599 } Elf32_crinfo2;
600
601 typedef struct
602 {
603   bfd_byte info[4];
604   bfd_byte konst[4];
605   bfd_byte vaddr[4];
606 } Elf32_External_crinfo;
607
608 typedef struct
609 {
610   bfd_byte info[4];
611   bfd_byte konst[4];
612 } Elf32_External_crinfo2;
613
614 /* These are the constants used to swap the bitfields in a crinfo.  */
615
616 #define CRINFO_CTYPE (0x1)
617 #define CRINFO_CTYPE_SH (31)
618 #define CRINFO_RTYPE (0xf)
619 #define CRINFO_RTYPE_SH (27)
620 #define CRINFO_DIST2TO (0xff)
621 #define CRINFO_DIST2TO_SH (19)
622 #define CRINFO_RELVADDR (0x7ffff)
623 #define CRINFO_RELVADDR_SH (0)
624
625 /* A compact relocation info has long (3 words) or short (2 words)
626    formats.  A short format doesn't have VADDR field and relvaddr
627    fields contains ((VADDR - vaddr of the previous entry) >> 2).  */
628 #define CRF_MIPS_LONG                   1
629 #define CRF_MIPS_SHORT                  0
630
631 /* There are 4 types of compact relocation at least. The value KONST
632    has different meaning for each type:
633
634    (type)               (konst)
635    CT_MIPS_REL32        Address in data
636    CT_MIPS_WORD         Address in word (XXX)
637    CT_MIPS_GPHI_LO      GP - vaddr
638    CT_MIPS_JMPAD        Address to jump
639    */
640
641 #define CRT_MIPS_REL32                  0xa
642 #define CRT_MIPS_WORD                   0xb
643 #define CRT_MIPS_GPHI_LO                0xc
644 #define CRT_MIPS_JMPAD                  0xd
645
646 #define mips_elf_set_cr_format(x,format)        ((x).ctype = (format))
647 #define mips_elf_set_cr_type(x,type)            ((x).rtype = (type))
648 #define mips_elf_set_cr_dist2to(x,v)            ((x).dist2to = (v))
649 #define mips_elf_set_cr_relvaddr(x,d)           ((x).relvaddr = (d)<<2)
650 \f
651 /* The structure of the runtime procedure descriptor created by the
652    loader for use by the static exception system.  */
653
654 typedef struct runtime_pdr {
655         bfd_vma adr;            /* Memory address of start of procedure.  */
656         long    regmask;        /* Save register mask.  */
657         long    regoffset;      /* Save register offset.  */
658         long    fregmask;       /* Save floating point register mask.  */
659         long    fregoffset;     /* Save floating point register offset.  */
660         long    frameoffset;    /* Frame size.  */
661         short   framereg;       /* Frame pointer register.  */
662         short   pcreg;          /* Offset or reg of return pc.  */
663         long    irpss;          /* Index into the runtime string table.  */
664         long    reserved;
665         struct exception_info *exception_info;/* Pointer to exception array.  */
666 } RPDR, *pRPDR;
667 #define cbRPDR sizeof (RPDR)
668 #define rpdNil ((pRPDR) 0)
669 \f
670 static struct mips_got_entry *mips_elf_create_local_got_entry
671   (bfd *, struct bfd_link_info *, bfd *, bfd_vma, unsigned long,
672    struct mips_elf_link_hash_entry *, int);
673 static bfd_boolean mips_elf_sort_hash_table_f
674   (struct mips_elf_link_hash_entry *, void *);
675 static bfd_vma mips_elf_high
676   (bfd_vma);
677 static bfd_boolean mips_elf_create_dynamic_relocation
678   (bfd *, struct bfd_link_info *, const Elf_Internal_Rela *,
679    struct mips_elf_link_hash_entry *, asection *, bfd_vma,
680    bfd_vma *, asection *);
681 static bfd_vma mips_elf_adjust_gp
682   (bfd *, struct mips_got_info *, bfd *);
683
684 /* This will be used when we sort the dynamic relocation records.  */
685 static bfd *reldyn_sorting_bfd;
686
687 /* True if ABFD is for CPUs with load interlocking that include
688    non-MIPS1 CPUs and R3900.  */
689 #define LOAD_INTERLOCKS_P(abfd) \
690   (   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) != E_MIPS_ARCH_1) \
691    || ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_3900))
692
693 /* True if ABFD is for CPUs that are faster if JAL is converted to BAL.
694    This should be safe for all architectures.  We enable this predicate
695    for RM9000 for now.  */
696 #define JAL_TO_BAL_P(abfd) \
697   ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == E_MIPS_MACH_9000)
698
699 /* True if ABFD is for CPUs that are faster if JALR is converted to BAL.
700    This should be safe for all architectures.  We enable this predicate for
701    all CPUs.  */
702 #define JALR_TO_BAL_P(abfd) 1
703
704 /* True if ABFD is for CPUs that are faster if JR is converted to B.
705    This should be safe for all architectures.  We enable this predicate for
706    all CPUs.  */
707 #define JR_TO_B_P(abfd) 1
708
709 /* True if ABFD is a PIC object.  */
710 #define PIC_OBJECT_P(abfd) \
711   ((elf_elfheader (abfd)->e_flags & EF_MIPS_PIC) != 0)
712
713 /* Nonzero if ABFD is using the N32 ABI.  */
714 #define ABI_N32_P(abfd) \
715   ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI2) != 0)
716
717 /* Nonzero if ABFD is using the N64 ABI.  */
718 #define ABI_64_P(abfd) \
719   (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS64)
720
721 /* Nonzero if ABFD is using NewABI conventions.  */
722 #define NEWABI_P(abfd) (ABI_N32_P (abfd) || ABI_64_P (abfd))
723
724 /* The IRIX compatibility level we are striving for.  */
725 #define IRIX_COMPAT(abfd) \
726   (get_elf_backend_data (abfd)->elf_backend_mips_irix_compat (abfd))
727
728 /* Whether we are trying to be compatible with IRIX at all.  */
729 #define SGI_COMPAT(abfd) \
730   (IRIX_COMPAT (abfd) != ict_none)
731
732 /* The name of the options section.  */
733 #define MIPS_ELF_OPTIONS_SECTION_NAME(abfd) \
734   (NEWABI_P (abfd) ? ".MIPS.options" : ".options")
735
736 /* True if NAME is the recognized name of any SHT_MIPS_OPTIONS section.
737    Some IRIX system files do not use MIPS_ELF_OPTIONS_SECTION_NAME.  */
738 #define MIPS_ELF_OPTIONS_SECTION_NAME_P(NAME) \
739   (strcmp (NAME, ".MIPS.options") == 0 || strcmp (NAME, ".options") == 0)
740
741 /* Whether the section is readonly.  */
742 #define MIPS_ELF_READONLY_SECTION(sec) \
743   ((sec->flags & (SEC_ALLOC | SEC_LOAD | SEC_READONLY))         \
744    == (SEC_ALLOC | SEC_LOAD | SEC_READONLY))
745
746 /* The name of the stub section.  */
747 #define MIPS_ELF_STUB_SECTION_NAME(abfd) ".MIPS.stubs"
748
749 /* The size of an external REL relocation.  */
750 #define MIPS_ELF_REL_SIZE(abfd) \
751   (get_elf_backend_data (abfd)->s->sizeof_rel)
752
753 /* The size of an external RELA relocation.  */
754 #define MIPS_ELF_RELA_SIZE(abfd) \
755   (get_elf_backend_data (abfd)->s->sizeof_rela)
756
757 /* The size of an external dynamic table entry.  */
758 #define MIPS_ELF_DYN_SIZE(abfd) \
759   (get_elf_backend_data (abfd)->s->sizeof_dyn)
760
761 /* The size of a GOT entry.  */
762 #define MIPS_ELF_GOT_SIZE(abfd) \
763   (get_elf_backend_data (abfd)->s->arch_size / 8)
764
765 /* The size of the .rld_map section. */
766 #define MIPS_ELF_RLD_MAP_SIZE(abfd) \
767   (get_elf_backend_data (abfd)->s->arch_size / 8)
768
769 /* The size of a symbol-table entry.  */
770 #define MIPS_ELF_SYM_SIZE(abfd) \
771   (get_elf_backend_data (abfd)->s->sizeof_sym)
772
773 /* The default alignment for sections, as a power of two.  */
774 #define MIPS_ELF_LOG_FILE_ALIGN(abfd)                           \
775   (get_elf_backend_data (abfd)->s->log_file_align)
776
777 /* Get word-sized data.  */
778 #define MIPS_ELF_GET_WORD(abfd, ptr) \
779   (ABI_64_P (abfd) ? bfd_get_64 (abfd, ptr) : bfd_get_32 (abfd, ptr))
780
781 /* Put out word-sized data.  */
782 #define MIPS_ELF_PUT_WORD(abfd, val, ptr)       \
783   (ABI_64_P (abfd)                              \
784    ? bfd_put_64 (abfd, val, ptr)                \
785    : bfd_put_32 (abfd, val, ptr))
786
787 /* The opcode for word-sized loads (LW or LD).  */
788 #define MIPS_ELF_LOAD_WORD(abfd) \
789   (ABI_64_P (abfd) ? 0xdc000000 : 0x8c000000)
790
791 /* Add a dynamic symbol table-entry.  */
792 #define MIPS_ELF_ADD_DYNAMIC_ENTRY(info, tag, val)      \
793   _bfd_elf_add_dynamic_entry (info, tag, val)
794
795 #define MIPS_ELF_RTYPE_TO_HOWTO(abfd, rtype, rela)                      \
796   (get_elf_backend_data (abfd)->elf_backend_mips_rtype_to_howto (rtype, rela))
797
798 /* The name of the dynamic relocation section.  */
799 #define MIPS_ELF_REL_DYN_NAME(INFO) \
800   (mips_elf_hash_table (INFO)->is_vxworks ? ".rela.dyn" : ".rel.dyn")
801
802 /* In case we're on a 32-bit machine, construct a 64-bit "-1" value
803    from smaller values.  Start with zero, widen, *then* decrement.  */
804 #define MINUS_ONE       (((bfd_vma)0) - 1)
805 #define MINUS_TWO       (((bfd_vma)0) - 2)
806
807 /* The value to write into got[1] for SVR4 targets, to identify it is
808    a GNU object.  The dynamic linker can then use got[1] to store the
809    module pointer.  */
810 #define MIPS_ELF_GNU_GOT1_MASK(abfd) \
811   ((bfd_vma) 1 << (ABI_64_P (abfd) ? 63 : 31))
812
813 /* The offset of $gp from the beginning of the .got section.  */
814 #define ELF_MIPS_GP_OFFSET(INFO) \
815   (mips_elf_hash_table (INFO)->is_vxworks ? 0x0 : 0x7ff0)
816
817 /* The maximum size of the GOT for it to be addressable using 16-bit
818    offsets from $gp.  */
819 #define MIPS_ELF_GOT_MAX_SIZE(INFO) (ELF_MIPS_GP_OFFSET (INFO) + 0x7fff)
820
821 /* Instructions which appear in a stub.  */
822 #define STUB_LW(abfd)                                                   \
823   ((ABI_64_P (abfd)                                                     \
824     ? 0xdf998010                                /* ld t9,0x8010(gp) */  \
825     : 0x8f998010))                              /* lw t9,0x8010(gp) */
826 #define STUB_MOVE(abfd)                                                 \
827    ((ABI_64_P (abfd)                                                    \
828      ? 0x03e0782d                               /* daddu t7,ra */       \
829      : 0x03e07821))                             /* addu t7,ra */
830 #define STUB_LUI(VAL) (0x3c180000 + (VAL))      /* lui t8,VAL */
831 #define STUB_JALR 0x0320f809                    /* jalr t9,ra */
832 #define STUB_ORI(VAL) (0x37180000 + (VAL))      /* ori t8,t8,VAL */
833 #define STUB_LI16U(VAL) (0x34180000 + (VAL))    /* ori t8,zero,VAL unsigned */
834 #define STUB_LI16S(abfd, VAL)                                           \
835    ((ABI_64_P (abfd)                                                    \
836     ? (0x64180000 + (VAL))      /* daddiu t8,zero,VAL sign extended */  \
837     : (0x24180000 + (VAL))))    /* addiu t8,zero,VAL sign extended */
838
839 #define MIPS_FUNCTION_STUB_NORMAL_SIZE 16
840 #define MIPS_FUNCTION_STUB_BIG_SIZE 20
841
842 /* The name of the dynamic interpreter.  This is put in the .interp
843    section.  */
844
845 #define ELF_DYNAMIC_INTERPRETER(abfd)           \
846    (ABI_N32_P (abfd) ? "/usr/lib32/libc.so.1"   \
847     : ABI_64_P (abfd) ? "/usr/lib64/libc.so.1"  \
848     : "/usr/lib/libc.so.1")
849
850 #ifdef BFD64
851 #define MNAME(bfd,pre,pos) \
852   (ABI_64_P (bfd) ? CONCAT4 (pre,64,_,pos) : CONCAT4 (pre,32,_,pos))
853 #define ELF_R_SYM(bfd, i)                                       \
854   (ABI_64_P (bfd) ? ELF64_R_SYM (i) : ELF32_R_SYM (i))
855 #define ELF_R_TYPE(bfd, i)                                      \
856   (ABI_64_P (bfd) ? ELF64_MIPS_R_TYPE (i) : ELF32_R_TYPE (i))
857 #define ELF_R_INFO(bfd, s, t)                                   \
858   (ABI_64_P (bfd) ? ELF64_R_INFO (s, t) : ELF32_R_INFO (s, t))
859 #else
860 #define MNAME(bfd,pre,pos) CONCAT4 (pre,32,_,pos)
861 #define ELF_R_SYM(bfd, i)                                       \
862   (ELF32_R_SYM (i))
863 #define ELF_R_TYPE(bfd, i)                                      \
864   (ELF32_R_TYPE (i))
865 #define ELF_R_INFO(bfd, s, t)                                   \
866   (ELF32_R_INFO (s, t))
867 #endif
868 \f
869   /* The mips16 compiler uses a couple of special sections to handle
870      floating point arguments.
871
872      Section names that look like .mips16.fn.FNNAME contain stubs that
873      copy floating point arguments from the fp regs to the gp regs and
874      then jump to FNNAME.  If any 32 bit function calls FNNAME, the
875      call should be redirected to the stub instead.  If no 32 bit
876      function calls FNNAME, the stub should be discarded.  We need to
877      consider any reference to the function, not just a call, because
878      if the address of the function is taken we will need the stub,
879      since the address might be passed to a 32 bit function.
880
881      Section names that look like .mips16.call.FNNAME contain stubs
882      that copy floating point arguments from the gp regs to the fp
883      regs and then jump to FNNAME.  If FNNAME is a 32 bit function,
884      then any 16 bit function that calls FNNAME should be redirected
885      to the stub instead.  If FNNAME is not a 32 bit function, the
886      stub should be discarded.
887
888      .mips16.call.fp.FNNAME sections are similar, but contain stubs
889      which call FNNAME and then copy the return value from the fp regs
890      to the gp regs.  These stubs store the return value in $18 while
891      calling FNNAME; any function which might call one of these stubs
892      must arrange to save $18 around the call.  (This case is not
893      needed for 32 bit functions that call 16 bit functions, because
894      16 bit functions always return floating point values in both
895      $f0/$f1 and $2/$3.)
896
897      Note that in all cases FNNAME might be defined statically.
898      Therefore, FNNAME is not used literally.  Instead, the relocation
899      information will indicate which symbol the section is for.
900
901      We record any stubs that we find in the symbol table.  */
902
903 #define FN_STUB ".mips16.fn."
904 #define CALL_STUB ".mips16.call."
905 #define CALL_FP_STUB ".mips16.call.fp."
906
907 #define FN_STUB_P(name) CONST_STRNEQ (name, FN_STUB)
908 #define CALL_STUB_P(name) CONST_STRNEQ (name, CALL_STUB)
909 #define CALL_FP_STUB_P(name) CONST_STRNEQ (name, CALL_FP_STUB)
910 \f
911 /* The format of the first PLT entry in an O32 executable.  */
912 static const bfd_vma mips_o32_exec_plt0_entry[] =
913 {
914   0x3c1c0000,   /* lui $28, %hi(&GOTPLT[0])                             */
915   0x8f990000,   /* lw $25, %lo(&GOTPLT[0])($28)                         */
916   0x279c0000,   /* addiu $28, $28, %lo(&GOTPLT[0])                      */
917   0x031cc023,   /* subu $24, $24, $28                                   */
918   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
919   0x0018c082,   /* srl $24, $24, 2                                      */
920   0x0320f809,   /* jalr $25                                             */
921   0x2718fffe    /* subu $24, $24, 2                                     */
922 };
923
924 /* The format of the first PLT entry in an N32 executable.  Different
925    because gp ($28) is not available; we use t2 ($14) instead.  */
926 static const bfd_vma mips_n32_exec_plt0_entry[] =
927 {
928   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
929   0x8dd90000,   /* lw $25, %lo(&GOTPLT[0])($14)                         */
930   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
931   0x030ec023,   /* subu $24, $24, $14                                   */
932   0x03e07821,   /* move $15, $31        # 32-bit move (addu)            */
933   0x0018c082,   /* srl $24, $24, 2                                      */
934   0x0320f809,   /* jalr $25                                             */
935   0x2718fffe    /* subu $24, $24, 2                                     */
936 };
937
938 /* The format of the first PLT entry in an N64 executable.  Different
939    from N32 because of the increased size of GOT entries.  */
940 static const bfd_vma mips_n64_exec_plt0_entry[] =
941 {
942   0x3c0e0000,   /* lui $14, %hi(&GOTPLT[0])                             */
943   0xddd90000,   /* ld $25, %lo(&GOTPLT[0])($14)                         */
944   0x25ce0000,   /* addiu $14, $14, %lo(&GOTPLT[0])                      */
945   0x030ec023,   /* subu $24, $24, $14                                   */
946   0x03e0782d,   /* move $15, $31        # 64-bit move (daddu)           */
947   0x0018c0c2,   /* srl $24, $24, 3                                      */
948   0x0320f809,   /* jalr $25                                             */
949   0x2718fffe    /* subu $24, $24, 2                                     */
950 };
951
952 /* The format of subsequent PLT entries.  */
953 static const bfd_vma mips_exec_plt_entry[] =
954 {
955   0x3c0f0000,   /* lui $15, %hi(.got.plt entry)                 */
956   0x01f90000,   /* l[wd] $25, %lo(.got.plt entry)($15)          */
957   0x25f80000,   /* addiu $24, $15, %lo(.got.plt entry)          */
958   0x03200008    /* jr $25                                       */
959 };
960
961 /* The format of the first PLT entry in a VxWorks executable.  */
962 static const bfd_vma mips_vxworks_exec_plt0_entry[] =
963 {
964   0x3c190000,   /* lui t9, %hi(_GLOBAL_OFFSET_TABLE_)           */
965   0x27390000,   /* addiu t9, t9, %lo(_GLOBAL_OFFSET_TABLE_)     */
966   0x8f390008,   /* lw t9, 8(t9)                                 */
967   0x00000000,   /* nop                                          */
968   0x03200008,   /* jr t9                                        */
969   0x00000000    /* nop                                          */
970 };
971
972 /* The format of subsequent PLT entries.  */
973 static const bfd_vma mips_vxworks_exec_plt_entry[] =
974 {
975   0x10000000,   /* b .PLT_resolver                      */
976   0x24180000,   /* li t8, <pltindex>                    */
977   0x3c190000,   /* lui t9, %hi(<.got.plt slot>)         */
978   0x27390000,   /* addiu t9, t9, %lo(<.got.plt slot>)   */
979   0x8f390000,   /* lw t9, 0(t9)                         */
980   0x00000000,   /* nop                                  */
981   0x03200008,   /* jr t9                                */
982   0x00000000    /* nop                                  */
983 };
984
985 /* The format of the first PLT entry in a VxWorks shared object.  */
986 static const bfd_vma mips_vxworks_shared_plt0_entry[] =
987 {
988   0x8f990008,   /* lw t9, 8(gp)         */
989   0x00000000,   /* nop                  */
990   0x03200008,   /* jr t9                */
991   0x00000000,   /* nop                  */
992   0x00000000,   /* nop                  */
993   0x00000000    /* nop                  */
994 };
995
996 /* The format of subsequent PLT entries.  */
997 static const bfd_vma mips_vxworks_shared_plt_entry[] =
998 {
999   0x10000000,   /* b .PLT_resolver      */
1000   0x24180000    /* li t8, <pltindex>    */
1001 };
1002 \f
1003 /* microMIPS 32-bit opcode helper installer.  */
1004
1005 static void
1006 bfd_put_micromips_32 (const bfd *abfd, bfd_vma opcode, bfd_byte *ptr)
1007 {
1008   bfd_put_16 (abfd, (opcode >> 16) & 0xffff, ptr);
1009   bfd_put_16 (abfd,  opcode        & 0xffff, ptr + 2);
1010 }
1011
1012 /* microMIPS 32-bit opcode helper retriever.  */
1013
1014 static bfd_vma
1015 bfd_get_micromips_32 (const bfd *abfd, const bfd_byte *ptr)
1016 {
1017   return (bfd_get_16 (abfd, ptr) << 16) | bfd_get_16 (abfd, ptr + 2);
1018 }
1019 \f
1020 /* Look up an entry in a MIPS ELF linker hash table.  */
1021
1022 #define mips_elf_link_hash_lookup(table, string, create, copy, follow)  \
1023   ((struct mips_elf_link_hash_entry *)                                  \
1024    elf_link_hash_lookup (&(table)->root, (string), (create),            \
1025                          (copy), (follow)))
1026
1027 /* Traverse a MIPS ELF linker hash table.  */
1028
1029 #define mips_elf_link_hash_traverse(table, func, info)                  \
1030   (elf_link_hash_traverse                                               \
1031    (&(table)->root,                                                     \
1032     (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func),    \
1033     (info)))
1034
1035 /* Find the base offsets for thread-local storage in this object,
1036    for GD/LD and IE/LE respectively.  */
1037
1038 #define TP_OFFSET 0x7000
1039 #define DTP_OFFSET 0x8000
1040
1041 static bfd_vma
1042 dtprel_base (struct bfd_link_info *info)
1043 {
1044   /* If tls_sec is NULL, we should have signalled an error already.  */
1045   if (elf_hash_table (info)->tls_sec == NULL)
1046     return 0;
1047   return elf_hash_table (info)->tls_sec->vma + DTP_OFFSET;
1048 }
1049
1050 static bfd_vma
1051 tprel_base (struct bfd_link_info *info)
1052 {
1053   /* If tls_sec is NULL, we should have signalled an error already.  */
1054   if (elf_hash_table (info)->tls_sec == NULL)
1055     return 0;
1056   return elf_hash_table (info)->tls_sec->vma + TP_OFFSET;
1057 }
1058
1059 /* Create an entry in a MIPS ELF linker hash table.  */
1060
1061 static struct bfd_hash_entry *
1062 mips_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
1063                             struct bfd_hash_table *table, const char *string)
1064 {
1065   struct mips_elf_link_hash_entry *ret =
1066     (struct mips_elf_link_hash_entry *) entry;
1067
1068   /* Allocate the structure if it has not already been allocated by a
1069      subclass.  */
1070   if (ret == NULL)
1071     ret = bfd_hash_allocate (table, sizeof (struct mips_elf_link_hash_entry));
1072   if (ret == NULL)
1073     return (struct bfd_hash_entry *) ret;
1074
1075   /* Call the allocation method of the superclass.  */
1076   ret = ((struct mips_elf_link_hash_entry *)
1077          _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret,
1078                                      table, string));
1079   if (ret != NULL)
1080     {
1081       /* Set local fields.  */
1082       memset (&ret->esym, 0, sizeof (EXTR));
1083       /* We use -2 as a marker to indicate that the information has
1084          not been set.  -1 means there is no associated ifd.  */
1085       ret->esym.ifd = -2;
1086       ret->la25_stub = 0;
1087       ret->possibly_dynamic_relocs = 0;
1088       ret->fn_stub = NULL;
1089       ret->call_stub = NULL;
1090       ret->call_fp_stub = NULL;
1091       ret->global_got_area = GGA_NONE;
1092       ret->got_only_for_calls = TRUE;
1093       ret->readonly_reloc = FALSE;
1094       ret->has_static_relocs = FALSE;
1095       ret->no_fn_stub = FALSE;
1096       ret->need_fn_stub = FALSE;
1097       ret->has_nonpic_branches = FALSE;
1098       ret->needs_lazy_stub = FALSE;
1099     }
1100
1101   return (struct bfd_hash_entry *) ret;
1102 }
1103
1104 /* Allocate MIPS ELF private object data.  */
1105
1106 bfd_boolean
1107 _bfd_mips_elf_mkobject (bfd *abfd)
1108 {
1109   return bfd_elf_allocate_object (abfd, sizeof (struct mips_elf_obj_tdata),
1110                                   MIPS_ELF_DATA);
1111 }
1112
1113 bfd_boolean
1114 _bfd_mips_elf_new_section_hook (bfd *abfd, asection *sec)
1115 {
1116   if (!sec->used_by_bfd)
1117     {
1118       struct _mips_elf_section_data *sdata;
1119       bfd_size_type amt = sizeof (*sdata);
1120
1121       sdata = bfd_zalloc (abfd, amt);
1122       if (sdata == NULL)
1123         return FALSE;
1124       sec->used_by_bfd = sdata;
1125     }
1126
1127   return _bfd_elf_new_section_hook (abfd, sec);
1128 }
1129 \f
1130 /* Read ECOFF debugging information from a .mdebug section into a
1131    ecoff_debug_info structure.  */
1132
1133 bfd_boolean
1134 _bfd_mips_elf_read_ecoff_info (bfd *abfd, asection *section,
1135                                struct ecoff_debug_info *debug)
1136 {
1137   HDRR *symhdr;
1138   const struct ecoff_debug_swap *swap;
1139   char *ext_hdr;
1140
1141   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1142   memset (debug, 0, sizeof (*debug));
1143
1144   ext_hdr = bfd_malloc (swap->external_hdr_size);
1145   if (ext_hdr == NULL && swap->external_hdr_size != 0)
1146     goto error_return;
1147
1148   if (! bfd_get_section_contents (abfd, section, ext_hdr, 0,
1149                                   swap->external_hdr_size))
1150     goto error_return;
1151
1152   symhdr = &debug->symbolic_header;
1153   (*swap->swap_hdr_in) (abfd, ext_hdr, symhdr);
1154
1155   /* The symbolic header contains absolute file offsets and sizes to
1156      read.  */
1157 #define READ(ptr, offset, count, size, type)                            \
1158   if (symhdr->count == 0)                                               \
1159     debug->ptr = NULL;                                                  \
1160   else                                                                  \
1161     {                                                                   \
1162       bfd_size_type amt = (bfd_size_type) size * symhdr->count;         \
1163       debug->ptr = bfd_malloc (amt);                                    \
1164       if (debug->ptr == NULL)                                           \
1165         goto error_return;                                              \
1166       if (bfd_seek (abfd, symhdr->offset, SEEK_SET) != 0                \
1167           || bfd_bread (debug->ptr, amt, abfd) != amt)                  \
1168         goto error_return;                                              \
1169     }
1170
1171   READ (line, cbLineOffset, cbLine, sizeof (unsigned char), unsigned char *);
1172   READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *);
1173   READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *);
1174   READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *);
1175   READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *);
1176   READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext),
1177         union aux_ext *);
1178   READ (ss, cbSsOffset, issMax, sizeof (char), char *);
1179   READ (ssext, cbSsExtOffset, issExtMax, sizeof (char), char *);
1180   READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *);
1181   READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *);
1182   READ (external_ext, cbExtOffset, iextMax, swap->external_ext_size, void *);
1183 #undef READ
1184
1185   debug->fdr = NULL;
1186
1187   return TRUE;
1188
1189  error_return:
1190   if (ext_hdr != NULL)
1191     free (ext_hdr);
1192   if (debug->line != NULL)
1193     free (debug->line);
1194   if (debug->external_dnr != NULL)
1195     free (debug->external_dnr);
1196   if (debug->external_pdr != NULL)
1197     free (debug->external_pdr);
1198   if (debug->external_sym != NULL)
1199     free (debug->external_sym);
1200   if (debug->external_opt != NULL)
1201     free (debug->external_opt);
1202   if (debug->external_aux != NULL)
1203     free (debug->external_aux);
1204   if (debug->ss != NULL)
1205     free (debug->ss);
1206   if (debug->ssext != NULL)
1207     free (debug->ssext);
1208   if (debug->external_fdr != NULL)
1209     free (debug->external_fdr);
1210   if (debug->external_rfd != NULL)
1211     free (debug->external_rfd);
1212   if (debug->external_ext != NULL)
1213     free (debug->external_ext);
1214   return FALSE;
1215 }
1216 \f
1217 /* Swap RPDR (runtime procedure table entry) for output.  */
1218
1219 static void
1220 ecoff_swap_rpdr_out (bfd *abfd, const RPDR *in, struct rpdr_ext *ex)
1221 {
1222   H_PUT_S32 (abfd, in->adr, ex->p_adr);
1223   H_PUT_32 (abfd, in->regmask, ex->p_regmask);
1224   H_PUT_32 (abfd, in->regoffset, ex->p_regoffset);
1225   H_PUT_32 (abfd, in->fregmask, ex->p_fregmask);
1226   H_PUT_32 (abfd, in->fregoffset, ex->p_fregoffset);
1227   H_PUT_32 (abfd, in->frameoffset, ex->p_frameoffset);
1228
1229   H_PUT_16 (abfd, in->framereg, ex->p_framereg);
1230   H_PUT_16 (abfd, in->pcreg, ex->p_pcreg);
1231
1232   H_PUT_32 (abfd, in->irpss, ex->p_irpss);
1233 }
1234
1235 /* Create a runtime procedure table from the .mdebug section.  */
1236
1237 static bfd_boolean
1238 mips_elf_create_procedure_table (void *handle, bfd *abfd,
1239                                  struct bfd_link_info *info, asection *s,
1240                                  struct ecoff_debug_info *debug)
1241 {
1242   const struct ecoff_debug_swap *swap;
1243   HDRR *hdr = &debug->symbolic_header;
1244   RPDR *rpdr, *rp;
1245   struct rpdr_ext *erp;
1246   void *rtproc;
1247   struct pdr_ext *epdr;
1248   struct sym_ext *esym;
1249   char *ss, **sv;
1250   char *str;
1251   bfd_size_type size;
1252   bfd_size_type count;
1253   unsigned long sindex;
1254   unsigned long i;
1255   PDR pdr;
1256   SYMR sym;
1257   const char *no_name_func = _("static procedure (no name)");
1258
1259   epdr = NULL;
1260   rpdr = NULL;
1261   esym = NULL;
1262   ss = NULL;
1263   sv = NULL;
1264
1265   swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1266
1267   sindex = strlen (no_name_func) + 1;
1268   count = hdr->ipdMax;
1269   if (count > 0)
1270     {
1271       size = swap->external_pdr_size;
1272
1273       epdr = bfd_malloc (size * count);
1274       if (epdr == NULL)
1275         goto error_return;
1276
1277       if (! _bfd_ecoff_get_accumulated_pdr (handle, (bfd_byte *) epdr))
1278         goto error_return;
1279
1280       size = sizeof (RPDR);
1281       rp = rpdr = bfd_malloc (size * count);
1282       if (rpdr == NULL)
1283         goto error_return;
1284
1285       size = sizeof (char *);
1286       sv = bfd_malloc (size * count);
1287       if (sv == NULL)
1288         goto error_return;
1289
1290       count = hdr->isymMax;
1291       size = swap->external_sym_size;
1292       esym = bfd_malloc (size * count);
1293       if (esym == NULL)
1294         goto error_return;
1295
1296       if (! _bfd_ecoff_get_accumulated_sym (handle, (bfd_byte *) esym))
1297         goto error_return;
1298
1299       count = hdr->issMax;
1300       ss = bfd_malloc (count);
1301       if (ss == NULL)
1302         goto error_return;
1303       if (! _bfd_ecoff_get_accumulated_ss (handle, (bfd_byte *) ss))
1304         goto error_return;
1305
1306       count = hdr->ipdMax;
1307       for (i = 0; i < (unsigned long) count; i++, rp++)
1308         {
1309           (*swap->swap_pdr_in) (abfd, epdr + i, &pdr);
1310           (*swap->swap_sym_in) (abfd, &esym[pdr.isym], &sym);
1311           rp->adr = sym.value;
1312           rp->regmask = pdr.regmask;
1313           rp->regoffset = pdr.regoffset;
1314           rp->fregmask = pdr.fregmask;
1315           rp->fregoffset = pdr.fregoffset;
1316           rp->frameoffset = pdr.frameoffset;
1317           rp->framereg = pdr.framereg;
1318           rp->pcreg = pdr.pcreg;
1319           rp->irpss = sindex;
1320           sv[i] = ss + sym.iss;
1321           sindex += strlen (sv[i]) + 1;
1322         }
1323     }
1324
1325   size = sizeof (struct rpdr_ext) * (count + 2) + sindex;
1326   size = BFD_ALIGN (size, 16);
1327   rtproc = bfd_alloc (abfd, size);
1328   if (rtproc == NULL)
1329     {
1330       mips_elf_hash_table (info)->procedure_count = 0;
1331       goto error_return;
1332     }
1333
1334   mips_elf_hash_table (info)->procedure_count = count + 2;
1335
1336   erp = rtproc;
1337   memset (erp, 0, sizeof (struct rpdr_ext));
1338   erp++;
1339   str = (char *) rtproc + sizeof (struct rpdr_ext) * (count + 2);
1340   strcpy (str, no_name_func);
1341   str += strlen (no_name_func) + 1;
1342   for (i = 0; i < count; i++)
1343     {
1344       ecoff_swap_rpdr_out (abfd, rpdr + i, erp + i);
1345       strcpy (str, sv[i]);
1346       str += strlen (sv[i]) + 1;
1347     }
1348   H_PUT_S32 (abfd, -1, (erp + count)->p_adr);
1349
1350   /* Set the size and contents of .rtproc section.  */
1351   s->size = size;
1352   s->contents = rtproc;
1353
1354   /* Skip this section later on (I don't think this currently
1355      matters, but someday it might).  */
1356   s->map_head.link_order = NULL;
1357
1358   if (epdr != NULL)
1359     free (epdr);
1360   if (rpdr != NULL)
1361     free (rpdr);
1362   if (esym != NULL)
1363     free (esym);
1364   if (ss != NULL)
1365     free (ss);
1366   if (sv != NULL)
1367     free (sv);
1368
1369   return TRUE;
1370
1371  error_return:
1372   if (epdr != NULL)
1373     free (epdr);
1374   if (rpdr != NULL)
1375     free (rpdr);
1376   if (esym != NULL)
1377     free (esym);
1378   if (ss != NULL)
1379     free (ss);
1380   if (sv != NULL)
1381     free (sv);
1382   return FALSE;
1383 }
1384 \f
1385 /* We're going to create a stub for H.  Create a symbol for the stub's
1386    value and size, to help make the disassembly easier to read.  */
1387
1388 static bfd_boolean
1389 mips_elf_create_stub_symbol (struct bfd_link_info *info,
1390                              struct mips_elf_link_hash_entry *h,
1391                              const char *prefix, asection *s, bfd_vma value,
1392                              bfd_vma size)
1393 {
1394   struct bfd_link_hash_entry *bh;
1395   struct elf_link_hash_entry *elfh;
1396   const char *name;
1397
1398   if (ELF_ST_IS_MICROMIPS (h->root.other))
1399     value |= 1;
1400
1401   /* Create a new symbol.  */
1402   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1403   bh = NULL;
1404   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1405                                          BSF_LOCAL, s, value, NULL,
1406                                          TRUE, FALSE, &bh))
1407     return FALSE;
1408
1409   /* Make it a local function.  */
1410   elfh = (struct elf_link_hash_entry *) bh;
1411   elfh->type = ELF_ST_INFO (STB_LOCAL, STT_FUNC);
1412   elfh->size = size;
1413   elfh->forced_local = 1;
1414   return TRUE;
1415 }
1416
1417 /* We're about to redefine H.  Create a symbol to represent H's
1418    current value and size, to help make the disassembly easier
1419    to read.  */
1420
1421 static bfd_boolean
1422 mips_elf_create_shadow_symbol (struct bfd_link_info *info,
1423                                struct mips_elf_link_hash_entry *h,
1424                                const char *prefix)
1425 {
1426   struct bfd_link_hash_entry *bh;
1427   struct elf_link_hash_entry *elfh;
1428   const char *name;
1429   asection *s;
1430   bfd_vma value;
1431
1432   /* Read the symbol's value.  */
1433   BFD_ASSERT (h->root.root.type == bfd_link_hash_defined
1434               || h->root.root.type == bfd_link_hash_defweak);
1435   s = h->root.root.u.def.section;
1436   value = h->root.root.u.def.value;
1437
1438   /* Create a new symbol.  */
1439   name = ACONCAT ((prefix, h->root.root.root.string, NULL));
1440   bh = NULL;
1441   if (!_bfd_generic_link_add_one_symbol (info, s->owner, name,
1442                                          BSF_LOCAL, s, value, NULL,
1443                                          TRUE, FALSE, &bh))
1444     return FALSE;
1445
1446   /* Make it local and copy the other attributes from H.  */
1447   elfh = (struct elf_link_hash_entry *) bh;
1448   elfh->type = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (h->root.type));
1449   elfh->other = h->root.other;
1450   elfh->size = h->root.size;
1451   elfh->forced_local = 1;
1452   return TRUE;
1453 }
1454
1455 /* Return TRUE if relocations in SECTION can refer directly to a MIPS16
1456    function rather than to a hard-float stub.  */
1457
1458 static bfd_boolean
1459 section_allows_mips16_refs_p (asection *section)
1460 {
1461   const char *name;
1462
1463   name = bfd_get_section_name (section->owner, section);
1464   return (FN_STUB_P (name)
1465           || CALL_STUB_P (name)
1466           || CALL_FP_STUB_P (name)
1467           || strcmp (name, ".pdr") == 0);
1468 }
1469
1470 /* [RELOCS, RELEND) are the relocations against SEC, which is a MIPS16
1471    stub section of some kind.  Return the R_SYMNDX of the target
1472    function, or 0 if we can't decide which function that is.  */
1473
1474 static unsigned long
1475 mips16_stub_symndx (const struct elf_backend_data *bed,
1476                     asection *sec ATTRIBUTE_UNUSED,
1477                     const Elf_Internal_Rela *relocs,
1478                     const Elf_Internal_Rela *relend)
1479 {
1480   int int_rels_per_ext_rel = bed->s->int_rels_per_ext_rel;
1481   const Elf_Internal_Rela *rel;
1482
1483   /* Trust the first R_MIPS_NONE relocation, if any, but not a subsequent
1484      one in a compound relocation.  */
1485   for (rel = relocs; rel < relend; rel += int_rels_per_ext_rel)
1486     if (ELF_R_TYPE (sec->owner, rel->r_info) == R_MIPS_NONE)
1487       return ELF_R_SYM (sec->owner, rel->r_info);
1488
1489   /* Otherwise trust the first relocation, whatever its kind.  This is
1490      the traditional behavior.  */
1491   if (relocs < relend)
1492     return ELF_R_SYM (sec->owner, relocs->r_info);
1493
1494   return 0;
1495 }
1496
1497 /* Check the mips16 stubs for a particular symbol, and see if we can
1498    discard them.  */
1499
1500 static void
1501 mips_elf_check_mips16_stubs (struct bfd_link_info *info,
1502                              struct mips_elf_link_hash_entry *h)
1503 {
1504   /* Dynamic symbols must use the standard call interface, in case other
1505      objects try to call them.  */
1506   if (h->fn_stub != NULL
1507       && h->root.dynindx != -1)
1508     {
1509       mips_elf_create_shadow_symbol (info, h, ".mips16.");
1510       h->need_fn_stub = TRUE;
1511     }
1512
1513   if (h->fn_stub != NULL
1514       && ! h->need_fn_stub)
1515     {
1516       /* We don't need the fn_stub; the only references to this symbol
1517          are 16 bit calls.  Clobber the size to 0 to prevent it from
1518          being included in the link.  */
1519       h->fn_stub->size = 0;
1520       h->fn_stub->flags &= ~SEC_RELOC;
1521       h->fn_stub->reloc_count = 0;
1522       h->fn_stub->flags |= SEC_EXCLUDE;
1523     }
1524
1525   if (h->call_stub != NULL
1526       && ELF_ST_IS_MIPS16 (h->root.other))
1527     {
1528       /* We don't need the call_stub; this is a 16 bit function, so
1529          calls from other 16 bit functions are OK.  Clobber the size
1530          to 0 to prevent it from being included in the link.  */
1531       h->call_stub->size = 0;
1532       h->call_stub->flags &= ~SEC_RELOC;
1533       h->call_stub->reloc_count = 0;
1534       h->call_stub->flags |= SEC_EXCLUDE;
1535     }
1536
1537   if (h->call_fp_stub != NULL
1538       && ELF_ST_IS_MIPS16 (h->root.other))
1539     {
1540       /* We don't need the call_stub; this is a 16 bit function, so
1541          calls from other 16 bit functions are OK.  Clobber the size
1542          to 0 to prevent it from being included in the link.  */
1543       h->call_fp_stub->size = 0;
1544       h->call_fp_stub->flags &= ~SEC_RELOC;
1545       h->call_fp_stub->reloc_count = 0;
1546       h->call_fp_stub->flags |= SEC_EXCLUDE;
1547     }
1548 }
1549
1550 /* Hashtable callbacks for mips_elf_la25_stubs.  */
1551
1552 static hashval_t
1553 mips_elf_la25_stub_hash (const void *entry_)
1554 {
1555   const struct mips_elf_la25_stub *entry;
1556
1557   entry = (struct mips_elf_la25_stub *) entry_;
1558   return entry->h->root.root.u.def.section->id
1559     + entry->h->root.root.u.def.value;
1560 }
1561
1562 static int
1563 mips_elf_la25_stub_eq (const void *entry1_, const void *entry2_)
1564 {
1565   const struct mips_elf_la25_stub *entry1, *entry2;
1566
1567   entry1 = (struct mips_elf_la25_stub *) entry1_;
1568   entry2 = (struct mips_elf_la25_stub *) entry2_;
1569   return ((entry1->h->root.root.u.def.section
1570            == entry2->h->root.root.u.def.section)
1571           && (entry1->h->root.root.u.def.value
1572               == entry2->h->root.root.u.def.value));
1573 }
1574
1575 /* Called by the linker to set up the la25 stub-creation code.  FN is
1576    the linker's implementation of add_stub_function.  Return true on
1577    success.  */
1578
1579 bfd_boolean
1580 _bfd_mips_elf_init_stubs (struct bfd_link_info *info,
1581                           asection *(*fn) (const char *, asection *,
1582                                            asection *))
1583 {
1584   struct mips_elf_link_hash_table *htab;
1585
1586   htab = mips_elf_hash_table (info);
1587   if (htab == NULL)
1588     return FALSE;
1589
1590   htab->add_stub_section = fn;
1591   htab->la25_stubs = htab_try_create (1, mips_elf_la25_stub_hash,
1592                                       mips_elf_la25_stub_eq, NULL);
1593   if (htab->la25_stubs == NULL)
1594     return FALSE;
1595
1596   return TRUE;
1597 }
1598
1599 /* Return true if H is a locally-defined PIC function, in the sense
1600    that it or its fn_stub might need $25 to be valid on entry.
1601    Note that MIPS16 functions set up $gp using PC-relative instructions,
1602    so they themselves never need $25 to be valid.  Only non-MIPS16
1603    entry points are of interest here.  */
1604
1605 static bfd_boolean
1606 mips_elf_local_pic_function_p (struct mips_elf_link_hash_entry *h)
1607 {
1608   return ((h->root.root.type == bfd_link_hash_defined
1609            || h->root.root.type == bfd_link_hash_defweak)
1610           && h->root.def_regular
1611           && !bfd_is_abs_section (h->root.root.u.def.section)
1612           && (!ELF_ST_IS_MIPS16 (h->root.other)
1613               || (h->fn_stub && h->need_fn_stub))
1614           && (PIC_OBJECT_P (h->root.root.u.def.section->owner)
1615               || ELF_ST_IS_MIPS_PIC (h->root.other)));
1616 }
1617
1618 /* Set *SEC to the input section that contains the target of STUB.
1619    Return the offset of the target from the start of that section.  */
1620
1621 static bfd_vma
1622 mips_elf_get_la25_target (struct mips_elf_la25_stub *stub,
1623                           asection **sec)
1624 {
1625   if (ELF_ST_IS_MIPS16 (stub->h->root.other))
1626     {
1627       BFD_ASSERT (stub->h->need_fn_stub);
1628       *sec = stub->h->fn_stub;
1629       return 0;
1630     }
1631   else
1632     {
1633       *sec = stub->h->root.root.u.def.section;
1634       return stub->h->root.root.u.def.value;
1635     }
1636 }
1637
1638 /* STUB describes an la25 stub that we have decided to implement
1639    by inserting an LUI/ADDIU pair before the target function.
1640    Create the section and redirect the function symbol to it.  */
1641
1642 static bfd_boolean
1643 mips_elf_add_la25_intro (struct mips_elf_la25_stub *stub,
1644                          struct bfd_link_info *info)
1645 {
1646   struct mips_elf_link_hash_table *htab;
1647   char *name;
1648   asection *s, *input_section;
1649   unsigned int align;
1650
1651   htab = mips_elf_hash_table (info);
1652   if (htab == NULL)
1653     return FALSE;
1654
1655   /* Create a unique name for the new section.  */
1656   name = bfd_malloc (11 + sizeof (".text.stub."));
1657   if (name == NULL)
1658     return FALSE;
1659   sprintf (name, ".text.stub.%d", (int) htab_elements (htab->la25_stubs));
1660
1661   /* Create the section.  */
1662   mips_elf_get_la25_target (stub, &input_section);
1663   s = htab->add_stub_section (name, input_section,
1664                               input_section->output_section);
1665   if (s == NULL)
1666     return FALSE;
1667
1668   /* Make sure that any padding goes before the stub.  */
1669   align = input_section->alignment_power;
1670   if (!bfd_set_section_alignment (s->owner, s, align))
1671     return FALSE;
1672   if (align > 3)
1673     s->size = (1 << align) - 8;
1674
1675   /* Create a symbol for the stub.  */
1676   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 8);
1677   stub->stub_section = s;
1678   stub->offset = s->size;
1679
1680   /* Allocate room for it.  */
1681   s->size += 8;
1682   return TRUE;
1683 }
1684
1685 /* STUB describes an la25 stub that we have decided to implement
1686    with a separate trampoline.  Allocate room for it and redirect
1687    the function symbol to it.  */
1688
1689 static bfd_boolean
1690 mips_elf_add_la25_trampoline (struct mips_elf_la25_stub *stub,
1691                               struct bfd_link_info *info)
1692 {
1693   struct mips_elf_link_hash_table *htab;
1694   asection *s;
1695
1696   htab = mips_elf_hash_table (info);
1697   if (htab == NULL)
1698     return FALSE;
1699
1700   /* Create a trampoline section, if we haven't already.  */
1701   s = htab->strampoline;
1702   if (s == NULL)
1703     {
1704       asection *input_section = stub->h->root.root.u.def.section;
1705       s = htab->add_stub_section (".text", NULL,
1706                                   input_section->output_section);
1707       if (s == NULL || !bfd_set_section_alignment (s->owner, s, 4))
1708         return FALSE;
1709       htab->strampoline = s;
1710     }
1711
1712   /* Create a symbol for the stub.  */
1713   mips_elf_create_stub_symbol (info, stub->h, ".pic.", s, s->size, 16);
1714   stub->stub_section = s;
1715   stub->offset = s->size;
1716
1717   /* Allocate room for it.  */
1718   s->size += 16;
1719   return TRUE;
1720 }
1721
1722 /* H describes a symbol that needs an la25 stub.  Make sure that an
1723    appropriate stub exists and point H at it.  */
1724
1725 static bfd_boolean
1726 mips_elf_add_la25_stub (struct bfd_link_info *info,
1727                         struct mips_elf_link_hash_entry *h)
1728 {
1729   struct mips_elf_link_hash_table *htab;
1730   struct mips_elf_la25_stub search, *stub;
1731   bfd_boolean use_trampoline_p;
1732   asection *s;
1733   bfd_vma value;
1734   void **slot;
1735
1736   /* Describe the stub we want.  */
1737   search.stub_section = NULL;
1738   search.offset = 0;
1739   search.h = h;
1740
1741   /* See if we've already created an equivalent stub.  */
1742   htab = mips_elf_hash_table (info);
1743   if (htab == NULL)
1744     return FALSE;
1745
1746   slot = htab_find_slot (htab->la25_stubs, &search, INSERT);
1747   if (slot == NULL)
1748     return FALSE;
1749
1750   stub = (struct mips_elf_la25_stub *) *slot;
1751   if (stub != NULL)
1752     {
1753       /* We can reuse the existing stub.  */
1754       h->la25_stub = stub;
1755       return TRUE;
1756     }
1757
1758   /* Create a permanent copy of ENTRY and add it to the hash table.  */
1759   stub = bfd_malloc (sizeof (search));
1760   if (stub == NULL)
1761     return FALSE;
1762   *stub = search;
1763   *slot = stub;
1764
1765   /* Prefer to use LUI/ADDIU stubs if the function is at the beginning
1766      of the section and if we would need no more than 2 nops.  */
1767   value = mips_elf_get_la25_target (stub, &s);
1768   use_trampoline_p = (value != 0 || s->alignment_power > 4);
1769
1770   h->la25_stub = stub;
1771   return (use_trampoline_p
1772           ? mips_elf_add_la25_trampoline (stub, info)
1773           : mips_elf_add_la25_intro (stub, info));
1774 }
1775
1776 /* A mips_elf_link_hash_traverse callback that is called before sizing
1777    sections.  DATA points to a mips_htab_traverse_info structure.  */
1778
1779 static bfd_boolean
1780 mips_elf_check_symbols (struct mips_elf_link_hash_entry *h, void *data)
1781 {
1782   struct mips_htab_traverse_info *hti;
1783
1784   hti = (struct mips_htab_traverse_info *) data;
1785   if (!hti->info->relocatable)
1786     mips_elf_check_mips16_stubs (hti->info, h);
1787
1788   if (mips_elf_local_pic_function_p (h))
1789     {
1790       /* PR 12845: If H is in a section that has been garbage
1791          collected it will have its output section set to *ABS*.  */
1792       if (bfd_is_abs_section (h->root.root.u.def.section->output_section))
1793         return TRUE;
1794
1795       /* H is a function that might need $25 to be valid on entry.
1796          If we're creating a non-PIC relocatable object, mark H as
1797          being PIC.  If we're creating a non-relocatable object with
1798          non-PIC branches and jumps to H, make sure that H has an la25
1799          stub.  */
1800       if (hti->info->relocatable)
1801         {
1802           if (!PIC_OBJECT_P (hti->output_bfd))
1803             h->root.other = ELF_ST_SET_MIPS_PIC (h->root.other);
1804         }
1805       else if (h->has_nonpic_branches && !mips_elf_add_la25_stub (hti->info, h))
1806         {
1807           hti->error = TRUE;
1808           return FALSE;
1809         }
1810     }
1811   return TRUE;
1812 }
1813 \f
1814 /* R_MIPS16_26 is used for the mips16 jal and jalx instructions.
1815    Most mips16 instructions are 16 bits, but these instructions
1816    are 32 bits.
1817
1818    The format of these instructions is:
1819
1820    +--------------+--------------------------------+
1821    |     JALX     | X|   Imm 20:16  |   Imm 25:21  |
1822    +--------------+--------------------------------+
1823    |                Immediate  15:0                |
1824    +-----------------------------------------------+
1825
1826    JALX is the 5-bit value 00011.  X is 0 for jal, 1 for jalx.
1827    Note that the immediate value in the first word is swapped.
1828
1829    When producing a relocatable object file, R_MIPS16_26 is
1830    handled mostly like R_MIPS_26.  In particular, the addend is
1831    stored as a straight 26-bit value in a 32-bit instruction.
1832    (gas makes life simpler for itself by never adjusting a
1833    R_MIPS16_26 reloc to be against a section, so the addend is
1834    always zero).  However, the 32 bit instruction is stored as 2
1835    16-bit values, rather than a single 32-bit value.  In a
1836    big-endian file, the result is the same; in a little-endian
1837    file, the two 16-bit halves of the 32 bit value are swapped.
1838    This is so that a disassembler can recognize the jal
1839    instruction.
1840
1841    When doing a final link, R_MIPS16_26 is treated as a 32 bit
1842    instruction stored as two 16-bit values.  The addend A is the
1843    contents of the targ26 field.  The calculation is the same as
1844    R_MIPS_26.  When storing the calculated value, reorder the
1845    immediate value as shown above, and don't forget to store the
1846    value as two 16-bit values.
1847
1848    To put it in MIPS ABI terms, the relocation field is T-targ26-16,
1849    defined as
1850
1851    big-endian:
1852    +--------+----------------------+
1853    |        |                      |
1854    |        |    targ26-16         |
1855    |31    26|25                   0|
1856    +--------+----------------------+
1857
1858    little-endian:
1859    +----------+------+-------------+
1860    |          |      |             |
1861    |  sub1    |      |     sub2    |
1862    |0        9|10  15|16         31|
1863    +----------+--------------------+
1864    where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is
1865    ((sub1 << 16) | sub2)).
1866
1867    When producing a relocatable object file, the calculation is
1868    (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1869    When producing a fully linked file, the calculation is
1870    let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2)
1871    ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff)
1872
1873    The table below lists the other MIPS16 instruction relocations.
1874    Each one is calculated in the same way as the non-MIPS16 relocation
1875    given on the right, but using the extended MIPS16 layout of 16-bit
1876    immediate fields:
1877
1878         R_MIPS16_GPREL          R_MIPS_GPREL16
1879         R_MIPS16_GOT16          R_MIPS_GOT16
1880         R_MIPS16_CALL16         R_MIPS_CALL16
1881         R_MIPS16_HI16           R_MIPS_HI16
1882         R_MIPS16_LO16           R_MIPS_LO16
1883
1884    A typical instruction will have a format like this:
1885
1886    +--------------+--------------------------------+
1887    |    EXTEND    |     Imm 10:5    |   Imm 15:11  |
1888    +--------------+--------------------------------+
1889    |    Major     |   rx   |   ry   |   Imm  4:0   |
1890    +--------------+--------------------------------+
1891
1892    EXTEND is the five bit value 11110.  Major is the instruction
1893    opcode.
1894
1895    All we need to do here is shuffle the bits appropriately.
1896    As above, the two 16-bit halves must be swapped on a
1897    little-endian system.  */
1898
1899 static inline bfd_boolean
1900 mips16_reloc_p (int r_type)
1901 {
1902   switch (r_type)
1903     {
1904     case R_MIPS16_26:
1905     case R_MIPS16_GPREL:
1906     case R_MIPS16_GOT16:
1907     case R_MIPS16_CALL16:
1908     case R_MIPS16_HI16:
1909     case R_MIPS16_LO16:
1910     case R_MIPS16_TLS_GD:
1911     case R_MIPS16_TLS_LDM:
1912     case R_MIPS16_TLS_DTPREL_HI16:
1913     case R_MIPS16_TLS_DTPREL_LO16:
1914     case R_MIPS16_TLS_GOTTPREL:
1915     case R_MIPS16_TLS_TPREL_HI16:
1916     case R_MIPS16_TLS_TPREL_LO16:
1917       return TRUE;
1918
1919     default:
1920       return FALSE;
1921     }
1922 }
1923
1924 /* Check if a microMIPS reloc.  */
1925
1926 static inline bfd_boolean
1927 micromips_reloc_p (unsigned int r_type)
1928 {
1929   return r_type >= R_MICROMIPS_min && r_type < R_MICROMIPS_max;
1930 }
1931
1932 /* Similar to MIPS16, the two 16-bit halves in microMIPS must be swapped
1933    on a little-endian system.  This does not apply to R_MICROMIPS_PC7_S1
1934    and R_MICROMIPS_PC10_S1 relocs that apply to 16-bit instructions.  */
1935
1936 static inline bfd_boolean
1937 micromips_reloc_shuffle_p (unsigned int r_type)
1938 {
1939   return (micromips_reloc_p (r_type)
1940           && r_type != R_MICROMIPS_PC7_S1
1941           && r_type != R_MICROMIPS_PC10_S1);
1942 }
1943
1944 static inline bfd_boolean
1945 got16_reloc_p (int r_type)
1946 {
1947   return (r_type == R_MIPS_GOT16
1948           || r_type == R_MIPS16_GOT16
1949           || r_type == R_MICROMIPS_GOT16);
1950 }
1951
1952 static inline bfd_boolean
1953 call16_reloc_p (int r_type)
1954 {
1955   return (r_type == R_MIPS_CALL16
1956           || r_type == R_MIPS16_CALL16
1957           || r_type == R_MICROMIPS_CALL16);
1958 }
1959
1960 static inline bfd_boolean
1961 got_disp_reloc_p (unsigned int r_type)
1962 {
1963   return r_type == R_MIPS_GOT_DISP || r_type == R_MICROMIPS_GOT_DISP;
1964 }
1965
1966 static inline bfd_boolean
1967 got_page_reloc_p (unsigned int r_type)
1968 {
1969   return r_type == R_MIPS_GOT_PAGE || r_type == R_MICROMIPS_GOT_PAGE;
1970 }
1971
1972 static inline bfd_boolean
1973 got_ofst_reloc_p (unsigned int r_type)
1974 {
1975   return r_type == R_MIPS_GOT_OFST || r_type == R_MICROMIPS_GOT_OFST;
1976 }
1977
1978 static inline bfd_boolean
1979 got_hi16_reloc_p (unsigned int r_type)
1980 {
1981   return r_type == R_MIPS_GOT_HI16 || r_type == R_MICROMIPS_GOT_HI16;
1982 }
1983
1984 static inline bfd_boolean
1985 got_lo16_reloc_p (unsigned int r_type)
1986 {
1987   return r_type == R_MIPS_GOT_LO16 || r_type == R_MICROMIPS_GOT_LO16;
1988 }
1989
1990 static inline bfd_boolean
1991 call_hi16_reloc_p (unsigned int r_type)
1992 {
1993   return r_type == R_MIPS_CALL_HI16 || r_type == R_MICROMIPS_CALL_HI16;
1994 }
1995
1996 static inline bfd_boolean
1997 call_lo16_reloc_p (unsigned int r_type)
1998 {
1999   return r_type == R_MIPS_CALL_LO16 || r_type == R_MICROMIPS_CALL_LO16;
2000 }
2001
2002 static inline bfd_boolean
2003 hi16_reloc_p (int r_type)
2004 {
2005   return (r_type == R_MIPS_HI16
2006           || r_type == R_MIPS16_HI16
2007           || r_type == R_MICROMIPS_HI16);
2008 }
2009
2010 static inline bfd_boolean
2011 lo16_reloc_p (int r_type)
2012 {
2013   return (r_type == R_MIPS_LO16
2014           || r_type == R_MIPS16_LO16
2015           || r_type == R_MICROMIPS_LO16);
2016 }
2017
2018 static inline bfd_boolean
2019 mips16_call_reloc_p (int r_type)
2020 {
2021   return r_type == R_MIPS16_26 || r_type == R_MIPS16_CALL16;
2022 }
2023
2024 static inline bfd_boolean
2025 jal_reloc_p (int r_type)
2026 {
2027   return (r_type == R_MIPS_26
2028           || r_type == R_MIPS16_26
2029           || r_type == R_MICROMIPS_26_S1);
2030 }
2031
2032 static inline bfd_boolean
2033 micromips_branch_reloc_p (int r_type)
2034 {
2035   return (r_type == R_MICROMIPS_26_S1
2036           || r_type == R_MICROMIPS_PC16_S1
2037           || r_type == R_MICROMIPS_PC10_S1
2038           || r_type == R_MICROMIPS_PC7_S1);
2039 }
2040
2041 static inline bfd_boolean
2042 tls_gd_reloc_p (unsigned int r_type)
2043 {
2044   return (r_type == R_MIPS_TLS_GD
2045           || r_type == R_MIPS16_TLS_GD
2046           || r_type == R_MICROMIPS_TLS_GD);
2047 }
2048
2049 static inline bfd_boolean
2050 tls_ldm_reloc_p (unsigned int r_type)
2051 {
2052   return (r_type == R_MIPS_TLS_LDM
2053           || r_type == R_MIPS16_TLS_LDM
2054           || r_type == R_MICROMIPS_TLS_LDM);
2055 }
2056
2057 static inline bfd_boolean
2058 tls_gottprel_reloc_p (unsigned int r_type)
2059 {
2060   return (r_type == R_MIPS_TLS_GOTTPREL
2061           || r_type == R_MIPS16_TLS_GOTTPREL
2062           || r_type == R_MICROMIPS_TLS_GOTTPREL);
2063 }
2064
2065 void
2066 _bfd_mips_elf_reloc_unshuffle (bfd *abfd, int r_type,
2067                                bfd_boolean jal_shuffle, bfd_byte *data)
2068 {
2069   bfd_vma first, second, val;
2070
2071   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2072     return;
2073
2074   /* Pick up the first and second halfwords of the instruction.  */
2075   first = bfd_get_16 (abfd, data);
2076   second = bfd_get_16 (abfd, data + 2);
2077   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2078     val = first << 16 | second;
2079   else if (r_type != R_MIPS16_26)
2080     val = (((first & 0xf800) << 16) | ((second & 0xffe0) << 11)
2081            | ((first & 0x1f) << 11) | (first & 0x7e0) | (second & 0x1f));
2082   else
2083     val = (((first & 0xfc00) << 16) | ((first & 0x3e0) << 11)
2084            | ((first & 0x1f) << 21) | second);
2085   bfd_put_32 (abfd, val, data);
2086 }
2087
2088 void
2089 _bfd_mips_elf_reloc_shuffle (bfd *abfd, int r_type,
2090                              bfd_boolean jal_shuffle, bfd_byte *data)
2091 {
2092   bfd_vma first, second, val;
2093
2094   if (!mips16_reloc_p (r_type) && !micromips_reloc_shuffle_p (r_type))
2095     return;
2096
2097   val = bfd_get_32 (abfd, data);
2098   if (micromips_reloc_p (r_type) || (r_type == R_MIPS16_26 && !jal_shuffle))
2099     {
2100       second = val & 0xffff;
2101       first = val >> 16;
2102     }
2103   else if (r_type != R_MIPS16_26)
2104     {
2105       second = ((val >> 11) & 0xffe0) | (val & 0x1f);
2106       first = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0);
2107     }
2108   else
2109     {
2110       second = val & 0xffff;
2111       first = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0)
2112                | ((val >> 21) & 0x1f);
2113     }
2114   bfd_put_16 (abfd, second, data + 2);
2115   bfd_put_16 (abfd, first, data);
2116 }
2117
2118 bfd_reloc_status_type
2119 _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol,
2120                                arelent *reloc_entry, asection *input_section,
2121                                bfd_boolean relocatable, void *data, bfd_vma gp)
2122 {
2123   bfd_vma relocation;
2124   bfd_signed_vma val;
2125   bfd_reloc_status_type status;
2126
2127   if (bfd_is_com_section (symbol->section))
2128     relocation = 0;
2129   else
2130     relocation = symbol->value;
2131
2132   relocation += symbol->section->output_section->vma;
2133   relocation += symbol->section->output_offset;
2134
2135   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2136     return bfd_reloc_outofrange;
2137
2138   /* Set val to the offset into the section or symbol.  */
2139   val = reloc_entry->addend;
2140
2141   _bfd_mips_elf_sign_extend (val, 16);
2142
2143   /* Adjust val for the final section location and GP value.  If we
2144      are producing relocatable output, we don't want to do this for
2145      an external symbol.  */
2146   if (! relocatable
2147       || (symbol->flags & BSF_SECTION_SYM) != 0)
2148     val += relocation - gp;
2149
2150   if (reloc_entry->howto->partial_inplace)
2151     {
2152       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2153                                        (bfd_byte *) data
2154                                        + reloc_entry->address);
2155       if (status != bfd_reloc_ok)
2156         return status;
2157     }
2158   else
2159     reloc_entry->addend = val;
2160
2161   if (relocatable)
2162     reloc_entry->address += input_section->output_offset;
2163
2164   return bfd_reloc_ok;
2165 }
2166
2167 /* Used to store a REL high-part relocation such as R_MIPS_HI16 or
2168    R_MIPS_GOT16.  REL is the relocation, INPUT_SECTION is the section
2169    that contains the relocation field and DATA points to the start of
2170    INPUT_SECTION.  */
2171
2172 struct mips_hi16
2173 {
2174   struct mips_hi16 *next;
2175   bfd_byte *data;
2176   asection *input_section;
2177   arelent rel;
2178 };
2179
2180 /* FIXME: This should not be a static variable.  */
2181
2182 static struct mips_hi16 *mips_hi16_list;
2183
2184 /* A howto special_function for REL *HI16 relocations.  We can only
2185    calculate the correct value once we've seen the partnering
2186    *LO16 relocation, so just save the information for later.
2187
2188    The ABI requires that the *LO16 immediately follow the *HI16.
2189    However, as a GNU extension, we permit an arbitrary number of
2190    *HI16s to be associated with a single *LO16.  This significantly
2191    simplies the relocation handling in gcc.  */
2192
2193 bfd_reloc_status_type
2194 _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2195                           asymbol *symbol ATTRIBUTE_UNUSED, void *data,
2196                           asection *input_section, bfd *output_bfd,
2197                           char **error_message ATTRIBUTE_UNUSED)
2198 {
2199   struct mips_hi16 *n;
2200
2201   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2202     return bfd_reloc_outofrange;
2203
2204   n = bfd_malloc (sizeof *n);
2205   if (n == NULL)
2206     return bfd_reloc_outofrange;
2207
2208   n->next = mips_hi16_list;
2209   n->data = data;
2210   n->input_section = input_section;
2211   n->rel = *reloc_entry;
2212   mips_hi16_list = n;
2213
2214   if (output_bfd != NULL)
2215     reloc_entry->address += input_section->output_offset;
2216
2217   return bfd_reloc_ok;
2218 }
2219
2220 /* A howto special_function for REL R_MIPS*_GOT16 relocations.  This is just
2221    like any other 16-bit relocation when applied to global symbols, but is
2222    treated in the same as R_MIPS_HI16 when applied to local symbols.  */
2223
2224 bfd_reloc_status_type
2225 _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2226                            void *data, asection *input_section,
2227                            bfd *output_bfd, char **error_message)
2228 {
2229   if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2230       || bfd_is_und_section (bfd_get_section (symbol))
2231       || bfd_is_com_section (bfd_get_section (symbol)))
2232     /* The relocation is against a global symbol.  */
2233     return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2234                                         input_section, output_bfd,
2235                                         error_message);
2236
2237   return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
2238                                    input_section, output_bfd, error_message);
2239 }
2240
2241 /* A howto special_function for REL *LO16 relocations.  The *LO16 itself
2242    is a straightforward 16 bit inplace relocation, but we must deal with
2243    any partnering high-part relocations as well.  */
2244
2245 bfd_reloc_status_type
2246 _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
2247                           void *data, asection *input_section,
2248                           bfd *output_bfd, char **error_message)
2249 {
2250   bfd_vma vallo;
2251   bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2252
2253   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2254     return bfd_reloc_outofrange;
2255
2256   _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2257                                  location);
2258   vallo = bfd_get_32 (abfd, location);
2259   _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2260                                location);
2261
2262   while (mips_hi16_list != NULL)
2263     {
2264       bfd_reloc_status_type ret;
2265       struct mips_hi16 *hi;
2266
2267       hi = mips_hi16_list;
2268
2269       /* R_MIPS*_GOT16 relocations are something of a special case.  We
2270          want to install the addend in the same way as for a R_MIPS*_HI16
2271          relocation (with a rightshift of 16).  However, since GOT16
2272          relocations can also be used with global symbols, their howto
2273          has a rightshift of 0.  */
2274       if (hi->rel.howto->type == R_MIPS_GOT16)
2275         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE);
2276       else if (hi->rel.howto->type == R_MIPS16_GOT16)
2277         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS16_HI16, FALSE);
2278       else if (hi->rel.howto->type == R_MICROMIPS_GOT16)
2279         hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MICROMIPS_HI16, FALSE);
2280
2281       /* VALLO is a signed 16-bit number.  Bias it by 0x8000 so that any
2282          carry or borrow will induce a change of +1 or -1 in the high part.  */
2283       hi->rel.addend += (vallo + 0x8000) & 0xffff;
2284
2285       ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data,
2286                                          hi->input_section, output_bfd,
2287                                          error_message);
2288       if (ret != bfd_reloc_ok)
2289         return ret;
2290
2291       mips_hi16_list = hi->next;
2292       free (hi);
2293     }
2294
2295   return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data,
2296                                       input_section, output_bfd,
2297                                       error_message);
2298 }
2299
2300 /* A generic howto special_function.  This calculates and installs the
2301    relocation itself, thus avoiding the oft-discussed problems in
2302    bfd_perform_relocation and bfd_install_relocation.  */
2303
2304 bfd_reloc_status_type
2305 _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry,
2306                              asymbol *symbol, void *data ATTRIBUTE_UNUSED,
2307                              asection *input_section, bfd *output_bfd,
2308                              char **error_message ATTRIBUTE_UNUSED)
2309 {
2310   bfd_signed_vma val;
2311   bfd_reloc_status_type status;
2312   bfd_boolean relocatable;
2313
2314   relocatable = (output_bfd != NULL);
2315
2316   if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
2317     return bfd_reloc_outofrange;
2318
2319   /* Build up the field adjustment in VAL.  */
2320   val = 0;
2321   if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)
2322     {
2323       /* Either we're calculating the final field value or we have a
2324          relocation against a section symbol.  Add in the section's
2325          offset or address.  */
2326       val += symbol->section->output_section->vma;
2327       val += symbol->section->output_offset;
2328     }
2329
2330   if (!relocatable)
2331     {
2332       /* We're calculating the final field value.  Add in the symbol's value
2333          and, if pc-relative, subtract the address of the field itself.  */
2334       val += symbol->value;
2335       if (reloc_entry->howto->pc_relative)
2336         {
2337           val -= input_section->output_section->vma;
2338           val -= input_section->output_offset;
2339           val -= reloc_entry->address;
2340         }
2341     }
2342
2343   /* VAL is now the final adjustment.  If we're keeping this relocation
2344      in the output file, and if the relocation uses a separate addend,
2345      we just need to add VAL to that addend.  Otherwise we need to add
2346      VAL to the relocation field itself.  */
2347   if (relocatable && !reloc_entry->howto->partial_inplace)
2348     reloc_entry->addend += val;
2349   else
2350     {
2351       bfd_byte *location = (bfd_byte *) data + reloc_entry->address;
2352
2353       /* Add in the separate addend, if any.  */
2354       val += reloc_entry->addend;
2355
2356       /* Add VAL to the relocation field.  */
2357       _bfd_mips_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE,
2358                                      location);
2359       status = _bfd_relocate_contents (reloc_entry->howto, abfd, val,
2360                                        location);
2361       _bfd_mips_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE,
2362                                    location);
2363
2364       if (status != bfd_reloc_ok)
2365         return status;
2366     }
2367
2368   if (relocatable)
2369     reloc_entry->address += input_section->output_offset;
2370
2371   return bfd_reloc_ok;
2372 }
2373 \f
2374 /* Swap an entry in a .gptab section.  Note that these routines rely
2375    on the equivalence of the two elements of the union.  */
2376
2377 static void
2378 bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex,
2379                               Elf32_gptab *in)
2380 {
2381   in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value);
2382   in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes);
2383 }
2384
2385 static void
2386 bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in,
2387                                Elf32_External_gptab *ex)
2388 {
2389   H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value);
2390   H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes);
2391 }
2392
2393 static void
2394 bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in,
2395                                 Elf32_External_compact_rel *ex)
2396 {
2397   H_PUT_32 (abfd, in->id1, ex->id1);
2398   H_PUT_32 (abfd, in->num, ex->num);
2399   H_PUT_32 (abfd, in->id2, ex->id2);
2400   H_PUT_32 (abfd, in->offset, ex->offset);
2401   H_PUT_32 (abfd, in->reserved0, ex->reserved0);
2402   H_PUT_32 (abfd, in->reserved1, ex->reserved1);
2403 }
2404
2405 static void
2406 bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in,
2407                            Elf32_External_crinfo *ex)
2408 {
2409   unsigned long l;
2410
2411   l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH)
2412        | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH)
2413        | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH)
2414        | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH));
2415   H_PUT_32 (abfd, l, ex->info);
2416   H_PUT_32 (abfd, in->konst, ex->konst);
2417   H_PUT_32 (abfd, in->vaddr, ex->vaddr);
2418 }
2419 \f
2420 /* A .reginfo section holds a single Elf32_RegInfo structure.  These
2421    routines swap this structure in and out.  They are used outside of
2422    BFD, so they are globally visible.  */
2423
2424 void
2425 bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex,
2426                                 Elf32_RegInfo *in)
2427 {
2428   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2429   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2430   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2431   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2432   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2433   in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value);
2434 }
2435
2436 void
2437 bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in,
2438                                  Elf32_External_RegInfo *ex)
2439 {
2440   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2441   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2442   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2443   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2444   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2445   H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value);
2446 }
2447
2448 /* In the 64 bit ABI, the .MIPS.options section holds register
2449    information in an Elf64_Reginfo structure.  These routines swap
2450    them in and out.  They are globally visible because they are used
2451    outside of BFD.  These routines are here so that gas can call them
2452    without worrying about whether the 64 bit ABI has been included.  */
2453
2454 void
2455 bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex,
2456                                 Elf64_Internal_RegInfo *in)
2457 {
2458   in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask);
2459   in->ri_pad = H_GET_32 (abfd, ex->ri_pad);
2460   in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]);
2461   in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]);
2462   in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]);
2463   in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]);
2464   in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value);
2465 }
2466
2467 void
2468 bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in,
2469                                  Elf64_External_RegInfo *ex)
2470 {
2471   H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask);
2472   H_PUT_32 (abfd, in->ri_pad, ex->ri_pad);
2473   H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]);
2474   H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]);
2475   H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]);
2476   H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]);
2477   H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value);
2478 }
2479
2480 /* Swap in an options header.  */
2481
2482 void
2483 bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex,
2484                               Elf_Internal_Options *in)
2485 {
2486   in->kind = H_GET_8 (abfd, ex->kind);
2487   in->size = H_GET_8 (abfd, ex->size);
2488   in->section = H_GET_16 (abfd, ex->section);
2489   in->info = H_GET_32 (abfd, ex->info);
2490 }
2491
2492 /* Swap out an options header.  */
2493
2494 void
2495 bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in,
2496                                Elf_External_Options *ex)
2497 {
2498   H_PUT_8 (abfd, in->kind, ex->kind);
2499   H_PUT_8 (abfd, in->size, ex->size);
2500   H_PUT_16 (abfd, in->section, ex->section);
2501   H_PUT_32 (abfd, in->info, ex->info);
2502 }
2503 \f
2504 /* This function is called via qsort() to sort the dynamic relocation
2505    entries by increasing r_symndx value.  */
2506
2507 static int
2508 sort_dynamic_relocs (const void *arg1, const void *arg2)
2509 {
2510   Elf_Internal_Rela int_reloc1;
2511   Elf_Internal_Rela int_reloc2;
2512   int diff;
2513
2514   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
2515   bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
2516
2517   diff = ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info);
2518   if (diff != 0)
2519     return diff;
2520
2521   if (int_reloc1.r_offset < int_reloc2.r_offset)
2522     return -1;
2523   if (int_reloc1.r_offset > int_reloc2.r_offset)
2524     return 1;
2525   return 0;
2526 }
2527
2528 /* Like sort_dynamic_relocs, but used for elf64 relocations.  */
2529
2530 static int
2531 sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED,
2532                         const void *arg2 ATTRIBUTE_UNUSED)
2533 {
2534 #ifdef BFD64
2535   Elf_Internal_Rela int_reloc1[3];
2536   Elf_Internal_Rela int_reloc2[3];
2537
2538   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2539     (reldyn_sorting_bfd, arg1, int_reloc1);
2540   (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in)
2541     (reldyn_sorting_bfd, arg2, int_reloc2);
2542
2543   if (ELF64_R_SYM (int_reloc1[0].r_info) < ELF64_R_SYM (int_reloc2[0].r_info))
2544     return -1;
2545   if (ELF64_R_SYM (int_reloc1[0].r_info) > ELF64_R_SYM (int_reloc2[0].r_info))
2546     return 1;
2547
2548   if (int_reloc1[0].r_offset < int_reloc2[0].r_offset)
2549     return -1;
2550   if (int_reloc1[0].r_offset > int_reloc2[0].r_offset)
2551     return 1;
2552   return 0;
2553 #else
2554   abort ();
2555 #endif
2556 }
2557
2558
2559 /* This routine is used to write out ECOFF debugging external symbol
2560    information.  It is called via mips_elf_link_hash_traverse.  The
2561    ECOFF external symbol information must match the ELF external
2562    symbol information.  Unfortunately, at this point we don't know
2563    whether a symbol is required by reloc information, so the two
2564    tables may wind up being different.  We must sort out the external
2565    symbol information before we can set the final size of the .mdebug
2566    section, and we must set the size of the .mdebug section before we
2567    can relocate any sections, and we can't know which symbols are
2568    required by relocation until we relocate the sections.
2569    Fortunately, it is relatively unlikely that any symbol will be
2570    stripped but required by a reloc.  In particular, it can not happen
2571    when generating a final executable.  */
2572
2573 static bfd_boolean
2574 mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data)
2575 {
2576   struct extsym_info *einfo = data;
2577   bfd_boolean strip;
2578   asection *sec, *output_section;
2579
2580   if (h->root.indx == -2)
2581     strip = FALSE;
2582   else if ((h->root.def_dynamic
2583             || h->root.ref_dynamic
2584             || h->root.type == bfd_link_hash_new)
2585            && !h->root.def_regular
2586            && !h->root.ref_regular)
2587     strip = TRUE;
2588   else if (einfo->info->strip == strip_all
2589            || (einfo->info->strip == strip_some
2590                && bfd_hash_lookup (einfo->info->keep_hash,
2591                                    h->root.root.root.string,
2592                                    FALSE, FALSE) == NULL))
2593     strip = TRUE;
2594   else
2595     strip = FALSE;
2596
2597   if (strip)
2598     return TRUE;
2599
2600   if (h->esym.ifd == -2)
2601     {
2602       h->esym.jmptbl = 0;
2603       h->esym.cobol_main = 0;
2604       h->esym.weakext = 0;
2605       h->esym.reserved = 0;
2606       h->esym.ifd = ifdNil;
2607       h->esym.asym.value = 0;
2608       h->esym.asym.st = stGlobal;
2609
2610       if (h->root.root.type == bfd_link_hash_undefined
2611           || h->root.root.type == bfd_link_hash_undefweak)
2612         {
2613           const char *name;
2614
2615           /* Use undefined class.  Also, set class and type for some
2616              special symbols.  */
2617           name = h->root.root.root.string;
2618           if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
2619               || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
2620             {
2621               h->esym.asym.sc = scData;
2622               h->esym.asym.st = stLabel;
2623               h->esym.asym.value = 0;
2624             }
2625           else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
2626             {
2627               h->esym.asym.sc = scAbs;
2628               h->esym.asym.st = stLabel;
2629               h->esym.asym.value =
2630                 mips_elf_hash_table (einfo->info)->procedure_count;
2631             }
2632           else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd))
2633             {
2634               h->esym.asym.sc = scAbs;
2635               h->esym.asym.st = stLabel;
2636               h->esym.asym.value = elf_gp (einfo->abfd);
2637             }
2638           else
2639             h->esym.asym.sc = scUndefined;
2640         }
2641       else if (h->root.root.type != bfd_link_hash_defined
2642           && h->root.root.type != bfd_link_hash_defweak)
2643         h->esym.asym.sc = scAbs;
2644       else
2645         {
2646           const char *name;
2647
2648           sec = h->root.root.u.def.section;
2649           output_section = sec->output_section;
2650
2651           /* When making a shared library and symbol h is the one from
2652              the another shared library, OUTPUT_SECTION may be null.  */
2653           if (output_section == NULL)
2654             h->esym.asym.sc = scUndefined;
2655           else
2656             {
2657               name = bfd_section_name (output_section->owner, output_section);
2658
2659               if (strcmp (name, ".text") == 0)
2660                 h->esym.asym.sc = scText;
2661               else if (strcmp (name, ".data") == 0)
2662                 h->esym.asym.sc = scData;
2663               else if (strcmp (name, ".sdata") == 0)
2664                 h->esym.asym.sc = scSData;
2665               else if (strcmp (name, ".rodata") == 0
2666                        || strcmp (name, ".rdata") == 0)
2667                 h->esym.asym.sc = scRData;
2668               else if (strcmp (name, ".bss") == 0)
2669                 h->esym.asym.sc = scBss;
2670               else if (strcmp (name, ".sbss") == 0)
2671                 h->esym.asym.sc = scSBss;
2672               else if (strcmp (name, ".init") == 0)
2673                 h->esym.asym.sc = scInit;
2674               else if (strcmp (name, ".fini") == 0)
2675                 h->esym.asym.sc = scFini;
2676               else
2677                 h->esym.asym.sc = scAbs;
2678             }
2679         }
2680
2681       h->esym.asym.reserved = 0;
2682       h->esym.asym.index = indexNil;
2683     }
2684
2685   if (h->root.root.type == bfd_link_hash_common)
2686     h->esym.asym.value = h->root.root.u.c.size;
2687   else if (h->root.root.type == bfd_link_hash_defined
2688            || h->root.root.type == bfd_link_hash_defweak)
2689     {
2690       if (h->esym.asym.sc == scCommon)
2691         h->esym.asym.sc = scBss;
2692       else if (h->esym.asym.sc == scSCommon)
2693         h->esym.asym.sc = scSBss;
2694
2695       sec = h->root.root.u.def.section;
2696       output_section = sec->output_section;
2697       if (output_section != NULL)
2698         h->esym.asym.value = (h->root.root.u.def.value
2699                               + sec->output_offset
2700                               + output_section->vma);
2701       else
2702         h->esym.asym.value = 0;
2703     }
2704   else
2705     {
2706       struct mips_elf_link_hash_entry *hd = h;
2707
2708       while (hd->root.root.type == bfd_link_hash_indirect)
2709         hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link;
2710
2711       if (hd->needs_lazy_stub)
2712         {
2713           /* Set type and value for a symbol with a function stub.  */
2714           h->esym.asym.st = stProc;
2715           sec = hd->root.root.u.def.section;
2716           if (sec == NULL)
2717             h->esym.asym.value = 0;
2718           else
2719             {
2720               output_section = sec->output_section;
2721               if (output_section != NULL)
2722                 h->esym.asym.value = (hd->root.plt.offset
2723                                       + sec->output_offset
2724                                       + output_section->vma);
2725               else
2726                 h->esym.asym.value = 0;
2727             }
2728         }
2729     }
2730
2731   if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap,
2732                                       h->root.root.root.string,
2733                                       &h->esym))
2734     {
2735       einfo->failed = TRUE;
2736       return FALSE;
2737     }
2738
2739   return TRUE;
2740 }
2741
2742 /* A comparison routine used to sort .gptab entries.  */
2743
2744 static int
2745 gptab_compare (const void *p1, const void *p2)
2746 {
2747   const Elf32_gptab *a1 = p1;
2748   const Elf32_gptab *a2 = p2;
2749
2750   return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value;
2751 }
2752 \f
2753 /* Functions to manage the got entry hash table.  */
2754
2755 /* Use all 64 bits of a bfd_vma for the computation of a 32-bit
2756    hash number.  */
2757
2758 static INLINE hashval_t
2759 mips_elf_hash_bfd_vma (bfd_vma addr)
2760 {
2761 #ifdef BFD64
2762   return addr + (addr >> 32);
2763 #else
2764   return addr;
2765 #endif
2766 }
2767
2768 static hashval_t
2769 mips_elf_got_entry_hash (const void *entry_)
2770 {
2771   const struct mips_got_entry *entry = (struct mips_got_entry *)entry_;
2772
2773   return (entry->symndx
2774           + ((entry->tls_type == GOT_TLS_LDM) << 18)
2775           + (entry->tls_type == GOT_TLS_LDM ? 0
2776              : !entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address)
2777              : entry->symndx >= 0 ? (entry->abfd->id
2778                                      + mips_elf_hash_bfd_vma (entry->d.addend))
2779              : entry->d.h->root.root.root.hash));
2780 }
2781
2782 static int
2783 mips_elf_got_entry_eq (const void *entry1, const void *entry2)
2784 {
2785   const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1;
2786   const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2;
2787
2788   return (e1->symndx == e2->symndx
2789           && e1->tls_type == e2->tls_type
2790           && (e1->tls_type == GOT_TLS_LDM ? TRUE
2791               : !e1->abfd ? !e2->abfd && e1->d.address == e2->d.address
2792               : e1->symndx >= 0 ? (e1->abfd == e2->abfd
2793                                    && e1->d.addend == e2->d.addend)
2794               : e2->abfd && e1->d.h == e2->d.h));
2795 }
2796
2797 static hashval_t
2798 mips_got_page_ref_hash (const void *ref_)
2799 {
2800   const struct mips_got_page_ref *ref;
2801
2802   ref = (const struct mips_got_page_ref *) ref_;
2803   return ((ref->symndx >= 0
2804            ? (hashval_t) (ref->u.abfd->id + ref->symndx)
2805            : ref->u.h->root.root.root.hash)
2806           + mips_elf_hash_bfd_vma (ref->addend));
2807 }
2808
2809 static int
2810 mips_got_page_ref_eq (const void *ref1_, const void *ref2_)
2811 {
2812   const struct mips_got_page_ref *ref1, *ref2;
2813
2814   ref1 = (const struct mips_got_page_ref *) ref1_;
2815   ref2 = (const struct mips_got_page_ref *) ref2_;
2816   return (ref1->symndx == ref2->symndx
2817           && (ref1->symndx < 0
2818               ? ref1->u.h == ref2->u.h
2819               : ref1->u.abfd == ref2->u.abfd)
2820           && ref1->addend == ref2->addend);
2821 }
2822
2823 static hashval_t
2824 mips_got_page_entry_hash (const void *entry_)
2825 {
2826   const struct mips_got_page_entry *entry;
2827
2828   entry = (const struct mips_got_page_entry *) entry_;
2829   return entry->sec->id;
2830 }
2831
2832 static int
2833 mips_got_page_entry_eq (const void *entry1_, const void *entry2_)
2834 {
2835   const struct mips_got_page_entry *entry1, *entry2;
2836
2837   entry1 = (const struct mips_got_page_entry *) entry1_;
2838   entry2 = (const struct mips_got_page_entry *) entry2_;
2839   return entry1->sec == entry2->sec;
2840 }
2841 \f
2842 /* Create and return a new mips_got_info structure.  */
2843
2844 static struct mips_got_info *
2845 mips_elf_create_got_info (bfd *abfd)
2846 {
2847   struct mips_got_info *g;
2848
2849   g = bfd_zalloc (abfd, sizeof (struct mips_got_info));
2850   if (g == NULL)
2851     return NULL;
2852
2853   g->got_entries = htab_try_create (1, mips_elf_got_entry_hash,
2854                                     mips_elf_got_entry_eq, NULL);
2855   if (g->got_entries == NULL)
2856     return NULL;
2857
2858   g->got_page_refs = htab_try_create (1, mips_got_page_ref_hash,
2859                                       mips_got_page_ref_eq, NULL);
2860   if (g->got_page_refs == NULL)
2861     return NULL;
2862
2863   return g;
2864 }
2865
2866 /* Return the GOT info for input bfd ABFD, trying to create a new one if
2867    CREATE_P and if ABFD doesn't already have a GOT.  */
2868
2869 static struct mips_got_info *
2870 mips_elf_bfd_got (bfd *abfd, bfd_boolean create_p)
2871 {
2872   struct mips_elf_obj_tdata *tdata;
2873
2874   if (!is_mips_elf (abfd))
2875     return NULL;
2876
2877   tdata = mips_elf_tdata (abfd);
2878   if (!tdata->got && create_p)
2879     tdata->got = mips_elf_create_got_info (abfd);
2880   return tdata->got;
2881 }
2882
2883 /* Record that ABFD should use output GOT G.  */
2884
2885 static void
2886 mips_elf_replace_bfd_got (bfd *abfd, struct mips_got_info *g)
2887 {
2888   struct mips_elf_obj_tdata *tdata;
2889
2890   BFD_ASSERT (is_mips_elf (abfd));
2891   tdata = mips_elf_tdata (abfd);
2892   if (tdata->got)
2893     {
2894       /* The GOT structure itself and the hash table entries are
2895          allocated to a bfd, but the hash tables aren't.  */
2896       htab_delete (tdata->got->got_entries);
2897       htab_delete (tdata->got->got_page_refs);
2898       if (tdata->got->got_page_entries)
2899         htab_delete (tdata->got->got_page_entries);
2900     }
2901   tdata->got = g;
2902 }
2903
2904 /* Return the dynamic relocation section.  If it doesn't exist, try to
2905    create a new it if CREATE_P, otherwise return NULL.  Also return NULL
2906    if creation fails.  */
2907
2908 static asection *
2909 mips_elf_rel_dyn_section (struct bfd_link_info *info, bfd_boolean create_p)
2910 {
2911   const char *dname;
2912   asection *sreloc;
2913   bfd *dynobj;
2914
2915   dname = MIPS_ELF_REL_DYN_NAME (info);
2916   dynobj = elf_hash_table (info)->dynobj;
2917   sreloc = bfd_get_linker_section (dynobj, dname);
2918   if (sreloc == NULL && create_p)
2919     {
2920       sreloc = bfd_make_section_anyway_with_flags (dynobj, dname,
2921                                                    (SEC_ALLOC
2922                                                     | SEC_LOAD
2923                                                     | SEC_HAS_CONTENTS
2924                                                     | SEC_IN_MEMORY
2925                                                     | SEC_LINKER_CREATED
2926                                                     | SEC_READONLY));
2927       if (sreloc == NULL
2928           || ! bfd_set_section_alignment (dynobj, sreloc,
2929                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
2930         return NULL;
2931     }
2932   return sreloc;
2933 }
2934
2935 /* Return the GOT_TLS_* type required by relocation type R_TYPE.  */
2936
2937 static int
2938 mips_elf_reloc_tls_type (unsigned int r_type)
2939 {
2940   if (tls_gd_reloc_p (r_type))
2941     return GOT_TLS_GD;
2942
2943   if (tls_ldm_reloc_p (r_type))
2944     return GOT_TLS_LDM;
2945
2946   if (tls_gottprel_reloc_p (r_type))
2947     return GOT_TLS_IE;
2948
2949   return GOT_TLS_NONE;
2950 }
2951
2952 /* Return the number of GOT slots needed for GOT TLS type TYPE.  */
2953
2954 static int
2955 mips_tls_got_entries (unsigned int type)
2956 {
2957   switch (type)
2958     {
2959     case GOT_TLS_GD:
2960     case GOT_TLS_LDM:
2961       return 2;
2962
2963     case GOT_TLS_IE:
2964       return 1;
2965
2966     case GOT_TLS_NONE:
2967       return 0;
2968     }
2969   abort ();
2970 }
2971
2972 /* Count the number of relocations needed for a TLS GOT entry, with
2973    access types from TLS_TYPE, and symbol H (or a local symbol if H
2974    is NULL).  */
2975
2976 static int
2977 mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type,
2978                      struct elf_link_hash_entry *h)
2979 {
2980   int indx = 0;
2981   bfd_boolean need_relocs = FALSE;
2982   bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
2983
2984   if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, h)
2985       && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, h)))
2986     indx = h->dynindx;
2987
2988   if ((info->shared || indx != 0)
2989       && (h == NULL
2990           || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2991           || h->root.type != bfd_link_hash_undefweak))
2992     need_relocs = TRUE;
2993
2994   if (!need_relocs)
2995     return 0;
2996
2997   switch (tls_type)
2998     {
2999     case GOT_TLS_GD:
3000       return indx != 0 ? 2 : 1;
3001
3002     case GOT_TLS_IE:
3003       return 1;
3004
3005     case GOT_TLS_LDM:
3006       return info->shared ? 1 : 0;
3007
3008     default:
3009       return 0;
3010     }
3011 }
3012
3013 /* Add the number of GOT entries and TLS relocations required by ENTRY
3014    to G.  */
3015
3016 static void
3017 mips_elf_count_got_entry (struct bfd_link_info *info,
3018                           struct mips_got_info *g,
3019                           struct mips_got_entry *entry)
3020 {
3021   if (entry->tls_type)
3022     {
3023       g->tls_gotno += mips_tls_got_entries (entry->tls_type);
3024       g->relocs += mips_tls_got_relocs (info, entry->tls_type,
3025                                         entry->symndx < 0
3026                                         ? &entry->d.h->root : NULL);
3027     }
3028   else if (entry->symndx >= 0 || entry->d.h->global_got_area == GGA_NONE)
3029     g->local_gotno += 1;
3030   else
3031     g->global_gotno += 1;
3032 }
3033
3034 /* Output a simple dynamic relocation into SRELOC.  */
3035
3036 static void
3037 mips_elf_output_dynamic_relocation (bfd *output_bfd,
3038                                     asection *sreloc,
3039                                     unsigned long reloc_index,
3040                                     unsigned long indx,
3041                                     int r_type,
3042                                     bfd_vma offset)
3043 {
3044   Elf_Internal_Rela rel[3];
3045
3046   memset (rel, 0, sizeof (rel));
3047
3048   rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type);
3049   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
3050
3051   if (ABI_64_P (output_bfd))
3052     {
3053       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
3054         (output_bfd, &rel[0],
3055          (sreloc->contents
3056           + reloc_index * sizeof (Elf64_Mips_External_Rel)));
3057     }
3058   else
3059     bfd_elf32_swap_reloc_out
3060       (output_bfd, &rel[0],
3061        (sreloc->contents
3062         + reloc_index * sizeof (Elf32_External_Rel)));
3063 }
3064
3065 /* Initialize a set of TLS GOT entries for one symbol.  */
3066
3067 static void
3068 mips_elf_initialize_tls_slots (bfd *abfd, struct bfd_link_info *info,
3069                                struct mips_got_entry *entry,
3070                                struct mips_elf_link_hash_entry *h,
3071                                bfd_vma value)
3072 {
3073   struct mips_elf_link_hash_table *htab;
3074   int indx;
3075   asection *sreloc, *sgot;
3076   bfd_vma got_offset, got_offset2;
3077   bfd_boolean need_relocs = FALSE;
3078
3079   htab = mips_elf_hash_table (info);
3080   if (htab == NULL)
3081     return;
3082
3083   sgot = htab->sgot;
3084
3085   indx = 0;
3086   if (h != NULL)
3087     {
3088       bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created;
3089
3090       if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, &h->root)
3091           && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, &h->root)))
3092         indx = h->root.dynindx;
3093     }
3094
3095   if (entry->tls_initialized)
3096     return;
3097
3098   if ((info->shared || indx != 0)
3099       && (h == NULL
3100           || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT
3101           || h->root.type != bfd_link_hash_undefweak))
3102     need_relocs = TRUE;
3103
3104   /* MINUS_ONE means the symbol is not defined in this object.  It may not
3105      be defined at all; assume that the value doesn't matter in that
3106      case.  Otherwise complain if we would use the value.  */
3107   BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs)
3108               || h->root.root.type == bfd_link_hash_undefweak);
3109
3110   /* Emit necessary relocations.  */
3111   sreloc = mips_elf_rel_dyn_section (info, FALSE);
3112   got_offset = entry->gotidx;
3113
3114   switch (entry->tls_type)
3115     {
3116     case GOT_TLS_GD:
3117       /* General Dynamic.  */
3118       got_offset2 = got_offset + MIPS_ELF_GOT_SIZE (abfd);
3119
3120       if (need_relocs)
3121         {
3122           mips_elf_output_dynamic_relocation
3123             (abfd, sreloc, sreloc->reloc_count++, indx,
3124              ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3125              sgot->output_offset + sgot->output_section->vma + got_offset);
3126
3127           if (indx)
3128             mips_elf_output_dynamic_relocation
3129               (abfd, sreloc, sreloc->reloc_count++, indx,
3130                ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32,
3131                sgot->output_offset + sgot->output_section->vma + got_offset2);
3132           else
3133             MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3134                                sgot->contents + got_offset2);
3135         }
3136       else
3137         {
3138           MIPS_ELF_PUT_WORD (abfd, 1,
3139                              sgot->contents + got_offset);
3140           MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info),
3141                              sgot->contents + got_offset2);
3142         }
3143       break;
3144
3145     case GOT_TLS_IE:
3146       /* Initial Exec model.  */
3147       if (need_relocs)
3148         {
3149           if (indx == 0)
3150             MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma,
3151                                sgot->contents + got_offset);
3152           else
3153             MIPS_ELF_PUT_WORD (abfd, 0,
3154                                sgot->contents + got_offset);
3155
3156           mips_elf_output_dynamic_relocation
3157             (abfd, sreloc, sreloc->reloc_count++, indx,
3158              ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32,
3159              sgot->output_offset + sgot->output_section->vma + got_offset);
3160         }
3161       else
3162         MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info),
3163                            sgot->contents + got_offset);
3164       break;
3165
3166     case GOT_TLS_LDM:
3167       /* The initial offset is zero, and the LD offsets will include the
3168          bias by DTP_OFFSET.  */
3169       MIPS_ELF_PUT_WORD (abfd, 0,
3170                          sgot->contents + got_offset
3171                          + MIPS_ELF_GOT_SIZE (abfd));
3172
3173       if (!info->shared)
3174         MIPS_ELF_PUT_WORD (abfd, 1,
3175                            sgot->contents + got_offset);
3176       else
3177         mips_elf_output_dynamic_relocation
3178           (abfd, sreloc, sreloc->reloc_count++, indx,
3179            ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32,
3180            sgot->output_offset + sgot->output_section->vma + got_offset);
3181       break;
3182
3183     default:
3184       abort ();
3185     }
3186
3187   entry->tls_initialized = TRUE;
3188 }
3189
3190 /* Return the offset from _GLOBAL_OFFSET_TABLE_ of the .got.plt entry
3191    for global symbol H.  .got.plt comes before the GOT, so the offset
3192    will be negative.  */
3193
3194 static bfd_vma
3195 mips_elf_gotplt_index (struct bfd_link_info *info,
3196                        struct elf_link_hash_entry *h)
3197 {
3198   bfd_vma plt_index, got_address, got_value;
3199   struct mips_elf_link_hash_table *htab;
3200
3201   htab = mips_elf_hash_table (info);
3202   BFD_ASSERT (htab != NULL);
3203
3204   BFD_ASSERT (h->plt.offset != (bfd_vma) -1);
3205
3206   /* This function only works for VxWorks, because a non-VxWorks .got.plt
3207      section starts with reserved entries.  */
3208   BFD_ASSERT (htab->is_vxworks);
3209
3210   /* Calculate the index of the symbol's PLT entry.  */
3211   plt_index = (h->plt.offset - htab->plt_header_size) / htab->plt_entry_size;
3212
3213   /* Calculate the address of the associated .got.plt entry.  */
3214   got_address = (htab->sgotplt->output_section->vma
3215                  + htab->sgotplt->output_offset
3216                  + plt_index * 4);
3217
3218   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
3219   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
3220                + htab->root.hgot->root.u.def.section->output_offset
3221                + htab->root.hgot->root.u.def.value);
3222
3223   return got_address - got_value;
3224 }
3225
3226 /* Return the GOT offset for address VALUE.   If there is not yet a GOT
3227    entry for this value, create one.  If R_SYMNDX refers to a TLS symbol,
3228    create a TLS GOT entry instead.  Return -1 if no satisfactory GOT
3229    offset can be found.  */
3230
3231 static bfd_vma
3232 mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3233                           bfd_vma value, unsigned long r_symndx,
3234                           struct mips_elf_link_hash_entry *h, int r_type)
3235 {
3236   struct mips_elf_link_hash_table *htab;
3237   struct mips_got_entry *entry;
3238
3239   htab = mips_elf_hash_table (info);
3240   BFD_ASSERT (htab != NULL);
3241
3242   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value,
3243                                            r_symndx, h, r_type);
3244   if (!entry)
3245     return MINUS_ONE;
3246
3247   if (entry->tls_type)
3248     mips_elf_initialize_tls_slots (abfd, info, entry, h, value);
3249   return entry->gotidx;
3250 }
3251
3252 /* Return the GOT index of global symbol H in the primary GOT.  */
3253
3254 static bfd_vma
3255 mips_elf_primary_global_got_index (bfd *obfd, struct bfd_link_info *info,
3256                                    struct elf_link_hash_entry *h)
3257 {
3258   struct mips_elf_link_hash_table *htab;
3259   long global_got_dynindx;
3260   struct mips_got_info *g;
3261   bfd_vma got_index;
3262
3263   htab = mips_elf_hash_table (info);
3264   BFD_ASSERT (htab != NULL);
3265
3266   global_got_dynindx = 0;
3267   if (htab->global_gotsym != NULL)
3268     global_got_dynindx = htab->global_gotsym->dynindx;
3269
3270   /* Once we determine the global GOT entry with the lowest dynamic
3271      symbol table index, we must put all dynamic symbols with greater
3272      indices into the primary GOT.  That makes it easy to calculate the
3273      GOT offset.  */
3274   BFD_ASSERT (h->dynindx >= global_got_dynindx);
3275   g = mips_elf_bfd_got (obfd, FALSE);
3276   got_index = ((h->dynindx - global_got_dynindx + g->local_gotno)
3277                * MIPS_ELF_GOT_SIZE (obfd));
3278   BFD_ASSERT (got_index < htab->sgot->size);
3279
3280   return got_index;
3281 }
3282
3283 /* Return the GOT index for the global symbol indicated by H, which is
3284    referenced by a relocation of type R_TYPE in IBFD.  */
3285
3286 static bfd_vma
3287 mips_elf_global_got_index (bfd *obfd, struct bfd_link_info *info, bfd *ibfd,
3288                            struct elf_link_hash_entry *h, int r_type)
3289 {
3290   struct mips_elf_link_hash_table *htab;
3291   struct mips_got_info *g;
3292   struct mips_got_entry lookup, *entry;
3293   bfd_vma gotidx;
3294
3295   htab = mips_elf_hash_table (info);
3296   BFD_ASSERT (htab != NULL);
3297
3298   g = mips_elf_bfd_got (ibfd, FALSE);
3299   BFD_ASSERT (g);
3300
3301   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3302   if (!lookup.tls_type && g == mips_elf_bfd_got (obfd, FALSE))
3303     return mips_elf_primary_global_got_index (obfd, info, h);
3304
3305   lookup.abfd = ibfd;
3306   lookup.symndx = -1;
3307   lookup.d.h = (struct mips_elf_link_hash_entry *) h;
3308   entry = htab_find (g->got_entries, &lookup);
3309   BFD_ASSERT (entry);
3310
3311   gotidx = entry->gotidx;
3312   BFD_ASSERT (gotidx > 0 && gotidx < htab->sgot->size);
3313
3314   if (lookup.tls_type)
3315     {
3316       bfd_vma value = MINUS_ONE;
3317
3318       if ((h->root.type == bfd_link_hash_defined
3319            || h->root.type == bfd_link_hash_defweak)
3320           && h->root.u.def.section->output_section)
3321         value = (h->root.u.def.value
3322                  + h->root.u.def.section->output_offset
3323                  + h->root.u.def.section->output_section->vma);
3324
3325       mips_elf_initialize_tls_slots (obfd, info, entry, lookup.d.h, value);
3326     }
3327   return gotidx;
3328 }
3329
3330 /* Find a GOT page entry that points to within 32KB of VALUE.  These
3331    entries are supposed to be placed at small offsets in the GOT, i.e.,
3332    within 32KB of GP.  Return the index of the GOT entry, or -1 if no
3333    entry could be created.  If OFFSETP is nonnull, use it to return the
3334    offset of the GOT entry from VALUE.  */
3335
3336 static bfd_vma
3337 mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3338                    bfd_vma value, bfd_vma *offsetp)
3339 {
3340   bfd_vma page, got_index;
3341   struct mips_got_entry *entry;
3342
3343   page = (value + 0x8000) & ~(bfd_vma) 0xffff;
3344   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, page, 0,
3345                                            NULL, R_MIPS_GOT_PAGE);
3346
3347   if (!entry)
3348     return MINUS_ONE;
3349
3350   got_index = entry->gotidx;
3351
3352   if (offsetp)
3353     *offsetp = value - entry->d.address;
3354
3355   return got_index;
3356 }
3357
3358 /* Find a local GOT entry for an R_MIPS*_GOT16 relocation against VALUE.
3359    EXTERNAL is true if the relocation was originally against a global
3360    symbol that binds locally.  */
3361
3362 static bfd_vma
3363 mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
3364                       bfd_vma value, bfd_boolean external)
3365 {
3366   struct mips_got_entry *entry;
3367
3368   /* GOT16 relocations against local symbols are followed by a LO16
3369      relocation; those against global symbols are not.  Thus if the
3370      symbol was originally local, the GOT16 relocation should load the
3371      equivalent of %hi(VALUE), otherwise it should load VALUE itself.  */
3372   if (! external)
3373     value = mips_elf_high (value) << 16;
3374
3375   /* It doesn't matter whether the original relocation was R_MIPS_GOT16,
3376      R_MIPS16_GOT16, R_MIPS_CALL16, etc.  The format of the entry is the
3377      same in all cases.  */
3378   entry = mips_elf_create_local_got_entry (abfd, info, ibfd, value, 0,
3379                                            NULL, R_MIPS_GOT16);
3380   if (entry)
3381     return entry->gotidx;
3382   else
3383     return MINUS_ONE;
3384 }
3385
3386 /* Returns the offset for the entry at the INDEXth position
3387    in the GOT.  */
3388
3389 static bfd_vma
3390 mips_elf_got_offset_from_index (struct bfd_link_info *info, bfd *output_bfd,
3391                                 bfd *input_bfd, bfd_vma got_index)
3392 {
3393   struct mips_elf_link_hash_table *htab;
3394   asection *sgot;
3395   bfd_vma gp;
3396
3397   htab = mips_elf_hash_table (info);
3398   BFD_ASSERT (htab != NULL);
3399
3400   sgot = htab->sgot;
3401   gp = _bfd_get_gp_value (output_bfd)
3402     + mips_elf_adjust_gp (output_bfd, htab->got_info, input_bfd);
3403
3404   return sgot->output_section->vma + sgot->output_offset + got_index - gp;
3405 }
3406
3407 /* Create and return a local GOT entry for VALUE, which was calculated
3408    from a symbol belonging to INPUT_SECTON.  Return NULL if it could not
3409    be created.  If R_SYMNDX refers to a TLS symbol, create a TLS entry
3410    instead.  */
3411
3412 static struct mips_got_entry *
3413 mips_elf_create_local_got_entry (bfd *abfd, struct bfd_link_info *info,
3414                                  bfd *ibfd, bfd_vma value,
3415                                  unsigned long r_symndx,
3416                                  struct mips_elf_link_hash_entry *h,
3417                                  int r_type)
3418 {
3419   struct mips_got_entry lookup, *entry;
3420   void **loc;
3421   struct mips_got_info *g;
3422   struct mips_elf_link_hash_table *htab;
3423   bfd_vma gotidx;
3424
3425   htab = mips_elf_hash_table (info);
3426   BFD_ASSERT (htab != NULL);
3427
3428   g = mips_elf_bfd_got (ibfd, FALSE);
3429   if (g == NULL)
3430     {
3431       g = mips_elf_bfd_got (abfd, FALSE);
3432       BFD_ASSERT (g != NULL);
3433     }
3434
3435   /* This function shouldn't be called for symbols that live in the global
3436      area of the GOT.  */
3437   BFD_ASSERT (h == NULL || h->global_got_area == GGA_NONE);
3438
3439   lookup.tls_type = mips_elf_reloc_tls_type (r_type);
3440   if (lookup.tls_type)
3441     {
3442       lookup.abfd = ibfd;
3443       if (tls_ldm_reloc_p (r_type))
3444         {
3445           lookup.symndx = 0;
3446           lookup.d.addend = 0;
3447         }
3448       else if (h == NULL)
3449         {
3450           lookup.symndx = r_symndx;
3451           lookup.d.addend = 0;
3452         }
3453       else
3454         {
3455           lookup.symndx = -1;
3456           lookup.d.h = h;
3457         }
3458
3459       entry = (struct mips_got_entry *) htab_find (g->got_entries, &lookup);
3460       BFD_ASSERT (entry);
3461
3462       gotidx = entry->gotidx;
3463       BFD_ASSERT (gotidx > 0 && gotidx < htab->sgot->size);
3464
3465       return entry;
3466     }
3467
3468   lookup.abfd = NULL;
3469   lookup.symndx = -1;
3470   lookup.d.address = value;
3471   loc = htab_find_slot (g->got_entries, &lookup, INSERT);
3472   if (!loc)
3473     return NULL;
3474
3475   entry = (struct mips_got_entry *) *loc;
3476   if (entry)
3477     return entry;
3478
3479   if (g->assigned_gotno >= g->local_gotno)
3480     {
3481       /* We didn't allocate enough space in the GOT.  */
3482       (*_bfd_error_handler)
3483         (_("not enough GOT space for local GOT entries"));
3484       bfd_set_error (bfd_error_bad_value);
3485       return NULL;
3486     }
3487
3488   entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3489   if (!entry)
3490     return NULL;
3491
3492   lookup.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_gotno++;
3493   *entry = lookup;
3494   *loc = entry;
3495
3496   MIPS_ELF_PUT_WORD (abfd, value, htab->sgot->contents + entry->gotidx);
3497
3498   /* These GOT entries need a dynamic relocation on VxWorks.  */
3499   if (htab->is_vxworks)
3500     {
3501       Elf_Internal_Rela outrel;
3502       asection *s;
3503       bfd_byte *rloc;
3504       bfd_vma got_address;
3505
3506       s = mips_elf_rel_dyn_section (info, FALSE);
3507       got_address = (htab->sgot->output_section->vma
3508                      + htab->sgot->output_offset
3509                      + entry->gotidx);
3510
3511       rloc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
3512       outrel.r_offset = got_address;
3513       outrel.r_info = ELF32_R_INFO (STN_UNDEF, R_MIPS_32);
3514       outrel.r_addend = value;
3515       bfd_elf32_swap_reloca_out (abfd, &outrel, rloc);
3516     }
3517
3518   return entry;
3519 }
3520
3521 /* Return the number of dynamic section symbols required by OUTPUT_BFD.
3522    The number might be exact or a worst-case estimate, depending on how
3523    much information is available to elf_backend_omit_section_dynsym at
3524    the current linking stage.  */
3525
3526 static bfd_size_type
3527 count_section_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
3528 {
3529   bfd_size_type count;
3530
3531   count = 0;
3532   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
3533     {
3534       asection *p;
3535       const struct elf_backend_data *bed;
3536
3537       bed = get_elf_backend_data (output_bfd);
3538       for (p = output_bfd->sections; p ; p = p->next)
3539         if ((p->flags & SEC_EXCLUDE) == 0
3540             && (p->flags & SEC_ALLOC) != 0
3541             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
3542           ++count;
3543     }
3544   return count;
3545 }
3546
3547 /* Sort the dynamic symbol table so that symbols that need GOT entries
3548    appear towards the end.  */
3549
3550 static bfd_boolean
3551 mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
3552 {
3553   struct mips_elf_link_hash_table *htab;
3554   struct mips_elf_hash_sort_data hsd;
3555   struct mips_got_info *g;
3556
3557   if (elf_hash_table (info)->dynsymcount == 0)
3558     return TRUE;
3559
3560   htab = mips_elf_hash_table (info);
3561   BFD_ASSERT (htab != NULL);
3562
3563   g = htab->got_info;
3564   if (g == NULL)
3565     return TRUE;
3566
3567   hsd.low = NULL;
3568   hsd.max_unref_got_dynindx
3569     = hsd.min_got_dynindx
3570     = (elf_hash_table (info)->dynsymcount - g->reloc_only_gotno);
3571   hsd.max_non_got_dynindx = count_section_dynsyms (abfd, info) + 1;
3572   mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *)
3573                                 elf_hash_table (info)),
3574                                mips_elf_sort_hash_table_f,
3575                                &hsd);
3576
3577   /* There should have been enough room in the symbol table to
3578      accommodate both the GOT and non-GOT symbols.  */
3579   BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
3580   BFD_ASSERT ((unsigned long) hsd.max_unref_got_dynindx
3581               == elf_hash_table (info)->dynsymcount);
3582   BFD_ASSERT (elf_hash_table (info)->dynsymcount - hsd.min_got_dynindx
3583               == g->global_gotno);
3584
3585   /* Now we know which dynamic symbol has the lowest dynamic symbol
3586      table index in the GOT.  */
3587   htab->global_gotsym = hsd.low;
3588
3589   return TRUE;
3590 }
3591
3592 /* If H needs a GOT entry, assign it the highest available dynamic
3593    index.  Otherwise, assign it the lowest available dynamic
3594    index.  */
3595
3596 static bfd_boolean
3597 mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data)
3598 {
3599   struct mips_elf_hash_sort_data *hsd = data;
3600
3601   /* Symbols without dynamic symbol table entries aren't interesting
3602      at all.  */
3603   if (h->root.dynindx == -1)
3604     return TRUE;
3605
3606   switch (h->global_got_area)
3607     {
3608     case GGA_NONE:
3609       h->root.dynindx = hsd->max_non_got_dynindx++;
3610       break;
3611
3612     case GGA_NORMAL:
3613       h->root.dynindx = --hsd->min_got_dynindx;
3614       hsd->low = (struct elf_link_hash_entry *) h;
3615       break;
3616
3617     case GGA_RELOC_ONLY:
3618       if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
3619         hsd->low = (struct elf_link_hash_entry *) h;
3620       h->root.dynindx = hsd->max_unref_got_dynindx++;
3621       break;
3622     }
3623
3624   return TRUE;
3625 }
3626
3627 /* Record that input bfd ABFD requires a GOT entry like *LOOKUP
3628    (which is owned by the caller and shouldn't be added to the
3629    hash table directly).  */
3630
3631 static bfd_boolean
3632 mips_elf_record_got_entry (struct bfd_link_info *info, bfd *abfd,
3633                            struct mips_got_entry *lookup)
3634 {
3635   struct mips_elf_link_hash_table *htab;
3636   struct mips_got_entry *entry;
3637   struct mips_got_info *g;
3638   void **loc, **bfd_loc;
3639
3640   /* Make sure there's a slot for this entry in the master GOT.  */
3641   htab = mips_elf_hash_table (info);
3642   g = htab->got_info;
3643   loc = htab_find_slot (g->got_entries, lookup, INSERT);
3644   if (!loc)
3645     return FALSE;
3646
3647   /* Populate the entry if it isn't already.  */
3648   entry = (struct mips_got_entry *) *loc;
3649   if (!entry)
3650     {
3651       entry = (struct mips_got_entry *) bfd_alloc (abfd, sizeof (*entry));
3652       if (!entry)
3653         return FALSE;
3654
3655       lookup->tls_initialized = FALSE;
3656       lookup->gotidx = -1;
3657       *entry = *lookup;
3658       *loc = entry;
3659     }
3660
3661   /* Reuse the same GOT entry for the BFD's GOT.  */
3662   g = mips_elf_bfd_got (abfd, TRUE);
3663   if (!g)
3664     return FALSE;
3665
3666   bfd_loc = htab_find_slot (g->got_entries, lookup, INSERT);
3667   if (!bfd_loc)
3668     return FALSE;
3669
3670   if (!*bfd_loc)
3671     *bfd_loc = entry;
3672   return TRUE;
3673 }
3674
3675 /* ABFD has a GOT relocation of type R_TYPE against H.  Reserve a GOT
3676    entry for it.  FOR_CALL is true if the caller is only interested in
3677    using the GOT entry for calls.  */
3678
3679 static bfd_boolean
3680 mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
3681                                    bfd *abfd, struct bfd_link_info *info,
3682                                    bfd_boolean for_call, int r_type)
3683 {
3684   struct mips_elf_link_hash_table *htab;
3685   struct mips_elf_link_hash_entry *hmips;
3686   struct mips_got_entry entry;
3687   unsigned char tls_type;
3688
3689   htab = mips_elf_hash_table (info);
3690   BFD_ASSERT (htab != NULL);
3691
3692   hmips = (struct mips_elf_link_hash_entry *) h;
3693   if (!for_call)
3694     hmips->got_only_for_calls = FALSE;
3695
3696   /* A global symbol in the GOT must also be in the dynamic symbol
3697      table.  */
3698   if (h->dynindx == -1)
3699     {
3700       switch (ELF_ST_VISIBILITY (h->other))
3701         {
3702         case STV_INTERNAL:
3703         case STV_HIDDEN:
3704           _bfd_elf_link_hash_hide_symbol (info, h, TRUE);
3705           break;
3706         }
3707       if (!bfd_elf_link_record_dynamic_symbol (info, h))
3708         return FALSE;
3709     }
3710
3711   tls_type = mips_elf_reloc_tls_type (r_type);
3712   if (tls_type == GOT_TLS_NONE && hmips->global_got_area > GGA_NORMAL)
3713     hmips->global_got_area = GGA_NORMAL;
3714
3715   entry.abfd = abfd;
3716   entry.symndx = -1;
3717   entry.d.h = (struct mips_elf_link_hash_entry *) h;
3718   entry.tls_type = tls_type;
3719   return mips_elf_record_got_entry (info, abfd, &entry);
3720 }
3721
3722 /* ABFD has a GOT relocation of type R_TYPE against symbol SYMNDX + ADDEND,
3723    where SYMNDX is a local symbol.  Reserve a GOT entry for it.  */
3724
3725 static bfd_boolean
3726 mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend,
3727                                   struct bfd_link_info *info, int r_type)
3728 {
3729   struct mips_elf_link_hash_table *htab;
3730   struct mips_got_info *g;
3731   struct mips_got_entry entry;
3732
3733   htab = mips_elf_hash_table (info);
3734   BFD_ASSERT (htab != NULL);
3735
3736   g = htab->got_info;
3737   BFD_ASSERT (g != NULL);
3738
3739   entry.abfd = abfd;
3740   entry.symndx = symndx;
3741   entry.d.addend = addend;
3742   entry.tls_type = mips_elf_reloc_tls_type (r_type);
3743   return mips_elf_record_got_entry (info, abfd, &entry);
3744 }
3745
3746 /* Record that ABFD has a page relocation against SYMNDX + ADDEND.
3747    H is the symbol's hash table entry, or null if SYMNDX is local
3748    to ABFD.  */
3749
3750 static bfd_boolean
3751 mips_elf_record_got_page_ref (struct bfd_link_info *info, bfd *abfd,
3752                               long symndx, struct elf_link_hash_entry *h,
3753                               bfd_signed_vma addend)
3754 {
3755   struct mips_elf_link_hash_table *htab;
3756   struct mips_got_info *g1, *g2;
3757   struct mips_got_page_ref lookup, *entry;
3758   void **loc, **bfd_loc;
3759
3760   htab = mips_elf_hash_table (info);
3761   BFD_ASSERT (htab != NULL);
3762
3763   g1 = htab->got_info;
3764   BFD_ASSERT (g1 != NULL);
3765
3766   if (h)
3767     {
3768       lookup.symndx = -1;
3769       lookup.u.h = (struct mips_elf_link_hash_entry *) h;
3770     }
3771   else
3772     {
3773       lookup.symndx = symndx;
3774       lookup.u.abfd = abfd;
3775     }
3776   lookup.addend = addend;
3777   loc = htab_find_slot (g1->got_page_refs, &lookup, INSERT);
3778   if (loc == NULL)
3779     return FALSE;
3780
3781   entry = (struct mips_got_page_ref *) *loc;
3782   if (!entry)
3783     {
3784       entry = bfd_alloc (abfd, sizeof (*entry));
3785       if (!entry)
3786         return FALSE;
3787
3788       *entry = lookup;
3789       *loc = entry;
3790     }
3791
3792   /* Add the same entry to the BFD's GOT.  */
3793   g2 = mips_elf_bfd_got (abfd, TRUE);
3794   if (!g2)
3795     return FALSE;
3796
3797   bfd_loc = htab_find_slot (g2->got_page_refs, &lookup, INSERT);
3798   if (!bfd_loc)
3799     return FALSE;
3800
3801   if (!*bfd_loc)
3802     *bfd_loc = entry;
3803
3804   return TRUE;
3805 }
3806
3807 /* Add room for N relocations to the .rel(a).dyn section in ABFD.  */
3808
3809 static void
3810 mips_elf_allocate_dynamic_relocations (bfd *abfd, struct bfd_link_info *info,
3811                                        unsigned int n)
3812 {
3813   asection *s;
3814   struct mips_elf_link_hash_table *htab;
3815
3816   htab = mips_elf_hash_table (info);
3817   BFD_ASSERT (htab != NULL);
3818
3819   s = mips_elf_rel_dyn_section (info, FALSE);
3820   BFD_ASSERT (s != NULL);
3821
3822   if (htab->is_vxworks)
3823     s->size += n * MIPS_ELF_RELA_SIZE (abfd);
3824   else
3825     {
3826       if (s->size == 0)
3827         {
3828           /* Make room for a null element.  */
3829           s->size += MIPS_ELF_REL_SIZE (abfd);
3830           ++s->reloc_count;
3831         }
3832       s->size += n * MIPS_ELF_REL_SIZE (abfd);
3833     }
3834 }
3835 \f
3836 /* A htab_traverse callback for GOT entries, with DATA pointing to a
3837    mips_elf_traverse_got_arg structure.  Count the number of GOT
3838    entries and TLS relocs.  Set DATA->value to true if we need
3839    to resolve indirect or warning symbols and then recreate the GOT.  */
3840
3841 static int
3842 mips_elf_check_recreate_got (void **entryp, void *data)
3843 {
3844   struct mips_got_entry *entry;
3845   struct mips_elf_traverse_got_arg *arg;
3846
3847   entry = (struct mips_got_entry *) *entryp;
3848   arg = (struct mips_elf_traverse_got_arg *) data;
3849   if (entry->abfd != NULL && entry->symndx == -1)
3850     {
3851       struct mips_elf_link_hash_entry *h;
3852
3853       h = entry->d.h;
3854       if (h->root.root.type == bfd_link_hash_indirect
3855           || h->root.root.type == bfd_link_hash_warning)
3856         {
3857           arg->value = TRUE;
3858           return 0;
3859         }
3860     }
3861   mips_elf_count_got_entry (arg->info, arg->g, entry);
3862   return 1;
3863 }
3864
3865 /* A htab_traverse callback for GOT entries, with DATA pointing to a
3866    mips_elf_traverse_got_arg structure.  Add all entries to DATA->g,
3867    converting entries for indirect and warning symbols into entries
3868    for the target symbol.  Set DATA->g to null on error.  */
3869
3870 static int
3871 mips_elf_recreate_got (void **entryp, void *data)
3872 {
3873   struct mips_got_entry new_entry, *entry;
3874   struct mips_elf_traverse_got_arg *arg;
3875   void **slot;
3876
3877   entry = (struct mips_got_entry *) *entryp;
3878   arg = (struct mips_elf_traverse_got_arg *) data;
3879   if (entry->abfd != NULL
3880       && entry->symndx == -1
3881       && (entry->d.h->root.root.type == bfd_link_hash_indirect
3882           || entry->d.h->root.root.type == bfd_link_hash_warning))
3883     {
3884       struct mips_elf_link_hash_entry *h;
3885
3886       new_entry = *entry;
3887       entry = &new_entry;
3888       h = entry->d.h;
3889       do
3890         {
3891           BFD_ASSERT (h->global_got_area == GGA_NONE);
3892           h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
3893         }
3894       while (h->root.root.type == bfd_link_hash_indirect
3895              || h->root.root.type == bfd_link_hash_warning);
3896       entry->d.h = h;
3897     }
3898   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
3899   if (slot == NULL)
3900     {
3901       arg->g = NULL;
3902       return 0;
3903     }
3904   if (*slot == NULL)
3905     {
3906       if (entry == &new_entry)
3907         {
3908           entry = bfd_alloc (entry->abfd, sizeof (*entry));
3909           if (!entry)
3910             {
3911               arg->g = NULL;
3912               return 0;
3913             }
3914           *entry = new_entry;
3915         }
3916       *slot = entry;
3917       mips_elf_count_got_entry (arg->info, arg->g, entry);
3918     }
3919   return 1;
3920 }
3921
3922 /* Return the maximum number of GOT page entries required for RANGE.  */
3923
3924 static bfd_vma
3925 mips_elf_pages_for_range (const struct mips_got_page_range *range)
3926 {
3927   return (range->max_addend - range->min_addend + 0x1ffff) >> 16;
3928 }
3929
3930 /* Record that G requires a page entry that can reach SEC + ADDEND.  */
3931
3932 static bfd_boolean
3933 mips_elf_record_got_page_entry (struct mips_got_info *g,
3934                                 asection *sec, bfd_signed_vma addend)
3935 {
3936   struct mips_got_page_entry lookup, *entry;
3937   struct mips_got_page_range **range_ptr, *range;
3938   bfd_vma old_pages, new_pages;
3939   void **loc;
3940
3941   /* Find the mips_got_page_entry hash table entry for this section.  */
3942   lookup.sec = sec;
3943   loc = htab_find_slot (g->got_page_entries, &lookup, INSERT);
3944   if (loc == NULL)
3945     return FALSE;
3946
3947   /* Create a mips_got_page_entry if this is the first time we've
3948      seen the section.  */
3949   entry = (struct mips_got_page_entry *) *loc;
3950   if (!entry)
3951     {
3952       entry = bfd_zalloc (sec->owner, sizeof (*entry));
3953       if (!entry)
3954         return FALSE;
3955
3956       entry->sec = sec;
3957       *loc = entry;
3958     }
3959
3960   /* Skip over ranges whose maximum extent cannot share a page entry
3961      with ADDEND.  */
3962   range_ptr = &entry->ranges;
3963   while (*range_ptr && addend > (*range_ptr)->max_addend + 0xffff)
3964     range_ptr = &(*range_ptr)->next;
3965
3966   /* If we scanned to the end of the list, or found a range whose
3967      minimum extent cannot share a page entry with ADDEND, create
3968      a new singleton range.  */
3969   range = *range_ptr;
3970   if (!range || addend < range->min_addend - 0xffff)
3971     {
3972       range = bfd_zalloc (sec->owner, sizeof (*range));
3973       if (!range)
3974         return FALSE;
3975
3976       range->next = *range_ptr;
3977       range->min_addend = addend;
3978       range->max_addend = addend;
3979
3980       *range_ptr = range;
3981       entry->num_pages++;
3982       g->page_gotno++;
3983       return TRUE;
3984     }
3985
3986   /* Remember how many pages the old range contributed.  */
3987   old_pages = mips_elf_pages_for_range (range);
3988
3989   /* Update the ranges.  */
3990   if (addend < range->min_addend)
3991     range->min_addend = addend;
3992   else if (addend > range->max_addend)
3993     {
3994       if (range->next && addend >= range->next->min_addend - 0xffff)
3995         {
3996           old_pages += mips_elf_pages_for_range (range->next);
3997           range->max_addend = range->next->max_addend;
3998           range->next = range->next->next;
3999         }
4000       else
4001         range->max_addend = addend;
4002     }
4003
4004   /* Record any change in the total estimate.  */
4005   new_pages = mips_elf_pages_for_range (range);
4006   if (old_pages != new_pages)
4007     {
4008       entry->num_pages += new_pages - old_pages;
4009       g->page_gotno += new_pages - old_pages;
4010     }
4011
4012   return TRUE;
4013 }
4014
4015 /* A htab_traverse callback for which *REFP points to a mips_got_page_ref
4016    and for which DATA points to a mips_elf_traverse_got_arg.  Work out
4017    whether the page reference described by *REFP needs a GOT page entry,
4018    and record that entry in DATA->g if so.  Set DATA->g to null on failure.  */
4019
4020 static bfd_boolean
4021 mips_elf_resolve_got_page_ref (void **refp, void *data)
4022 {
4023   struct mips_got_page_ref *ref;
4024   struct mips_elf_traverse_got_arg *arg;
4025   struct mips_elf_link_hash_table *htab;
4026   asection *sec;
4027   bfd_vma addend;
4028
4029   ref = (struct mips_got_page_ref *) *refp;
4030   arg = (struct mips_elf_traverse_got_arg *) data;
4031   htab = mips_elf_hash_table (arg->info);
4032
4033   if (ref->symndx < 0)
4034     {
4035       struct mips_elf_link_hash_entry *h;
4036
4037       /* Global GOT_PAGEs decay to GOT_DISP and so don't need page entries.  */
4038       h = ref->u.h;
4039       if (!SYMBOL_REFERENCES_LOCAL (arg->info, &h->root))
4040         return 1;
4041
4042       /* Ignore undefined symbols; we'll issue an error later if
4043          appropriate.  */
4044       if (!((h->root.root.type == bfd_link_hash_defined
4045              || h->root.root.type == bfd_link_hash_defweak)
4046             && h->root.root.u.def.section))
4047         return 1;
4048
4049       sec = h->root.root.u.def.section;
4050       addend = h->root.root.u.def.value + ref->addend;
4051     }
4052   else
4053     {
4054       Elf_Internal_Sym *isym;
4055
4056       /* Read in the symbol.  */
4057       isym = bfd_sym_from_r_symndx (&htab->sym_cache, ref->u.abfd,
4058                                     ref->symndx);
4059       if (isym == NULL)
4060         {
4061           arg->g = NULL;
4062           return 0;
4063         }
4064
4065       /* Get the associated input section.  */
4066       sec = bfd_section_from_elf_index (ref->u.abfd, isym->st_shndx);
4067       if (sec == NULL)
4068         {
4069           arg->g = NULL;
4070           return 0;
4071         }
4072
4073       /* If this is a mergable section, work out the section and offset
4074          of the merged data.  For section symbols, the addend specifies
4075          of the offset _of_ the first byte in the data, otherwise it
4076          specifies the offset _from_ the first byte.  */
4077       if (sec->flags & SEC_MERGE)
4078         {
4079           void *secinfo;
4080
4081           secinfo = elf_section_data (sec)->sec_info;
4082           if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
4083             addend = _bfd_merged_section_offset (ref->u.abfd, &sec, secinfo,
4084                                                  isym->st_value + ref->addend);
4085           else
4086             addend = _bfd_merged_section_offset (ref->u.abfd, &sec, secinfo,
4087                                                  isym->st_value) + ref->addend;
4088         }
4089       else
4090         addend = isym->st_value + ref->addend;
4091     }
4092   if (!mips_elf_record_got_page_entry (arg->g, sec, addend))
4093     {
4094       arg->g = NULL;
4095       return 0;
4096     }
4097   return 1;
4098 }
4099
4100 /* If any entries in G->got_entries are for indirect or warning symbols,
4101    replace them with entries for the target symbol.  Convert g->got_page_refs
4102    into got_page_entry structures and estimate the number of page entries
4103    that they require.  */
4104
4105 static bfd_boolean
4106 mips_elf_resolve_final_got_entries (struct bfd_link_info *info,
4107                                     struct mips_got_info *g)
4108 {
4109   struct mips_elf_traverse_got_arg tga;
4110   struct mips_got_info oldg;
4111
4112   oldg = *g;
4113
4114   tga.info = info;
4115   tga.g = g;
4116   tga.value = FALSE;
4117   htab_traverse (g->got_entries, mips_elf_check_recreate_got, &tga);
4118   if (tga.value)
4119     {
4120       *g = oldg;
4121       g->got_entries = htab_create (htab_size (oldg.got_entries),
4122                                     mips_elf_got_entry_hash,
4123                                     mips_elf_got_entry_eq, NULL);
4124       if (!g->got_entries)
4125         return FALSE;
4126
4127       htab_traverse (oldg.got_entries, mips_elf_recreate_got, &tga);
4128       if (!tga.g)
4129         return FALSE;
4130
4131       htab_delete (oldg.got_entries);
4132     }
4133
4134   g->got_page_entries = htab_try_create (1, mips_got_page_entry_hash,
4135                                          mips_got_page_entry_eq, NULL);
4136   if (g->got_page_entries == NULL)
4137     return FALSE;
4138
4139   tga.info = info;
4140   tga.g = g;
4141   htab_traverse (g->got_page_refs, mips_elf_resolve_got_page_ref, &tga);
4142
4143   return TRUE;
4144 }
4145
4146 /* A mips_elf_link_hash_traverse callback for which DATA points to the
4147    link_info structure.  Decide whether the hash entry needs an entry in
4148    the global part of the primary GOT, setting global_got_area accordingly.
4149    Count the number of global symbols that are in the primary GOT only
4150    because they have relocations against them (reloc_only_gotno).  */
4151
4152 static int
4153 mips_elf_count_got_symbols (struct mips_elf_link_hash_entry *h, void *data)
4154 {
4155   struct bfd_link_info *info;
4156   struct mips_elf_link_hash_table *htab;
4157   struct mips_got_info *g;
4158
4159   info = (struct bfd_link_info *) data;
4160   htab = mips_elf_hash_table (info);
4161   g = htab->got_info;
4162   if (h->global_got_area != GGA_NONE)
4163     {
4164       /* Make a final decision about whether the symbol belongs in the
4165          local or global GOT.  Symbols that bind locally can (and in the
4166          case of forced-local symbols, must) live in the local GOT.
4167          Those that are aren't in the dynamic symbol table must also
4168          live in the local GOT.
4169
4170          Note that the former condition does not always imply the
4171          latter: symbols do not bind locally if they are completely
4172          undefined.  We'll report undefined symbols later if appropriate.  */
4173       if (h->root.dynindx == -1
4174           || (h->got_only_for_calls
4175               ? SYMBOL_CALLS_LOCAL (info, &h->root)
4176               : SYMBOL_REFERENCES_LOCAL (info, &h->root)))
4177         /* The symbol belongs in the local GOT.  We no longer need this
4178            entry if it was only used for relocations; those relocations
4179            will be against the null or section symbol instead of H.  */
4180         h->global_got_area = GGA_NONE;
4181       else if (htab->is_vxworks
4182                && h->got_only_for_calls
4183                && h->root.plt.offset != MINUS_ONE)
4184         /* On VxWorks, calls can refer directly to the .got.plt entry;
4185            they don't need entries in the regular GOT.  .got.plt entries
4186            will be allocated by _bfd_mips_elf_adjust_dynamic_symbol.  */
4187         h->global_got_area = GGA_NONE;
4188       else if (h->global_got_area == GGA_RELOC_ONLY)
4189         {
4190           g->reloc_only_gotno++;
4191           g->global_gotno++;
4192         }
4193     }
4194   return 1;
4195 }
4196 \f
4197 /* A htab_traverse callback for GOT entries.  Add each one to the GOT
4198    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4199
4200 static int
4201 mips_elf_add_got_entry (void **entryp, void *data)
4202 {
4203   struct mips_got_entry *entry;
4204   struct mips_elf_traverse_got_arg *arg;
4205   void **slot;
4206
4207   entry = (struct mips_got_entry *) *entryp;
4208   arg = (struct mips_elf_traverse_got_arg *) data;
4209   slot = htab_find_slot (arg->g->got_entries, entry, INSERT);
4210   if (!slot)
4211     {
4212       arg->g = NULL;
4213       return 0;
4214     }
4215   if (!*slot)
4216     {
4217       *slot = entry;
4218       mips_elf_count_got_entry (arg->info, arg->g, entry);
4219     }
4220   return 1;
4221 }
4222
4223 /* A htab_traverse callback for GOT page entries.  Add each one to the GOT
4224    given in mips_elf_traverse_got_arg DATA.  Clear DATA->G on error.  */
4225
4226 static int
4227 mips_elf_add_got_page_entry (void **entryp, void *data)
4228 {
4229   struct mips_got_page_entry *entry;
4230   struct mips_elf_traverse_got_arg *arg;
4231   void **slot;
4232
4233   entry = (struct mips_got_page_entry *) *entryp;
4234   arg = (struct mips_elf_traverse_got_arg *) data;
4235   slot = htab_find_slot (arg->g->got_page_entries, entry, INSERT);
4236   if (!slot)
4237     {
4238       arg->g = NULL;
4239       return 0;
4240     }
4241   if (!*slot)
4242     {
4243       *slot = entry;
4244       arg->g->page_gotno += entry->num_pages;
4245     }
4246   return 1;
4247 }
4248
4249 /* Consider merging FROM, which is ABFD's GOT, into TO.  Return -1 if
4250    this would lead to overflow, 1 if they were merged successfully,
4251    and 0 if a merge failed due to lack of memory.  (These values are chosen
4252    so that nonnegative return values can be returned by a htab_traverse
4253    callback.)  */
4254
4255 static int
4256 mips_elf_merge_got_with (bfd *abfd, struct mips_got_info *from,
4257                          struct mips_got_info *to,
4258                          struct mips_elf_got_per_bfd_arg *arg)
4259 {
4260   struct mips_elf_traverse_got_arg tga;
4261   unsigned int estimate;
4262
4263   /* Work out how many page entries we would need for the combined GOT.  */
4264   estimate = arg->max_pages;
4265   if (estimate >= from->page_gotno + to->page_gotno)
4266     estimate = from->page_gotno + to->page_gotno;
4267
4268   /* And conservatively estimate how many local and TLS entries
4269      would be needed.  */
4270   estimate += from->local_gotno + to->local_gotno;
4271   estimate += from->tls_gotno + to->tls_gotno;
4272
4273   /* If we're merging with the primary got, any TLS relocations will
4274      come after the full set of global entries.  Otherwise estimate those
4275      conservatively as well.  */
4276   if (to == arg->primary && from->tls_gotno + to->tls_gotno)
4277     estimate += arg->global_count;
4278   else
4279     estimate += from->global_gotno + to->global_gotno;
4280
4281   /* Bail out if the combined GOT might be too big.  */
4282   if (estimate > arg->max_count)
4283     return -1;
4284
4285   /* Transfer the bfd's got information from FROM to TO.  */
4286   tga.info = arg->info;
4287   tga.g = to;
4288   htab_traverse (from->got_entries, mips_elf_add_got_entry, &tga);
4289   if (!tga.g)
4290     return 0;
4291
4292   htab_traverse (from->got_page_entries, mips_elf_add_got_page_entry, &tga);
4293   if (!tga.g)
4294     return 0;
4295
4296   mips_elf_replace_bfd_got (abfd, to);
4297   return 1;
4298 }
4299
4300 /* Attempt to merge GOT G, which belongs to ABFD.  Try to use as much
4301    as possible of the primary got, since it doesn't require explicit
4302    dynamic relocations, but don't use bfds that would reference global
4303    symbols out of the addressable range.  Failing the primary got,
4304    attempt to merge with the current got, or finish the current got
4305    and then make make the new got current.  */
4306
4307 static bfd_boolean
4308 mips_elf_merge_got (bfd *abfd, struct mips_got_info *g,
4309                     struct mips_elf_got_per_bfd_arg *arg)
4310 {
4311   unsigned int estimate;
4312   int result;
4313
4314   if (!mips_elf_resolve_final_got_entries (arg->info, g))
4315     return FALSE;
4316
4317   /* Work out the number of page, local and TLS entries.  */
4318   estimate = arg->max_pages;
4319   if (estimate > g->page_gotno)
4320     estimate = g->page_gotno;
4321   estimate += g->local_gotno + g->tls_gotno;
4322
4323   /* We place TLS GOT entries after both locals and globals.  The globals
4324      for the primary GOT may overflow the normal GOT size limit, so be
4325      sure not to merge a GOT which requires TLS with the primary GOT in that
4326      case.  This doesn't affect non-primary GOTs.  */
4327   estimate += (g->tls_gotno > 0 ? arg->global_count : g->global_gotno);
4328
4329   if (estimate <= arg->max_count)
4330     {
4331       /* If we don't have a primary GOT, use it as
4332          a starting point for the primary GOT.  */
4333       if (!arg->primary)
4334         {
4335           arg->primary = g;
4336           return TRUE;
4337         }
4338
4339       /* Try merging with the primary GOT.  */
4340       result = mips_elf_merge_got_with (abfd, g, arg->primary, arg);
4341       if (result >= 0)
4342         return result;
4343     }
4344
4345   /* If we can merge with the last-created got, do it.  */
4346   if (arg->current)
4347     {
4348       result = mips_elf_merge_got_with (abfd, g, arg->current, arg);
4349       if (result >= 0)
4350         return result;
4351     }
4352
4353   /* Well, we couldn't merge, so create a new GOT.  Don't check if it
4354      fits; if it turns out that it doesn't, we'll get relocation
4355      overflows anyway.  */
4356   g->next = arg->current;
4357   arg->current = g;
4358
4359   return TRUE;
4360 }
4361
4362 /* ENTRYP is a hash table entry for a mips_got_entry.  Set its gotidx
4363    to GOTIDX, duplicating the entry if it has already been assigned
4364    an index in a different GOT.  */
4365
4366 static bfd_boolean
4367 mips_elf_set_gotidx (void **entryp, long gotidx)
4368 {
4369   struct mips_got_entry *entry;
4370
4371   entry = (struct mips_got_entry *) *entryp;
4372   if (entry->gotidx > 0)
4373     {
4374       struct mips_got_entry *new_entry;
4375
4376       new_entry = bfd_alloc (entry->abfd, sizeof (*entry));
4377       if (!new_entry)
4378         return FALSE;
4379
4380       *new_entry = *entry;
4381       *entryp = new_entry;
4382       entry = new_entry;
4383     }
4384   entry->gotidx = gotidx;
4385   return TRUE;
4386 }
4387
4388 /* Set the TLS GOT index for the GOT entry in ENTRYP.  DATA points to a
4389    mips_elf_traverse_got_arg in which DATA->value is the size of one
4390    GOT entry.  Set DATA->g to null on failure.  */
4391
4392 static int
4393 mips_elf_initialize_tls_index (void **entryp, void *data)
4394 {
4395   struct mips_got_entry *entry;
4396   struct mips_elf_traverse_got_arg *arg;
4397
4398   /* We're only interested in TLS symbols.  */
4399   entry = (struct mips_got_entry *) *entryp;
4400   if (entry->tls_type == GOT_TLS_NONE)
4401     return 1;
4402
4403   arg = (struct mips_elf_traverse_got_arg *) data;
4404   if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->tls_assigned_gotno))
4405     {
4406       arg->g = NULL;
4407       return 0;
4408     }
4409
4410   /* Account for the entries we've just allocated.  */
4411   arg->g->tls_assigned_gotno += mips_tls_got_entries (entry->tls_type);
4412   return 1;
4413 }
4414
4415 /* A htab_traverse callback for GOT entries, where DATA points to a
4416    mips_elf_traverse_got_arg.  Set the global_got_area of each global
4417    symbol to DATA->value.  */
4418
4419 static int
4420 mips_elf_set_global_got_area (void **entryp, void *data)
4421 {
4422   struct mips_got_entry *entry;
4423   struct mips_elf_traverse_got_arg *arg;
4424
4425   entry = (struct mips_got_entry *) *entryp;
4426   arg = (struct mips_elf_traverse_got_arg *) data;
4427   if (entry->abfd != NULL
4428       && entry->symndx == -1
4429       && entry->d.h->global_got_area != GGA_NONE)
4430     entry->d.h->global_got_area = arg->value;
4431   return 1;
4432 }
4433
4434 /* A htab_traverse callback for secondary GOT entries, where DATA points
4435    to a mips_elf_traverse_got_arg.  Assign GOT indices to global entries
4436    and record the number of relocations they require.  DATA->value is
4437    the size of one GOT entry.  Set DATA->g to null on failure.  */
4438
4439 static int
4440 mips_elf_set_global_gotidx (void **entryp, void *data)
4441 {
4442   struct mips_got_entry *entry;
4443   struct mips_elf_traverse_got_arg *arg;
4444
4445   entry = (struct mips_got_entry *) *entryp;
4446   arg = (struct mips_elf_traverse_got_arg *) data;
4447   if (entry->abfd != NULL
4448       && entry->symndx == -1
4449       && entry->d.h->global_got_area != GGA_NONE)
4450     {
4451       if (!mips_elf_set_gotidx (entryp, arg->value * arg->g->assigned_gotno))
4452         {
4453           arg->g = NULL;
4454           return 0;
4455         }
4456       arg->g->assigned_gotno += 1;
4457
4458       if (arg->info->shared
4459           || (elf_hash_table (arg->info)->dynamic_sections_created
4460               && entry->d.h->root.def_dynamic
4461               && !entry->d.h->root.def_regular))
4462         arg->g->relocs += 1;
4463     }
4464
4465   return 1;
4466 }
4467
4468 /* A htab_traverse callback for GOT entries for which DATA is the
4469    bfd_link_info.  Forbid any global symbols from having traditional
4470    lazy-binding stubs.  */
4471
4472 static int
4473 mips_elf_forbid_lazy_stubs (void **entryp, void *data)
4474 {
4475   struct bfd_link_info *info;
4476   struct mips_elf_link_hash_table *htab;
4477   struct mips_got_entry *entry;
4478
4479   entry = (struct mips_got_entry *) *entryp;
4480   info = (struct bfd_link_info *) data;
4481   htab = mips_elf_hash_table (info);
4482   BFD_ASSERT (htab != NULL);
4483
4484   if (entry->abfd != NULL
4485       && entry->symndx == -1
4486       && entry->d.h->needs_lazy_stub)
4487     {
4488       entry->d.h->needs_lazy_stub = FALSE;
4489       htab->lazy_stub_count--;
4490     }
4491
4492   return 1;
4493 }
4494
4495 /* Return the offset of an input bfd IBFD's GOT from the beginning of
4496    the primary GOT.  */
4497 static bfd_vma
4498 mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd)
4499 {
4500   if (!g->next)
4501     return 0;
4502
4503   g = mips_elf_bfd_got (ibfd, FALSE);
4504   if (! g)
4505     return 0;
4506
4507   BFD_ASSERT (g->next);
4508
4509   g = g->next;
4510
4511   return (g->local_gotno + g->global_gotno + g->tls_gotno)
4512     * MIPS_ELF_GOT_SIZE (abfd);
4513 }
4514
4515 /* Turn a single GOT that is too big for 16-bit addressing into
4516    a sequence of GOTs, each one 16-bit addressable.  */
4517
4518 static bfd_boolean
4519 mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info,
4520                     asection *got, bfd_size_type pages)
4521 {
4522   struct mips_elf_link_hash_table *htab;
4523   struct mips_elf_got_per_bfd_arg got_per_bfd_arg;
4524   struct mips_elf_traverse_got_arg tga;
4525   struct mips_got_info *g, *gg;
4526   unsigned int assign, needed_relocs;
4527   bfd *dynobj, *ibfd;
4528
4529   dynobj = elf_hash_table (info)->dynobj;
4530   htab = mips_elf_hash_table (info);
4531   BFD_ASSERT (htab != NULL);
4532
4533   g = htab->got_info;
4534
4535   got_per_bfd_arg.obfd = abfd;
4536   got_per_bfd_arg.info = info;
4537   got_per_bfd_arg.current = NULL;
4538   got_per_bfd_arg.primary = NULL;
4539   got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (info)
4540                                 / MIPS_ELF_GOT_SIZE (abfd))
4541                                - htab->reserved_gotno);
4542   got_per_bfd_arg.max_pages = pages;
4543   /* The number of globals that will be included in the primary GOT.
4544      See the calls to mips_elf_set_global_got_area below for more
4545      information.  */
4546   got_per_bfd_arg.global_count = g->global_gotno;
4547
4548   /* Try to merge the GOTs of input bfds together, as long as they
4549      don't seem to exceed the maximum GOT size, choosing one of them
4550      to be the primary GOT.  */
4551   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
4552     {
4553       gg = mips_elf_bfd_got (ibfd, FALSE);
4554       if (gg && !mips_elf_merge_got (ibfd, gg, &got_per_bfd_arg))
4555         return FALSE;
4556     }
4557
4558   /* If we do not find any suitable primary GOT, create an empty one.  */
4559   if (got_per_bfd_arg.primary == NULL)
4560     g->next = mips_elf_create_got_info (abfd);
4561   else
4562     g->next = got_per_bfd_arg.primary;
4563   g->next->next = got_per_bfd_arg.current;
4564
4565   /* GG is now the master GOT, and G is the primary GOT.  */
4566   gg = g;
4567   g = g->next;
4568
4569   /* Map the output bfd to the primary got.  That's what we're going
4570      to use for bfds that use GOT16 or GOT_PAGE relocations that we
4571      didn't mark in check_relocs, and we want a quick way to find it.
4572      We can't just use gg->next because we're going to reverse the
4573      list.  */
4574   mips_elf_replace_bfd_got (abfd, g);
4575
4576   /* Every symbol that is referenced in a dynamic relocation must be
4577      present in the primary GOT, so arrange for them to appear after
4578      those that are actually referenced.  */
4579   gg->reloc_only_gotno = gg->global_gotno - g->global_gotno;
4580   g->global_gotno = gg->global_gotno;
4581
4582   tga.info = info;
4583   tga.value = GGA_RELOC_ONLY;
4584   htab_traverse (gg->got_entries, mips_elf_set_global_got_area, &tga);
4585   tga.value = GGA_NORMAL;
4586   htab_traverse (g->got_entries, mips_elf_set_global_got_area, &tga);
4587
4588   /* Now go through the GOTs assigning them offset ranges.
4589      [assigned_gotno, local_gotno[ will be set to the range of local
4590      entries in each GOT.  We can then compute the end of a GOT by
4591      adding local_gotno to global_gotno.  We reverse the list and make
4592      it circular since then we'll be able to quickly compute the
4593      beginning of a GOT, by computing the end of its predecessor.  To
4594      avoid special cases for the primary GOT, while still preserving
4595      assertions that are valid for both single- and multi-got links,
4596      we arrange for the main got struct to have the right number of
4597      global entries, but set its local_gotno such that the initial
4598      offset of the primary GOT is zero.  Remember that the primary GOT
4599      will become the last item in the circular linked list, so it
4600      points back to the master GOT.  */
4601   gg->local_gotno = -g->global_gotno;
4602   gg->global_gotno = g->global_gotno;
4603   gg->tls_gotno = 0;
4604   assign = 0;
4605   gg->next = gg;
4606
4607   do
4608     {
4609       struct mips_got_info *gn;
4610
4611       assign += htab->reserved_gotno;
4612       g->assigned_gotno = assign;
4613       g->local_gotno += assign;
4614       g->local_gotno += (pages < g->page_gotno ? pages : g->page_gotno);
4615       assign = g->local_gotno + g->global_gotno + g->tls_gotno;
4616
4617       /* Take g out of the direct list, and push it onto the reversed
4618          list that gg points to.  g->next is guaranteed to be nonnull after
4619          this operation, as required by mips_elf_initialize_tls_index. */
4620       gn = g->next;
4621       g->next = gg->next;
4622       gg->next = g;
4623
4624       /* Set up any TLS entries.  We always place the TLS entries after
4625          all non-TLS entries.  */
4626       g->tls_assigned_gotno = g->local_gotno + g->global_gotno;
4627       tga.g = g;
4628       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4629       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
4630       if (!tga.g)
4631         return FALSE;
4632       BFD_ASSERT (g->tls_assigned_gotno == assign);
4633
4634       /* Move onto the next GOT.  It will be a secondary GOT if nonull.  */
4635       g = gn;
4636
4637       /* Forbid global symbols in every non-primary GOT from having
4638          lazy-binding stubs.  */
4639       if (g)
4640         htab_traverse (g->got_entries, mips_elf_forbid_lazy_stubs, info);
4641     }
4642   while (g);
4643
4644   got->size = assign * MIPS_ELF_GOT_SIZE (abfd);
4645
4646   needed_relocs = 0;
4647   for (g = gg->next; g && g->next != gg; g = g->next)
4648     {
4649       unsigned int save_assign;
4650
4651       /* Assign offsets to global GOT entries and count how many
4652          relocations they need.  */
4653       save_assign = g->assigned_gotno;
4654       g->assigned_gotno = g->local_gotno;
4655       tga.info = info;
4656       tga.value = MIPS_ELF_GOT_SIZE (abfd);
4657       tga.g = g;
4658       htab_traverse (g->got_entries, mips_elf_set_global_gotidx, &tga);
4659       if (!tga.g)
4660         return FALSE;
4661       BFD_ASSERT (g->assigned_gotno == g->local_gotno + g->global_gotno);
4662       g->assigned_gotno = save_assign;
4663
4664       if (info->shared)
4665         {
4666           g->relocs += g->local_gotno - g->assigned_gotno;
4667           BFD_ASSERT (g->assigned_gotno == g->next->local_gotno
4668                       + g->next->global_gotno
4669                       + g->next->tls_gotno
4670                       + htab->reserved_gotno);
4671         }
4672       needed_relocs += g->relocs;
4673     }
4674   needed_relocs += g->relocs;
4675
4676   if (needed_relocs)
4677     mips_elf_allocate_dynamic_relocations (dynobj, info,
4678                                            needed_relocs);
4679
4680   return TRUE;
4681 }
4682
4683 \f
4684 /* Returns the first relocation of type r_type found, beginning with
4685    RELOCATION.  RELEND is one-past-the-end of the relocation table.  */
4686
4687 static const Elf_Internal_Rela *
4688 mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
4689                           const Elf_Internal_Rela *relocation,
4690                           const Elf_Internal_Rela *relend)
4691 {
4692   unsigned long r_symndx = ELF_R_SYM (abfd, relocation->r_info);
4693
4694   while (relocation < relend)
4695     {
4696       if (ELF_R_TYPE (abfd, relocation->r_info) == r_type
4697           && ELF_R_SYM (abfd, relocation->r_info) == r_symndx)
4698         return relocation;
4699
4700       ++relocation;
4701     }
4702
4703   /* We didn't find it.  */
4704   return NULL;
4705 }
4706
4707 /* Return whether an input relocation is against a local symbol.  */
4708
4709 static bfd_boolean
4710 mips_elf_local_relocation_p (bfd *input_bfd,
4711                              const Elf_Internal_Rela *relocation,
4712                              asection **local_sections)
4713 {
4714   unsigned long r_symndx;
4715   Elf_Internal_Shdr *symtab_hdr;
4716   size_t extsymoff;
4717
4718   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
4719   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
4720   extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
4721
4722   if (r_symndx < extsymoff)
4723     return TRUE;
4724   if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
4725     return TRUE;
4726
4727   return FALSE;
4728 }
4729 \f
4730 /* Sign-extend VALUE, which has the indicated number of BITS.  */
4731
4732 bfd_vma
4733 _bfd_mips_elf_sign_extend (bfd_vma value, int bits)
4734 {
4735   if (value & ((bfd_vma) 1 << (bits - 1)))
4736     /* VALUE is negative.  */
4737     value |= ((bfd_vma) - 1) << bits;
4738
4739   return value;
4740 }
4741
4742 /* Return non-zero if the indicated VALUE has overflowed the maximum
4743    range expressible by a signed number with the indicated number of
4744    BITS.  */
4745
4746 static bfd_boolean
4747 mips_elf_overflow_p (bfd_vma value, int bits)
4748 {
4749   bfd_signed_vma svalue = (bfd_signed_vma) value;
4750
4751   if (svalue > (1 << (bits - 1)) - 1)
4752     /* The value is too big.  */
4753     return TRUE;
4754   else if (svalue < -(1 << (bits - 1)))
4755     /* The value is too small.  */
4756     return TRUE;
4757
4758   /* All is well.  */
4759   return FALSE;
4760 }
4761
4762 /* Calculate the %high function.  */
4763
4764 static bfd_vma
4765 mips_elf_high (bfd_vma value)
4766 {
4767   return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
4768 }
4769
4770 /* Calculate the %higher function.  */
4771
4772 static bfd_vma
4773 mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED)
4774 {
4775 #ifdef BFD64
4776   return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff;
4777 #else
4778   abort ();
4779   return MINUS_ONE;
4780 #endif
4781 }
4782
4783 /* Calculate the %highest function.  */
4784
4785 static bfd_vma
4786 mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED)
4787 {
4788 #ifdef BFD64
4789   return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff;
4790 #else
4791   abort ();
4792   return MINUS_ONE;
4793 #endif
4794 }
4795 \f
4796 /* Create the .compact_rel section.  */
4797
4798 static bfd_boolean
4799 mips_elf_create_compact_rel_section
4800   (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
4801 {
4802   flagword flags;
4803   register asection *s;
4804
4805   if (bfd_get_linker_section (abfd, ".compact_rel") == NULL)
4806     {
4807       flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED
4808                | SEC_READONLY);
4809
4810       s = bfd_make_section_anyway_with_flags (abfd, ".compact_rel", flags);
4811       if (s == NULL
4812           || ! bfd_set_section_alignment (abfd, s,
4813                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
4814         return FALSE;
4815
4816       s->size = sizeof (Elf32_External_compact_rel);
4817     }
4818
4819   return TRUE;
4820 }
4821
4822 /* Create the .got section to hold the global offset table.  */
4823
4824 static bfd_boolean
4825 mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
4826 {
4827   flagword flags;
4828   register asection *s;
4829   struct elf_link_hash_entry *h;
4830   struct bfd_link_hash_entry *bh;
4831   struct mips_elf_link_hash_table *htab;
4832
4833   htab = mips_elf_hash_table (info);
4834   BFD_ASSERT (htab != NULL);
4835
4836   /* This function may be called more than once.  */
4837   if (htab->sgot)
4838     return TRUE;
4839
4840   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
4841            | SEC_LINKER_CREATED);
4842
4843   /* We have to use an alignment of 2**4 here because this is hardcoded
4844      in the function stub generation and in the linker script.  */
4845   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
4846   if (s == NULL
4847       || ! bfd_set_section_alignment (abfd, s, 4))
4848     return FALSE;
4849   htab->sgot = s;
4850
4851   /* Define the symbol _GLOBAL_OFFSET_TABLE_.  We don't do this in the
4852      linker script because we don't want to define the symbol if we
4853      are not creating a global offset table.  */
4854   bh = NULL;
4855   if (! (_bfd_generic_link_add_one_symbol
4856          (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
4857           0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
4858     return FALSE;
4859
4860   h = (struct elf_link_hash_entry *) bh;
4861   h->non_elf = 0;
4862   h->def_regular = 1;
4863   h->type = STT_OBJECT;
4864   elf_hash_table (info)->hgot = h;
4865
4866   if (info->shared
4867       && ! bfd_elf_link_record_dynamic_symbol (info, h))
4868     return FALSE;
4869
4870   htab->got_info = mips_elf_create_got_info (abfd);
4871   mips_elf_section_data (s)->elf.this_hdr.sh_flags
4872     |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
4873
4874   /* We also need a .got.plt section when generating PLTs.  */
4875   s = bfd_make_section_anyway_with_flags (abfd, ".got.plt",
4876                                           SEC_ALLOC | SEC_LOAD
4877                                           | SEC_HAS_CONTENTS
4878                                           | SEC_IN_MEMORY
4879                                           | SEC_LINKER_CREATED);
4880   if (s == NULL)
4881     return FALSE;
4882   htab->sgotplt = s;
4883
4884   return TRUE;
4885 }
4886 \f
4887 /* Return true if H refers to the special VxWorks __GOTT_BASE__ or
4888    __GOTT_INDEX__ symbols.  These symbols are only special for
4889    shared objects; they are not used in executables.  */
4890
4891 static bfd_boolean
4892 is_gott_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h)
4893 {
4894   return (mips_elf_hash_table (info)->is_vxworks
4895           && info->shared
4896           && (strcmp (h->root.root.string, "__GOTT_BASE__") == 0
4897               || strcmp (h->root.root.string, "__GOTT_INDEX__") == 0));
4898 }
4899
4900 /* Return TRUE if a relocation of type R_TYPE from INPUT_BFD might
4901    require an la25 stub.  See also mips_elf_local_pic_function_p,
4902    which determines whether the destination function ever requires a
4903    stub.  */
4904
4905 static bfd_boolean
4906 mips_elf_relocation_needs_la25_stub (bfd *input_bfd, int r_type,
4907                                      bfd_boolean target_is_16_bit_code_p)
4908 {
4909   /* We specifically ignore branches and jumps from EF_PIC objects,
4910      where the onus is on the compiler or programmer to perform any
4911      necessary initialization of $25.  Sometimes such initialization
4912      is unnecessary; for example, -mno-shared functions do not use
4913      the incoming value of $25, and may therefore be called directly.  */
4914   if (PIC_OBJECT_P (input_bfd))
4915     return FALSE;
4916
4917   switch (r_type)
4918     {
4919     case R_MIPS_26:
4920     case R_MIPS_PC16:
4921     case R_MICROMIPS_26_S1:
4922     case R_MICROMIPS_PC7_S1:
4923     case R_MICROMIPS_PC10_S1:
4924     case R_MICROMIPS_PC16_S1:
4925     case R_MICROMIPS_PC23_S2:
4926       return TRUE;
4927
4928     case R_MIPS16_26:
4929       return !target_is_16_bit_code_p;
4930
4931     default:
4932       return FALSE;
4933     }
4934 }
4935 \f
4936 /* Calculate the value produced by the RELOCATION (which comes from
4937    the INPUT_BFD).  The ADDEND is the addend to use for this
4938    RELOCATION; RELOCATION->R_ADDEND is ignored.
4939
4940    The result of the relocation calculation is stored in VALUEP.
4941    On exit, set *CROSS_MODE_JUMP_P to true if the relocation field
4942    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
4943
4944    This function returns bfd_reloc_continue if the caller need take no
4945    further action regarding this relocation, bfd_reloc_notsupported if
4946    something goes dramatically wrong, bfd_reloc_overflow if an
4947    overflow occurs, and bfd_reloc_ok to indicate success.  */
4948
4949 static bfd_reloc_status_type
4950 mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd,
4951                                asection *input_section,
4952                                struct bfd_link_info *info,
4953                                const Elf_Internal_Rela *relocation,
4954                                bfd_vma addend, reloc_howto_type *howto,
4955                                Elf_Internal_Sym *local_syms,
4956                                asection **local_sections, bfd_vma *valuep,
4957                                const char **namep,
4958                                bfd_boolean *cross_mode_jump_p,
4959                                bfd_boolean save_addend)
4960 {
4961   /* The eventual value we will return.  */
4962   bfd_vma value;
4963   /* The address of the symbol against which the relocation is
4964      occurring.  */
4965   bfd_vma symbol = 0;
4966   /* The final GP value to be used for the relocatable, executable, or
4967      shared object file being produced.  */
4968   bfd_vma gp;
4969   /* The place (section offset or address) of the storage unit being
4970      relocated.  */
4971   bfd_vma p;
4972   /* The value of GP used to create the relocatable object.  */
4973   bfd_vma gp0;
4974   /* The offset into the global offset table at which the address of
4975      the relocation entry symbol, adjusted by the addend, resides
4976      during execution.  */
4977   bfd_vma g = MINUS_ONE;
4978   /* The section in which the symbol referenced by the relocation is
4979      located.  */
4980   asection *sec = NULL;
4981   struct mips_elf_link_hash_entry *h = NULL;
4982   /* TRUE if the symbol referred to by this relocation is a local
4983      symbol.  */
4984   bfd_boolean local_p, was_local_p;
4985   /* TRUE if the symbol referred to by this relocation is "_gp_disp".  */
4986   bfd_boolean gp_disp_p = FALSE;
4987   /* TRUE if the symbol referred to by this relocation is
4988      "__gnu_local_gp".  */
4989   bfd_boolean gnu_local_gp_p = FALSE;
4990   Elf_Internal_Shdr *symtab_hdr;
4991   size_t extsymoff;
4992   unsigned long r_symndx;
4993   int r_type;
4994   /* TRUE if overflow occurred during the calculation of the
4995      relocation value.  */
4996   bfd_boolean overflowed_p;
4997   /* TRUE if this relocation refers to a MIPS16 function.  */
4998   bfd_boolean target_is_16_bit_code_p = FALSE;
4999   bfd_boolean target_is_micromips_code_p = FALSE;
5000   struct mips_elf_link_hash_table *htab;
5001   bfd *dynobj;
5002
5003   dynobj = elf_hash_table (info)->dynobj;
5004   htab = mips_elf_hash_table (info);
5005   BFD_ASSERT (htab != NULL);
5006
5007   /* Parse the relocation.  */
5008   r_symndx = ELF_R_SYM (input_bfd, relocation->r_info);
5009   r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5010   p = (input_section->output_section->vma
5011        + input_section->output_offset
5012        + relocation->r_offset);
5013
5014   /* Assume that there will be no overflow.  */
5015   overflowed_p = FALSE;
5016
5017   /* Figure out whether or not the symbol is local, and get the offset
5018      used in the array of hash table entries.  */
5019   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
5020   local_p = mips_elf_local_relocation_p (input_bfd, relocation,
5021                                          local_sections);
5022   was_local_p = local_p;
5023   if (! elf_bad_symtab (input_bfd))
5024     extsymoff = symtab_hdr->sh_info;
5025   else
5026     {
5027       /* The symbol table does not follow the rule that local symbols
5028          must come before globals.  */
5029       extsymoff = 0;
5030     }
5031
5032   /* Figure out the value of the symbol.  */
5033   if (local_p)
5034     {
5035       Elf_Internal_Sym *sym;
5036
5037       sym = local_syms + r_symndx;
5038       sec = local_sections[r_symndx];
5039
5040       symbol = sec->output_section->vma + sec->output_offset;
5041       if (ELF_ST_TYPE (sym->st_info) != STT_SECTION
5042           || (sec->flags & SEC_MERGE))
5043         symbol += sym->st_value;
5044       if ((sec->flags & SEC_MERGE)
5045           && ELF_ST_TYPE (sym->st_info) == STT_SECTION)
5046         {
5047           addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend);
5048           addend -= symbol;
5049           addend += sec->output_section->vma + sec->output_offset;
5050         }
5051
5052       /* MIPS16/microMIPS text labels should be treated as odd.  */
5053       if (ELF_ST_IS_COMPRESSED (sym->st_other))
5054         ++symbol;
5055
5056       /* Record the name of this symbol, for our caller.  */
5057       *namep = bfd_elf_string_from_elf_section (input_bfd,
5058                                                 symtab_hdr->sh_link,
5059                                                 sym->st_name);
5060       if (*namep == '\0')
5061         *namep = bfd_section_name (input_bfd, sec);
5062
5063       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (sym->st_other);
5064       target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (sym->st_other);
5065     }
5066   else
5067     {
5068       /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ?  */
5069
5070       /* For global symbols we look up the symbol in the hash-table.  */
5071       h = ((struct mips_elf_link_hash_entry *)
5072            elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
5073       /* Find the real hash-table entry for this symbol.  */
5074       while (h->root.root.type == bfd_link_hash_indirect
5075              || h->root.root.type == bfd_link_hash_warning)
5076         h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
5077
5078       /* Record the name of this symbol, for our caller.  */
5079       *namep = h->root.root.root.string;
5080
5081       /* See if this is the special _gp_disp symbol.  Note that such a
5082          symbol must always be a global symbol.  */
5083       if (strcmp (*namep, "_gp_disp") == 0
5084           && ! NEWABI_P (input_bfd))
5085         {
5086           /* Relocations against _gp_disp are permitted only with
5087              R_MIPS_HI16 and R_MIPS_LO16 relocations.  */
5088           if (!hi16_reloc_p (r_type) && !lo16_reloc_p (r_type))
5089             return bfd_reloc_notsupported;
5090
5091           gp_disp_p = TRUE;
5092         }
5093       /* See if this is the special _gp symbol.  Note that such a
5094          symbol must always be a global symbol.  */
5095       else if (strcmp (*namep, "__gnu_local_gp") == 0)
5096         gnu_local_gp_p = TRUE;
5097
5098
5099       /* If this symbol is defined, calculate its address.  Note that
5100          _gp_disp is a magic symbol, always implicitly defined by the
5101          linker, so it's inappropriate to check to see whether or not
5102          its defined.  */
5103       else if ((h->root.root.type == bfd_link_hash_defined
5104                 || h->root.root.type == bfd_link_hash_defweak)
5105                && h->root.root.u.def.section)
5106         {
5107           sec = h->root.root.u.def.section;
5108           if (sec->output_section)
5109             symbol = (h->root.root.u.def.value
5110                       + sec->output_section->vma
5111                       + sec->output_offset);
5112           else
5113             symbol = h->root.root.u.def.value;
5114         }
5115       else if (h->root.root.type == bfd_link_hash_undefweak)
5116         /* We allow relocations against undefined weak symbols, giving
5117            it the value zero, so that you can undefined weak functions
5118            and check to see if they exist by looking at their
5119            addresses.  */
5120         symbol = 0;
5121       else if (info->unresolved_syms_in_objects == RM_IGNORE
5122                && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5123         symbol = 0;
5124       else if (strcmp (*namep, SGI_COMPAT (input_bfd)
5125                        ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0)
5126         {
5127           /* If this is a dynamic link, we should have created a
5128              _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol
5129              in in _bfd_mips_elf_create_dynamic_sections.
5130              Otherwise, we should define the symbol with a value of 0.
5131              FIXME: It should probably get into the symbol table
5132              somehow as well.  */
5133           BFD_ASSERT (! info->shared);
5134           BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL);
5135           symbol = 0;
5136         }
5137       else if (ELF_MIPS_IS_OPTIONAL (h->root.other))
5138         {
5139           /* This is an optional symbol - an Irix specific extension to the
5140              ELF spec.  Ignore it for now.
5141              XXX - FIXME - there is more to the spec for OPTIONAL symbols
5142              than simply ignoring them, but we do not handle this for now.
5143              For information see the "64-bit ELF Object File Specification"
5144              which is available from here:
5145              http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf  */
5146           symbol = 0;
5147         }
5148       else if ((*info->callbacks->undefined_symbol)
5149                (info, h->root.root.root.string, input_bfd,
5150                 input_section, relocation->r_offset,
5151                 (info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
5152                  || ELF_ST_VISIBILITY (h->root.other)))
5153         {
5154           return bfd_reloc_undefined;
5155         }
5156       else
5157         {
5158           return bfd_reloc_notsupported;
5159         }
5160
5161       target_is_16_bit_code_p = ELF_ST_IS_MIPS16 (h->root.other);
5162       /* If the output section is the PLT section,
5163          then the target is not microMIPS.  */
5164       target_is_micromips_code_p = (htab->splt != sec
5165                                     && ELF_ST_IS_MICROMIPS (h->root.other));
5166     }
5167
5168   /* If this is a reference to a 16-bit function with a stub, we need
5169      to redirect the relocation to the stub unless:
5170
5171      (a) the relocation is for a MIPS16 JAL;
5172
5173      (b) the relocation is for a MIPS16 PIC call, and there are no
5174          non-MIPS16 uses of the GOT slot; or
5175
5176      (c) the section allows direct references to MIPS16 functions.  */
5177   if (r_type != R_MIPS16_26
5178       && !info->relocatable
5179       && ((h != NULL
5180            && h->fn_stub != NULL
5181            && (r_type != R_MIPS16_CALL16 || h->need_fn_stub))
5182           || (local_p
5183               && elf_tdata (input_bfd)->local_stubs != NULL
5184               && elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL))
5185       && !section_allows_mips16_refs_p (input_section))
5186     {
5187       /* This is a 32- or 64-bit call to a 16-bit function.  We should
5188          have already noticed that we were going to need the
5189          stub.  */
5190       if (local_p)
5191         {
5192           sec = elf_tdata (input_bfd)->local_stubs[r_symndx];
5193           value = 0;
5194         }
5195       else
5196         {
5197           BFD_ASSERT (h->need_fn_stub);
5198           if (h->la25_stub)
5199             {
5200               /* If a LA25 header for the stub itself exists, point to the
5201                  prepended LUI/ADDIU sequence.  */
5202               sec = h->la25_stub->stub_section;
5203               value = h->la25_stub->offset;
5204             }
5205           else
5206             {
5207               sec = h->fn_stub;
5208               value = 0;
5209             }
5210         }
5211
5212       symbol = sec->output_section->vma + sec->output_offset + value;
5213       /* The target is 16-bit, but the stub isn't.  */
5214       target_is_16_bit_code_p = FALSE;
5215     }
5216   /* If this is a 16-bit call to a 32- or 64-bit function with a stub, we
5217      need to redirect the call to the stub.  Note that we specifically
5218      exclude R_MIPS16_CALL16 from this behavior; indirect calls should
5219      use an indirect stub instead.  */
5220   else if (r_type == R_MIPS16_26 && !info->relocatable
5221            && ((h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL))
5222                || (local_p
5223                    && elf_tdata (input_bfd)->local_call_stubs != NULL
5224                    && elf_tdata (input_bfd)->local_call_stubs[r_symndx] != NULL))
5225            && !target_is_16_bit_code_p)
5226     {
5227       if (local_p)
5228         sec = elf_tdata (input_bfd)->local_call_stubs[r_symndx];
5229       else
5230         {
5231           /* If both call_stub and call_fp_stub are defined, we can figure
5232              out which one to use by checking which one appears in the input
5233              file.  */
5234           if (h->call_stub != NULL && h->call_fp_stub != NULL)
5235             {
5236               asection *o;
5237
5238               sec = NULL;
5239               for (o = input_bfd->sections; o != NULL; o = o->next)
5240                 {
5241                   if (CALL_FP_STUB_P (bfd_get_section_name (input_bfd, o)))
5242                     {
5243                       sec = h->call_fp_stub;
5244                       break;
5245                     }
5246                 }
5247               if (sec == NULL)
5248                 sec = h->call_stub;
5249             }
5250           else if (h->call_stub != NULL)
5251             sec = h->call_stub;
5252           else
5253             sec = h->call_fp_stub;
5254         }
5255
5256       BFD_ASSERT (sec->size > 0);
5257       symbol = sec->output_section->vma + sec->output_offset;
5258     }
5259   /* If this is a direct call to a PIC function, redirect to the
5260      non-PIC stub.  */
5261   else if (h != NULL && h->la25_stub
5262            && mips_elf_relocation_needs_la25_stub (input_bfd, r_type,
5263                                                    target_is_16_bit_code_p))
5264     symbol = (h->la25_stub->stub_section->output_section->vma
5265               + h->la25_stub->stub_section->output_offset
5266               + h->la25_stub->offset);
5267
5268   /* Make sure MIPS16 and microMIPS are not used together.  */
5269   if ((r_type == R_MIPS16_26 && target_is_micromips_code_p)
5270       || (micromips_branch_reloc_p (r_type) && target_is_16_bit_code_p))
5271    {
5272       (*_bfd_error_handler)
5273         (_("MIPS16 and microMIPS functions cannot call each other"));
5274       return bfd_reloc_notsupported;
5275    }
5276
5277   /* Calls from 16-bit code to 32-bit code and vice versa require the
5278      mode change.  However, we can ignore calls to undefined weak symbols,
5279      which should never be executed at runtime.  This exception is important
5280      because the assembly writer may have "known" that any definition of the
5281      symbol would be 16-bit code, and that direct jumps were therefore
5282      acceptable.  */
5283   *cross_mode_jump_p = (!info->relocatable
5284                         && !(h && h->root.root.type == bfd_link_hash_undefweak)
5285                         && ((r_type == R_MIPS16_26 && !target_is_16_bit_code_p)
5286                             || (r_type == R_MICROMIPS_26_S1
5287                                 && !target_is_micromips_code_p)
5288                             || ((r_type == R_MIPS_26 || r_type == R_MIPS_JALR)
5289                                 && (target_is_16_bit_code_p
5290                                     || target_is_micromips_code_p))));
5291
5292   local_p = (h == NULL
5293              || (h->got_only_for_calls
5294                  ? SYMBOL_CALLS_LOCAL (info, &h->root)
5295                  : SYMBOL_REFERENCES_LOCAL (info, &h->root)));
5296
5297   gp0 = _bfd_get_gp_value (input_bfd);
5298   gp = _bfd_get_gp_value (abfd);
5299   if (htab->got_info)
5300     gp += mips_elf_adjust_gp (abfd, htab->got_info, input_bfd);
5301
5302   if (gnu_local_gp_p)
5303     symbol = gp;
5304
5305   /* Global R_MIPS_GOT_PAGE/R_MICROMIPS_GOT_PAGE relocations are equivalent
5306      to R_MIPS_GOT_DISP/R_MICROMIPS_GOT_DISP.  The addend is applied by the
5307      corresponding R_MIPS_GOT_OFST/R_MICROMIPS_GOT_OFST.  */
5308   if (got_page_reloc_p (r_type) && !local_p)
5309     {
5310       r_type = (micromips_reloc_p (r_type)
5311                 ? R_MICROMIPS_GOT_DISP : R_MIPS_GOT_DISP);
5312       addend = 0;
5313     }
5314
5315   /* If we haven't already determined the GOT offset, and we're going
5316      to need it, get it now.  */
5317   switch (r_type)
5318     {
5319     case R_MIPS16_CALL16:
5320     case R_MIPS16_GOT16:
5321     case R_MIPS_CALL16:
5322     case R_MIPS_GOT16:
5323     case R_MIPS_GOT_DISP:
5324     case R_MIPS_GOT_HI16:
5325     case R_MIPS_CALL_HI16:
5326     case R_MIPS_GOT_LO16:
5327     case R_MIPS_CALL_LO16:
5328     case R_MICROMIPS_CALL16:
5329     case R_MICROMIPS_GOT16:
5330     case R_MICROMIPS_GOT_DISP:
5331     case R_MICROMIPS_GOT_HI16:
5332     case R_MICROMIPS_CALL_HI16:
5333     case R_MICROMIPS_GOT_LO16:
5334     case R_MICROMIPS_CALL_LO16:
5335     case R_MIPS_TLS_GD:
5336     case R_MIPS_TLS_GOTTPREL:
5337     case R_MIPS_TLS_LDM:
5338     case R_MIPS16_TLS_GD:
5339     case R_MIPS16_TLS_GOTTPREL:
5340     case R_MIPS16_TLS_LDM:
5341     case R_MICROMIPS_TLS_GD:
5342     case R_MICROMIPS_TLS_GOTTPREL:
5343     case R_MICROMIPS_TLS_LDM:
5344       /* Find the index into the GOT where this value is located.  */
5345       if (tls_ldm_reloc_p (r_type))
5346         {
5347           g = mips_elf_local_got_index (abfd, input_bfd, info,
5348                                         0, 0, NULL, r_type);
5349           if (g == MINUS_ONE)
5350             return bfd_reloc_outofrange;
5351         }
5352       else if (!local_p)
5353         {
5354           /* On VxWorks, CALL relocations should refer to the .got.plt
5355              entry, which is initialized to point at the PLT stub.  */
5356           if (htab->is_vxworks
5357               && (call_hi16_reloc_p (r_type)
5358                   || call_lo16_reloc_p (r_type)
5359                   || call16_reloc_p (r_type)))
5360             {
5361               BFD_ASSERT (addend == 0);
5362               BFD_ASSERT (h->root.needs_plt);
5363               g = mips_elf_gotplt_index (info, &h->root);
5364             }
5365           else
5366             {
5367               BFD_ASSERT (addend == 0);
5368               g = mips_elf_global_got_index (abfd, info, input_bfd,
5369                                              &h->root, r_type);
5370               if (!TLS_RELOC_P (r_type)
5371                   && !elf_hash_table (info)->dynamic_sections_created)
5372                 /* This is a static link.  We must initialize the GOT entry.  */
5373                 MIPS_ELF_PUT_WORD (dynobj, symbol, htab->sgot->contents + g);
5374             }
5375         }
5376       else if (!htab->is_vxworks
5377                && (call16_reloc_p (r_type) || got16_reloc_p (r_type)))
5378         /* The calculation below does not involve "g".  */
5379         break;
5380       else
5381         {
5382           g = mips_elf_local_got_index (abfd, input_bfd, info,
5383                                         symbol + addend, r_symndx, h, r_type);
5384           if (g == MINUS_ONE)
5385             return bfd_reloc_outofrange;
5386         }
5387
5388       /* Convert GOT indices to actual offsets.  */
5389       g = mips_elf_got_offset_from_index (info, abfd, input_bfd, g);
5390       break;
5391     }
5392
5393   /* Relocations against the VxWorks __GOTT_BASE__ and __GOTT_INDEX__
5394      symbols are resolved by the loader.  Add them to .rela.dyn.  */
5395   if (h != NULL && is_gott_symbol (info, &h->root))
5396     {
5397       Elf_Internal_Rela outrel;
5398       bfd_byte *loc;
5399       asection *s;
5400
5401       s = mips_elf_rel_dyn_section (info, FALSE);
5402       loc = s->contents + s->reloc_count++ * sizeof (Elf32_External_Rela);
5403
5404       outrel.r_offset = (input_section->output_section->vma
5405                          + input_section->output_offset
5406                          + relocation->r_offset);
5407       outrel.r_info = ELF32_R_INFO (h->root.dynindx, r_type);
5408       outrel.r_addend = addend;
5409       bfd_elf32_swap_reloca_out (abfd, &outrel, loc);
5410
5411       /* If we've written this relocation for a readonly section,
5412          we need to set DF_TEXTREL again, so that we do not delete the
5413          DT_TEXTREL tag.  */
5414       if (MIPS_ELF_READONLY_SECTION (input_section))
5415         info->flags |= DF_TEXTREL;
5416
5417       *valuep = 0;
5418       return bfd_reloc_ok;
5419     }
5420
5421   /* Figure out what kind of relocation is being performed.  */
5422   switch (r_type)
5423     {
5424     case R_MIPS_NONE:
5425       return bfd_reloc_continue;
5426
5427     case R_MIPS_16:
5428       value = symbol + _bfd_mips_elf_sign_extend (addend, 16);
5429       overflowed_p = mips_elf_overflow_p (value, 16);
5430       break;
5431
5432     case R_MIPS_32:
5433     case R_MIPS_REL32:
5434     case R_MIPS_64:
5435       if ((info->shared
5436            || (htab->root.dynamic_sections_created
5437                && h != NULL
5438                && h->root.def_dynamic
5439                && !h->root.def_regular
5440                && !h->has_static_relocs))
5441           && r_symndx != STN_UNDEF
5442           && (h == NULL
5443               || h->root.root.type != bfd_link_hash_undefweak
5444               || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
5445           && (input_section->flags & SEC_ALLOC) != 0)
5446         {
5447           /* If we're creating a shared library, then we can't know
5448              where the symbol will end up.  So, we create a relocation
5449              record in the output, and leave the job up to the dynamic
5450              linker.  We must do the same for executable references to
5451              shared library symbols, unless we've decided to use copy
5452              relocs or PLTs instead.  */
5453           value = addend;
5454           if (!mips_elf_create_dynamic_relocation (abfd,
5455                                                    info,
5456                                                    relocation,
5457                                                    h,
5458                                                    sec,
5459                                                    symbol,
5460                                                    &value,
5461                                                    input_section))
5462             return bfd_reloc_undefined;
5463         }
5464       else
5465         {
5466           if (r_type != R_MIPS_REL32)
5467             value = symbol + addend;
5468           else
5469             value = addend;
5470         }
5471       value &= howto->dst_mask;
5472       break;
5473
5474     case R_MIPS_PC32:
5475       value = symbol + addend - p;
5476       value &= howto->dst_mask;
5477       break;
5478
5479     case R_MIPS16_26:
5480       /* The calculation for R_MIPS16_26 is just the same as for an
5481          R_MIPS_26.  It's only the storage of the relocated field into
5482          the output file that's different.  That's handled in
5483          mips_elf_perform_relocation.  So, we just fall through to the
5484          R_MIPS_26 case here.  */
5485     case R_MIPS_26:
5486     case R_MICROMIPS_26_S1:
5487       {
5488         unsigned int shift;
5489
5490         /* Make sure the target of JALX is word-aligned.  Bit 0 must be
5491            the correct ISA mode selector and bit 1 must be 0.  */
5492         if (*cross_mode_jump_p && (symbol & 3) != (r_type == R_MIPS_26))
5493           return bfd_reloc_outofrange;
5494
5495         /* Shift is 2, unusually, for microMIPS JALX.  */
5496         shift = (!*cross_mode_jump_p && r_type == R_MICROMIPS_26_S1) ? 1 : 2;
5497
5498         if (was_local_p)
5499           value = addend | ((p + 4) & (0xfc000000 << shift));
5500         else
5501           value = _bfd_mips_elf_sign_extend (addend, 26 + shift);
5502         value = (value + symbol) >> shift;
5503         if (!was_local_p && h->root.root.type != bfd_link_hash_undefweak)
5504           overflowed_p = (value >> 26) != ((p + 4) >> (26 + shift));
5505         value &= howto->dst_mask;
5506       }
5507       break;
5508
5509     case R_MIPS_TLS_DTPREL_HI16:
5510     case R_MIPS16_TLS_DTPREL_HI16:
5511     case R_MICROMIPS_TLS_DTPREL_HI16:
5512       value = (mips_elf_high (addend + symbol - dtprel_base (info))
5513                & howto->dst_mask);
5514       break;
5515
5516     case R_MIPS_TLS_DTPREL_LO16:
5517     case R_MIPS_TLS_DTPREL32:
5518     case R_MIPS_TLS_DTPREL64:
5519     case R_MIPS16_TLS_DTPREL_LO16:
5520     case R_MICROMIPS_TLS_DTPREL_LO16:
5521       value = (symbol + addend - dtprel_base (info)) & howto->dst_mask;
5522       break;
5523
5524     case R_MIPS_TLS_TPREL_HI16:
5525     case R_MIPS16_TLS_TPREL_HI16:
5526     case R_MICROMIPS_TLS_TPREL_HI16:
5527       value = (mips_elf_high (addend + symbol - tprel_base (info))
5528                & howto->dst_mask);
5529       break;
5530
5531     case R_MIPS_TLS_TPREL_LO16:
5532     case R_MIPS_TLS_TPREL32:
5533     case R_MIPS_TLS_TPREL64:
5534     case R_MIPS16_TLS_TPREL_LO16:
5535     case R_MICROMIPS_TLS_TPREL_LO16:
5536       value = (symbol + addend - tprel_base (info)) & howto->dst_mask;
5537       break;
5538
5539     case R_MIPS_HI16:
5540     case R_MIPS16_HI16:
5541     case R_MICROMIPS_HI16:
5542       if (!gp_disp_p)
5543         {
5544           value = mips_elf_high (addend + symbol);
5545           value &= howto->dst_mask;
5546         }
5547       else
5548         {
5549           /* For MIPS16 ABI code we generate this sequence
5550                 0: li      $v0,%hi(_gp_disp)
5551                 4: addiupc $v1,%lo(_gp_disp)
5552                 8: sll     $v0,16
5553                12: addu    $v0,$v1
5554                14: move    $gp,$v0
5555              So the offsets of hi and lo relocs are the same, but the
5556              base $pc is that used by the ADDIUPC instruction at $t9 + 4.
5557              ADDIUPC clears the low two bits of the instruction address,
5558              so the base is ($t9 + 4) & ~3.  */
5559           if (r_type == R_MIPS16_HI16)
5560             value = mips_elf_high (addend + gp - ((p + 4) & ~(bfd_vma) 0x3));
5561           /* The microMIPS .cpload sequence uses the same assembly
5562              instructions as the traditional psABI version, but the
5563              incoming $t9 has the low bit set.  */
5564           else if (r_type == R_MICROMIPS_HI16)
5565             value = mips_elf_high (addend + gp - p - 1);
5566           else
5567             value = mips_elf_high (addend + gp - p);
5568           overflowed_p = mips_elf_overflow_p (value, 16);
5569         }
5570       break;
5571
5572     case R_MIPS_LO16:
5573     case R_MIPS16_LO16:
5574     case R_MICROMIPS_LO16:
5575     case R_MICROMIPS_HI0_LO16:
5576       if (!gp_disp_p)
5577         value = (symbol + addend) & howto->dst_mask;
5578       else
5579         {
5580           /* See the comment for R_MIPS16_HI16 above for the reason
5581              for this conditional.  */
5582           if (r_type == R_MIPS16_LO16)
5583             value = addend + gp - (p & ~(bfd_vma) 0x3);
5584           else if (r_type == R_MICROMIPS_LO16
5585                    || r_type == R_MICROMIPS_HI0_LO16)
5586             value = addend + gp - p + 3;
5587           else
5588             value = addend + gp - p + 4;
5589           /* The MIPS ABI requires checking the R_MIPS_LO16 relocation
5590              for overflow.  But, on, say, IRIX5, relocations against
5591              _gp_disp are normally generated from the .cpload
5592              pseudo-op.  It generates code that normally looks like
5593              this:
5594
5595                lui    $gp,%hi(_gp_disp)
5596                addiu  $gp,$gp,%lo(_gp_disp)
5597                addu   $gp,$gp,$t9
5598
5599              Here $t9 holds the address of the function being called,
5600              as required by the MIPS ELF ABI.  The R_MIPS_LO16
5601              relocation can easily overflow in this situation, but the
5602              R_MIPS_HI16 relocation will handle the overflow.
5603              Therefore, we consider this a bug in the MIPS ABI, and do
5604              not check for overflow here.  */
5605         }
5606       break;
5607
5608     case R_MIPS_LITERAL:
5609     case R_MICROMIPS_LITERAL:
5610       /* Because we don't merge literal sections, we can handle this
5611          just like R_MIPS_GPREL16.  In the long run, we should merge
5612          shared literals, and then we will need to additional work
5613          here.  */
5614
5615       /* Fall through.  */
5616
5617     case R_MIPS16_GPREL:
5618       /* The R_MIPS16_GPREL performs the same calculation as
5619          R_MIPS_GPREL16, but stores the relocated bits in a different
5620          order.  We don't need to do anything special here; the
5621          differences are handled in mips_elf_perform_relocation.  */
5622     case R_MIPS_GPREL16:
5623     case R_MICROMIPS_GPREL7_S2:
5624     case R_MICROMIPS_GPREL16:
5625       /* Only sign-extend the addend if it was extracted from the
5626          instruction.  If the addend was separate, leave it alone,
5627          otherwise we may lose significant bits.  */
5628       if (howto->partial_inplace)
5629         addend = _bfd_mips_elf_sign_extend (addend, 16);
5630       value = symbol + addend - gp;
5631       /* If the symbol was local, any earlier relocatable links will
5632          have adjusted its addend with the gp offset, so compensate
5633          for that now.  Don't do it for symbols forced local in this
5634          link, though, since they won't have had the gp offset applied
5635          to them before.  */
5636       if (was_local_p)
5637         value += gp0;
5638       overflowed_p = mips_elf_overflow_p (value, 16);
5639       break;
5640
5641     case R_MIPS16_GOT16:
5642     case R_MIPS16_CALL16:
5643     case R_MIPS_GOT16:
5644     case R_MIPS_CALL16:
5645     case R_MICROMIPS_GOT16:
5646     case R_MICROMIPS_CALL16:
5647       /* VxWorks does not have separate local and global semantics for
5648          R_MIPS*_GOT16; every relocation evaluates to "G".  */
5649       if (!htab->is_vxworks && local_p)
5650         {
5651           value = mips_elf_got16_entry (abfd, input_bfd, info,
5652                                         symbol + addend, !was_local_p);
5653           if (value == MINUS_ONE)
5654             return bfd_reloc_outofrange;
5655           value
5656             = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5657           overflowed_p = mips_elf_overflow_p (value, 16);
5658           break;
5659         }
5660
5661       /* Fall through.  */
5662
5663     case R_MIPS_TLS_GD:
5664     case R_MIPS_TLS_GOTTPREL:
5665     case R_MIPS_TLS_LDM:
5666     case R_MIPS_GOT_DISP:
5667     case R_MIPS16_TLS_GD:
5668     case R_MIPS16_TLS_GOTTPREL:
5669     case R_MIPS16_TLS_LDM:
5670     case R_MICROMIPS_TLS_GD:
5671     case R_MICROMIPS_TLS_GOTTPREL:
5672     case R_MICROMIPS_TLS_LDM:
5673     case R_MICROMIPS_GOT_DISP:
5674       value = g;
5675       overflowed_p = mips_elf_overflow_p (value, 16);
5676       break;
5677
5678     case R_MIPS_GPREL32:
5679       value = (addend + symbol + gp0 - gp);
5680       if (!save_addend)
5681         value &= howto->dst_mask;
5682       break;
5683
5684     case R_MIPS_PC16:
5685     case R_MIPS_GNU_REL16_S2:
5686       value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p;
5687       overflowed_p = mips_elf_overflow_p (value, 18);
5688       value >>= howto->rightshift;
5689       value &= howto->dst_mask;
5690       break;
5691
5692     case R_MICROMIPS_PC7_S1:
5693       value = symbol + _bfd_mips_elf_sign_extend (addend, 8) - p;
5694       overflowed_p = mips_elf_overflow_p (value, 8);
5695       value >>= howto->rightshift;
5696       value &= howto->dst_mask;
5697       break;
5698
5699     case R_MICROMIPS_PC10_S1:
5700       value = symbol + _bfd_mips_elf_sign_extend (addend, 11) - p;
5701       overflowed_p = mips_elf_overflow_p (value, 11);
5702       value >>= howto->rightshift;
5703       value &= howto->dst_mask;
5704       break;
5705
5706     case R_MICROMIPS_PC16_S1:
5707       value = symbol + _bfd_mips_elf_sign_extend (addend, 17) - p;
5708       overflowed_p = mips_elf_overflow_p (value, 17);
5709       value >>= howto->rightshift;
5710       value &= howto->dst_mask;
5711       break;
5712
5713     case R_MICROMIPS_PC23_S2:
5714       value = symbol + _bfd_mips_elf_sign_extend (addend, 25) - ((p | 3) ^ 3);
5715       overflowed_p = mips_elf_overflow_p (value, 25);
5716       value >>= howto->rightshift;
5717       value &= howto->dst_mask;
5718       break;
5719
5720     case R_MIPS_GOT_HI16:
5721     case R_MIPS_CALL_HI16:
5722     case R_MICROMIPS_GOT_HI16:
5723     case R_MICROMIPS_CALL_HI16:
5724       /* We're allowed to handle these two relocations identically.
5725          The dynamic linker is allowed to handle the CALL relocations
5726          differently by creating a lazy evaluation stub.  */
5727       value = g;
5728       value = mips_elf_high (value);
5729       value &= howto->dst_mask;
5730       break;
5731
5732     case R_MIPS_GOT_LO16:
5733     case R_MIPS_CALL_LO16:
5734     case R_MICROMIPS_GOT_LO16:
5735     case R_MICROMIPS_CALL_LO16:
5736       value = g & howto->dst_mask;
5737       break;
5738
5739     case R_MIPS_GOT_PAGE:
5740     case R_MICROMIPS_GOT_PAGE:
5741       value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL);
5742       if (value == MINUS_ONE)
5743         return bfd_reloc_outofrange;
5744       value = mips_elf_got_offset_from_index (info, abfd, input_bfd, value);
5745       overflowed_p = mips_elf_overflow_p (value, 16);
5746       break;
5747
5748     case R_MIPS_GOT_OFST:
5749     case R_MICROMIPS_GOT_OFST:
5750       if (local_p)
5751         mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value);
5752       else
5753         value = addend;
5754       overflowed_p = mips_elf_overflow_p (value, 16);
5755       break;
5756
5757     case R_MIPS_SUB:
5758     case R_MICROMIPS_SUB:
5759       value = symbol - addend;
5760       value &= howto->dst_mask;
5761       break;
5762
5763     case R_MIPS_HIGHER:
5764     case R_MICROMIPS_HIGHER:
5765       value = mips_elf_higher (addend + symbol);
5766       value &= howto->dst_mask;
5767       break;
5768
5769     case R_MIPS_HIGHEST:
5770     case R_MICROMIPS_HIGHEST:
5771       value = mips_elf_highest (addend + symbol);
5772       value &= howto->dst_mask;
5773       break;
5774
5775     case R_MIPS_SCN_DISP:
5776     case R_MICROMIPS_SCN_DISP:
5777       value = symbol + addend - sec->output_offset;
5778       value &= howto->dst_mask;
5779       break;
5780
5781     case R_MIPS_JALR:
5782     case R_MICROMIPS_JALR:
5783       /* This relocation is only a hint.  In some cases, we optimize
5784          it into a bal instruction.  But we don't try to optimize
5785          when the symbol does not resolve locally.  */
5786       if (h != NULL && !SYMBOL_CALLS_LOCAL (info, &h->root))
5787         return bfd_reloc_continue;
5788       value = symbol + addend;
5789       break;
5790
5791     case R_MIPS_PJUMP:
5792     case R_MIPS_GNU_VTINHERIT:
5793     case R_MIPS_GNU_VTENTRY:
5794       /* We don't do anything with these at present.  */
5795       return bfd_reloc_continue;
5796
5797     default:
5798       /* An unrecognized relocation type.  */
5799       return bfd_reloc_notsupported;
5800     }
5801
5802   /* Store the VALUE for our caller.  */
5803   *valuep = value;
5804   return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok;
5805 }
5806
5807 /* Obtain the field relocated by RELOCATION.  */
5808
5809 static bfd_vma
5810 mips_elf_obtain_contents (reloc_howto_type *howto,
5811                           const Elf_Internal_Rela *relocation,
5812                           bfd *input_bfd, bfd_byte *contents)
5813 {
5814   bfd_vma x;
5815   bfd_byte *location = contents + relocation->r_offset;
5816
5817   /* Obtain the bytes.  */
5818   x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location);
5819
5820   return x;
5821 }
5822
5823 /* It has been determined that the result of the RELOCATION is the
5824    VALUE.  Use HOWTO to place VALUE into the output file at the
5825    appropriate position.  The SECTION is the section to which the
5826    relocation applies.
5827    CROSS_MODE_JUMP_P is true if the relocation field
5828    is a MIPS16 or microMIPS jump to standard MIPS code, or vice versa.
5829
5830    Returns FALSE if anything goes wrong.  */
5831
5832 static bfd_boolean
5833 mips_elf_perform_relocation (struct bfd_link_info *info,
5834                              reloc_howto_type *howto,
5835                              const Elf_Internal_Rela *relocation,
5836                              bfd_vma value, bfd *input_bfd,
5837                              asection *input_section, bfd_byte *contents,
5838                              bfd_boolean cross_mode_jump_p)
5839 {
5840   bfd_vma x;
5841   bfd_byte *location;
5842   int r_type = ELF_R_TYPE (input_bfd, relocation->r_info);
5843
5844   /* Figure out where the relocation is occurring.  */
5845   location = contents + relocation->r_offset;
5846
5847   _bfd_mips_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location);
5848
5849   /* Obtain the current value.  */
5850   x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents);
5851
5852   /* Clear the field we are setting.  */
5853   x &= ~howto->dst_mask;
5854
5855   /* Set the field.  */
5856   x |= (value & howto->dst_mask);
5857
5858   /* If required, turn JAL into JALX.  */
5859   if (cross_mode_jump_p && jal_reloc_p (r_type))
5860     {
5861       bfd_boolean ok;
5862       bfd_vma opcode = x >> 26;
5863       bfd_vma jalx_opcode;
5864
5865       /* Check to see if the opcode is already JAL or JALX.  */
5866       if (r_type == R_MIPS16_26)
5867         {
5868           ok = ((opcode == 0x6) || (opcode == 0x7));
5869           jalx_opcode = 0x7;
5870         }
5871       else if (r_type == R_MICROMIPS_26_S1)
5872         {
5873           ok = ((opcode == 0x3d) || (opcode == 0x3c));
5874           jalx_opcode = 0x3c;
5875         }
5876       else
5877         {
5878           ok = ((opcode == 0x3) || (opcode == 0x1d));
5879           jalx_opcode = 0x1d;
5880         }
5881
5882       /* If the opcode is not JAL or JALX, there's a problem.  We cannot
5883          convert J or JALS to JALX.  */
5884       if (!ok)
5885         {
5886           (*_bfd_error_handler)
5887             (_("%B: %A+0x%lx: Unsupported jump between ISA modes; consider recompiling with interlinking enabled."),
5888              input_bfd,
5889              input_section,
5890              (unsigned long) relocation->r_offset);
5891           bfd_set_error (bfd_error_bad_value);
5892           return FALSE;
5893         }
5894
5895       /* Make this the JALX opcode.  */
5896       x = (x & ~(0x3f << 26)) | (jalx_opcode << 26);
5897     }
5898
5899   /* Try converting JAL to BAL and J(AL)R to B(AL), if the target is in
5900      range.  */
5901   if (!info->relocatable
5902       && !cross_mode_jump_p
5903       && ((JAL_TO_BAL_P (input_bfd)
5904            && r_type == R_MIPS_26
5905            && (x >> 26) == 0x3)         /* jal addr */
5906           || (JALR_TO_BAL_P (input_bfd)
5907               && r_type == R_MIPS_JALR
5908               && x == 0x0320f809)       /* jalr t9 */
5909           || (JR_TO_B_P (input_bfd)
5910               && r_type == R_MIPS_JALR
5911               && x == 0x03200008)))     /* jr t9 */
5912     {
5913       bfd_vma addr;
5914       bfd_vma dest;
5915       bfd_signed_vma off;
5916
5917       addr = (input_section->output_section->vma
5918               + input_section->output_offset
5919               + relocation->r_offset
5920               + 4);
5921       if (r_type == R_MIPS_26)
5922         dest = (value << 2) | ((addr >> 28) << 28);
5923       else
5924         dest = value;
5925       off = dest - addr;
5926       if (off <= 0x1ffff && off >= -0x20000)
5927         {
5928           if (x == 0x03200008)  /* jr t9 */
5929             x = 0x10000000 | (((bfd_vma) off >> 2) & 0xffff);   /* b addr */
5930           else
5931             x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff);   /* bal addr */
5932         }
5933     }
5934
5935   /* Put the value into the output.  */
5936   bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location);
5937
5938   _bfd_mips_elf_reloc_shuffle (input_bfd, r_type, !info->relocatable,
5939                                location);
5940
5941   return TRUE;
5942 }
5943 \f
5944 /* Create a rel.dyn relocation for the dynamic linker to resolve.  REL
5945    is the original relocation, which is now being transformed into a
5946    dynamic relocation.  The ADDENDP is adjusted if necessary; the
5947    caller should store the result in place of the original addend.  */
5948
5949 static bfd_boolean
5950 mips_elf_create_dynamic_relocation (bfd *output_bfd,
5951                                     struct bfd_link_info *info,
5952                                     const Elf_Internal_Rela *rel,
5953                                     struct mips_elf_link_hash_entry *h,
5954                                     asection *sec, bfd_vma symbol,
5955                                     bfd_vma *addendp, asection *input_section)
5956 {
5957   Elf_Internal_Rela outrel[3];
5958   asection *sreloc;
5959   bfd *dynobj;
5960   int r_type;
5961   long indx;
5962   bfd_boolean defined_p;
5963   struct mips_elf_link_hash_table *htab;
5964
5965   htab = mips_elf_hash_table (info);
5966   BFD_ASSERT (htab != NULL);
5967
5968   r_type = ELF_R_TYPE (output_bfd, rel->r_info);
5969   dynobj = elf_hash_table (info)->dynobj;
5970   sreloc = mips_elf_rel_dyn_section (info, FALSE);
5971   BFD_ASSERT (sreloc != NULL);
5972   BFD_ASSERT (sreloc->contents != NULL);
5973   BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd)
5974               < sreloc->size);
5975
5976   outrel[0].r_offset =
5977     _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
5978   if (ABI_64_P (output_bfd))
5979     {
5980       outrel[1].r_offset =
5981         _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
5982       outrel[2].r_offset =
5983         _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
5984     }
5985
5986   if (outrel[0].r_offset == MINUS_ONE)
5987     /* The relocation field has been deleted.  */
5988     return TRUE;
5989
5990   if (outrel[0].r_offset == MINUS_TWO)
5991     {
5992       /* The relocation field has been converted into a relative value of
5993          some sort.  Functions like _bfd_elf_write_section_eh_frame expect
5994          the field to be fully relocated, so add in the symbol's value.  */
5995       *addendp += symbol;
5996       return TRUE;
5997     }
5998
5999   /* We must now calculate the dynamic symbol table index to use
6000      in the relocation.  */
6001   if (h != NULL && ! SYMBOL_REFERENCES_LOCAL (info, &h->root))
6002     {
6003       BFD_ASSERT (htab->is_vxworks || h->global_got_area != GGA_NONE);
6004       indx = h->root.dynindx;
6005       if (SGI_COMPAT (output_bfd))
6006         defined_p = h->root.def_regular;
6007       else
6008         /* ??? glibc's ld.so just adds the final GOT entry to the
6009            relocation field.  It therefore treats relocs against
6010            defined symbols in the same way as relocs against
6011            undefined symbols.  */
6012         defined_p = FALSE;
6013     }
6014   else
6015     {
6016       if (sec != NULL && bfd_is_abs_section (sec))
6017         indx = 0;
6018       else if (sec == NULL || sec->owner == NULL)
6019         {
6020           bfd_set_error (bfd_error_bad_value);
6021           return FALSE;
6022         }
6023       else
6024         {
6025           indx = elf_section_data (sec->output_section)->dynindx;
6026           if (indx == 0)
6027             {
6028               asection *osec = htab->root.text_index_section;
6029               indx = elf_section_data (osec)->dynindx;
6030             }
6031           if (indx == 0)
6032             abort ();
6033         }
6034
6035       /* Instead of generating a relocation using the section
6036          symbol, we may as well make it a fully relative
6037          relocation.  We want to avoid generating relocations to
6038          local symbols because we used to generate them
6039          incorrectly, without adding the original symbol value,
6040          which is mandated by the ABI for section symbols.  In
6041          order to give dynamic loaders and applications time to
6042          phase out the incorrect use, we refrain from emitting
6043          section-relative relocations.  It's not like they're
6044          useful, after all.  This should be a bit more efficient
6045          as well.  */
6046       /* ??? Although this behavior is compatible with glibc's ld.so,
6047          the ABI says that relocations against STN_UNDEF should have
6048          a symbol value of 0.  Irix rld honors this, so relocations
6049          against STN_UNDEF have no effect.  */
6050       if (!SGI_COMPAT (output_bfd))
6051         indx = 0;
6052       defined_p = TRUE;
6053     }
6054
6055   /* If the relocation was previously an absolute relocation and
6056      this symbol will not be referred to by the relocation, we must
6057      adjust it by the value we give it in the dynamic symbol table.
6058      Otherwise leave the job up to the dynamic linker.  */
6059   if (defined_p && r_type != R_MIPS_REL32)
6060     *addendp += symbol;
6061
6062   if (htab->is_vxworks)
6063     /* VxWorks uses non-relative relocations for this.  */
6064     outrel[0].r_info = ELF32_R_INFO (indx, R_MIPS_32);
6065   else
6066     /* The relocation is always an REL32 relocation because we don't
6067        know where the shared library will wind up at load-time.  */
6068     outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx,
6069                                    R_MIPS_REL32);
6070
6071   /* For strict adherence to the ABI specification, we should
6072      generate a R_MIPS_64 relocation record by itself before the
6073      _REL32/_64 record as well, such that the addend is read in as
6074      a 64-bit value (REL32 is a 32-bit relocation, after all).
6075      However, since none of the existing ELF64 MIPS dynamic
6076      loaders seems to care, we don't waste space with these
6077      artificial relocations.  If this turns out to not be true,
6078      mips_elf_allocate_dynamic_relocation() should be tweaked so
6079      as to make room for a pair of dynamic relocations per
6080      invocation if ABI_64_P, and here we should generate an
6081      additional relocation record with R_MIPS_64 by itself for a
6082      NULL symbol before this relocation record.  */
6083   outrel[1].r_info = ELF_R_INFO (output_bfd, 0,
6084                                  ABI_64_P (output_bfd)
6085                                  ? R_MIPS_64
6086                                  : R_MIPS_NONE);
6087   outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE);
6088
6089   /* Adjust the output offset of the relocation to reference the
6090      correct location in the output file.  */
6091   outrel[0].r_offset += (input_section->output_section->vma
6092                          + input_section->output_offset);
6093   outrel[1].r_offset += (input_section->output_section->vma
6094                          + input_section->output_offset);
6095   outrel[2].r_offset += (input_section->output_section->vma
6096                          + input_section->output_offset);
6097
6098   /* Put the relocation back out.  We have to use the special
6099      relocation outputter in the 64-bit case since the 64-bit
6100      relocation format is non-standard.  */
6101   if (ABI_64_P (output_bfd))
6102     {
6103       (*get_elf_backend_data (output_bfd)->s->swap_reloc_out)
6104         (output_bfd, &outrel[0],
6105          (sreloc->contents
6106           + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel)));
6107     }
6108   else if (htab->is_vxworks)
6109     {
6110       /* VxWorks uses RELA rather than REL dynamic relocations.  */
6111       outrel[0].r_addend = *addendp;
6112       bfd_elf32_swap_reloca_out
6113         (output_bfd, &outrel[0],
6114          (sreloc->contents
6115           + sreloc->reloc_count * sizeof (Elf32_External_Rela)));
6116     }
6117   else
6118     bfd_elf32_swap_reloc_out
6119       (output_bfd, &outrel[0],
6120        (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
6121
6122   /* We've now added another relocation.  */
6123   ++sreloc->reloc_count;
6124
6125   /* Make sure the output section is writable.  The dynamic linker
6126      will be writing to it.  */
6127   elf_section_data (input_section->output_section)->this_hdr.sh_flags
6128     |= SHF_WRITE;
6129
6130   /* On IRIX5, make an entry of compact relocation info.  */
6131   if (IRIX_COMPAT (output_bfd) == ict_irix5)
6132     {
6133       asection *scpt = bfd_get_linker_section (dynobj, ".compact_rel");
6134       bfd_byte *cr;
6135
6136       if (scpt)
6137         {
6138           Elf32_crinfo cptrel;
6139
6140           mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG);
6141           cptrel.vaddr = (rel->r_offset
6142                           + input_section->output_section->vma
6143                           + input_section->output_offset);
6144           if (r_type == R_MIPS_REL32)
6145             mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32);
6146           else
6147             mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD);
6148           mips_elf_set_cr_dist2to (cptrel, 0);
6149           cptrel.konst = *addendp;
6150
6151           cr = (scpt->contents
6152                 + sizeof (Elf32_External_compact_rel));
6153           mips_elf_set_cr_relvaddr (cptrel, 0);
6154           bfd_elf32_swap_crinfo_out (output_bfd, &cptrel,
6155                                      ((Elf32_External_crinfo *) cr
6156                                       + scpt->reloc_count));
6157           ++scpt->reloc_count;
6158         }
6159     }
6160
6161   /* If we've written this relocation for a readonly section,
6162      we need to set DF_TEXTREL again, so that we do not delete the
6163      DT_TEXTREL tag.  */
6164   if (MIPS_ELF_READONLY_SECTION (input_section))
6165     info->flags |= DF_TEXTREL;
6166
6167   return TRUE;
6168 }
6169 \f
6170 /* Return the MACH for a MIPS e_flags value.  */
6171
6172 unsigned long
6173 _bfd_elf_mips_mach (flagword flags)
6174 {
6175   switch (flags & EF_MIPS_MACH)
6176     {
6177     case E_MIPS_MACH_3900:
6178       return bfd_mach_mips3900;
6179
6180     case E_MIPS_MACH_4010:
6181       return bfd_mach_mips4010;
6182
6183     case E_MIPS_MACH_4100:
6184       return bfd_mach_mips4100;
6185
6186     case E_MIPS_MACH_4111:
6187       return bfd_mach_mips4111;
6188
6189     case E_MIPS_MACH_4120:
6190       return bfd_mach_mips4120;
6191
6192     case E_MIPS_MACH_4650:
6193       return bfd_mach_mips4650;
6194
6195     case E_MIPS_MACH_5400:
6196       return bfd_mach_mips5400;
6197
6198     case E_MIPS_MACH_5500:
6199       return bfd_mach_mips5500;
6200
6201     case E_MIPS_MACH_5900:
6202       return bfd_mach_mips5900;
6203
6204     case E_MIPS_MACH_9000:
6205       return bfd_mach_mips9000;
6206
6207     case E_MIPS_MACH_SB1:
6208       return bfd_mach_mips_sb1;
6209
6210     case E_MIPS_MACH_LS2E:
6211       return bfd_mach_mips_loongson_2e;
6212
6213     case E_MIPS_MACH_LS2F:
6214       return bfd_mach_mips_loongson_2f;
6215
6216     case E_MIPS_MACH_LS3A:
6217       return bfd_mach_mips_loongson_3a;
6218
6219     case E_MIPS_MACH_OCTEON2:
6220       return bfd_mach_mips_octeon2;
6221
6222     case E_MIPS_MACH_OCTEON:
6223       return bfd_mach_mips_octeon;
6224
6225     case E_MIPS_MACH_XLR:
6226       return bfd_mach_mips_xlr;
6227
6228     default:
6229       switch (flags & EF_MIPS_ARCH)
6230         {
6231         default:
6232         case E_MIPS_ARCH_1:
6233           return bfd_mach_mips3000;
6234
6235         case E_MIPS_ARCH_2:
6236           return bfd_mach_mips6000;
6237
6238         case E_MIPS_ARCH_3:
6239           return bfd_mach_mips4000;
6240
6241         case E_MIPS_ARCH_4:
6242           return bfd_mach_mips8000;
6243
6244         case E_MIPS_ARCH_5:
6245           return bfd_mach_mips5;
6246
6247         case E_MIPS_ARCH_32:
6248           return bfd_mach_mipsisa32;
6249
6250         case E_MIPS_ARCH_64:
6251           return bfd_mach_mipsisa64;
6252
6253         case E_MIPS_ARCH_32R2:
6254           return bfd_mach_mipsisa32r2;
6255
6256         case E_MIPS_ARCH_64R2:
6257           return bfd_mach_mipsisa64r2;
6258         }
6259     }
6260
6261   return 0;
6262 }
6263
6264 /* Return printable name for ABI.  */
6265
6266 static INLINE char *
6267 elf_mips_abi_name (bfd *abfd)
6268 {
6269   flagword flags;
6270
6271   flags = elf_elfheader (abfd)->e_flags;
6272   switch (flags & EF_MIPS_ABI)
6273     {
6274     case 0:
6275       if (ABI_N32_P (abfd))
6276         return "N32";
6277       else if (ABI_64_P (abfd))
6278         return "64";
6279       else
6280         return "none";
6281     case E_MIPS_ABI_O32:
6282       return "O32";
6283     case E_MIPS_ABI_O64:
6284       return "O64";
6285     case E_MIPS_ABI_EABI32:
6286       return "EABI32";
6287     case E_MIPS_ABI_EABI64:
6288       return "EABI64";
6289     default:
6290       return "unknown abi";
6291     }
6292 }
6293 \f
6294 /* MIPS ELF uses two common sections.  One is the usual one, and the
6295    other is for small objects.  All the small objects are kept
6296    together, and then referenced via the gp pointer, which yields
6297    faster assembler code.  This is what we use for the small common
6298    section.  This approach is copied from ecoff.c.  */
6299 static asection mips_elf_scom_section;
6300 static asymbol mips_elf_scom_symbol;
6301 static asymbol *mips_elf_scom_symbol_ptr;
6302
6303 /* MIPS ELF also uses an acommon section, which represents an
6304    allocated common symbol which may be overridden by a
6305    definition in a shared library.  */
6306 static asection mips_elf_acom_section;
6307 static asymbol mips_elf_acom_symbol;
6308 static asymbol *mips_elf_acom_symbol_ptr;
6309
6310 /* This is used for both the 32-bit and the 64-bit ABI.  */
6311
6312 void
6313 _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym)
6314 {
6315   elf_symbol_type *elfsym;
6316
6317   /* Handle the special MIPS section numbers that a symbol may use.  */
6318   elfsym = (elf_symbol_type *) asym;
6319   switch (elfsym->internal_elf_sym.st_shndx)
6320     {
6321     case SHN_MIPS_ACOMMON:
6322       /* This section is used in a dynamically linked executable file.
6323          It is an allocated common section.  The dynamic linker can
6324          either resolve these symbols to something in a shared
6325          library, or it can just leave them here.  For our purposes,
6326          we can consider these symbols to be in a new section.  */
6327       if (mips_elf_acom_section.name == NULL)
6328         {
6329           /* Initialize the acommon section.  */
6330           mips_elf_acom_section.name = ".acommon";
6331           mips_elf_acom_section.flags = SEC_ALLOC;
6332           mips_elf_acom_section.output_section = &mips_elf_acom_section;
6333           mips_elf_acom_section.symbol = &mips_elf_acom_symbol;
6334           mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr;
6335           mips_elf_acom_symbol.name = ".acommon";
6336           mips_elf_acom_symbol.flags = BSF_SECTION_SYM;
6337           mips_elf_acom_symbol.section = &mips_elf_acom_section;
6338           mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol;
6339         }
6340       asym->section = &mips_elf_acom_section;
6341       break;
6342
6343     case SHN_COMMON:
6344       /* Common symbols less than the GP size are automatically
6345          treated as SHN_MIPS_SCOMMON symbols on IRIX5.  */
6346       if (asym->value > elf_gp_size (abfd)
6347           || ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_TLS
6348           || IRIX_COMPAT (abfd) == ict_irix6)
6349         break;
6350       /* Fall through.  */
6351     case SHN_MIPS_SCOMMON:
6352       if (mips_elf_scom_section.name == NULL)
6353         {
6354           /* Initialize the small common section.  */
6355           mips_elf_scom_section.name = ".scommon";
6356           mips_elf_scom_section.flags = SEC_IS_COMMON;
6357           mips_elf_scom_section.output_section = &mips_elf_scom_section;
6358           mips_elf_scom_section.symbol = &mips_elf_scom_symbol;
6359           mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr;
6360           mips_elf_scom_symbol.name = ".scommon";
6361           mips_elf_scom_symbol.flags = BSF_SECTION_SYM;
6362           mips_elf_scom_symbol.section = &mips_elf_scom_section;
6363           mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol;
6364         }
6365       asym->section = &mips_elf_scom_section;
6366       asym->value = elfsym->internal_elf_sym.st_size;
6367       break;
6368
6369     case SHN_MIPS_SUNDEFINED:
6370       asym->section = bfd_und_section_ptr;
6371       break;
6372
6373     case SHN_MIPS_TEXT:
6374       {
6375         asection *section = bfd_get_section_by_name (abfd, ".text");
6376
6377         if (section != NULL)
6378           {
6379             asym->section = section;
6380             /* MIPS_TEXT is a bit special, the address is not an offset
6381                to the base of the .text section.  So substract the section
6382                base address to make it an offset.  */
6383             asym->value -= section->vma;
6384           }
6385       }
6386       break;
6387
6388     case SHN_MIPS_DATA:
6389       {
6390         asection *section = bfd_get_section_by_name (abfd, ".data");
6391
6392         if (section != NULL)
6393           {
6394             asym->section = section;
6395             /* MIPS_DATA is a bit special, the address is not an offset
6396                to the base of the .data section.  So substract the section
6397                base address to make it an offset.  */
6398             asym->value -= section->vma;
6399           }
6400       }
6401       break;
6402     }
6403
6404   /* If this is an odd-valued function symbol, assume it's a MIPS16
6405      or microMIPS one.  */
6406   if (ELF_ST_TYPE (elfsym->internal_elf_sym.st_info) == STT_FUNC
6407       && (asym->value & 1) != 0)
6408     {
6409       asym->value--;
6410       if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
6411         elfsym->internal_elf_sym.st_other
6412           = ELF_ST_SET_MICROMIPS (elfsym->internal_elf_sym.st_other);
6413       else
6414         elfsym->internal_elf_sym.st_other
6415           = ELF_ST_SET_MIPS16 (elfsym->internal_elf_sym.st_other);
6416     }
6417 }
6418 \f
6419 /* Implement elf_backend_eh_frame_address_size.  This differs from
6420    the default in the way it handles EABI64.
6421
6422    EABI64 was originally specified as an LP64 ABI, and that is what
6423    -mabi=eabi normally gives on a 64-bit target.  However, gcc has
6424    historically accepted the combination of -mabi=eabi and -mlong32,
6425    and this ILP32 variation has become semi-official over time.
6426    Both forms use elf32 and have pointer-sized FDE addresses.
6427
6428    If an EABI object was generated by GCC 4.0 or above, it will have
6429    an empty .gcc_compiled_longXX section, where XX is the size of longs
6430    in bits.  Unfortunately, ILP32 objects generated by earlier compilers
6431    have no special marking to distinguish them from LP64 objects.
6432
6433    We don't want users of the official LP64 ABI to be punished for the
6434    existence of the ILP32 variant, but at the same time, we don't want
6435    to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects.
6436    We therefore take the following approach:
6437
6438       - If ABFD contains a .gcc_compiled_longXX section, use it to
6439         determine the pointer size.
6440
6441       - Otherwise check the type of the first relocation.  Assume that
6442         the LP64 ABI is being used if the relocation is of type R_MIPS_64.
6443
6444       - Otherwise punt.
6445
6446    The second check is enough to detect LP64 objects generated by pre-4.0
6447    compilers because, in the kind of output generated by those compilers,
6448    the first relocation will be associated with either a CIE personality
6449    routine or an FDE start address.  Furthermore, the compilers never
6450    used a special (non-pointer) encoding for this ABI.
6451
6452    Checking the relocation type should also be safe because there is no
6453    reason to use R_MIPS_64 in an ILP32 object.  Pre-4.0 compilers never
6454    did so.  */
6455
6456 unsigned int
6457 _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec)
6458 {
6459   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
6460     return 8;
6461   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
6462     {
6463       bfd_boolean long32_p, long64_p;
6464
6465       long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0;
6466       long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0;
6467       if (long32_p && long64_p)
6468         return 0;
6469       if (long32_p)
6470         return 4;
6471       if (long64_p)
6472         return 8;
6473
6474       if (sec->reloc_count > 0
6475           && elf_section_data (sec)->relocs != NULL
6476           && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info)
6477               == R_MIPS_64))
6478         return 8;
6479
6480       return 0;
6481     }
6482   return 4;
6483 }
6484 \f
6485 /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP
6486    relocations against two unnamed section symbols to resolve to the
6487    same address.  For example, if we have code like:
6488
6489         lw      $4,%got_disp(.data)($gp)
6490         lw      $25,%got_disp(.text)($gp)
6491         jalr    $25
6492
6493    then the linker will resolve both relocations to .data and the program
6494    will jump there rather than to .text.
6495
6496    We can work around this problem by giving names to local section symbols.
6497    This is also what the MIPSpro tools do.  */
6498
6499 bfd_boolean
6500 _bfd_mips_elf_name_local_section_symbols (bfd *abfd)
6501 {
6502   return SGI_COMPAT (abfd);
6503 }
6504 \f
6505 /* Work over a section just before writing it out.  This routine is
6506    used by both the 32-bit and the 64-bit ABI.  FIXME: We recognize
6507    sections that need the SHF_MIPS_GPREL flag by name; there has to be
6508    a better way.  */
6509
6510 bfd_boolean
6511 _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr)
6512 {
6513   if (hdr->sh_type == SHT_MIPS_REGINFO
6514       && hdr->sh_size > 0)
6515     {
6516       bfd_byte buf[4];
6517
6518       BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo));
6519       BFD_ASSERT (hdr->contents == NULL);
6520
6521       if (bfd_seek (abfd,
6522                     hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4,
6523                     SEEK_SET) != 0)
6524         return FALSE;
6525       H_PUT_32 (abfd, elf_gp (abfd), buf);
6526       if (bfd_bwrite (buf, 4, abfd) != 4)
6527         return FALSE;
6528     }
6529
6530   if (hdr->sh_type == SHT_MIPS_OPTIONS
6531       && hdr->bfd_section != NULL
6532       && mips_elf_section_data (hdr->bfd_section) != NULL
6533       && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL)
6534     {
6535       bfd_byte *contents, *l, *lend;
6536
6537       /* We stored the section contents in the tdata field in the
6538          set_section_contents routine.  We save the section contents
6539          so that we don't have to read them again.
6540          At this point we know that elf_gp is set, so we can look
6541          through the section contents to see if there is an
6542          ODK_REGINFO structure.  */
6543
6544       contents = mips_elf_section_data (hdr->bfd_section)->u.tdata;
6545       l = contents;
6546       lend = contents + hdr->sh_size;
6547       while (l + sizeof (Elf_External_Options) <= lend)
6548         {
6549           Elf_Internal_Options intopt;
6550
6551           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6552                                         &intopt);
6553           if (intopt.size < sizeof (Elf_External_Options))
6554             {
6555               (*_bfd_error_handler)
6556                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6557                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6558               break;
6559             }
6560           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6561             {
6562               bfd_byte buf[8];
6563
6564               if (bfd_seek (abfd,
6565                             (hdr->sh_offset
6566                              + (l - contents)
6567                              + sizeof (Elf_External_Options)
6568                              + (sizeof (Elf64_External_RegInfo) - 8)),
6569                              SEEK_SET) != 0)
6570                 return FALSE;
6571               H_PUT_64 (abfd, elf_gp (abfd), buf);
6572               if (bfd_bwrite (buf, 8, abfd) != 8)
6573                 return FALSE;
6574             }
6575           else if (intopt.kind == ODK_REGINFO)
6576             {
6577               bfd_byte buf[4];
6578
6579               if (bfd_seek (abfd,
6580                             (hdr->sh_offset
6581                              + (l - contents)
6582                              + sizeof (Elf_External_Options)
6583                              + (sizeof (Elf32_External_RegInfo) - 4)),
6584                             SEEK_SET) != 0)
6585                 return FALSE;
6586               H_PUT_32 (abfd, elf_gp (abfd), buf);
6587               if (bfd_bwrite (buf, 4, abfd) != 4)
6588                 return FALSE;
6589             }
6590           l += intopt.size;
6591         }
6592     }
6593
6594   if (hdr->bfd_section != NULL)
6595     {
6596       const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
6597
6598       /* .sbss is not handled specially here because the GNU/Linux
6599          prelinker can convert .sbss from NOBITS to PROGBITS and
6600          changing it back to NOBITS breaks the binary.  The entry in
6601          _bfd_mips_elf_special_sections will ensure the correct flags
6602          are set on .sbss if BFD creates it without reading it from an
6603          input file, and without special handling here the flags set
6604          on it in an input file will be followed.  */
6605       if (strcmp (name, ".sdata") == 0
6606           || strcmp (name, ".lit8") == 0
6607           || strcmp (name, ".lit4") == 0)
6608         {
6609           hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL;
6610           hdr->sh_type = SHT_PROGBITS;
6611         }
6612       else if (strcmp (name, ".srdata") == 0)
6613         {
6614           hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL;
6615           hdr->sh_type = SHT_PROGBITS;
6616         }
6617       else if (strcmp (name, ".compact_rel") == 0)
6618         {
6619           hdr->sh_flags = 0;
6620           hdr->sh_type = SHT_PROGBITS;
6621         }
6622       else if (strcmp (name, ".rtproc") == 0)
6623         {
6624           if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0)
6625             {
6626               unsigned int adjust;
6627
6628               adjust = hdr->sh_size % hdr->sh_addralign;
6629               if (adjust != 0)
6630                 hdr->sh_size += hdr->sh_addralign - adjust;
6631             }
6632         }
6633     }
6634
6635   return TRUE;
6636 }
6637
6638 /* Handle a MIPS specific section when reading an object file.  This
6639    is called when elfcode.h finds a section with an unknown type.
6640    This routine supports both the 32-bit and 64-bit ELF ABI.
6641
6642    FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure
6643    how to.  */
6644
6645 bfd_boolean
6646 _bfd_mips_elf_section_from_shdr (bfd *abfd,
6647                                  Elf_Internal_Shdr *hdr,
6648                                  const char *name,
6649                                  int shindex)
6650 {
6651   flagword flags = 0;
6652
6653   /* There ought to be a place to keep ELF backend specific flags, but
6654      at the moment there isn't one.  We just keep track of the
6655      sections by their name, instead.  Fortunately, the ABI gives
6656      suggested names for all the MIPS specific sections, so we will
6657      probably get away with this.  */
6658   switch (hdr->sh_type)
6659     {
6660     case SHT_MIPS_LIBLIST:
6661       if (strcmp (name, ".liblist") != 0)
6662         return FALSE;
6663       break;
6664     case SHT_MIPS_MSYM:
6665       if (strcmp (name, ".msym") != 0)
6666         return FALSE;
6667       break;
6668     case SHT_MIPS_CONFLICT:
6669       if (strcmp (name, ".conflict") != 0)
6670         return FALSE;
6671       break;
6672     case SHT_MIPS_GPTAB:
6673       if (! CONST_STRNEQ (name, ".gptab."))
6674         return FALSE;
6675       break;
6676     case SHT_MIPS_UCODE:
6677       if (strcmp (name, ".ucode") != 0)
6678         return FALSE;
6679       break;
6680     case SHT_MIPS_DEBUG:
6681       if (strcmp (name, ".mdebug") != 0)
6682         return FALSE;
6683       flags = SEC_DEBUGGING;
6684       break;
6685     case SHT_MIPS_REGINFO:
6686       if (strcmp (name, ".reginfo") != 0
6687           || hdr->sh_size != sizeof (Elf32_External_RegInfo))
6688         return FALSE;
6689       flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE);
6690       break;
6691     case SHT_MIPS_IFACE:
6692       if (strcmp (name, ".MIPS.interfaces") != 0)
6693         return FALSE;
6694       break;
6695     case SHT_MIPS_CONTENT:
6696       if (! CONST_STRNEQ (name, ".MIPS.content"))
6697         return FALSE;
6698       break;
6699     case SHT_MIPS_OPTIONS:
6700       if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6701         return FALSE;
6702       break;
6703     case SHT_MIPS_DWARF:
6704       if (! CONST_STRNEQ (name, ".debug_")
6705           && ! CONST_STRNEQ (name, ".zdebug_"))
6706         return FALSE;
6707       break;
6708     case SHT_MIPS_SYMBOL_LIB:
6709       if (strcmp (name, ".MIPS.symlib") != 0)
6710         return FALSE;
6711       break;
6712     case SHT_MIPS_EVENTS:
6713       if (! CONST_STRNEQ (name, ".MIPS.events")
6714           && ! CONST_STRNEQ (name, ".MIPS.post_rel"))
6715         return FALSE;
6716       break;
6717     default:
6718       break;
6719     }
6720
6721   if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
6722     return FALSE;
6723
6724   if (flags)
6725     {
6726       if (! bfd_set_section_flags (abfd, hdr->bfd_section,
6727                                    (bfd_get_section_flags (abfd,
6728                                                            hdr->bfd_section)
6729                                     | flags)))
6730         return FALSE;
6731     }
6732
6733   /* FIXME: We should record sh_info for a .gptab section.  */
6734
6735   /* For a .reginfo section, set the gp value in the tdata information
6736      from the contents of this section.  We need the gp value while
6737      processing relocs, so we just get it now.  The .reginfo section
6738      is not used in the 64-bit MIPS ELF ABI.  */
6739   if (hdr->sh_type == SHT_MIPS_REGINFO)
6740     {
6741       Elf32_External_RegInfo ext;
6742       Elf32_RegInfo s;
6743
6744       if (! bfd_get_section_contents (abfd, hdr->bfd_section,
6745                                       &ext, 0, sizeof ext))
6746         return FALSE;
6747       bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s);
6748       elf_gp (abfd) = s.ri_gp_value;
6749     }
6750
6751   /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and
6752      set the gp value based on what we find.  We may see both
6753      SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case,
6754      they should agree.  */
6755   if (hdr->sh_type == SHT_MIPS_OPTIONS)
6756     {
6757       bfd_byte *contents, *l, *lend;
6758
6759       contents = bfd_malloc (hdr->sh_size);
6760       if (contents == NULL)
6761         return FALSE;
6762       if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents,
6763                                       0, hdr->sh_size))
6764         {
6765           free (contents);
6766           return FALSE;
6767         }
6768       l = contents;
6769       lend = contents + hdr->sh_size;
6770       while (l + sizeof (Elf_External_Options) <= lend)
6771         {
6772           Elf_Internal_Options intopt;
6773
6774           bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l,
6775                                         &intopt);
6776           if (intopt.size < sizeof (Elf_External_Options))
6777             {
6778               (*_bfd_error_handler)
6779                 (_("%B: Warning: bad `%s' option size %u smaller than its header"),
6780                 abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size);
6781               break;
6782             }
6783           if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO)
6784             {
6785               Elf64_Internal_RegInfo intreg;
6786
6787               bfd_mips_elf64_swap_reginfo_in
6788                 (abfd,
6789                  ((Elf64_External_RegInfo *)
6790                   (l + sizeof (Elf_External_Options))),
6791                  &intreg);
6792               elf_gp (abfd) = intreg.ri_gp_value;
6793             }
6794           else if (intopt.kind == ODK_REGINFO)
6795             {
6796               Elf32_RegInfo intreg;
6797
6798               bfd_mips_elf32_swap_reginfo_in
6799                 (abfd,
6800                  ((Elf32_External_RegInfo *)
6801                   (l + sizeof (Elf_External_Options))),
6802                  &intreg);
6803               elf_gp (abfd) = intreg.ri_gp_value;
6804             }
6805           l += intopt.size;
6806         }
6807       free (contents);
6808     }
6809
6810   return TRUE;
6811 }
6812
6813 /* Set the correct type for a MIPS ELF section.  We do this by the
6814    section name, which is a hack, but ought to work.  This routine is
6815    used by both the 32-bit and the 64-bit ABI.  */
6816
6817 bfd_boolean
6818 _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec)
6819 {
6820   const char *name = bfd_get_section_name (abfd, sec);
6821
6822   if (strcmp (name, ".liblist") == 0)
6823     {
6824       hdr->sh_type = SHT_MIPS_LIBLIST;
6825       hdr->sh_info = sec->size / sizeof (Elf32_Lib);
6826       /* The sh_link field is set in final_write_processing.  */
6827     }
6828   else if (strcmp (name, ".conflict") == 0)
6829     hdr->sh_type = SHT_MIPS_CONFLICT;
6830   else if (CONST_STRNEQ (name, ".gptab."))
6831     {
6832       hdr->sh_type = SHT_MIPS_GPTAB;
6833       hdr->sh_entsize = sizeof (Elf32_External_gptab);
6834       /* The sh_info field is set in final_write_processing.  */
6835     }
6836   else if (strcmp (name, ".ucode") == 0)
6837     hdr->sh_type = SHT_MIPS_UCODE;
6838   else if (strcmp (name, ".mdebug") == 0)
6839     {
6840       hdr->sh_type = SHT_MIPS_DEBUG;
6841       /* In a shared object on IRIX 5.3, the .mdebug section has an
6842          entsize of 0.  FIXME: Does this matter?  */
6843       if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0)
6844         hdr->sh_entsize = 0;
6845       else
6846         hdr->sh_entsize = 1;
6847     }
6848   else if (strcmp (name, ".reginfo") == 0)
6849     {
6850       hdr->sh_type = SHT_MIPS_REGINFO;
6851       /* In a shared object on IRIX 5.3, the .reginfo section has an
6852          entsize of 0x18.  FIXME: Does this matter?  */
6853       if (SGI_COMPAT (abfd))
6854         {
6855           if ((abfd->flags & DYNAMIC) != 0)
6856             hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6857           else
6858             hdr->sh_entsize = 1;
6859         }
6860       else
6861         hdr->sh_entsize = sizeof (Elf32_External_RegInfo);
6862     }
6863   else if (SGI_COMPAT (abfd)
6864            && (strcmp (name, ".hash") == 0
6865                || strcmp (name, ".dynamic") == 0
6866                || strcmp (name, ".dynstr") == 0))
6867     {
6868       if (SGI_COMPAT (abfd))
6869         hdr->sh_entsize = 0;
6870 #if 0
6871       /* This isn't how the IRIX6 linker behaves.  */
6872       hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES;
6873 #endif
6874     }
6875   else if (strcmp (name, ".got") == 0
6876            || strcmp (name, ".srdata") == 0
6877            || strcmp (name, ".sdata") == 0
6878            || strcmp (name, ".sbss") == 0
6879            || strcmp (name, ".lit4") == 0
6880            || strcmp (name, ".lit8") == 0)
6881     hdr->sh_flags |= SHF_MIPS_GPREL;
6882   else if (strcmp (name, ".MIPS.interfaces") == 0)
6883     {
6884       hdr->sh_type = SHT_MIPS_IFACE;
6885       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6886     }
6887   else if (CONST_STRNEQ (name, ".MIPS.content"))
6888     {
6889       hdr->sh_type = SHT_MIPS_CONTENT;
6890       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6891       /* The sh_info field is set in final_write_processing.  */
6892     }
6893   else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name))
6894     {
6895       hdr->sh_type = SHT_MIPS_OPTIONS;
6896       hdr->sh_entsize = 1;
6897       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6898     }
6899   else if (CONST_STRNEQ (name, ".debug_")
6900            || CONST_STRNEQ (name, ".zdebug_"))
6901     {
6902       hdr->sh_type = SHT_MIPS_DWARF;
6903
6904       /* Irix facilities such as libexc expect a single .debug_frame
6905          per executable, the system ones have NOSTRIP set and the linker
6906          doesn't merge sections with different flags so ...  */
6907       if (SGI_COMPAT (abfd) && CONST_STRNEQ (name, ".debug_frame"))
6908         hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6909     }
6910   else if (strcmp (name, ".MIPS.symlib") == 0)
6911     {
6912       hdr->sh_type = SHT_MIPS_SYMBOL_LIB;
6913       /* The sh_link and sh_info fields are set in
6914          final_write_processing.  */
6915     }
6916   else if (CONST_STRNEQ (name, ".MIPS.events")
6917            || CONST_STRNEQ (name, ".MIPS.post_rel"))
6918     {
6919       hdr->sh_type = SHT_MIPS_EVENTS;
6920       hdr->sh_flags |= SHF_MIPS_NOSTRIP;
6921       /* The sh_link field is set in final_write_processing.  */
6922     }
6923   else if (strcmp (name, ".msym") == 0)
6924     {
6925       hdr->sh_type = SHT_MIPS_MSYM;
6926       hdr->sh_flags |= SHF_ALLOC;
6927       hdr->sh_entsize = 8;
6928     }
6929
6930   /* The generic elf_fake_sections will set up REL_HDR using the default
6931    kind of relocations.  We used to set up a second header for the
6932    non-default kind of relocations here, but only NewABI would use
6933    these, and the IRIX ld doesn't like resulting empty RELA sections.
6934    Thus we create those header only on demand now.  */
6935
6936   return TRUE;
6937 }
6938
6939 /* Given a BFD section, try to locate the corresponding ELF section
6940    index.  This is used by both the 32-bit and the 64-bit ABI.
6941    Actually, it's not clear to me that the 64-bit ABI supports these,
6942    but for non-PIC objects we will certainly want support for at least
6943    the .scommon section.  */
6944
6945 bfd_boolean
6946 _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
6947                                         asection *sec, int *retval)
6948 {
6949   if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
6950     {
6951       *retval = SHN_MIPS_SCOMMON;
6952       return TRUE;
6953     }
6954   if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0)
6955     {
6956       *retval = SHN_MIPS_ACOMMON;
6957       return TRUE;
6958     }
6959   return FALSE;
6960 }
6961 \f
6962 /* Hook called by the linker routine which adds symbols from an object
6963    file.  We must handle the special MIPS section numbers here.  */
6964
6965 bfd_boolean
6966 _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
6967                                Elf_Internal_Sym *sym, const char **namep,
6968                                flagword *flagsp ATTRIBUTE_UNUSED,
6969                                asection **secp, bfd_vma *valp)
6970 {
6971   if (SGI_COMPAT (abfd)
6972       && (abfd->flags & DYNAMIC) != 0
6973       && strcmp (*namep, "_rld_new_interface") == 0)
6974     {
6975       /* Skip IRIX5 rld entry name.  */
6976       *namep = NULL;
6977       return TRUE;
6978     }
6979
6980   /* Shared objects may have a dynamic symbol '_gp_disp' defined as
6981      a SECTION *ABS*.  This causes ld to think it can resolve _gp_disp
6982      by setting a DT_NEEDED for the shared object.  Since _gp_disp is
6983      a magic symbol resolved by the linker, we ignore this bogus definition
6984      of _gp_disp.  New ABI objects do not suffer from this problem so this
6985      is not done for them. */
6986   if (!NEWABI_P(abfd)
6987       && (sym->st_shndx == SHN_ABS)
6988       && (strcmp (*namep, "_gp_disp") == 0))
6989     {
6990       *namep = NULL;
6991       return TRUE;
6992     }
6993
6994   switch (sym->st_shndx)
6995     {
6996     case SHN_COMMON:
6997       /* Common symbols less than the GP size are automatically
6998          treated as SHN_MIPS_SCOMMON symbols.  */
6999       if (sym->st_size > elf_gp_size (abfd)
7000           || ELF_ST_TYPE (sym->st_info) == STT_TLS
7001           || IRIX_COMPAT (abfd) == ict_irix6)
7002         break;
7003       /* Fall through.  */
7004     case SHN_MIPS_SCOMMON:
7005       *secp = bfd_make_section_old_way (abfd, ".scommon");
7006       (*secp)->flags |= SEC_IS_COMMON;
7007       *valp = sym->st_size;
7008       break;
7009
7010     case SHN_MIPS_TEXT:
7011       /* This section is used in a shared object.  */
7012       if (elf_tdata (abfd)->elf_text_section == NULL)
7013         {
7014           asymbol *elf_text_symbol;
7015           asection *elf_text_section;
7016           bfd_size_type amt = sizeof (asection);
7017
7018           elf_text_section = bfd_zalloc (abfd, amt);
7019           if (elf_text_section == NULL)
7020             return FALSE;
7021
7022           amt = sizeof (asymbol);
7023           elf_text_symbol = bfd_zalloc (abfd, amt);
7024           if (elf_text_symbol == NULL)
7025             return FALSE;
7026
7027           /* Initialize the section.  */
7028
7029           elf_tdata (abfd)->elf_text_section = elf_text_section;
7030           elf_tdata (abfd)->elf_text_symbol = elf_text_symbol;
7031
7032           elf_text_section->symbol = elf_text_symbol;
7033           elf_text_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_text_symbol;
7034
7035           elf_text_section->name = ".text";
7036           elf_text_section->flags = SEC_NO_FLAGS;
7037           elf_text_section->output_section = NULL;
7038           elf_text_section->owner = abfd;
7039           elf_text_symbol->name = ".text";
7040           elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7041           elf_text_symbol->section = elf_text_section;
7042         }
7043       /* This code used to do *secp = bfd_und_section_ptr if
7044          info->shared.  I don't know why, and that doesn't make sense,
7045          so I took it out.  */
7046       *secp = elf_tdata (abfd)->elf_text_section;
7047       break;
7048
7049     case SHN_MIPS_ACOMMON:
7050       /* Fall through. XXX Can we treat this as allocated data?  */
7051     case SHN_MIPS_DATA:
7052       /* This section is used in a shared object.  */
7053       if (elf_tdata (abfd)->elf_data_section == NULL)
7054         {
7055           asymbol *elf_data_symbol;
7056           asection *elf_data_section;
7057           bfd_size_type amt = sizeof (asection);
7058
7059           elf_data_section = bfd_zalloc (abfd, amt);
7060           if (elf_data_section == NULL)
7061             return FALSE;
7062
7063           amt = sizeof (asymbol);
7064           elf_data_symbol = bfd_zalloc (abfd, amt);
7065           if (elf_data_symbol == NULL)
7066             return FALSE;
7067
7068           /* Initialize the section.  */
7069
7070           elf_tdata (abfd)->elf_data_section = elf_data_section;
7071           elf_tdata (abfd)->elf_data_symbol = elf_data_symbol;
7072
7073           elf_data_section->symbol = elf_data_symbol;
7074           elf_data_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_data_symbol;
7075
7076           elf_data_section->name = ".data";
7077           elf_data_section->flags = SEC_NO_FLAGS;
7078           elf_data_section->output_section = NULL;
7079           elf_data_section->owner = abfd;
7080           elf_data_symbol->name = ".data";
7081           elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC;
7082           elf_data_symbol->section = elf_data_section;
7083         }
7084       /* This code used to do *secp = bfd_und_section_ptr if
7085          info->shared.  I don't know why, and that doesn't make sense,
7086          so I took it out.  */
7087       *secp = elf_tdata (abfd)->elf_data_section;
7088       break;
7089
7090     case SHN_MIPS_SUNDEFINED:
7091       *secp = bfd_und_section_ptr;
7092       break;
7093     }
7094
7095   if (SGI_COMPAT (abfd)
7096       && ! info->shared
7097       && info->output_bfd->xvec == abfd->xvec
7098       && strcmp (*namep, "__rld_obj_head") == 0)
7099     {
7100       struct elf_link_hash_entry *h;
7101       struct bfd_link_hash_entry *bh;
7102
7103       /* Mark __rld_obj_head as dynamic.  */
7104       bh = NULL;
7105       if (! (_bfd_generic_link_add_one_symbol
7106              (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE,
7107               get_elf_backend_data (abfd)->collect, &bh)))
7108         return FALSE;
7109
7110       h = (struct elf_link_hash_entry *) bh;
7111       h->non_elf = 0;
7112       h->def_regular = 1;
7113       h->type = STT_OBJECT;
7114
7115       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7116         return FALSE;
7117
7118       mips_elf_hash_table (info)->use_rld_obj_head = TRUE;
7119       mips_elf_hash_table (info)->rld_symbol = h;
7120     }
7121
7122   /* If this is a mips16 text symbol, add 1 to the value to make it
7123      odd.  This will cause something like .word SYM to come up with
7124      the right value when it is loaded into the PC.  */
7125   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7126     ++*valp;
7127
7128   return TRUE;
7129 }
7130
7131 /* This hook function is called before the linker writes out a global
7132    symbol.  We mark symbols as small common if appropriate.  This is
7133    also where we undo the increment of the value for a mips16 symbol.  */
7134
7135 int
7136 _bfd_mips_elf_link_output_symbol_hook
7137   (struct bfd_link_info *info ATTRIBUTE_UNUSED,
7138    const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym,
7139    asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
7140 {
7141   /* If we see a common symbol, which implies a relocatable link, then
7142      if a symbol was small common in an input file, mark it as small
7143      common in the output file.  */
7144   if (sym->st_shndx == SHN_COMMON
7145       && strcmp (input_sec->name, ".scommon") == 0)
7146     sym->st_shndx = SHN_MIPS_SCOMMON;
7147
7148   if (ELF_ST_IS_COMPRESSED (sym->st_other))
7149     sym->st_value &= ~1;
7150
7151   return 1;
7152 }
7153 \f
7154 /* Functions for the dynamic linker.  */
7155
7156 /* Create dynamic sections when linking against a dynamic object.  */
7157
7158 bfd_boolean
7159 _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
7160 {
7161   struct elf_link_hash_entry *h;
7162   struct bfd_link_hash_entry *bh;
7163   flagword flags;
7164   register asection *s;
7165   const char * const *namep;
7166   struct mips_elf_link_hash_table *htab;
7167
7168   htab = mips_elf_hash_table (info);
7169   BFD_ASSERT (htab != NULL);
7170
7171   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
7172            | SEC_LINKER_CREATED | SEC_READONLY);
7173
7174   /* The psABI requires a read-only .dynamic section, but the VxWorks
7175      EABI doesn't.  */
7176   if (!htab->is_vxworks)
7177     {
7178       s = bfd_get_linker_section (abfd, ".dynamic");
7179       if (s != NULL)
7180         {
7181           if (! bfd_set_section_flags (abfd, s, flags))
7182             return FALSE;
7183         }
7184     }
7185
7186   /* We need to create .got section.  */
7187   if (!mips_elf_create_got_section (abfd, info))
7188     return FALSE;
7189
7190   if (! mips_elf_rel_dyn_section (info, TRUE))
7191     return FALSE;
7192
7193   /* Create .stub section.  */
7194   s = bfd_make_section_anyway_with_flags (abfd,
7195                                           MIPS_ELF_STUB_SECTION_NAME (abfd),
7196                                           flags | SEC_CODE);
7197   if (s == NULL
7198       || ! bfd_set_section_alignment (abfd, s,
7199                                       MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7200     return FALSE;
7201   htab->sstubs = s;
7202
7203   if (!mips_elf_hash_table (info)->use_rld_obj_head
7204       && !info->shared
7205       && bfd_get_linker_section (abfd, ".rld_map") == NULL)
7206     {
7207       s = bfd_make_section_anyway_with_flags (abfd, ".rld_map",
7208                                               flags &~ (flagword) SEC_READONLY);
7209       if (s == NULL
7210           || ! bfd_set_section_alignment (abfd, s,
7211                                           MIPS_ELF_LOG_FILE_ALIGN (abfd)))
7212         return FALSE;
7213     }
7214
7215   /* On IRIX5, we adjust add some additional symbols and change the
7216      alignments of several sections.  There is no ABI documentation
7217      indicating that this is necessary on IRIX6, nor any evidence that
7218      the linker takes such action.  */
7219   if (IRIX_COMPAT (abfd) == ict_irix5)
7220     {
7221       for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++)
7222         {
7223           bh = NULL;
7224           if (! (_bfd_generic_link_add_one_symbol
7225                  (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0,
7226                   NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7227             return FALSE;
7228
7229           h = (struct elf_link_hash_entry *) bh;
7230           h->non_elf = 0;
7231           h->def_regular = 1;
7232           h->type = STT_SECTION;
7233
7234           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7235             return FALSE;
7236         }
7237
7238       /* We need to create a .compact_rel section.  */
7239       if (SGI_COMPAT (abfd))
7240         {
7241           if (!mips_elf_create_compact_rel_section (abfd, info))
7242             return FALSE;
7243         }
7244
7245       /* Change alignments of some sections.  */
7246       s = bfd_get_linker_section (abfd, ".hash");
7247       if (s != NULL)
7248         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7249       s = bfd_get_linker_section (abfd, ".dynsym");
7250       if (s != NULL)
7251         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7252       s = bfd_get_linker_section (abfd, ".dynstr");
7253       if (s != NULL)
7254         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7255       /* ??? */
7256       s = bfd_get_section_by_name (abfd, ".reginfo");
7257       if (s != NULL)
7258         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7259       s = bfd_get_linker_section (abfd, ".dynamic");
7260       if (s != NULL)
7261         bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd));
7262     }
7263
7264   if (!info->shared)
7265     {
7266       const char *name;
7267
7268       name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING";
7269       bh = NULL;
7270       if (!(_bfd_generic_link_add_one_symbol
7271             (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0,
7272              NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
7273         return FALSE;
7274
7275       h = (struct elf_link_hash_entry *) bh;
7276       h->non_elf = 0;
7277       h->def_regular = 1;
7278       h->type = STT_SECTION;
7279
7280       if (! bfd_elf_link_record_dynamic_symbol (info, h))
7281         return FALSE;
7282
7283       if (! mips_elf_hash_table (info)->use_rld_obj_head)
7284         {
7285           /* __rld_map is a four byte word located in the .data section
7286              and is filled in by the rtld to contain a pointer to
7287              the _r_debug structure. Its symbol value will be set in
7288              _bfd_mips_elf_finish_dynamic_symbol.  */
7289           s = bfd_get_linker_section (abfd, ".rld_map");
7290           BFD_ASSERT (s != NULL);
7291
7292           name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP";
7293           bh = NULL;
7294           if (!(_bfd_generic_link_add_one_symbol
7295                 (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE,
7296                  get_elf_backend_data (abfd)->collect, &bh)))
7297             return FALSE;
7298
7299           h = (struct elf_link_hash_entry *) bh;
7300           h->non_elf = 0;
7301           h->def_regular = 1;
7302           h->type = STT_OBJECT;
7303
7304           if (! bfd_elf_link_record_dynamic_symbol (info, h))
7305             return FALSE;
7306           mips_elf_hash_table (info)->rld_symbol = h;
7307         }
7308     }
7309
7310   /* Create the .plt, .rel(a).plt, .dynbss and .rel(a).bss sections.
7311      Also create the _PROCEDURE_LINKAGE_TABLE symbol.  */
7312   if (!_bfd_elf_create_dynamic_sections (abfd, info))
7313     return FALSE;
7314
7315   /* Cache the sections created above.  */
7316   htab->splt = bfd_get_linker_section (abfd, ".plt");
7317   htab->sdynbss = bfd_get_linker_section (abfd, ".dynbss");
7318   if (htab->is_vxworks)
7319     {
7320       htab->srelbss = bfd_get_linker_section (abfd, ".rela.bss");
7321       htab->srelplt = bfd_get_linker_section (abfd, ".rela.plt");
7322     }
7323   else
7324     htab->srelplt = bfd_get_linker_section (abfd, ".rel.plt");
7325   if (!htab->sdynbss
7326       || (htab->is_vxworks && !htab->srelbss && !info->shared)
7327       || !htab->srelplt
7328       || !htab->splt)
7329     abort ();
7330
7331   if (htab->is_vxworks)
7332     {
7333       /* Do the usual VxWorks handling.  */
7334       if (!elf_vxworks_create_dynamic_sections (abfd, info, &htab->srelplt2))
7335         return FALSE;
7336
7337       /* Work out the PLT sizes.  */
7338       if (info->shared)
7339         {
7340           htab->plt_header_size
7341             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt0_entry);
7342           htab->plt_entry_size
7343             = 4 * ARRAY_SIZE (mips_vxworks_shared_plt_entry);
7344         }
7345       else
7346         {
7347           htab->plt_header_size
7348             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt0_entry);
7349           htab->plt_entry_size
7350             = 4 * ARRAY_SIZE (mips_vxworks_exec_plt_entry);
7351         }
7352     }
7353   else if (!info->shared)
7354     {
7355       /* All variants of the plt0 entry are the same size.  */
7356       htab->plt_header_size = 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry);
7357       htab->plt_entry_size = 4 * ARRAY_SIZE (mips_exec_plt_entry);
7358     }
7359
7360   return TRUE;
7361 }
7362 \f
7363 /* Return true if relocation REL against section SEC is a REL rather than
7364    RELA relocation.  RELOCS is the first relocation in the section and
7365    ABFD is the bfd that contains SEC.  */
7366
7367 static bfd_boolean
7368 mips_elf_rel_relocation_p (bfd *abfd, asection *sec,
7369                            const Elf_Internal_Rela *relocs,
7370                            const Elf_Internal_Rela *rel)
7371 {
7372   Elf_Internal_Shdr *rel_hdr;
7373   const struct elf_backend_data *bed;
7374
7375   /* To determine which flavor of relocation this is, we depend on the
7376      fact that the INPUT_SECTION's REL_HDR is read before RELA_HDR.  */
7377   rel_hdr = elf_section_data (sec)->rel.hdr;
7378   if (rel_hdr == NULL)
7379     return FALSE;
7380   bed = get_elf_backend_data (abfd);
7381   return ((size_t) (rel - relocs)
7382           < NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel);
7383 }
7384
7385 /* Read the addend for REL relocation REL, which belongs to bfd ABFD.
7386    HOWTO is the relocation's howto and CONTENTS points to the contents
7387    of the section that REL is against.  */
7388
7389 static bfd_vma
7390 mips_elf_read_rel_addend (bfd *abfd, const Elf_Internal_Rela *rel,
7391                           reloc_howto_type *howto, bfd_byte *contents)
7392 {
7393   bfd_byte *location;
7394   unsigned int r_type;
7395   bfd_vma addend;
7396
7397   r_type = ELF_R_TYPE (abfd, rel->r_info);
7398   location = contents + rel->r_offset;
7399
7400   /* Get the addend, which is stored in the input file.  */
7401   _bfd_mips_elf_reloc_unshuffle (abfd, r_type, FALSE, location);
7402   addend = mips_elf_obtain_contents (howto, rel, abfd, contents);
7403   _bfd_mips_elf_reloc_shuffle (abfd, r_type, FALSE, location);
7404
7405   return addend & howto->src_mask;
7406 }
7407
7408 /* REL is a relocation in ABFD that needs a partnering LO16 relocation
7409    and *ADDEND is the addend for REL itself.  Look for the LO16 relocation
7410    and update *ADDEND with the final addend.  Return true on success
7411    or false if the LO16 could not be found.  RELEND is the exclusive
7412    upper bound on the relocations for REL's section.  */
7413
7414 static bfd_boolean
7415 mips_elf_add_lo16_rel_addend (bfd *abfd,
7416                               const Elf_Internal_Rela *rel,
7417                               const Elf_Internal_Rela *relend,
7418                               bfd_byte *contents, bfd_vma *addend)
7419 {
7420   unsigned int r_type, lo16_type;
7421   const Elf_Internal_Rela *lo16_relocation;
7422   reloc_howto_type *lo16_howto;
7423   bfd_vma l;
7424
7425   r_type = ELF_R_TYPE (abfd, rel->r_info);
7426   if (mips16_reloc_p (r_type))
7427     lo16_type = R_MIPS16_LO16;
7428   else if (micromips_reloc_p (r_type))
7429     lo16_type = R_MICROMIPS_LO16;
7430   else
7431     lo16_type = R_MIPS_LO16;
7432
7433   /* The combined value is the sum of the HI16 addend, left-shifted by
7434      sixteen bits, and the LO16 addend, sign extended.  (Usually, the
7435      code does a `lui' of the HI16 value, and then an `addiu' of the
7436      LO16 value.)
7437
7438      Scan ahead to find a matching LO16 relocation.
7439
7440      According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must
7441      be immediately following.  However, for the IRIX6 ABI, the next
7442      relocation may be a composed relocation consisting of several
7443      relocations for the same address.  In that case, the R_MIPS_LO16
7444      relocation may occur as one of these.  We permit a similar
7445      extension in general, as that is useful for GCC.
7446
7447      In some cases GCC dead code elimination removes the LO16 but keeps
7448      the corresponding HI16.  This is strictly speaking a violation of
7449      the ABI but not immediately harmful.  */
7450   lo16_relocation = mips_elf_next_relocation (abfd, lo16_type, rel, relend);
7451   if (lo16_relocation == NULL)
7452     return FALSE;
7453
7454   /* Obtain the addend kept there.  */
7455   lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, lo16_type, FALSE);
7456   l = mips_elf_read_rel_addend (abfd, lo16_relocation, lo16_howto, contents);
7457
7458   l <<= lo16_howto->rightshift;
7459   l = _bfd_mips_elf_sign_extend (l, 16);
7460
7461   *addend <<= 16;
7462   *addend += l;
7463   return TRUE;
7464 }
7465
7466 /* Try to read the contents of section SEC in bfd ABFD.  Return true and
7467    store the contents in *CONTENTS on success.  Assume that *CONTENTS
7468    already holds the contents if it is nonull on entry.  */
7469
7470 static bfd_boolean
7471 mips_elf_get_section_contents (bfd *abfd, asection *sec, bfd_byte **contents)
7472 {
7473   if (*contents)
7474     return TRUE;
7475
7476   /* Get cached copy if it exists.  */
7477   if (elf_section_data (sec)->this_hdr.contents != NULL)
7478     {
7479       *contents = elf_section_data (sec)->this_hdr.contents;
7480       return TRUE;
7481     }
7482
7483   return bfd_malloc_and_get_section (abfd, sec, contents);
7484 }
7485
7486 /* Look through the relocs for a section during the first phase, and
7487    allocate space in the global offset table.  */
7488
7489 bfd_boolean
7490 _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
7491                             asection *sec, const Elf_Internal_Rela *relocs)
7492 {
7493   const char *name;
7494   bfd *dynobj;
7495   Elf_Internal_Shdr *symtab_hdr;
7496   struct elf_link_hash_entry **sym_hashes;
7497   size_t extsymoff;
7498   const Elf_Internal_Rela *rel;
7499   const Elf_Internal_Rela *rel_end;
7500   asection *sreloc;
7501   const struct elf_backend_data *bed;
7502   struct mips_elf_link_hash_table *htab;
7503   bfd_byte *contents;
7504   bfd_vma addend;
7505   reloc_howto_type *howto;
7506
7507   if (info->relocatable)
7508     return TRUE;
7509
7510   htab = mips_elf_hash_table (info);
7511   BFD_ASSERT (htab != NULL);
7512
7513   dynobj = elf_hash_table (info)->dynobj;
7514   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7515   sym_hashes = elf_sym_hashes (abfd);
7516   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
7517
7518   bed = get_elf_backend_data (abfd);
7519   rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
7520
7521   /* Check for the mips16 stub sections.  */
7522
7523   name = bfd_get_section_name (abfd, sec);
7524   if (FN_STUB_P (name))
7525     {
7526       unsigned long r_symndx;
7527
7528       /* Look at the relocation information to figure out which symbol
7529          this is for.  */
7530
7531       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7532       if (r_symndx == 0)
7533         {
7534           (*_bfd_error_handler)
7535             (_("%B: Warning: cannot determine the target function for"
7536                " stub section `%s'"),
7537              abfd, name);
7538           bfd_set_error (bfd_error_bad_value);
7539           return FALSE;
7540         }
7541
7542       if (r_symndx < extsymoff
7543           || sym_hashes[r_symndx - extsymoff] == NULL)
7544         {
7545           asection *o;
7546
7547           /* This stub is for a local symbol.  This stub will only be
7548              needed if there is some relocation in this BFD, other
7549              than a 16 bit function call, which refers to this symbol.  */
7550           for (o = abfd->sections; o != NULL; o = o->next)
7551             {
7552               Elf_Internal_Rela *sec_relocs;
7553               const Elf_Internal_Rela *r, *rend;
7554
7555               /* We can ignore stub sections when looking for relocs.  */
7556               if ((o->flags & SEC_RELOC) == 0
7557                   || o->reloc_count == 0
7558                   || section_allows_mips16_refs_p (o))
7559                 continue;
7560
7561               sec_relocs
7562                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7563                                              info->keep_memory);
7564               if (sec_relocs == NULL)
7565                 return FALSE;
7566
7567               rend = sec_relocs + o->reloc_count;
7568               for (r = sec_relocs; r < rend; r++)
7569                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7570                     && !mips16_call_reloc_p (ELF_R_TYPE (abfd, r->r_info)))
7571                   break;
7572
7573               if (elf_section_data (o)->relocs != sec_relocs)
7574                 free (sec_relocs);
7575
7576               if (r < rend)
7577                 break;
7578             }
7579
7580           if (o == NULL)
7581             {
7582               /* There is no non-call reloc for this stub, so we do
7583                  not need it.  Since this function is called before
7584                  the linker maps input sections to output sections, we
7585                  can easily discard it by setting the SEC_EXCLUDE
7586                  flag.  */
7587               sec->flags |= SEC_EXCLUDE;
7588               return TRUE;
7589             }
7590
7591           /* Record this stub in an array of local symbol stubs for
7592              this BFD.  */
7593           if (elf_tdata (abfd)->local_stubs == NULL)
7594             {
7595               unsigned long symcount;
7596               asection **n;
7597               bfd_size_type amt;
7598
7599               if (elf_bad_symtab (abfd))
7600                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7601               else
7602                 symcount = symtab_hdr->sh_info;
7603               amt = symcount * sizeof (asection *);
7604               n = bfd_zalloc (abfd, amt);
7605               if (n == NULL)
7606                 return FALSE;
7607               elf_tdata (abfd)->local_stubs = n;
7608             }
7609
7610           sec->flags |= SEC_KEEP;
7611           elf_tdata (abfd)->local_stubs[r_symndx] = sec;
7612
7613           /* We don't need to set mips16_stubs_seen in this case.
7614              That flag is used to see whether we need to look through
7615              the global symbol table for stubs.  We don't need to set
7616              it here, because we just have a local stub.  */
7617         }
7618       else
7619         {
7620           struct mips_elf_link_hash_entry *h;
7621
7622           h = ((struct mips_elf_link_hash_entry *)
7623                sym_hashes[r_symndx - extsymoff]);
7624
7625           while (h->root.root.type == bfd_link_hash_indirect
7626                  || h->root.root.type == bfd_link_hash_warning)
7627             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
7628
7629           /* H is the symbol this stub is for.  */
7630
7631           /* If we already have an appropriate stub for this function, we
7632              don't need another one, so we can discard this one.  Since
7633              this function is called before the linker maps input sections
7634              to output sections, we can easily discard it by setting the
7635              SEC_EXCLUDE flag.  */
7636           if (h->fn_stub != NULL)
7637             {
7638               sec->flags |= SEC_EXCLUDE;
7639               return TRUE;
7640             }
7641
7642           sec->flags |= SEC_KEEP;
7643           h->fn_stub = sec;
7644           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7645         }
7646     }
7647   else if (CALL_STUB_P (name) || CALL_FP_STUB_P (name))
7648     {
7649       unsigned long r_symndx;
7650       struct mips_elf_link_hash_entry *h;
7651       asection **loc;
7652
7653       /* Look at the relocation information to figure out which symbol
7654          this is for.  */
7655
7656       r_symndx = mips16_stub_symndx (bed, sec, relocs, rel_end);
7657       if (r_symndx == 0)
7658         {
7659           (*_bfd_error_handler)
7660             (_("%B: Warning: cannot determine the target function for"
7661                " stub section `%s'"),
7662              abfd, name);
7663           bfd_set_error (bfd_error_bad_value);
7664           return FALSE;
7665         }
7666
7667       if (r_symndx < extsymoff
7668           || sym_hashes[r_symndx - extsymoff] == NULL)
7669         {
7670           asection *o;
7671
7672           /* This stub is for a local symbol.  This stub will only be
7673              needed if there is some relocation (R_MIPS16_26) in this BFD
7674              that refers to this symbol.  */
7675           for (o = abfd->sections; o != NULL; o = o->next)
7676             {
7677               Elf_Internal_Rela *sec_relocs;
7678               const Elf_Internal_Rela *r, *rend;
7679
7680               /* We can ignore stub sections when looking for relocs.  */
7681               if ((o->flags & SEC_RELOC) == 0
7682                   || o->reloc_count == 0
7683                   || section_allows_mips16_refs_p (o))
7684                 continue;
7685
7686               sec_relocs
7687                 = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
7688                                              info->keep_memory);
7689               if (sec_relocs == NULL)
7690                 return FALSE;
7691
7692               rend = sec_relocs + o->reloc_count;
7693               for (r = sec_relocs; r < rend; r++)
7694                 if (ELF_R_SYM (abfd, r->r_info) == r_symndx
7695                     && ELF_R_TYPE (abfd, r->r_info) == R_MIPS16_26)
7696                     break;
7697
7698               if (elf_section_data (o)->relocs != sec_relocs)
7699                 free (sec_relocs);
7700
7701               if (r < rend)
7702                 break;
7703             }
7704
7705           if (o == NULL)
7706             {
7707               /* There is no non-call reloc for this stub, so we do
7708                  not need it.  Since this function is called before
7709                  the linker maps input sections to output sections, we
7710                  can easily discard it by setting the SEC_EXCLUDE
7711                  flag.  */
7712               sec->flags |= SEC_EXCLUDE;
7713               return TRUE;
7714             }
7715
7716           /* Record this stub in an array of local symbol call_stubs for
7717              this BFD.  */
7718           if (elf_tdata (abfd)->local_call_stubs == NULL)
7719             {
7720               unsigned long symcount;
7721               asection **n;
7722               bfd_size_type amt;
7723
7724               if (elf_bad_symtab (abfd))
7725                 symcount = NUM_SHDR_ENTRIES (symtab_hdr);
7726               else
7727                 symcount = symtab_hdr->sh_info;
7728               amt = symcount * sizeof (asection *);
7729               n = bfd_zalloc (abfd, amt);
7730               if (n == NULL)
7731                 return FALSE;
7732               elf_tdata (abfd)->local_call_stubs = n;
7733             }
7734
7735           sec->flags |= SEC_KEEP;
7736           elf_tdata (abfd)->local_call_stubs[r_symndx] = sec;
7737
7738           /* We don't need to set mips16_stubs_seen in this case.
7739              That flag is used to see whether we need to look through
7740              the global symbol table for stubs.  We don't need to set
7741              it here, because we just have a local stub.  */
7742         }
7743       else
7744         {
7745           h = ((struct mips_elf_link_hash_entry *)
7746                sym_hashes[r_symndx - extsymoff]);
7747
7748           /* H is the symbol this stub is for.  */
7749
7750           if (CALL_FP_STUB_P (name))
7751             loc = &h->call_fp_stub;
7752           else
7753             loc = &h->call_stub;
7754
7755           /* If we already have an appropriate stub for this function, we
7756              don't need another one, so we can discard this one.  Since
7757              this function is called before the linker maps input sections
7758              to output sections, we can easily discard it by setting the
7759              SEC_EXCLUDE flag.  */
7760           if (*loc != NULL)
7761             {
7762               sec->flags |= SEC_EXCLUDE;
7763               return TRUE;
7764             }
7765
7766           sec->flags |= SEC_KEEP;
7767           *loc = sec;
7768           mips_elf_hash_table (info)->mips16_stubs_seen = TRUE;
7769         }
7770     }
7771
7772   sreloc = NULL;
7773   contents = NULL;
7774   for (rel = relocs; rel < rel_end; ++rel)
7775     {
7776       unsigned long r_symndx;
7777       unsigned int r_type;
7778       struct elf_link_hash_entry *h;
7779       bfd_boolean can_make_dynamic_p;
7780
7781       r_symndx = ELF_R_SYM (abfd, rel->r_info);
7782       r_type = ELF_R_TYPE (abfd, rel->r_info);
7783
7784       if (r_symndx < extsymoff)
7785         h = NULL;
7786       else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
7787         {
7788           (*_bfd_error_handler)
7789             (_("%B: Malformed reloc detected for section %s"),
7790              abfd, name);
7791           bfd_set_error (bfd_error_bad_value);
7792           return FALSE;
7793         }
7794       else
7795         {
7796           h = sym_hashes[r_symndx - extsymoff];
7797           while (h != NULL
7798                  && (h->root.type == bfd_link_hash_indirect
7799                      || h->root.type == bfd_link_hash_warning))
7800             h = (struct elf_link_hash_entry *) h->root.u.i.link;
7801         }
7802
7803       /* Set CAN_MAKE_DYNAMIC_P to true if we can convert this
7804          relocation into a dynamic one.  */
7805       can_make_dynamic_p = FALSE;
7806       switch (r_type)
7807         {
7808         case R_MIPS_GOT16:
7809         case R_MIPS_CALL16:
7810         case R_MIPS_CALL_HI16:
7811         case R_MIPS_CALL_LO16:
7812         case R_MIPS_GOT_HI16:
7813         case R_MIPS_GOT_LO16:
7814         case R_MIPS_GOT_PAGE:
7815         case R_MIPS_GOT_OFST:
7816         case R_MIPS_GOT_DISP:
7817         case R_MIPS_TLS_GOTTPREL:
7818         case R_MIPS_TLS_GD:
7819         case R_MIPS_TLS_LDM:
7820         case R_MIPS16_GOT16:
7821         case R_MIPS16_CALL16:
7822         case R_MIPS16_TLS_GOTTPREL:
7823         case R_MIPS16_TLS_GD:
7824         case R_MIPS16_TLS_LDM:
7825         case R_MICROMIPS_GOT16:
7826         case R_MICROMIPS_CALL16:
7827         case R_MICROMIPS_CALL_HI16:
7828         case R_MICROMIPS_CALL_LO16:
7829         case R_MICROMIPS_GOT_HI16:
7830         case R_MICROMIPS_GOT_LO16:
7831         case R_MICROMIPS_GOT_PAGE:
7832         case R_MICROMIPS_GOT_OFST:
7833         case R_MICROMIPS_GOT_DISP:
7834         case R_MICROMIPS_TLS_GOTTPREL:
7835         case R_MICROMIPS_TLS_GD:
7836         case R_MICROMIPS_TLS_LDM:
7837           if (dynobj == NULL)
7838             elf_hash_table (info)->dynobj = dynobj = abfd;
7839           if (!mips_elf_create_got_section (dynobj, info))
7840             return FALSE;
7841           if (htab->is_vxworks && !info->shared)
7842             {
7843               (*_bfd_error_handler)
7844                 (_("%B: GOT reloc at 0x%lx not expected in executables"),
7845                  abfd, (unsigned long) rel->r_offset);
7846               bfd_set_error (bfd_error_bad_value);
7847               return FALSE;
7848             }
7849           break;
7850
7851           /* This is just a hint; it can safely be ignored.  Don't set
7852              has_static_relocs for the corresponding symbol.  */
7853         case R_MIPS_JALR:
7854         case R_MICROMIPS_JALR:
7855           break;
7856
7857         case R_MIPS_32:
7858         case R_MIPS_REL32:
7859         case R_MIPS_64:
7860           /* In VxWorks executables, references to external symbols
7861              must be handled using copy relocs or PLT entries; it is not
7862              possible to convert this relocation into a dynamic one.
7863
7864              For executables that use PLTs and copy-relocs, we have a
7865              choice between converting the relocation into a dynamic
7866              one or using copy relocations or PLT entries.  It is
7867              usually better to do the former, unless the relocation is
7868              against a read-only section.  */
7869           if ((info->shared
7870                || (h != NULL
7871                    && !htab->is_vxworks
7872                    && strcmp (h->root.root.string, "__gnu_local_gp") != 0
7873                    && !(!info->nocopyreloc
7874                         && !PIC_OBJECT_P (abfd)
7875                         && MIPS_ELF_READONLY_SECTION (sec))))
7876               && (sec->flags & SEC_ALLOC) != 0)
7877             {
7878               can_make_dynamic_p = TRUE;
7879               if (dynobj == NULL)
7880                 elf_hash_table (info)->dynobj = dynobj = abfd;
7881               break;
7882             }
7883           /* For sections that are not SEC_ALLOC a copy reloc would be
7884              output if possible (implying questionable semantics for
7885              read-only data objects) or otherwise the final link would
7886              fail as ld.so will not process them and could not therefore
7887              handle any outstanding dynamic relocations.
7888
7889              For such sections that are also SEC_DEBUGGING, we can avoid
7890              these problems by simply ignoring any relocs as these
7891              sections have a predefined use and we know it is safe to do
7892              so.
7893
7894              This is needed in cases such as a global symbol definition
7895              in a shared library causing a common symbol from an object
7896              file to be converted to an undefined reference.  If that
7897              happens, then all the relocations against this symbol from
7898              SEC_DEBUGGING sections in the object file will resolve to
7899              nil.  */
7900           if ((sec->flags & SEC_DEBUGGING) != 0)
7901             break;
7902           /* Fall through.  */
7903
7904         default:
7905           /* Most static relocations require pointer equality, except
7906              for branches.  */
7907           if (h)
7908             h->pointer_equality_needed = TRUE;
7909           /* Fall through.  */
7910
7911         case R_MIPS_26:
7912         case R_MIPS_PC16:
7913         case R_MIPS16_26:
7914         case R_MICROMIPS_26_S1:
7915         case R_MICROMIPS_PC7_S1:
7916         case R_MICROMIPS_PC10_S1:
7917         case R_MICROMIPS_PC16_S1:
7918         case R_MICROMIPS_PC23_S2:
7919           if (h)
7920             ((struct mips_elf_link_hash_entry *) h)->has_static_relocs = TRUE;
7921           break;
7922         }
7923
7924       if (h)
7925         {
7926           /* Relocations against the special VxWorks __GOTT_BASE__ and
7927              __GOTT_INDEX__ symbols must be left to the loader.  Allocate
7928              room for them in .rela.dyn.  */
7929           if (is_gott_symbol (info, h))
7930             {
7931               if (sreloc == NULL)
7932                 {
7933                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
7934                   if (sreloc == NULL)
7935                     return FALSE;
7936                 }
7937               mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
7938               if (MIPS_ELF_READONLY_SECTION (sec))
7939                 /* We tell the dynamic linker that there are
7940                    relocations against the text segment.  */
7941                 info->flags |= DF_TEXTREL;
7942             }
7943         }
7944       else if (call_lo16_reloc_p (r_type)
7945                || got_lo16_reloc_p (r_type)
7946                || got_disp_reloc_p (r_type)
7947                || (got16_reloc_p (r_type) && htab->is_vxworks))
7948         {
7949           /* We may need a local GOT entry for this relocation.  We
7950              don't count R_MIPS_GOT_PAGE because we can estimate the
7951              maximum number of pages needed by looking at the size of
7952              the segment.  Similar comments apply to R_MIPS*_GOT16 and
7953              R_MIPS*_CALL16, except on VxWorks, where GOT relocations
7954              always evaluate to "G".  We don't count R_MIPS_GOT_HI16, or
7955              R_MIPS_CALL_HI16 because these are always followed by an
7956              R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16.  */
7957           if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
7958                                                  rel->r_addend, info, r_type))
7959             return FALSE;
7960         }
7961
7962       if (h != NULL
7963           && mips_elf_relocation_needs_la25_stub (abfd, r_type,
7964                                                   ELF_ST_IS_MIPS16 (h->other)))
7965         ((struct mips_elf_link_hash_entry *) h)->has_nonpic_branches = TRUE;
7966
7967       switch (r_type)
7968         {
7969         case R_MIPS_CALL16:
7970         case R_MIPS16_CALL16:
7971         case R_MICROMIPS_CALL16:
7972           if (h == NULL)
7973             {
7974               (*_bfd_error_handler)
7975                 (_("%B: CALL16 reloc at 0x%lx not against global symbol"),
7976                  abfd, (unsigned long) rel->r_offset);
7977               bfd_set_error (bfd_error_bad_value);
7978               return FALSE;
7979             }
7980           /* Fall through.  */
7981
7982         case R_MIPS_CALL_HI16:
7983         case R_MIPS_CALL_LO16:
7984         case R_MICROMIPS_CALL_HI16:
7985         case R_MICROMIPS_CALL_LO16:
7986           if (h != NULL)
7987             {
7988               /* Make sure there is room in the regular GOT to hold the
7989                  function's address.  We may eliminate it in favour of
7990                  a .got.plt entry later; see mips_elf_count_got_symbols.  */
7991               if (!mips_elf_record_global_got_symbol (h, abfd, info, TRUE,
7992                                                       r_type))
7993                 return FALSE;
7994
7995               /* We need a stub, not a plt entry for the undefined
7996                  function.  But we record it as if it needs plt.  See
7997                  _bfd_elf_adjust_dynamic_symbol.  */
7998               h->needs_plt = 1;
7999               h->type = STT_FUNC;
8000             }
8001           break;
8002
8003         case R_MIPS_GOT_PAGE:
8004         case R_MICROMIPS_GOT_PAGE:
8005         case R_MIPS16_GOT16:
8006         case R_MIPS_GOT16:
8007         case R_MIPS_GOT_HI16:
8008         case R_MIPS_GOT_LO16:
8009         case R_MICROMIPS_GOT16:
8010         case R_MICROMIPS_GOT_HI16:
8011         case R_MICROMIPS_GOT_LO16:
8012           if (!h || got_page_reloc_p (r_type))
8013             {
8014               /* This relocation needs (or may need, if h != NULL) a
8015                  page entry in the GOT.  For R_MIPS_GOT_PAGE we do not
8016                  know for sure until we know whether the symbol is
8017                  preemptible.  */
8018               if (mips_elf_rel_relocation_p (abfd, sec, relocs, rel))
8019                 {
8020                   if (!mips_elf_get_section_contents (abfd, sec, &contents))
8021                     return FALSE;
8022                   howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8023                   addend = mips_elf_read_rel_addend (abfd, rel,
8024                                                      howto, contents);
8025                   if (got16_reloc_p (r_type))
8026                     mips_elf_add_lo16_rel_addend (abfd, rel, rel_end,
8027                                                   contents, &addend);
8028                   else
8029                     addend <<= howto->rightshift;
8030                 }
8031               else
8032                 addend = rel->r_addend;
8033               if (!mips_elf_record_got_page_ref (info, abfd, r_symndx,
8034                                                  h, addend))
8035                 return FALSE;
8036
8037               if (h)
8038                 {
8039                   struct mips_elf_link_hash_entry *hmips =
8040                     (struct mips_elf_link_hash_entry *) h;
8041
8042                   /* This symbol is definitely not overridable.  */
8043                   if (hmips->root.def_regular
8044                       && ! (info->shared && ! info->symbolic
8045                             && ! hmips->root.forced_local))
8046                     h = NULL;
8047                 }
8048             }
8049           /* If this is a global, overridable symbol, GOT_PAGE will
8050              decay to GOT_DISP, so we'll need a GOT entry for it.  */
8051           /* Fall through.  */
8052
8053         case R_MIPS_GOT_DISP:
8054         case R_MICROMIPS_GOT_DISP:
8055           if (h && !mips_elf_record_global_got_symbol (h, abfd, info,
8056                                                        FALSE, r_type))
8057             return FALSE;
8058           break;
8059
8060         case R_MIPS_TLS_GOTTPREL:
8061         case R_MIPS16_TLS_GOTTPREL:
8062         case R_MICROMIPS_TLS_GOTTPREL:
8063           if (info->shared)
8064             info->flags |= DF_STATIC_TLS;
8065           /* Fall through */
8066
8067         case R_MIPS_TLS_LDM:
8068         case R_MIPS16_TLS_LDM:
8069         case R_MICROMIPS_TLS_LDM:
8070           if (tls_ldm_reloc_p (r_type))
8071             {
8072               r_symndx = STN_UNDEF;
8073               h = NULL;
8074             }
8075           /* Fall through */
8076
8077         case R_MIPS_TLS_GD:
8078         case R_MIPS16_TLS_GD:
8079         case R_MICROMIPS_TLS_GD:
8080           /* This symbol requires a global offset table entry, or two
8081              for TLS GD relocations.  */
8082           if (h != NULL)
8083             {
8084               if (!mips_elf_record_global_got_symbol (h, abfd, info,
8085                                                       FALSE, r_type))
8086                 return FALSE;
8087             }
8088           else
8089             {
8090               if (!mips_elf_record_local_got_symbol (abfd, r_symndx,
8091                                                      rel->r_addend,
8092                                                      info, r_type))
8093                 return FALSE;
8094             }
8095           break;
8096
8097         case R_MIPS_32:
8098         case R_MIPS_REL32:
8099         case R_MIPS_64:
8100           /* In VxWorks executables, references to external symbols
8101              are handled using copy relocs or PLT stubs, so there's
8102              no need to add a .rela.dyn entry for this relocation.  */
8103           if (can_make_dynamic_p)
8104             {
8105               if (sreloc == NULL)
8106                 {
8107                   sreloc = mips_elf_rel_dyn_section (info, TRUE);
8108                   if (sreloc == NULL)
8109                     return FALSE;
8110                 }
8111               if (info->shared && h == NULL)
8112                 {
8113                   /* When creating a shared object, we must copy these
8114                      reloc types into the output file as R_MIPS_REL32
8115                      relocs.  Make room for this reloc in .rel(a).dyn.  */
8116                   mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8117                   if (MIPS_ELF_READONLY_SECTION (sec))
8118                     /* We tell the dynamic linker that there are
8119                        relocations against the text segment.  */
8120                     info->flags |= DF_TEXTREL;
8121                 }
8122               else
8123                 {
8124                   struct mips_elf_link_hash_entry *hmips;
8125
8126                   /* For a shared object, we must copy this relocation
8127                      unless the symbol turns out to be undefined and
8128                      weak with non-default visibility, in which case
8129                      it will be left as zero.
8130
8131                      We could elide R_MIPS_REL32 for locally binding symbols
8132                      in shared libraries, but do not yet do so.
8133
8134                      For an executable, we only need to copy this
8135                      reloc if the symbol is defined in a dynamic
8136                      object.  */
8137                   hmips = (struct mips_elf_link_hash_entry *) h;
8138                   ++hmips->possibly_dynamic_relocs;
8139                   if (MIPS_ELF_READONLY_SECTION (sec))
8140                     /* We need it to tell the dynamic linker if there
8141                        are relocations against the text segment.  */
8142                     hmips->readonly_reloc = TRUE;
8143                 }
8144             }
8145
8146           if (SGI_COMPAT (abfd))
8147             mips_elf_hash_table (info)->compact_rel_size +=
8148               sizeof (Elf32_External_crinfo);
8149           break;
8150
8151         case R_MIPS_26:
8152         case R_MIPS_GPREL16:
8153         case R_MIPS_LITERAL:
8154         case R_MIPS_GPREL32:
8155         case R_MICROMIPS_26_S1:
8156         case R_MICROMIPS_GPREL16:
8157         case R_MICROMIPS_LITERAL:
8158         case R_MICROMIPS_GPREL7_S2:
8159           if (SGI_COMPAT (abfd))
8160             mips_elf_hash_table (info)->compact_rel_size +=
8161               sizeof (Elf32_External_crinfo);
8162           break;
8163
8164           /* This relocation describes the C++ object vtable hierarchy.
8165              Reconstruct it for later use during GC.  */
8166         case R_MIPS_GNU_VTINHERIT:
8167           if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
8168             return FALSE;
8169           break;
8170
8171           /* This relocation describes which C++ vtable entries are actually
8172              used.  Record for later use during GC.  */
8173         case R_MIPS_GNU_VTENTRY:
8174           BFD_ASSERT (h != NULL);
8175           if (h != NULL
8176               && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
8177             return FALSE;
8178           break;
8179
8180         default:
8181           break;
8182         }
8183
8184       /* We must not create a stub for a symbol that has relocations
8185          related to taking the function's address.  This doesn't apply to
8186          VxWorks, where CALL relocs refer to a .got.plt entry instead of
8187          a normal .got entry.  */
8188       if (!htab->is_vxworks && h != NULL)
8189         switch (r_type)
8190           {
8191           default:
8192             ((struct mips_elf_link_hash_entry *) h)->no_fn_stub = TRUE;
8193             break;
8194           case R_MIPS16_CALL16:
8195           case R_MIPS_CALL16:
8196           case R_MIPS_CALL_HI16:
8197           case R_MIPS_CALL_LO16:
8198           case R_MIPS_JALR:
8199           case R_MICROMIPS_CALL16:
8200           case R_MICROMIPS_CALL_HI16:
8201           case R_MICROMIPS_CALL_LO16:
8202           case R_MICROMIPS_JALR:
8203             break;
8204           }
8205
8206       /* See if this reloc would need to refer to a MIPS16 hard-float stub,
8207          if there is one.  We only need to handle global symbols here;
8208          we decide whether to keep or delete stubs for local symbols
8209          when processing the stub's relocations.  */
8210       if (h != NULL
8211           && !mips16_call_reloc_p (r_type)
8212           && !section_allows_mips16_refs_p (sec))
8213         {
8214           struct mips_elf_link_hash_entry *mh;
8215
8216           mh = (struct mips_elf_link_hash_entry *) h;
8217           mh->need_fn_stub = TRUE;
8218         }
8219
8220       /* Refuse some position-dependent relocations when creating a
8221          shared library.  Do not refuse R_MIPS_32 / R_MIPS_64; they're
8222          not PIC, but we can create dynamic relocations and the result
8223          will be fine.  Also do not refuse R_MIPS_LO16, which can be
8224          combined with R_MIPS_GOT16.  */
8225       if (info->shared)
8226         {
8227           switch (r_type)
8228             {
8229             case R_MIPS16_HI16:
8230             case R_MIPS_HI16:
8231             case R_MIPS_HIGHER:
8232             case R_MIPS_HIGHEST:
8233             case R_MICROMIPS_HI16:
8234             case R_MICROMIPS_HIGHER:
8235             case R_MICROMIPS_HIGHEST:
8236               /* Don't refuse a high part relocation if it's against
8237                  no symbol (e.g. part of a compound relocation).  */
8238               if (r_symndx == STN_UNDEF)
8239                 break;
8240
8241               /* R_MIPS_HI16 against _gp_disp is used for $gp setup,
8242                  and has a special meaning.  */
8243               if (!NEWABI_P (abfd) && h != NULL
8244                   && strcmp (h->root.root.string, "_gp_disp") == 0)
8245                 break;
8246
8247               /* Likewise __GOTT_BASE__ and __GOTT_INDEX__ on VxWorks.  */
8248               if (is_gott_symbol (info, h))
8249                 break;
8250
8251               /* FALLTHROUGH */
8252
8253             case R_MIPS16_26:
8254             case R_MIPS_26:
8255             case R_MICROMIPS_26_S1:
8256               howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, FALSE);
8257               (*_bfd_error_handler)
8258                 (_("%B: relocation %s against `%s' can not be used when making a shared object; recompile with -fPIC"),
8259                  abfd, howto->name,
8260                  (h) ? h->root.root.string : "a local symbol");
8261               bfd_set_error (bfd_error_bad_value);
8262               return FALSE;
8263             default:
8264               break;
8265             }
8266         }
8267     }
8268
8269   return TRUE;
8270 }
8271 \f
8272 bfd_boolean
8273 _bfd_mips_relax_section (bfd *abfd, asection *sec,
8274                          struct bfd_link_info *link_info,
8275                          bfd_boolean *again)
8276 {
8277   Elf_Internal_Rela *internal_relocs;
8278   Elf_Internal_Rela *irel, *irelend;
8279   Elf_Internal_Shdr *symtab_hdr;
8280   bfd_byte *contents = NULL;
8281   size_t extsymoff;
8282   bfd_boolean changed_contents = FALSE;
8283   bfd_vma sec_start = sec->output_section->vma + sec->output_offset;
8284   Elf_Internal_Sym *isymbuf = NULL;
8285
8286   /* We are not currently changing any sizes, so only one pass.  */
8287   *again = FALSE;
8288
8289   if (link_info->relocatable)
8290     return TRUE;
8291
8292   internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
8293                                                link_info->keep_memory);
8294   if (internal_relocs == NULL)
8295     return TRUE;
8296
8297   irelend = internal_relocs + sec->reloc_count
8298     * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel;
8299   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
8300   extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
8301
8302   for (irel = internal_relocs; irel < irelend; irel++)
8303     {
8304       bfd_vma symval;
8305       bfd_signed_vma sym_offset;
8306       unsigned int r_type;
8307       unsigned long r_symndx;
8308       asection *sym_sec;
8309       unsigned long instruction;
8310
8311       /* Turn jalr into bgezal, and jr into beq, if they're marked
8312          with a JALR relocation, that indicate where they jump to.
8313          This saves some pipeline bubbles.  */
8314       r_type = ELF_R_TYPE (abfd, irel->r_info);
8315       if (r_type != R_MIPS_JALR)
8316         continue;
8317
8318       r_symndx = ELF_R_SYM (abfd, irel->r_info);
8319       /* Compute the address of the jump target.  */
8320       if (r_symndx >= extsymoff)
8321         {
8322           struct mips_elf_link_hash_entry *h
8323             = ((struct mips_elf_link_hash_entry *)
8324                elf_sym_hashes (abfd) [r_symndx - extsymoff]);
8325
8326           while (h->root.root.type == bfd_link_hash_indirect
8327                  || h->root.root.type == bfd_link_hash_warning)
8328             h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link;
8329
8330           /* If a symbol is undefined, or if it may be overridden,
8331              skip it.  */
8332           if (! ((h->root.root.type == bfd_link_hash_defined
8333                   || h->root.root.type == bfd_link_hash_defweak)
8334                  && h->root.root.u.def.section)
8335               || (link_info->shared && ! link_info->symbolic
8336                   && !h->root.forced_local))
8337             continue;
8338
8339           sym_sec = h->root.root.u.def.section;
8340           if (sym_sec->output_section)
8341             symval = (h->root.root.u.def.value
8342                       + sym_sec->output_section->vma
8343                       + sym_sec->output_offset);
8344           else
8345             symval = h->root.root.u.def.value;
8346         }
8347       else
8348         {
8349           Elf_Internal_Sym *isym;
8350
8351           /* Read this BFD's symbols if we haven't done so already.  */
8352           if (isymbuf == NULL && symtab_hdr->sh_info != 0)
8353             {
8354               isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8355               if (isymbuf == NULL)
8356                 isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
8357                                                 symtab_hdr->sh_info, 0,
8358                                                 NULL, NULL, NULL);
8359               if (isymbuf == NULL)
8360                 goto relax_return;
8361             }
8362
8363           isym = isymbuf + r_symndx;
8364           if (isym->st_shndx == SHN_UNDEF)
8365             continue;
8366           else if (isym->st_shndx == SHN_ABS)
8367             sym_sec = bfd_abs_section_ptr;
8368           else if (isym->st_shndx == SHN_COMMON)
8369             sym_sec = bfd_com_section_ptr;
8370           else
8371             sym_sec
8372               = bfd_section_from_elf_index (abfd, isym->st_shndx);
8373           symval = isym->st_value
8374             + sym_sec->output_section->vma
8375             + sym_sec->output_offset;
8376         }
8377
8378       /* Compute branch offset, from delay slot of the jump to the
8379          branch target.  */
8380       sym_offset = (symval + irel->r_addend)
8381         - (sec_start + irel->r_offset + 4);
8382
8383       /* Branch offset must be properly aligned.  */
8384       if ((sym_offset & 3) != 0)
8385         continue;
8386
8387       sym_offset >>= 2;
8388
8389       /* Check that it's in range.  */
8390       if (sym_offset < -0x8000 || sym_offset >= 0x8000)
8391         continue;
8392
8393       /* Get the section contents if we haven't done so already.  */
8394       if (!mips_elf_get_section_contents (abfd, sec, &contents))
8395         goto relax_return;
8396
8397       instruction = bfd_get_32 (abfd, contents + irel->r_offset);
8398
8399       /* If it was jalr <reg>, turn it into bgezal $zero, <target>.  */
8400       if ((instruction & 0xfc1fffff) == 0x0000f809)
8401         instruction = 0x04110000;
8402       /* If it was jr <reg>, turn it into b <target>.  */
8403       else if ((instruction & 0xfc1fffff) == 0x00000008)
8404         instruction = 0x10000000;
8405       else
8406         continue;
8407
8408       instruction |= (sym_offset & 0xffff);
8409       bfd_put_32 (abfd, instruction, contents + irel->r_offset);
8410       changed_contents = TRUE;
8411     }
8412
8413   if (contents != NULL
8414       && elf_section_data (sec)->this_hdr.contents != contents)
8415     {
8416       if (!changed_contents && !link_info->keep_memory)
8417         free (contents);
8418       else
8419         {
8420           /* Cache the section contents for elf_link_input_bfd.  */
8421           elf_section_data (sec)->this_hdr.contents = contents;
8422         }
8423     }
8424   return TRUE;
8425
8426  relax_return:
8427   if (contents != NULL
8428       && elf_section_data (sec)->this_hdr.contents != contents)
8429     free (contents);
8430   return FALSE;
8431 }
8432 \f
8433 /* Allocate space for global sym dynamic relocs.  */
8434
8435 static bfd_boolean
8436 allocate_dynrelocs (struct elf_link_hash_entry *h, void *inf)
8437 {
8438   struct bfd_link_info *info = inf;
8439   bfd *dynobj;
8440   struct mips_elf_link_hash_entry *hmips;
8441   struct mips_elf_link_hash_table *htab;
8442
8443   htab = mips_elf_hash_table (info);
8444   BFD_ASSERT (htab != NULL);
8445
8446   dynobj = elf_hash_table (info)->dynobj;
8447   hmips = (struct mips_elf_link_hash_entry *) h;
8448
8449   /* VxWorks executables are handled elsewhere; we only need to
8450      allocate relocations in shared objects.  */
8451   if (htab->is_vxworks && !info->shared)
8452     return TRUE;
8453
8454   /* Ignore indirect symbols.  All relocations against such symbols
8455      will be redirected to the target symbol.  */
8456   if (h->root.type == bfd_link_hash_indirect)
8457     return TRUE;
8458
8459   /* If this symbol is defined in a dynamic object, or we are creating
8460      a shared library, we will need to copy any R_MIPS_32 or
8461      R_MIPS_REL32 relocs against it into the output file.  */
8462   if (! info->relocatable
8463       && hmips->possibly_dynamic_relocs != 0
8464       && (h->root.type == bfd_link_hash_defweak
8465           || (!h->def_regular && !ELF_COMMON_DEF_P (h))
8466           || info->shared))
8467     {
8468       bfd_boolean do_copy = TRUE;
8469
8470       if (h->root.type == bfd_link_hash_undefweak)
8471         {
8472           /* Do not copy relocations for undefined weak symbols with
8473              non-default visibility.  */
8474           if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
8475             do_copy = FALSE;
8476
8477           /* Make sure undefined weak symbols are output as a dynamic
8478              symbol in PIEs.  */
8479           else if (h->dynindx == -1 && !h->forced_local)
8480             {
8481               if (! bfd_elf_link_record_dynamic_symbol (info, h))
8482                 return FALSE;
8483             }
8484         }
8485
8486       if (do_copy)
8487         {
8488           /* Even though we don't directly need a GOT entry for this symbol,
8489              the SVR4 psABI requires it to have a dynamic symbol table
8490              index greater that DT_MIPS_GOTSYM if there are dynamic
8491              relocations against it.
8492
8493              VxWorks does not enforce the same mapping between the GOT
8494              and the symbol table, so the same requirement does not
8495              apply there.  */
8496           if (!htab->is_vxworks)
8497             {
8498               if (hmips->global_got_area > GGA_RELOC_ONLY)
8499                 hmips->global_got_area = GGA_RELOC_ONLY;
8500               hmips->got_only_for_calls = FALSE;
8501             }
8502
8503           mips_elf_allocate_dynamic_relocations
8504             (dynobj, info, hmips->possibly_dynamic_relocs);
8505           if (hmips->readonly_reloc)
8506             /* We tell the dynamic linker that there are relocations
8507                against the text segment.  */
8508             info->flags |= DF_TEXTREL;
8509         }
8510     }
8511
8512   return TRUE;
8513 }
8514
8515 /* Adjust a symbol defined by a dynamic object and referenced by a
8516    regular object.  The current definition is in some section of the
8517    dynamic object, but we're not including those sections.  We have to
8518    change the definition to something the rest of the link can
8519    understand.  */
8520
8521 bfd_boolean
8522 _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
8523                                      struct elf_link_hash_entry *h)
8524 {
8525   bfd *dynobj;
8526   struct mips_elf_link_hash_entry *hmips;
8527   struct mips_elf_link_hash_table *htab;
8528
8529   htab = mips_elf_hash_table (info);
8530   BFD_ASSERT (htab != NULL);
8531
8532   dynobj = elf_hash_table (info)->dynobj;
8533   hmips = (struct mips_elf_link_hash_entry *) h;
8534
8535   /* Make sure we know what is going on here.  */
8536   BFD_ASSERT (dynobj != NULL
8537               && (h->needs_plt
8538                   || h->u.weakdef != NULL
8539                   || (h->def_dynamic
8540                       && h->ref_regular
8541                       && !h->def_regular)));
8542
8543   hmips = (struct mips_elf_link_hash_entry *) h;
8544
8545   /* If there are call relocations against an externally-defined symbol,
8546      see whether we can create a MIPS lazy-binding stub for it.  We can
8547      only do this if all references to the function are through call
8548      relocations, and in that case, the traditional lazy-binding stubs
8549      are much more efficient than PLT entries.
8550
8551      Traditional stubs are only available on SVR4 psABI-based systems;
8552      VxWorks always uses PLTs instead.  */
8553   if (!htab->is_vxworks && h->needs_plt && !hmips->no_fn_stub)
8554     {
8555       if (! elf_hash_table (info)->dynamic_sections_created)
8556         return TRUE;
8557
8558       /* If this symbol is not defined in a regular file, then set
8559          the symbol to the stub location.  This is required to make
8560          function pointers compare as equal between the normal
8561          executable and the shared library.  */
8562       if (!h->def_regular)
8563         {
8564           hmips->needs_lazy_stub = TRUE;
8565           htab->lazy_stub_count++;
8566           return TRUE;
8567         }
8568     }
8569   /* As above, VxWorks requires PLT entries for externally-defined
8570      functions that are only accessed through call relocations.
8571
8572      Both VxWorks and non-VxWorks targets also need PLT entries if there
8573      are static-only relocations against an externally-defined function.
8574      This can technically occur for shared libraries if there are
8575      branches to the symbol, although it is unlikely that this will be
8576      used in practice due to the short ranges involved.  It can occur
8577      for any relative or absolute relocation in executables; in that
8578      case, the PLT entry becomes the function's canonical address.  */
8579   else if (((h->needs_plt && !hmips->no_fn_stub)
8580             || (h->type == STT_FUNC && hmips->has_static_relocs))
8581            && htab->use_plts_and_copy_relocs
8582            && !SYMBOL_CALLS_LOCAL (info, h)
8583            && !(ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
8584                 && h->root.type == bfd_link_hash_undefweak))
8585     {
8586       /* If this is the first symbol to need a PLT entry, allocate room
8587          for the header.  */
8588       if (htab->splt->size == 0)
8589         {
8590           BFD_ASSERT (htab->sgotplt->size == 0);
8591
8592           /* If we're using the PLT additions to the psABI, each PLT
8593              entry is 16 bytes and the PLT0 entry is 32 bytes.
8594              Encourage better cache usage by aligning.  We do this
8595              lazily to avoid pessimizing traditional objects.  */
8596           if (!htab->is_vxworks
8597               && !bfd_set_section_alignment (dynobj, htab->splt, 5))
8598             return FALSE;
8599
8600           /* Make sure that .got.plt is word-aligned.  We do this lazily
8601              for the same reason as above.  */
8602           if (!bfd_set_section_alignment (dynobj, htab->sgotplt,
8603                                           MIPS_ELF_LOG_FILE_ALIGN (dynobj)))
8604             return FALSE;
8605
8606           htab->splt->size += htab->plt_header_size;
8607
8608           /* On non-VxWorks targets, the first two entries in .got.plt
8609              are reserved.  */
8610           if (!htab->is_vxworks)
8611             htab->sgotplt->size
8612               += get_elf_backend_data (dynobj)->got_header_size;
8613
8614           /* On VxWorks, also allocate room for the header's
8615              .rela.plt.unloaded entries.  */
8616           if (htab->is_vxworks && !info->shared)
8617             htab->srelplt2->size += 2 * sizeof (Elf32_External_Rela);
8618         }
8619
8620       /* Assign the next .plt entry to this symbol.  */
8621       h->plt.offset = htab->splt->size;
8622       htab->splt->size += htab->plt_entry_size;
8623
8624       /* If the output file has no definition of the symbol, set the
8625          symbol's value to the address of the stub.  */
8626       if (!info->shared && !h->def_regular)
8627         {
8628           h->root.u.def.section = htab->splt;
8629           h->root.u.def.value = h->plt.offset;
8630           /* For VxWorks, point at the PLT load stub rather than the
8631              lazy resolution stub; this stub will become the canonical
8632              function address.  */
8633           if (htab->is_vxworks)
8634             h->root.u.def.value += 8;
8635         }
8636
8637       /* Make room for the .got.plt entry and the R_MIPS_JUMP_SLOT
8638          relocation.  */
8639       htab->sgotplt->size += MIPS_ELF_GOT_SIZE (dynobj);
8640       htab->srelplt->size += (htab->is_vxworks
8641                               ? MIPS_ELF_RELA_SIZE (dynobj)
8642                               : MIPS_ELF_REL_SIZE (dynobj));
8643
8644       /* Make room for the .rela.plt.unloaded relocations.  */
8645       if (htab->is_vxworks && !info->shared)
8646         htab->srelplt2->size += 3 * sizeof (Elf32_External_Rela);
8647
8648       /* All relocations against this symbol that could have been made
8649          dynamic will now refer to the PLT entry instead.  */
8650       hmips->possibly_dynamic_relocs = 0;
8651
8652       return TRUE;
8653     }
8654
8655   /* If this is a weak symbol, and there is a real definition, the
8656      processor independent code will have arranged for us to see the
8657      real definition first, and we can just use the same value.  */
8658   if (h->u.weakdef != NULL)
8659     {
8660       BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
8661                   || h->u.weakdef->root.type == bfd_link_hash_defweak);
8662       h->root.u.def.section = h->u.weakdef->root.u.def.section;
8663       h->root.u.def.value = h->u.weakdef->root.u.def.value;
8664       return TRUE;
8665     }
8666
8667   /* Otherwise, there is nothing further to do for symbols defined
8668      in regular objects.  */
8669   if (h->def_regular)
8670     return TRUE;
8671
8672   /* There's also nothing more to do if we'll convert all relocations
8673      against this symbol into dynamic relocations.  */
8674   if (!hmips->has_static_relocs)
8675     return TRUE;
8676
8677   /* We're now relying on copy relocations.  Complain if we have
8678      some that we can't convert.  */
8679   if (!htab->use_plts_and_copy_relocs || info->shared)
8680     {
8681       (*_bfd_error_handler) (_("non-dynamic relocations refer to "
8682                                "dynamic symbol %s"),
8683                              h->root.root.string);
8684       bfd_set_error (bfd_error_bad_value);
8685       return FALSE;
8686     }
8687
8688   /* We must allocate the symbol in our .dynbss section, which will
8689      become part of the .bss section of the executable.  There will be
8690      an entry for this symbol in the .dynsym section.  The dynamic
8691      object will contain position independent code, so all references
8692      from the dynamic object to this symbol will go through the global
8693      offset table.  The dynamic linker will use the .dynsym entry to
8694      determine the address it must put in the global offset table, so
8695      both the dynamic object and the regular object will refer to the
8696      same memory location for the variable.  */
8697
8698   if ((h->root.u.def.section->flags & SEC_ALLOC) != 0)
8699     {
8700       if (htab->is_vxworks)
8701         htab->srelbss->size += sizeof (Elf32_External_Rela);
8702       else
8703         mips_elf_allocate_dynamic_relocations (dynobj, info, 1);
8704       h->needs_copy = 1;
8705     }
8706
8707   /* All relocations against this symbol that could have been made
8708      dynamic will now refer to the local copy instead.  */
8709   hmips->possibly_dynamic_relocs = 0;
8710
8711   return _bfd_elf_adjust_dynamic_copy (h, htab->sdynbss);
8712 }
8713 \f
8714 /* This function is called after all the input files have been read,
8715    and the input sections have been assigned to output sections.  We
8716    check for any mips16 stub sections that we can discard.  */
8717
8718 bfd_boolean
8719 _bfd_mips_elf_always_size_sections (bfd *output_bfd,
8720                                     struct bfd_link_info *info)
8721 {
8722   asection *ri;
8723   struct mips_elf_link_hash_table *htab;
8724   struct mips_htab_traverse_info hti;
8725
8726   htab = mips_elf_hash_table (info);
8727   BFD_ASSERT (htab != NULL);
8728
8729   /* The .reginfo section has a fixed size.  */
8730   ri = bfd_get_section_by_name (output_bfd, ".reginfo");
8731   if (ri != NULL)
8732     bfd_set_section_size (output_bfd, ri, sizeof (Elf32_External_RegInfo));
8733
8734   hti.info = info;
8735   hti.output_bfd = output_bfd;
8736   hti.error = FALSE;
8737   mips_elf_link_hash_traverse (mips_elf_hash_table (info),
8738                                mips_elf_check_symbols, &hti);
8739   if (hti.error)
8740     return FALSE;
8741
8742   return TRUE;
8743 }
8744
8745 /* If the link uses a GOT, lay it out and work out its size.  */
8746
8747 static bfd_boolean
8748 mips_elf_lay_out_got (bfd *output_bfd, struct bfd_link_info *info)
8749 {
8750   bfd *dynobj;
8751   asection *s;
8752   struct mips_got_info *g;
8753   bfd_size_type loadable_size = 0;
8754   bfd_size_type page_gotno;
8755   bfd *ibfd;
8756   struct mips_elf_traverse_got_arg tga;
8757   struct mips_elf_link_hash_table *htab;
8758
8759   htab = mips_elf_hash_table (info);
8760   BFD_ASSERT (htab != NULL);
8761
8762   s = htab->sgot;
8763   if (s == NULL)
8764     return TRUE;
8765
8766   dynobj = elf_hash_table (info)->dynobj;
8767   g = htab->got_info;
8768
8769   /* Allocate room for the reserved entries.  VxWorks always reserves
8770      3 entries; other objects only reserve 2 entries.  */
8771   BFD_ASSERT (g->assigned_gotno == 0);
8772   if (htab->is_vxworks)
8773     htab->reserved_gotno = 3;
8774   else
8775     htab->reserved_gotno = 2;
8776   g->local_gotno += htab->reserved_gotno;
8777   g->assigned_gotno = htab->reserved_gotno;
8778
8779   /* Decide which symbols need to go in the global part of the GOT and
8780      count the number of reloc-only GOT symbols.  */
8781   mips_elf_link_hash_traverse (htab, mips_elf_count_got_symbols, info);
8782
8783   if (!mips_elf_resolve_final_got_entries (info, g))
8784     return FALSE;
8785
8786   /* Calculate the total loadable size of the output.  That
8787      will give us the maximum number of GOT_PAGE entries
8788      required.  */
8789   for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
8790     {
8791       asection *subsection;
8792
8793       for (subsection = ibfd->sections;
8794            subsection;
8795            subsection = subsection->next)
8796         {
8797           if ((subsection->flags & SEC_ALLOC) == 0)
8798             continue;
8799           loadable_size += ((subsection->size + 0xf)
8800                             &~ (bfd_size_type) 0xf);
8801         }
8802     }
8803
8804   if (htab->is_vxworks)
8805     /* There's no need to allocate page entries for VxWorks; R_MIPS*_GOT16
8806        relocations against local symbols evaluate to "G", and the EABI does
8807        not include R_MIPS_GOT_PAGE.  */
8808     page_gotno = 0;
8809   else
8810     /* Assume there are two loadable segments consisting of contiguous
8811        sections.  Is 5 enough?  */
8812     page_gotno = (loadable_size >> 16) + 5;
8813
8814   /* Choose the smaller of the two page estimates; both are intended to be
8815      conservative.  */
8816   if (page_gotno > g->page_gotno)
8817     page_gotno = g->page_gotno;
8818
8819   g->local_gotno += page_gotno;
8820
8821   s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8822   s->size += g->global_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8823   s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd);
8824
8825   /* VxWorks does not support multiple GOTs.  It initializes $gp to
8826      __GOTT_BASE__[__GOTT_INDEX__], the value of which is set by the
8827      dynamic loader.  */
8828   if (!htab->is_vxworks && s->size > MIPS_ELF_GOT_MAX_SIZE (info))
8829     {
8830       if (!mips_elf_multi_got (output_bfd, info, s, page_gotno))
8831         return FALSE;
8832     }
8833   else
8834     {
8835       /* Record that all bfds use G.  This also has the effect of freeing
8836          the per-bfd GOTs, which we no longer need.  */
8837       for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link_next)
8838         if (mips_elf_bfd_got (ibfd, FALSE))
8839           mips_elf_replace_bfd_got (ibfd, g);
8840       mips_elf_replace_bfd_got (output_bfd, g);
8841
8842       /* Set up TLS entries.  */
8843       g->tls_assigned_gotno = g->global_gotno + g->local_gotno;
8844       tga.info = info;
8845       tga.g = g;
8846       tga.value = MIPS_ELF_GOT_SIZE (output_bfd);
8847       htab_traverse (g->got_entries, mips_elf_initialize_tls_index, &tga);
8848       if (!tga.g)
8849         return FALSE;
8850       BFD_ASSERT (g->tls_assigned_gotno
8851                   == g->global_gotno + g->local_gotno + g->tls_gotno);
8852
8853       /* Each VxWorks GOT entry needs an explicit relocation.  */
8854       if (htab->is_vxworks && info->shared)
8855         g->relocs += g->global_gotno + g->local_gotno - htab->reserved_gotno;
8856
8857       /* Allocate room for the TLS relocations.  */
8858       if (g->relocs)
8859         mips_elf_allocate_dynamic_relocations (dynobj, info, g->relocs);
8860     }
8861
8862   return TRUE;
8863 }
8864
8865 /* Estimate the size of the .MIPS.stubs section.  */
8866
8867 static void
8868 mips_elf_estimate_stub_size (bfd *output_bfd, struct bfd_link_info *info)
8869 {
8870   struct mips_elf_link_hash_table *htab;
8871   bfd_size_type dynsymcount;
8872
8873   htab = mips_elf_hash_table (info);
8874   BFD_ASSERT (htab != NULL);
8875
8876   if (htab->lazy_stub_count == 0)
8877     return;
8878
8879   /* IRIX rld assumes that a function stub isn't at the end of the .text
8880      section, so add a dummy entry to the end.  */
8881   htab->lazy_stub_count++;
8882
8883   /* Get a worst-case estimate of the number of dynamic symbols needed.
8884      At this point, dynsymcount does not account for section symbols
8885      and count_section_dynsyms may overestimate the number that will
8886      be needed.  */
8887   dynsymcount = (elf_hash_table (info)->dynsymcount
8888                  + count_section_dynsyms (output_bfd, info));
8889
8890   /* Determine the size of one stub entry.  */
8891   htab->function_stub_size = (dynsymcount > 0x10000
8892                               ? MIPS_FUNCTION_STUB_BIG_SIZE
8893                               : MIPS_FUNCTION_STUB_NORMAL_SIZE);
8894
8895   htab->sstubs->size = htab->lazy_stub_count * htab->function_stub_size;
8896 }
8897
8898 /* A mips_elf_link_hash_traverse callback for which DATA points to the
8899    MIPS hash table.  If H needs a traditional MIPS lazy-binding stub,
8900    allocate an entry in the stubs section.  */
8901
8902 static bfd_boolean
8903 mips_elf_allocate_lazy_stub (struct mips_elf_link_hash_entry *h, void **data)
8904 {
8905   struct mips_elf_link_hash_table *htab;
8906
8907   htab = (struct mips_elf_link_hash_table *) data;
8908   if (h->needs_lazy_stub)
8909     {
8910       h->root.root.u.def.section = htab->sstubs;
8911       h->root.root.u.def.value = htab->sstubs->size;
8912       h->root.plt.offset = htab->sstubs->size;
8913       htab->sstubs->size += htab->function_stub_size;
8914     }
8915   return TRUE;
8916 }
8917
8918 /* Allocate offsets in the stubs section to each symbol that needs one.
8919    Set the final size of the .MIPS.stub section.  */
8920
8921 static void
8922 mips_elf_lay_out_lazy_stubs (struct bfd_link_info *info)
8923 {
8924   struct mips_elf_link_hash_table *htab;
8925
8926   htab = mips_elf_hash_table (info);
8927   BFD_ASSERT (htab != NULL);
8928
8929   if (htab->lazy_stub_count == 0)
8930     return;
8931
8932   htab->sstubs->size = 0;
8933   mips_elf_link_hash_traverse (htab, mips_elf_allocate_lazy_stub, htab);
8934   htab->sstubs->size += htab->function_stub_size;
8935   BFD_ASSERT (htab->sstubs->size
8936               == htab->lazy_stub_count * htab->function_stub_size);
8937 }
8938
8939 /* Set the sizes of the dynamic sections.  */
8940
8941 bfd_boolean
8942 _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd,
8943                                      struct bfd_link_info *info)
8944 {
8945   bfd *dynobj;
8946   asection *s, *sreldyn;
8947   bfd_boolean reltext;
8948   struct mips_elf_link_hash_table *htab;
8949
8950   htab = mips_elf_hash_table (info);
8951   BFD_ASSERT (htab != NULL);
8952   dynobj = elf_hash_table (info)->dynobj;
8953   BFD_ASSERT (dynobj != NULL);
8954
8955   if (elf_hash_table (info)->dynamic_sections_created)
8956     {
8957       /* Set the contents of the .interp section to the interpreter.  */
8958       if (info->executable)
8959         {
8960           s = bfd_get_linker_section (dynobj, ".interp");
8961           BFD_ASSERT (s != NULL);
8962           s->size
8963             = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1;
8964           s->contents
8965             = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd);
8966         }
8967
8968       /* Create a symbol for the PLT, if we know that we are using it.  */
8969       if (htab->splt && htab->splt->size > 0 && htab->root.hplt == NULL)
8970         {
8971           struct elf_link_hash_entry *h;
8972
8973           BFD_ASSERT (htab->use_plts_and_copy_relocs);
8974
8975           h = _bfd_elf_define_linkage_sym (dynobj, info, htab->splt,
8976                                            "_PROCEDURE_LINKAGE_TABLE_");
8977           htab->root.hplt = h;
8978           if (h == NULL)
8979             return FALSE;
8980           h->type = STT_FUNC;
8981         }
8982     }
8983
8984   /* Allocate space for global sym dynamic relocs.  */
8985   elf_link_hash_traverse (&htab->root, allocate_dynrelocs, info);
8986
8987   mips_elf_estimate_stub_size (output_bfd, info);
8988
8989   if (!mips_elf_lay_out_got (output_bfd, info))
8990     return FALSE;
8991
8992   mips_elf_lay_out_lazy_stubs (info);
8993
8994   /* The check_relocs and adjust_dynamic_symbol entry points have
8995      determined the sizes of the various dynamic sections.  Allocate
8996      memory for them.  */
8997   reltext = FALSE;
8998   for (s = dynobj->sections; s != NULL; s = s->next)
8999     {
9000       const char *name;
9001
9002       /* It's OK to base decisions on the section name, because none
9003          of the dynobj section names depend upon the input files.  */
9004       name = bfd_get_section_name (dynobj, s);
9005
9006       if ((s->flags & SEC_LINKER_CREATED) == 0)
9007         continue;
9008
9009       if (CONST_STRNEQ (name, ".rel"))
9010         {
9011           if (s->size != 0)
9012             {
9013               const char *outname;
9014               asection *target;
9015
9016               /* If this relocation section applies to a read only
9017                  section, then we probably need a DT_TEXTREL entry.
9018                  If the relocation section is .rel(a).dyn, we always
9019                  assert a DT_TEXTREL entry rather than testing whether
9020                  there exists a relocation to a read only section or
9021                  not.  */
9022               outname = bfd_get_section_name (output_bfd,
9023                                               s->output_section);
9024               target = bfd_get_section_by_name (output_bfd, outname + 4);
9025               if ((target != NULL
9026                    && (target->flags & SEC_READONLY) != 0
9027                    && (target->flags & SEC_ALLOC) != 0)
9028                   || strcmp (outname, MIPS_ELF_REL_DYN_NAME (info)) == 0)
9029                 reltext = TRUE;
9030
9031               /* We use the reloc_count field as a counter if we need
9032                  to copy relocs into the output file.  */
9033               if (strcmp (name, MIPS_ELF_REL_DYN_NAME (info)) != 0)
9034                 s->reloc_count = 0;
9035
9036               /* If combreloc is enabled, elf_link_sort_relocs() will
9037                  sort relocations, but in a different way than we do,
9038                  and before we're done creating relocations.  Also, it
9039                  will move them around between input sections'
9040                  relocation's contents, so our sorting would be
9041                  broken, so don't let it run.  */
9042               info->combreloc = 0;
9043             }
9044         }
9045       else if (! info->shared
9046                && ! mips_elf_hash_table (info)->use_rld_obj_head
9047                && CONST_STRNEQ (name, ".rld_map"))
9048         {
9049           /* We add a room for __rld_map.  It will be filled in by the
9050              rtld to contain a pointer to the _r_debug structure.  */
9051           s->size += MIPS_ELF_RLD_MAP_SIZE (output_bfd);
9052         }
9053       else if (SGI_COMPAT (output_bfd)
9054                && CONST_STRNEQ (name, ".compact_rel"))
9055         s->size += mips_elf_hash_table (info)->compact_rel_size;
9056       else if (s == htab->splt)
9057         {
9058           /* If the last PLT entry has a branch delay slot, allocate
9059              room for an extra nop to fill the delay slot.  This is
9060              for CPUs without load interlocking.  */
9061           if (! LOAD_INTERLOCKS_P (output_bfd)
9062               && ! htab->is_vxworks && s->size > 0)
9063             s->size += 4;
9064         }
9065       else if (! CONST_STRNEQ (name, ".init")
9066                && s != htab->sgot
9067                && s != htab->sgotplt
9068                && s != htab->sstubs
9069                && s != htab->sdynbss)
9070         {
9071           /* It's not one of our sections, so don't allocate space.  */
9072           continue;
9073         }
9074
9075       if (s->size == 0)
9076         {
9077           s->flags |= SEC_EXCLUDE;
9078           continue;
9079         }
9080
9081       if ((s->flags & SEC_HAS_CONTENTS) == 0)
9082         continue;
9083
9084       /* Allocate memory for the section contents.  */
9085       s->contents = bfd_zalloc (dynobj, s->size);
9086       if (s->contents == NULL)
9087         {
9088           bfd_set_error (bfd_error_no_memory);
9089           return FALSE;
9090         }
9091     }
9092
9093   if (elf_hash_table (info)->dynamic_sections_created)
9094     {
9095       /* Add some entries to the .dynamic section.  We fill in the
9096          values later, in _bfd_mips_elf_finish_dynamic_sections, but we
9097          must add the entries now so that we get the correct size for
9098          the .dynamic section.  */
9099
9100       /* SGI object has the equivalence of DT_DEBUG in the
9101          DT_MIPS_RLD_MAP entry.  This must come first because glibc
9102          only fills in DT_MIPS_RLD_MAP (not DT_DEBUG) and some tools
9103          may only look at the first one they see.  */
9104       if (!info->shared
9105           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0))
9106         return FALSE;
9107
9108       /* The DT_DEBUG entry may be filled in by the dynamic linker and
9109          used by the debugger.  */
9110       if (info->executable
9111           && !SGI_COMPAT (output_bfd)
9112           && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
9113         return FALSE;
9114
9115       if (reltext && (SGI_COMPAT (output_bfd) || htab->is_vxworks))
9116         info->flags |= DF_TEXTREL;
9117
9118       if ((info->flags & DF_TEXTREL) != 0)
9119         {
9120           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
9121             return FALSE;
9122
9123           /* Clear the DF_TEXTREL flag.  It will be set again if we
9124              write out an actual text relocation; we may not, because
9125              at this point we do not know whether e.g. any .eh_frame
9126              absolute relocations have been converted to PC-relative.  */
9127           info->flags &= ~DF_TEXTREL;
9128         }
9129
9130       if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
9131         return FALSE;
9132
9133       sreldyn = mips_elf_rel_dyn_section (info, FALSE);
9134       if (htab->is_vxworks)
9135         {
9136           /* VxWorks uses .rela.dyn instead of .rel.dyn.  It does not
9137              use any of the DT_MIPS_* tags.  */
9138           if (sreldyn && sreldyn->size > 0)
9139             {
9140               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELA, 0))
9141                 return FALSE;
9142
9143               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELASZ, 0))
9144                 return FALSE;
9145
9146               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELAENT, 0))
9147                 return FALSE;
9148             }
9149         }
9150       else
9151         {
9152           if (sreldyn && sreldyn->size > 0)
9153             {
9154               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
9155                 return FALSE;
9156
9157               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
9158                 return FALSE;
9159
9160               if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
9161                 return FALSE;
9162             }
9163
9164           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0))
9165             return FALSE;
9166
9167           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0))
9168             return FALSE;
9169
9170           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0))
9171             return FALSE;
9172
9173           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0))
9174             return FALSE;
9175
9176           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0))
9177             return FALSE;
9178
9179           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0))
9180             return FALSE;
9181
9182           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0))
9183             return FALSE;
9184
9185           if (IRIX_COMPAT (dynobj) == ict_irix5
9186               && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0))
9187             return FALSE;
9188
9189           if (IRIX_COMPAT (dynobj) == ict_irix6
9190               && (bfd_get_section_by_name
9191                   (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj)))
9192               && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0))
9193             return FALSE;
9194         }
9195       if (htab->splt->size > 0)
9196         {
9197           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTREL, 0))
9198             return FALSE;
9199
9200           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_JMPREL, 0))
9201             return FALSE;
9202
9203           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTRELSZ, 0))
9204             return FALSE;
9205
9206           if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_PLTGOT, 0))
9207             return FALSE;
9208         }
9209       if (htab->is_vxworks
9210           && !elf_vxworks_add_dynamic_entries (output_bfd, info))
9211         return FALSE;
9212     }
9213
9214   return TRUE;
9215 }
9216 \f
9217 /* REL is a relocation in INPUT_BFD that is being copied to OUTPUT_BFD.
9218    Adjust its R_ADDEND field so that it is correct for the output file.
9219    LOCAL_SYMS and LOCAL_SECTIONS are arrays of INPUT_BFD's local symbols
9220    and sections respectively; both use symbol indexes.  */
9221
9222 static void
9223 mips_elf_adjust_addend (bfd *output_bfd, struct bfd_link_info *info,
9224                         bfd *input_bfd, Elf_Internal_Sym *local_syms,
9225                         asection **local_sections, Elf_Internal_Rela *rel)
9226 {
9227   unsigned int r_type, r_symndx;
9228   Elf_Internal_Sym *sym;
9229   asection *sec;
9230
9231   if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9232     {
9233       r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9234       if (gprel16_reloc_p (r_type)
9235           || r_type == R_MIPS_GPREL32
9236           || literal_reloc_p (r_type))
9237         {
9238           rel->r_addend += _bfd_get_gp_value (input_bfd);
9239           rel->r_addend -= _bfd_get_gp_value (output_bfd);
9240         }
9241
9242       r_symndx = ELF_R_SYM (output_bfd, rel->r_info);
9243       sym = local_syms + r_symndx;
9244
9245       /* Adjust REL's addend to account for section merging.  */
9246       if (!info->relocatable)
9247         {
9248           sec = local_sections[r_symndx];
9249           _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel);
9250         }
9251
9252       /* This would normally be done by the rela_normal code in elflink.c.  */
9253       if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
9254         rel->r_addend += local_sections[r_symndx]->output_offset;
9255     }
9256 }
9257
9258 /* Handle relocations against symbols from removed linkonce sections,
9259    or sections discarded by a linker script.  We use this wrapper around
9260    RELOC_AGAINST_DISCARDED_SECTION to handle triplets of compound relocs
9261    on 64-bit ELF targets.  In this case for any relocation handled, which
9262    always be the first in a triplet, the remaining two have to be processed
9263    together with the first, even if they are R_MIPS_NONE.  It is the symbol
9264    index referred by the first reloc that applies to all the three and the
9265    remaining two never refer to an object symbol.  And it is the final
9266    relocation (the last non-null one) that determines the output field of
9267    the whole relocation so retrieve the corresponding howto structure for
9268    the relocatable field to be cleared by RELOC_AGAINST_DISCARDED_SECTION.
9269
9270    Note that RELOC_AGAINST_DISCARDED_SECTION is a macro that uses "continue"
9271    and therefore requires to be pasted in a loop.  It also defines a block
9272    and does not protect any of its arguments, hence the extra brackets.  */
9273
9274 static void
9275 mips_reloc_against_discarded_section (bfd *output_bfd,
9276                                       struct bfd_link_info *info,
9277                                       bfd *input_bfd, asection *input_section,
9278                                       Elf_Internal_Rela **rel,
9279                                       const Elf_Internal_Rela **relend,
9280                                       bfd_boolean rel_reloc,
9281                                       reloc_howto_type *howto,
9282                                       bfd_byte *contents)
9283 {
9284   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
9285   int count = bed->s->int_rels_per_ext_rel;
9286   unsigned int r_type;
9287   int i;
9288
9289   for (i = count - 1; i > 0; i--)
9290     {
9291       r_type = ELF_R_TYPE (output_bfd, (*rel)[i].r_info);
9292       if (r_type != R_MIPS_NONE)
9293         {
9294           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9295           break;
9296         }
9297     }
9298   do
9299     {
9300        RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
9301                                         (*rel), count, (*relend),
9302                                         howto, i, contents);
9303     }
9304   while (0);
9305 }
9306
9307 /* Relocate a MIPS ELF section.  */
9308
9309 bfd_boolean
9310 _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
9311                                 bfd *input_bfd, asection *input_section,
9312                                 bfd_byte *contents, Elf_Internal_Rela *relocs,
9313                                 Elf_Internal_Sym *local_syms,
9314                                 asection **local_sections)
9315 {
9316   Elf_Internal_Rela *rel;
9317   const Elf_Internal_Rela *relend;
9318   bfd_vma addend = 0;
9319   bfd_boolean use_saved_addend_p = FALSE;
9320   const struct elf_backend_data *bed;
9321
9322   bed = get_elf_backend_data (output_bfd);
9323   relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
9324   for (rel = relocs; rel < relend; ++rel)
9325     {
9326       const char *name;
9327       bfd_vma value = 0;
9328       reloc_howto_type *howto;
9329       bfd_boolean cross_mode_jump_p;
9330       /* TRUE if the relocation is a RELA relocation, rather than a
9331          REL relocation.  */
9332       bfd_boolean rela_relocation_p = TRUE;
9333       unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info);
9334       const char *msg;
9335       unsigned long r_symndx;
9336       asection *sec;
9337       Elf_Internal_Shdr *symtab_hdr;
9338       struct elf_link_hash_entry *h;
9339       bfd_boolean rel_reloc;
9340
9341       rel_reloc = (NEWABI_P (input_bfd)
9342                    && mips_elf_rel_relocation_p (input_bfd, input_section,
9343                                                  relocs, rel));
9344       /* Find the relocation howto for this relocation.  */
9345       howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, !rel_reloc);
9346
9347       r_symndx = ELF_R_SYM (input_bfd, rel->r_info);
9348       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9349       if (mips_elf_local_relocation_p (input_bfd, rel, local_sections))
9350         {
9351           sec = local_sections[r_symndx];
9352           h = NULL;
9353         }
9354       else
9355         {
9356           unsigned long extsymoff;
9357
9358           extsymoff = 0;
9359           if (!elf_bad_symtab (input_bfd))
9360             extsymoff = symtab_hdr->sh_info;
9361           h = elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
9362           while (h->root.type == bfd_link_hash_indirect
9363                  || h->root.type == bfd_link_hash_warning)
9364             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9365
9366           sec = NULL;
9367           if (h->root.type == bfd_link_hash_defined
9368               || h->root.type == bfd_link_hash_defweak)
9369             sec = h->root.u.def.section;
9370         }
9371
9372       if (sec != NULL && discarded_section (sec))
9373         {
9374           mips_reloc_against_discarded_section (output_bfd, info, input_bfd,
9375                                                 input_section, &rel, &relend,
9376                                                 rel_reloc, howto, contents);
9377           continue;
9378         }
9379
9380       if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd))
9381         {
9382           /* Some 32-bit code uses R_MIPS_64.  In particular, people use
9383              64-bit code, but make sure all their addresses are in the
9384              lowermost or uppermost 32-bit section of the 64-bit address
9385              space.  Thus, when they use an R_MIPS_64 they mean what is
9386              usually meant by R_MIPS_32, with the exception that the
9387              stored value is sign-extended to 64 bits.  */
9388           howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE);
9389
9390           /* On big-endian systems, we need to lie about the position
9391              of the reloc.  */
9392           if (bfd_big_endian (input_bfd))
9393             rel->r_offset += 4;
9394         }
9395
9396       if (!use_saved_addend_p)
9397         {
9398           /* If these relocations were originally of the REL variety,
9399              we must pull the addend out of the field that will be
9400              relocated.  Otherwise, we simply use the contents of the
9401              RELA relocation.  */
9402           if (mips_elf_rel_relocation_p (input_bfd, input_section,
9403                                          relocs, rel))
9404             {
9405               rela_relocation_p = FALSE;
9406               addend = mips_elf_read_rel_addend (input_bfd, rel,
9407                                                  howto, contents);
9408               if (hi16_reloc_p (r_type)
9409                   || (got16_reloc_p (r_type)
9410                       && mips_elf_local_relocation_p (input_bfd, rel,
9411                                                       local_sections)))
9412                 {
9413                   if (!mips_elf_add_lo16_rel_addend (input_bfd, rel, relend,
9414                                                      contents, &addend))
9415                     {
9416                       if (h)
9417                         name = h->root.root.string;
9418                       else
9419                         name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9420                                                  local_syms + r_symndx,
9421                                                  sec);
9422                       (*_bfd_error_handler)
9423                         (_("%B: Can't find matching LO16 reloc against `%s' for %s at 0x%lx in section `%A'"),
9424                          input_bfd, input_section, name, howto->name,
9425                          rel->r_offset);
9426                     }
9427                 }
9428               else
9429                 addend <<= howto->rightshift;
9430             }
9431           else
9432             addend = rel->r_addend;
9433           mips_elf_adjust_addend (output_bfd, info, input_bfd,
9434                                   local_syms, local_sections, rel);
9435         }
9436
9437       if (info->relocatable)
9438         {
9439           if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)
9440               && bfd_big_endian (input_bfd))
9441             rel->r_offset -= 4;
9442
9443           if (!rela_relocation_p && rel->r_addend)
9444             {
9445               addend += rel->r_addend;
9446               if (hi16_reloc_p (r_type) || got16_reloc_p (r_type))
9447                 addend = mips_elf_high (addend);
9448               else if (r_type == R_MIPS_HIGHER)
9449                 addend = mips_elf_higher (addend);
9450               else if (r_type == R_MIPS_HIGHEST)
9451                 addend = mips_elf_highest (addend);
9452               else
9453                 addend >>= howto->rightshift;
9454
9455               /* We use the source mask, rather than the destination
9456                  mask because the place to which we are writing will be
9457                  source of the addend in the final link.  */
9458               addend &= howto->src_mask;
9459
9460               if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9461                 /* See the comment above about using R_MIPS_64 in the 32-bit
9462                    ABI.  Here, we need to update the addend.  It would be
9463                    possible to get away with just using the R_MIPS_32 reloc
9464                    but for endianness.  */
9465                 {
9466                   bfd_vma sign_bits;
9467                   bfd_vma low_bits;
9468                   bfd_vma high_bits;
9469
9470                   if (addend & ((bfd_vma) 1 << 31))
9471 #ifdef BFD64
9472                     sign_bits = ((bfd_vma) 1 << 32) - 1;
9473 #else
9474                     sign_bits = -1;
9475 #endif
9476                   else
9477                     sign_bits = 0;
9478
9479                   /* If we don't know that we have a 64-bit type,
9480                      do two separate stores.  */
9481                   if (bfd_big_endian (input_bfd))
9482                     {
9483                       /* Store the sign-bits (which are most significant)
9484                          first.  */
9485                       low_bits = sign_bits;
9486                       high_bits = addend;
9487                     }
9488                   else
9489                     {
9490                       low_bits = addend;
9491                       high_bits = sign_bits;
9492                     }
9493                   bfd_put_32 (input_bfd, low_bits,
9494                               contents + rel->r_offset);
9495                   bfd_put_32 (input_bfd, high_bits,
9496                               contents + rel->r_offset + 4);
9497                   continue;
9498                 }
9499
9500               if (! mips_elf_perform_relocation (info, howto, rel, addend,
9501                                                  input_bfd, input_section,
9502                                                  contents, FALSE))
9503                 return FALSE;
9504             }
9505
9506           /* Go on to the next relocation.  */
9507           continue;
9508         }
9509
9510       /* In the N32 and 64-bit ABIs there may be multiple consecutive
9511          relocations for the same offset.  In that case we are
9512          supposed to treat the output of each relocation as the addend
9513          for the next.  */
9514       if (rel + 1 < relend
9515           && rel->r_offset == rel[1].r_offset
9516           && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE)
9517         use_saved_addend_p = TRUE;
9518       else
9519         use_saved_addend_p = FALSE;
9520
9521       /* Figure out what value we are supposed to relocate.  */
9522       switch (mips_elf_calculate_relocation (output_bfd, input_bfd,
9523                                              input_section, info, rel,
9524                                              addend, howto, local_syms,
9525                                              local_sections, &value,
9526                                              &name, &cross_mode_jump_p,
9527                                              use_saved_addend_p))
9528         {
9529         case bfd_reloc_continue:
9530           /* There's nothing to do.  */
9531           continue;
9532
9533         case bfd_reloc_undefined:
9534           /* mips_elf_calculate_relocation already called the
9535              undefined_symbol callback.  There's no real point in
9536              trying to perform the relocation at this point, so we
9537              just skip ahead to the next relocation.  */
9538           continue;
9539
9540         case bfd_reloc_notsupported:
9541           msg = _("internal error: unsupported relocation error");
9542           info->callbacks->warning
9543             (info, msg, name, input_bfd, input_section, rel->r_offset);
9544           return FALSE;
9545
9546         case bfd_reloc_overflow:
9547           if (use_saved_addend_p)
9548             /* Ignore overflow until we reach the last relocation for
9549                a given location.  */
9550             ;
9551           else
9552             {
9553               struct mips_elf_link_hash_table *htab;
9554
9555               htab = mips_elf_hash_table (info);
9556               BFD_ASSERT (htab != NULL);
9557               BFD_ASSERT (name != NULL);
9558               if (!htab->small_data_overflow_reported
9559                   && (gprel16_reloc_p (howto->type)
9560                       || literal_reloc_p (howto->type)))
9561                 {
9562                   msg = _("small-data section exceeds 64KB;"
9563                           " lower small-data size limit (see option -G)");
9564
9565                   htab->small_data_overflow_reported = TRUE;
9566                   (*info->callbacks->einfo) ("%P: %s\n", msg);
9567                 }
9568               if (! ((*info->callbacks->reloc_overflow)
9569                      (info, NULL, name, howto->name, (bfd_vma) 0,
9570                       input_bfd, input_section, rel->r_offset)))
9571                 return FALSE;
9572             }
9573           break;
9574
9575         case bfd_reloc_ok:
9576           break;
9577
9578         case bfd_reloc_outofrange:
9579           if (jal_reloc_p (howto->type))
9580             {
9581               msg = _("JALX to a non-word-aligned address");
9582               info->callbacks->warning
9583                 (info, msg, name, input_bfd, input_section, rel->r_offset);
9584               return FALSE;
9585             }
9586           /* Fall through.  */
9587
9588         default:
9589           abort ();
9590           break;
9591         }
9592
9593       /* If we've got another relocation for the address, keep going
9594          until we reach the last one.  */
9595       if (use_saved_addend_p)
9596         {
9597           addend = value;
9598           continue;
9599         }
9600
9601       if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd))
9602         /* See the comment above about using R_MIPS_64 in the 32-bit
9603            ABI.  Until now, we've been using the HOWTO for R_MIPS_32;
9604            that calculated the right value.  Now, however, we
9605            sign-extend the 32-bit result to 64-bits, and store it as a
9606            64-bit value.  We are especially generous here in that we
9607            go to extreme lengths to support this usage on systems with
9608            only a 32-bit VMA.  */
9609         {
9610           bfd_vma sign_bits;
9611           bfd_vma low_bits;
9612           bfd_vma high_bits;
9613
9614           if (value & ((bfd_vma) 1 << 31))
9615 #ifdef BFD64
9616             sign_bits = ((bfd_vma) 1 << 32) - 1;
9617 #else
9618             sign_bits = -1;
9619 #endif
9620           else
9621             sign_bits = 0;
9622
9623           /* If we don't know that we have a 64-bit type,
9624              do two separate stores.  */
9625           if (bfd_big_endian (input_bfd))
9626             {
9627               /* Undo what we did above.  */
9628               rel->r_offset -= 4;
9629               /* Store the sign-bits (which are most significant)
9630                  first.  */
9631               low_bits = sign_bits;
9632               high_bits = value;
9633             }
9634           else
9635             {
9636               low_bits = value;
9637               high_bits = sign_bits;
9638             }
9639           bfd_put_32 (input_bfd, low_bits,
9640                       contents + rel->r_offset);
9641           bfd_put_32 (input_bfd, high_bits,
9642                       contents + rel->r_offset + 4);
9643           continue;
9644         }
9645
9646       /* Actually perform the relocation.  */
9647       if (! mips_elf_perform_relocation (info, howto, rel, value,
9648                                          input_bfd, input_section,
9649                                          contents, cross_mode_jump_p))
9650         return FALSE;
9651     }
9652
9653   return TRUE;
9654 }
9655 \f
9656 /* A function that iterates over each entry in la25_stubs and fills
9657    in the code for each one.  DATA points to a mips_htab_traverse_info.  */
9658
9659 static int
9660 mips_elf_create_la25_stub (void **slot, void *data)
9661 {
9662   struct mips_htab_traverse_info *hti;
9663   struct mips_elf_link_hash_table *htab;
9664   struct mips_elf_la25_stub *stub;
9665   asection *s;
9666   bfd_byte *loc;
9667   bfd_vma offset, target, target_high, target_low;
9668
9669   stub = (struct mips_elf_la25_stub *) *slot;
9670   hti = (struct mips_htab_traverse_info *) data;
9671   htab = mips_elf_hash_table (hti->info);
9672   BFD_ASSERT (htab != NULL);
9673
9674   /* Create the section contents, if we haven't already.  */
9675   s = stub->stub_section;
9676   loc = s->contents;
9677   if (loc == NULL)
9678     {
9679       loc = bfd_malloc (s->size);
9680       if (loc == NULL)
9681         {
9682           hti->error = TRUE;
9683           return FALSE;
9684         }
9685       s->contents = loc;
9686     }
9687
9688   /* Work out where in the section this stub should go.  */
9689   offset = stub->offset;
9690
9691   /* Work out the target address.  */
9692   target = mips_elf_get_la25_target (stub, &s);
9693   target += s->output_section->vma + s->output_offset;
9694
9695   target_high = ((target + 0x8000) >> 16) & 0xffff;
9696   target_low = (target & 0xffff);
9697
9698   if (stub->stub_section != htab->strampoline)
9699     {
9700       /* This is a simple LUI/ADDIU stub.  Zero out the beginning
9701          of the section and write the two instructions at the end.  */
9702       memset (loc, 0, offset);
9703       loc += offset;
9704       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9705         {
9706           bfd_put_micromips_32 (hti->output_bfd,
9707                                 LA25_LUI_MICROMIPS (target_high),
9708                                 loc);
9709           bfd_put_micromips_32 (hti->output_bfd,
9710                                 LA25_ADDIU_MICROMIPS (target_low),
9711                                 loc + 4);
9712         }
9713       else
9714         {
9715           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9716           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 4);
9717         }
9718     }
9719   else
9720     {
9721       /* This is trampoline.  */
9722       loc += offset;
9723       if (ELF_ST_IS_MICROMIPS (stub->h->root.other))
9724         {
9725           bfd_put_micromips_32 (hti->output_bfd,
9726                                 LA25_LUI_MICROMIPS (target_high), loc);
9727           bfd_put_micromips_32 (hti->output_bfd,
9728                                 LA25_J_MICROMIPS (target), loc + 4);
9729           bfd_put_micromips_32 (hti->output_bfd,
9730                                 LA25_ADDIU_MICROMIPS (target_low), loc + 8);
9731           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9732         }
9733       else
9734         {
9735           bfd_put_32 (hti->output_bfd, LA25_LUI (target_high), loc);
9736           bfd_put_32 (hti->output_bfd, LA25_J (target), loc + 4);
9737           bfd_put_32 (hti->output_bfd, LA25_ADDIU (target_low), loc + 8);
9738           bfd_put_32 (hti->output_bfd, 0, loc + 12);
9739         }
9740     }
9741   return TRUE;
9742 }
9743
9744 /* If NAME is one of the special IRIX6 symbols defined by the linker,
9745    adjust it appropriately now.  */
9746
9747 static void
9748 mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED,
9749                                       const char *name, Elf_Internal_Sym *sym)
9750 {
9751   /* The linker script takes care of providing names and values for
9752      these, but we must place them into the right sections.  */
9753   static const char* const text_section_symbols[] = {
9754     "_ftext",
9755     "_etext",
9756     "__dso_displacement",
9757     "__elf_header",
9758     "__program_header_table",
9759     NULL
9760   };
9761
9762   static const char* const data_section_symbols[] = {
9763     "_fdata",
9764     "_edata",
9765     "_end",
9766     "_fbss",
9767     NULL
9768   };
9769
9770   const char* const *p;
9771   int i;
9772
9773   for (i = 0; i < 2; ++i)
9774     for (p = (i == 0) ? text_section_symbols : data_section_symbols;
9775          *p;
9776          ++p)
9777       if (strcmp (*p, name) == 0)
9778         {
9779           /* All of these symbols are given type STT_SECTION by the
9780              IRIX6 linker.  */
9781           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
9782           sym->st_other = STO_PROTECTED;
9783
9784           /* The IRIX linker puts these symbols in special sections.  */
9785           if (i == 0)
9786             sym->st_shndx = SHN_MIPS_TEXT;
9787           else
9788             sym->st_shndx = SHN_MIPS_DATA;
9789
9790           break;
9791         }
9792 }
9793
9794 /* Finish up dynamic symbol handling.  We set the contents of various
9795    dynamic sections here.  */
9796
9797 bfd_boolean
9798 _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd,
9799                                      struct bfd_link_info *info,
9800                                      struct elf_link_hash_entry *h,
9801                                      Elf_Internal_Sym *sym)
9802 {
9803   bfd *dynobj;
9804   asection *sgot;
9805   struct mips_got_info *g, *gg;
9806   const char *name;
9807   int idx;
9808   struct mips_elf_link_hash_table *htab;
9809   struct mips_elf_link_hash_entry *hmips;
9810
9811   htab = mips_elf_hash_table (info);
9812   BFD_ASSERT (htab != NULL);
9813   dynobj = elf_hash_table (info)->dynobj;
9814   hmips = (struct mips_elf_link_hash_entry *) h;
9815
9816   BFD_ASSERT (!htab->is_vxworks);
9817
9818   if (h->plt.offset != MINUS_ONE && hmips->no_fn_stub)
9819     {
9820       /* We've decided to create a PLT entry for this symbol.  */
9821       bfd_byte *loc;
9822       bfd_vma header_address, plt_index, got_address;
9823       bfd_vma got_address_high, got_address_low, load;
9824       const bfd_vma *plt_entry;
9825
9826       BFD_ASSERT (htab->use_plts_and_copy_relocs);
9827       BFD_ASSERT (h->dynindx != -1);
9828       BFD_ASSERT (htab->splt != NULL);
9829       BFD_ASSERT (h->plt.offset <= htab->splt->size);
9830       BFD_ASSERT (!h->def_regular);
9831
9832       /* Calculate the address of the PLT header.  */
9833       header_address = (htab->splt->output_section->vma
9834                         + htab->splt->output_offset);
9835
9836       /* Calculate the index of the entry.  */
9837       plt_index = ((h->plt.offset - htab->plt_header_size)
9838                    / htab->plt_entry_size);
9839
9840       /* Calculate the address of the .got.plt entry.  */
9841       got_address = (htab->sgotplt->output_section->vma
9842                      + htab->sgotplt->output_offset
9843                      + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9844       got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
9845       got_address_low = got_address & 0xffff;
9846
9847       /* Initially point the .got.plt entry at the PLT header.  */
9848       loc = (htab->sgotplt->contents
9849              + (2 + plt_index) * MIPS_ELF_GOT_SIZE (dynobj));
9850       if (ABI_64_P (output_bfd))
9851         bfd_put_64 (output_bfd, header_address, loc);
9852       else
9853         bfd_put_32 (output_bfd, header_address, loc);
9854
9855       /* Find out where the .plt entry should go.  */
9856       loc = htab->splt->contents + h->plt.offset;
9857
9858       /* Pick the load opcode.  */
9859       load = MIPS_ELF_LOAD_WORD (output_bfd);
9860
9861       /* Fill in the PLT entry itself.  */
9862       plt_entry = mips_exec_plt_entry;
9863       bfd_put_32 (output_bfd, plt_entry[0] | got_address_high, loc);
9864       bfd_put_32 (output_bfd, plt_entry[1] | got_address_low | load, loc + 4);
9865
9866       if (! LOAD_INTERLOCKS_P (output_bfd))
9867         {
9868           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 8);
9869           bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
9870         }
9871       else
9872         {
9873           bfd_put_32 (output_bfd, plt_entry[3], loc + 8);
9874           bfd_put_32 (output_bfd, plt_entry[2] | got_address_low, loc + 12);
9875         }
9876
9877       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
9878       mips_elf_output_dynamic_relocation (output_bfd, htab->srelplt,
9879                                           plt_index, h->dynindx,
9880                                           R_MIPS_JUMP_SLOT, got_address);
9881
9882       /* We distinguish between PLT entries and lazy-binding stubs by
9883          giving the former an st_other value of STO_MIPS_PLT.  Set the
9884          flag and leave the value if there are any relocations in the
9885          binary where pointer equality matters.  */
9886       sym->st_shndx = SHN_UNDEF;
9887       if (h->pointer_equality_needed)
9888         sym->st_other = STO_MIPS_PLT;
9889       else
9890         sym->st_value = 0;
9891     }
9892   else if (h->plt.offset != MINUS_ONE)
9893     {
9894       /* We've decided to create a lazy-binding stub.  */
9895       bfd_byte stub[MIPS_FUNCTION_STUB_BIG_SIZE];
9896
9897       /* This symbol has a stub.  Set it up.  */
9898
9899       BFD_ASSERT (h->dynindx != -1);
9900
9901       BFD_ASSERT ((htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9902                   || (h->dynindx <= 0xffff));
9903
9904       /* Values up to 2^31 - 1 are allowed.  Larger values would cause
9905          sign extension at runtime in the stub, resulting in a negative
9906          index value.  */
9907       if (h->dynindx & ~0x7fffffff)
9908         return FALSE;
9909
9910       /* Fill the stub.  */
9911       idx = 0;
9912       bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub + idx);
9913       idx += 4;
9914       bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + idx);
9915       idx += 4;
9916       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9917         {
9918           bfd_put_32 (output_bfd, STUB_LUI ((h->dynindx >> 16) & 0x7fff),
9919                       stub + idx);
9920           idx += 4;
9921         }
9922       bfd_put_32 (output_bfd, STUB_JALR, stub + idx);
9923       idx += 4;
9924
9925       /* If a large stub is not required and sign extension is not a
9926          problem, then use legacy code in the stub.  */
9927       if (htab->function_stub_size == MIPS_FUNCTION_STUB_BIG_SIZE)
9928         bfd_put_32 (output_bfd, STUB_ORI (h->dynindx & 0xffff), stub + idx);
9929       else if (h->dynindx & ~0x7fff)
9930         bfd_put_32 (output_bfd, STUB_LI16U (h->dynindx & 0xffff), stub + idx);
9931       else
9932         bfd_put_32 (output_bfd, STUB_LI16S (output_bfd, h->dynindx),
9933                     stub + idx);
9934
9935       BFD_ASSERT (h->plt.offset <= htab->sstubs->size);
9936       memcpy (htab->sstubs->contents + h->plt.offset,
9937               stub, htab->function_stub_size);
9938
9939       /* Mark the symbol as undefined.  plt.offset != -1 occurs
9940          only for the referenced symbol.  */
9941       sym->st_shndx = SHN_UNDEF;
9942
9943       /* The run-time linker uses the st_value field of the symbol
9944          to reset the global offset table entry for this external
9945          to its stub address when unlinking a shared object.  */
9946       sym->st_value = (htab->sstubs->output_section->vma
9947                        + htab->sstubs->output_offset
9948                        + h->plt.offset);
9949     }
9950
9951   /* If we have a MIPS16 function with a stub, the dynamic symbol must
9952      refer to the stub, since only the stub uses the standard calling
9953      conventions.  */
9954   if (h->dynindx != -1 && hmips->fn_stub != NULL)
9955     {
9956       BFD_ASSERT (hmips->need_fn_stub);
9957       sym->st_value = (hmips->fn_stub->output_section->vma
9958                        + hmips->fn_stub->output_offset);
9959       sym->st_size = hmips->fn_stub->size;
9960       sym->st_other = ELF_ST_VISIBILITY (sym->st_other);
9961     }
9962
9963   BFD_ASSERT (h->dynindx != -1
9964               || h->forced_local);
9965
9966   sgot = htab->sgot;
9967   g = htab->got_info;
9968   BFD_ASSERT (g != NULL);
9969
9970   /* Run through the global symbol table, creating GOT entries for all
9971      the symbols that need them.  */
9972   if (hmips->global_got_area != GGA_NONE)
9973     {
9974       bfd_vma offset;
9975       bfd_vma value;
9976
9977       value = sym->st_value;
9978       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
9979       MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset);
9980     }
9981
9982   if (hmips->global_got_area != GGA_NONE && g->next)
9983     {
9984       struct mips_got_entry e, *p;
9985       bfd_vma entry;
9986       bfd_vma offset;
9987
9988       gg = g;
9989
9990       e.abfd = output_bfd;
9991       e.symndx = -1;
9992       e.d.h = hmips;
9993       e.tls_type = GOT_TLS_NONE;
9994
9995       for (g = g->next; g->next != gg; g = g->next)
9996         {
9997           if (g->got_entries
9998               && (p = (struct mips_got_entry *) htab_find (g->got_entries,
9999                                                            &e)))
10000             {
10001               offset = p->gotidx;
10002               BFD_ASSERT (offset > 0 && offset < htab->sgot->size);
10003               if (info->shared
10004                   || (elf_hash_table (info)->dynamic_sections_created
10005                       && p->d.h != NULL
10006                       && p->d.h->root.def_dynamic
10007                       && !p->d.h->root.def_regular))
10008                 {
10009                   /* Create an R_MIPS_REL32 relocation for this entry.  Due to
10010                      the various compatibility problems, it's easier to mock
10011                      up an R_MIPS_32 or R_MIPS_64 relocation and leave
10012                      mips_elf_create_dynamic_relocation to calculate the
10013                      appropriate addend.  */
10014                   Elf_Internal_Rela rel[3];
10015
10016                   memset (rel, 0, sizeof (rel));
10017                   if (ABI_64_P (output_bfd))
10018                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64);
10019                   else
10020                     rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32);
10021                   rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset;
10022
10023                   entry = 0;
10024                   if (! (mips_elf_create_dynamic_relocation
10025                          (output_bfd, info, rel,
10026                           e.d.h, NULL, sym->st_value, &entry, sgot)))
10027                     return FALSE;
10028                 }
10029               else
10030                 entry = sym->st_value;
10031               MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset);
10032             }
10033         }
10034     }
10035
10036   /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute.  */
10037   name = h->root.root.string;
10038   if (h == elf_hash_table (info)->hdynamic
10039       || h == elf_hash_table (info)->hgot)
10040     sym->st_shndx = SHN_ABS;
10041   else if (strcmp (name, "_DYNAMIC_LINK") == 0
10042            || strcmp (name, "_DYNAMIC_LINKING") == 0)
10043     {
10044       sym->st_shndx = SHN_ABS;
10045       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10046       sym->st_value = 1;
10047     }
10048   else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd))
10049     {
10050       sym->st_shndx = SHN_ABS;
10051       sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10052       sym->st_value = elf_gp (output_bfd);
10053     }
10054   else if (SGI_COMPAT (output_bfd))
10055     {
10056       if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0
10057           || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0)
10058         {
10059           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10060           sym->st_other = STO_PROTECTED;
10061           sym->st_value = 0;
10062           sym->st_shndx = SHN_MIPS_DATA;
10063         }
10064       else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0)
10065         {
10066           sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
10067           sym->st_other = STO_PROTECTED;
10068           sym->st_value = mips_elf_hash_table (info)->procedure_count;
10069           sym->st_shndx = SHN_ABS;
10070         }
10071       else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS)
10072         {
10073           if (h->type == STT_FUNC)
10074             sym->st_shndx = SHN_MIPS_TEXT;
10075           else if (h->type == STT_OBJECT)
10076             sym->st_shndx = SHN_MIPS_DATA;
10077         }
10078     }
10079
10080   /* Emit a copy reloc, if needed.  */
10081   if (h->needs_copy)
10082     {
10083       asection *s;
10084       bfd_vma symval;
10085
10086       BFD_ASSERT (h->dynindx != -1);
10087       BFD_ASSERT (htab->use_plts_and_copy_relocs);
10088
10089       s = mips_elf_rel_dyn_section (info, FALSE);
10090       symval = (h->root.u.def.section->output_section->vma
10091                 + h->root.u.def.section->output_offset
10092                 + h->root.u.def.value);
10093       mips_elf_output_dynamic_relocation (output_bfd, s, s->reloc_count++,
10094                                           h->dynindx, R_MIPS_COPY, symval);
10095     }
10096
10097   /* Handle the IRIX6-specific symbols.  */
10098   if (IRIX_COMPAT (output_bfd) == ict_irix6)
10099     mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym);
10100
10101   /* Keep dynamic MIPS16 symbols odd.  This allows the dynamic linker to
10102      treat MIPS16 symbols like any other.  */
10103   if (ELF_ST_IS_MIPS16 (sym->st_other))
10104     {
10105       BFD_ASSERT (sym->st_value & 1);
10106       sym->st_other -= STO_MIPS16;
10107     }
10108
10109   return TRUE;
10110 }
10111
10112 /* Likewise, for VxWorks.  */
10113
10114 bfd_boolean
10115 _bfd_mips_vxworks_finish_dynamic_symbol (bfd *output_bfd,
10116                                          struct bfd_link_info *info,
10117                                          struct elf_link_hash_entry *h,
10118                                          Elf_Internal_Sym *sym)
10119 {
10120   bfd *dynobj;
10121   asection *sgot;
10122   struct mips_got_info *g;
10123   struct mips_elf_link_hash_table *htab;
10124   struct mips_elf_link_hash_entry *hmips;
10125
10126   htab = mips_elf_hash_table (info);
10127   BFD_ASSERT (htab != NULL);
10128   dynobj = elf_hash_table (info)->dynobj;
10129   hmips = (struct mips_elf_link_hash_entry *) h;
10130
10131   if (h->plt.offset != (bfd_vma) -1)
10132     {
10133       bfd_byte *loc;
10134       bfd_vma plt_address, plt_index, got_address, got_offset, branch_offset;
10135       Elf_Internal_Rela rel;
10136       static const bfd_vma *plt_entry;
10137
10138       BFD_ASSERT (h->dynindx != -1);
10139       BFD_ASSERT (htab->splt != NULL);
10140       BFD_ASSERT (h->plt.offset <= htab->splt->size);
10141
10142       /* Calculate the address of the .plt entry.  */
10143       plt_address = (htab->splt->output_section->vma
10144                      + htab->splt->output_offset
10145                      + h->plt.offset);
10146
10147       /* Calculate the index of the entry.  */
10148       plt_index = ((h->plt.offset - htab->plt_header_size)
10149                    / htab->plt_entry_size);
10150
10151       /* Calculate the address of the .got.plt entry.  */
10152       got_address = (htab->sgotplt->output_section->vma
10153                      + htab->sgotplt->output_offset
10154                      + plt_index * 4);
10155
10156       /* Calculate the offset of the .got.plt entry from
10157          _GLOBAL_OFFSET_TABLE_.  */
10158       got_offset = mips_elf_gotplt_index (info, h);
10159
10160       /* Calculate the offset for the branch at the start of the PLT
10161          entry.  The branch jumps to the beginning of .plt.  */
10162       branch_offset = -(h->plt.offset / 4 + 1) & 0xffff;
10163
10164       /* Fill in the initial value of the .got.plt entry.  */
10165       bfd_put_32 (output_bfd, plt_address,
10166                   htab->sgotplt->contents + plt_index * 4);
10167
10168       /* Find out where the .plt entry should go.  */
10169       loc = htab->splt->contents + h->plt.offset;
10170
10171       if (info->shared)
10172         {
10173           plt_entry = mips_vxworks_shared_plt_entry;
10174           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10175           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10176         }
10177       else
10178         {
10179           bfd_vma got_address_high, got_address_low;
10180
10181           plt_entry = mips_vxworks_exec_plt_entry;
10182           got_address_high = ((got_address + 0x8000) >> 16) & 0xffff;
10183           got_address_low = got_address & 0xffff;
10184
10185           bfd_put_32 (output_bfd, plt_entry[0] | branch_offset, loc);
10186           bfd_put_32 (output_bfd, plt_entry[1] | plt_index, loc + 4);
10187           bfd_put_32 (output_bfd, plt_entry[2] | got_address_high, loc + 8);
10188           bfd_put_32 (output_bfd, plt_entry[3] | got_address_low, loc + 12);
10189           bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10190           bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10191           bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10192           bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10193
10194           loc = (htab->srelplt2->contents
10195                  + (plt_index * 3 + 2) * sizeof (Elf32_External_Rela));
10196
10197           /* Emit a relocation for the .got.plt entry.  */
10198           rel.r_offset = got_address;
10199           rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10200           rel.r_addend = h->plt.offset;
10201           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10202
10203           /* Emit a relocation for the lui of %hi(<.got.plt slot>).  */
10204           loc += sizeof (Elf32_External_Rela);
10205           rel.r_offset = plt_address + 8;
10206           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10207           rel.r_addend = got_offset;
10208           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10209
10210           /* Emit a relocation for the addiu of %lo(<.got.plt slot>).  */
10211           loc += sizeof (Elf32_External_Rela);
10212           rel.r_offset += 4;
10213           rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10214           bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10215         }
10216
10217       /* Emit an R_MIPS_JUMP_SLOT relocation against the .got.plt entry.  */
10218       loc = htab->srelplt->contents + plt_index * sizeof (Elf32_External_Rela);
10219       rel.r_offset = got_address;
10220       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_JUMP_SLOT);
10221       rel.r_addend = 0;
10222       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10223
10224       if (!h->def_regular)
10225         sym->st_shndx = SHN_UNDEF;
10226     }
10227
10228   BFD_ASSERT (h->dynindx != -1 || h->forced_local);
10229
10230   sgot = htab->sgot;
10231   g = htab->got_info;
10232   BFD_ASSERT (g != NULL);
10233
10234   /* See if this symbol has an entry in the GOT.  */
10235   if (hmips->global_got_area != GGA_NONE)
10236     {
10237       bfd_vma offset;
10238       Elf_Internal_Rela outrel;
10239       bfd_byte *loc;
10240       asection *s;
10241
10242       /* Install the symbol value in the GOT.   */
10243       offset = mips_elf_primary_global_got_index (output_bfd, info, h);
10244       MIPS_ELF_PUT_WORD (output_bfd, sym->st_value, sgot->contents + offset);
10245
10246       /* Add a dynamic relocation for it.  */
10247       s = mips_elf_rel_dyn_section (info, FALSE);
10248       loc = s->contents + (s->reloc_count++ * sizeof (Elf32_External_Rela));
10249       outrel.r_offset = (sgot->output_section->vma
10250                          + sgot->output_offset
10251                          + offset);
10252       outrel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_32);
10253       outrel.r_addend = 0;
10254       bfd_elf32_swap_reloca_out (dynobj, &outrel, loc);
10255     }
10256
10257   /* Emit a copy reloc, if needed.  */
10258   if (h->needs_copy)
10259     {
10260       Elf_Internal_Rela rel;
10261
10262       BFD_ASSERT (h->dynindx != -1);
10263
10264       rel.r_offset = (h->root.u.def.section->output_section->vma
10265                       + h->root.u.def.section->output_offset
10266                       + h->root.u.def.value);
10267       rel.r_info = ELF32_R_INFO (h->dynindx, R_MIPS_COPY);
10268       rel.r_addend = 0;
10269       bfd_elf32_swap_reloca_out (output_bfd, &rel,
10270                                  htab->srelbss->contents
10271                                  + (htab->srelbss->reloc_count
10272                                     * sizeof (Elf32_External_Rela)));
10273       ++htab->srelbss->reloc_count;
10274     }
10275
10276   /* If this is a mips16/microMIPS symbol, force the value to be even.  */
10277   if (ELF_ST_IS_COMPRESSED (sym->st_other))
10278     sym->st_value &= ~1;
10279
10280   return TRUE;
10281 }
10282
10283 /* Write out a plt0 entry to the beginning of .plt.  */
10284
10285 static void
10286 mips_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10287 {
10288   bfd_byte *loc;
10289   bfd_vma gotplt_value, gotplt_value_high, gotplt_value_low;
10290   static const bfd_vma *plt_entry;
10291   struct mips_elf_link_hash_table *htab;
10292
10293   htab = mips_elf_hash_table (info);
10294   BFD_ASSERT (htab != NULL);
10295
10296   if (ABI_64_P (output_bfd))
10297     plt_entry = mips_n64_exec_plt0_entry;
10298   else if (ABI_N32_P (output_bfd))
10299     plt_entry = mips_n32_exec_plt0_entry;
10300   else
10301     plt_entry = mips_o32_exec_plt0_entry;
10302
10303   /* Calculate the value of .got.plt.  */
10304   gotplt_value = (htab->sgotplt->output_section->vma
10305                   + htab->sgotplt->output_offset);
10306   gotplt_value_high = ((gotplt_value + 0x8000) >> 16) & 0xffff;
10307   gotplt_value_low = gotplt_value & 0xffff;
10308
10309   /* The PLT sequence is not safe for N64 if .got.plt's address can
10310      not be loaded in two instructions.  */
10311   BFD_ASSERT ((gotplt_value & ~(bfd_vma) 0x7fffffff) == 0
10312               || ~(gotplt_value | 0x7fffffff) == 0);
10313
10314   /* Install the PLT header.  */
10315   loc = htab->splt->contents;
10316   bfd_put_32 (output_bfd, plt_entry[0] | gotplt_value_high, loc);
10317   bfd_put_32 (output_bfd, plt_entry[1] | gotplt_value_low, loc + 4);
10318   bfd_put_32 (output_bfd, plt_entry[2] | gotplt_value_low, loc + 8);
10319   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10320   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10321   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10322   bfd_put_32 (output_bfd, plt_entry[6], loc + 24);
10323   bfd_put_32 (output_bfd, plt_entry[7], loc + 28);
10324 }
10325
10326 /* Install the PLT header for a VxWorks executable and finalize the
10327    contents of .rela.plt.unloaded.  */
10328
10329 static void
10330 mips_vxworks_finish_exec_plt (bfd *output_bfd, struct bfd_link_info *info)
10331 {
10332   Elf_Internal_Rela rela;
10333   bfd_byte *loc;
10334   bfd_vma got_value, got_value_high, got_value_low, plt_address;
10335   static const bfd_vma *plt_entry;
10336   struct mips_elf_link_hash_table *htab;
10337
10338   htab = mips_elf_hash_table (info);
10339   BFD_ASSERT (htab != NULL);
10340
10341   plt_entry = mips_vxworks_exec_plt0_entry;
10342
10343   /* Calculate the value of _GLOBAL_OFFSET_TABLE_.  */
10344   got_value = (htab->root.hgot->root.u.def.section->output_section->vma
10345                + htab->root.hgot->root.u.def.section->output_offset
10346                + htab->root.hgot->root.u.def.value);
10347
10348   got_value_high = ((got_value + 0x8000) >> 16) & 0xffff;
10349   got_value_low = got_value & 0xffff;
10350
10351   /* Calculate the address of the PLT header.  */
10352   plt_address = htab->splt->output_section->vma + htab->splt->output_offset;
10353
10354   /* Install the PLT header.  */
10355   loc = htab->splt->contents;
10356   bfd_put_32 (output_bfd, plt_entry[0] | got_value_high, loc);
10357   bfd_put_32 (output_bfd, plt_entry[1] | got_value_low, loc + 4);
10358   bfd_put_32 (output_bfd, plt_entry[2], loc + 8);
10359   bfd_put_32 (output_bfd, plt_entry[3], loc + 12);
10360   bfd_put_32 (output_bfd, plt_entry[4], loc + 16);
10361   bfd_put_32 (output_bfd, plt_entry[5], loc + 20);
10362
10363   /* Output the relocation for the lui of %hi(_GLOBAL_OFFSET_TABLE_).  */
10364   loc = htab->srelplt2->contents;
10365   rela.r_offset = plt_address;
10366   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10367   rela.r_addend = 0;
10368   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10369   loc += sizeof (Elf32_External_Rela);
10370
10371   /* Output the relocation for the following addiu of
10372      %lo(_GLOBAL_OFFSET_TABLE_).  */
10373   rela.r_offset += 4;
10374   rela.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10375   bfd_elf32_swap_reloca_out (output_bfd, &rela, loc);
10376   loc += sizeof (Elf32_External_Rela);
10377
10378   /* Fix up the remaining relocations.  They may have the wrong
10379      symbol index for _G_O_T_ or _P_L_T_ depending on the order
10380      in which symbols were output.  */
10381   while (loc < htab->srelplt2->contents + htab->srelplt2->size)
10382     {
10383       Elf_Internal_Rela rel;
10384
10385       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10386       rel.r_info = ELF32_R_INFO (htab->root.hplt->indx, R_MIPS_32);
10387       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10388       loc += sizeof (Elf32_External_Rela);
10389
10390       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10391       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_HI16);
10392       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10393       loc += sizeof (Elf32_External_Rela);
10394
10395       bfd_elf32_swap_reloca_in (output_bfd, loc, &rel);
10396       rel.r_info = ELF32_R_INFO (htab->root.hgot->indx, R_MIPS_LO16);
10397       bfd_elf32_swap_reloca_out (output_bfd, &rel, loc);
10398       loc += sizeof (Elf32_External_Rela);
10399     }
10400 }
10401
10402 /* Install the PLT header for a VxWorks shared library.  */
10403
10404 static void
10405 mips_vxworks_finish_shared_plt (bfd *output_bfd, struct bfd_link_info *info)
10406 {
10407   unsigned int i;
10408   struct mips_elf_link_hash_table *htab;
10409
10410   htab = mips_elf_hash_table (info);
10411   BFD_ASSERT (htab != NULL);
10412
10413   /* We just need to copy the entry byte-by-byte.  */
10414   for (i = 0; i < ARRAY_SIZE (mips_vxworks_shared_plt0_entry); i++)
10415     bfd_put_32 (output_bfd, mips_vxworks_shared_plt0_entry[i],
10416                 htab->splt->contents + i * 4);
10417 }
10418
10419 /* Finish up the dynamic sections.  */
10420
10421 bfd_boolean
10422 _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd,
10423                                        struct bfd_link_info *info)
10424 {
10425   bfd *dynobj;
10426   asection *sdyn;
10427   asection *sgot;
10428   struct mips_got_info *gg, *g;
10429   struct mips_elf_link_hash_table *htab;
10430
10431   htab = mips_elf_hash_table (info);
10432   BFD_ASSERT (htab != NULL);
10433
10434   dynobj = elf_hash_table (info)->dynobj;
10435
10436   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
10437
10438   sgot = htab->sgot;
10439   gg = htab->got_info;
10440
10441   if (elf_hash_table (info)->dynamic_sections_created)
10442     {
10443       bfd_byte *b;
10444       int dyn_to_skip = 0, dyn_skipped = 0;
10445
10446       BFD_ASSERT (sdyn != NULL);
10447       BFD_ASSERT (gg != NULL);
10448
10449       g = mips_elf_bfd_got (output_bfd, FALSE);
10450       BFD_ASSERT (g != NULL);
10451
10452       for (b = sdyn->contents;
10453            b < sdyn->contents + sdyn->size;
10454            b += MIPS_ELF_DYN_SIZE (dynobj))
10455         {
10456           Elf_Internal_Dyn dyn;
10457           const char *name;
10458           size_t elemsize;
10459           asection *s;
10460           bfd_boolean swap_out_p;
10461
10462           /* Read in the current dynamic entry.  */
10463           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10464
10465           /* Assume that we're going to modify it and write it out.  */
10466           swap_out_p = TRUE;
10467
10468           switch (dyn.d_tag)
10469             {
10470             case DT_RELENT:
10471               dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj);
10472               break;
10473
10474             case DT_RELAENT:
10475               BFD_ASSERT (htab->is_vxworks);
10476               dyn.d_un.d_val = MIPS_ELF_RELA_SIZE (dynobj);
10477               break;
10478
10479             case DT_STRSZ:
10480               /* Rewrite DT_STRSZ.  */
10481               dyn.d_un.d_val =
10482                 _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
10483               break;
10484
10485             case DT_PLTGOT:
10486               s = htab->sgot;
10487               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10488               break;
10489
10490             case DT_MIPS_PLTGOT:
10491               s = htab->sgotplt;
10492               dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
10493               break;
10494
10495             case DT_MIPS_RLD_VERSION:
10496               dyn.d_un.d_val = 1; /* XXX */
10497               break;
10498
10499             case DT_MIPS_FLAGS:
10500               dyn.d_un.d_val = RHF_NOTPOT; /* XXX */
10501               break;
10502
10503             case DT_MIPS_TIME_STAMP:
10504               {
10505                 time_t t;
10506                 time (&t);
10507                 dyn.d_un.d_val = t;
10508               }
10509               break;
10510
10511             case DT_MIPS_ICHECKSUM:
10512               /* XXX FIXME: */
10513               swap_out_p = FALSE;
10514               break;
10515
10516             case DT_MIPS_IVERSION:
10517               /* XXX FIXME: */
10518               swap_out_p = FALSE;
10519               break;
10520
10521             case DT_MIPS_BASE_ADDRESS:
10522               s = output_bfd->sections;
10523               BFD_ASSERT (s != NULL);
10524               dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
10525               break;
10526
10527             case DT_MIPS_LOCAL_GOTNO:
10528               dyn.d_un.d_val = g->local_gotno;
10529               break;
10530
10531             case DT_MIPS_UNREFEXTNO:
10532               /* The index into the dynamic symbol table which is the
10533                  entry of the first external symbol that is not
10534                  referenced within the same object.  */
10535               dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
10536               break;
10537
10538             case DT_MIPS_GOTSYM:
10539               if (htab->global_gotsym)
10540                 {
10541                   dyn.d_un.d_val = htab->global_gotsym->dynindx;
10542                   break;
10543                 }
10544               /* In case if we don't have global got symbols we default
10545                  to setting DT_MIPS_GOTSYM to the same value as
10546                  DT_MIPS_SYMTABNO, so we just fall through.  */
10547
10548             case DT_MIPS_SYMTABNO:
10549               name = ".dynsym";
10550               elemsize = MIPS_ELF_SYM_SIZE (output_bfd);
10551               s = bfd_get_section_by_name (output_bfd, name);
10552               BFD_ASSERT (s != NULL);
10553
10554               dyn.d_un.d_val = s->size / elemsize;
10555               break;
10556
10557             case DT_MIPS_HIPAGENO:
10558               dyn.d_un.d_val = g->local_gotno - htab->reserved_gotno;
10559               break;
10560
10561             case DT_MIPS_RLD_MAP:
10562               {
10563                 struct elf_link_hash_entry *h;
10564                 h = mips_elf_hash_table (info)->rld_symbol;
10565                 if (!h)
10566                   {
10567                     dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10568                     swap_out_p = FALSE;
10569                     break;
10570                   }
10571                 s = h->root.u.def.section;
10572                 dyn.d_un.d_ptr = (s->output_section->vma + s->output_offset
10573                                   + h->root.u.def.value);
10574               }
10575               break;
10576
10577             case DT_MIPS_OPTIONS:
10578               s = (bfd_get_section_by_name
10579                    (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd)));
10580               dyn.d_un.d_ptr = s->vma;
10581               break;
10582
10583             case DT_RELASZ:
10584               BFD_ASSERT (htab->is_vxworks);
10585               /* The count does not include the JUMP_SLOT relocations.  */
10586               if (htab->srelplt)
10587                 dyn.d_un.d_val -= htab->srelplt->size;
10588               break;
10589
10590             case DT_PLTREL:
10591               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10592               if (htab->is_vxworks)
10593                 dyn.d_un.d_val = DT_RELA;
10594               else
10595                 dyn.d_un.d_val = DT_REL;
10596               break;
10597
10598             case DT_PLTRELSZ:
10599               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10600               dyn.d_un.d_val = htab->srelplt->size;
10601               break;
10602
10603             case DT_JMPREL:
10604               BFD_ASSERT (htab->use_plts_and_copy_relocs);
10605               dyn.d_un.d_ptr = (htab->srelplt->output_section->vma
10606                                 + htab->srelplt->output_offset);
10607               break;
10608
10609             case DT_TEXTREL:
10610               /* If we didn't need any text relocations after all, delete
10611                  the dynamic tag.  */
10612               if (!(info->flags & DF_TEXTREL))
10613                 {
10614                   dyn_to_skip = MIPS_ELF_DYN_SIZE (dynobj);
10615                   swap_out_p = FALSE;
10616                 }
10617               break;
10618
10619             case DT_FLAGS:
10620               /* If we didn't need any text relocations after all, clear
10621                  DF_TEXTREL from DT_FLAGS.  */
10622               if (!(info->flags & DF_TEXTREL))
10623                 dyn.d_un.d_val &= ~DF_TEXTREL;
10624               else
10625                 swap_out_p = FALSE;
10626               break;
10627
10628             default:
10629               swap_out_p = FALSE;
10630               if (htab->is_vxworks
10631                   && elf_vxworks_finish_dynamic_entry (output_bfd, &dyn))
10632                 swap_out_p = TRUE;
10633               break;
10634             }
10635
10636           if (swap_out_p || dyn_skipped)
10637             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10638               (dynobj, &dyn, b - dyn_skipped);
10639
10640           if (dyn_to_skip)
10641             {
10642               dyn_skipped += dyn_to_skip;
10643               dyn_to_skip = 0;
10644             }
10645         }
10646
10647       /* Wipe out any trailing entries if we shifted down a dynamic tag.  */
10648       if (dyn_skipped > 0)
10649         memset (b - dyn_skipped, 0, dyn_skipped);
10650     }
10651
10652   if (sgot != NULL && sgot->size > 0
10653       && !bfd_is_abs_section (sgot->output_section))
10654     {
10655       if (htab->is_vxworks)
10656         {
10657           /* The first entry of the global offset table points to the
10658              ".dynamic" section.  The second is initialized by the
10659              loader and contains the shared library identifier.
10660              The third is also initialized by the loader and points
10661              to the lazy resolution stub.  */
10662           MIPS_ELF_PUT_WORD (output_bfd,
10663                              sdyn->output_offset + sdyn->output_section->vma,
10664                              sgot->contents);
10665           MIPS_ELF_PUT_WORD (output_bfd, 0,
10666                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10667           MIPS_ELF_PUT_WORD (output_bfd, 0,
10668                              sgot->contents
10669                              + 2 * MIPS_ELF_GOT_SIZE (output_bfd));
10670         }
10671       else
10672         {
10673           /* The first entry of the global offset table will be filled at
10674              runtime. The second entry will be used by some runtime loaders.
10675              This isn't the case of IRIX rld.  */
10676           MIPS_ELF_PUT_WORD (output_bfd, (bfd_vma) 0, sgot->contents);
10677           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10678                              sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd));
10679         }
10680
10681       elf_section_data (sgot->output_section)->this_hdr.sh_entsize
10682          = MIPS_ELF_GOT_SIZE (output_bfd);
10683     }
10684
10685   /* Generate dynamic relocations for the non-primary gots.  */
10686   if (gg != NULL && gg->next)
10687     {
10688       Elf_Internal_Rela rel[3];
10689       bfd_vma addend = 0;
10690
10691       memset (rel, 0, sizeof (rel));
10692       rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32);
10693
10694       for (g = gg->next; g->next != gg; g = g->next)
10695         {
10696           bfd_vma got_index = g->next->local_gotno + g->next->global_gotno
10697             + g->next->tls_gotno;
10698
10699           MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents
10700                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10701           MIPS_ELF_PUT_WORD (output_bfd, MIPS_ELF_GNU_GOT1_MASK (output_bfd),
10702                              sgot->contents
10703                              + got_index++ * MIPS_ELF_GOT_SIZE (output_bfd));
10704
10705           if (! info->shared)
10706             continue;
10707
10708           while (got_index < g->assigned_gotno)
10709             {
10710               rel[0].r_offset = rel[1].r_offset = rel[2].r_offset
10711                 = got_index++ * MIPS_ELF_GOT_SIZE (output_bfd);
10712               if (!(mips_elf_create_dynamic_relocation
10713                     (output_bfd, info, rel, NULL,
10714                      bfd_abs_section_ptr,
10715                      0, &addend, sgot)))
10716                 return FALSE;
10717               BFD_ASSERT (addend == 0);
10718             }
10719         }
10720     }
10721
10722   /* The generation of dynamic relocations for the non-primary gots
10723      adds more dynamic relocations.  We cannot count them until
10724      here.  */
10725
10726   if (elf_hash_table (info)->dynamic_sections_created)
10727     {
10728       bfd_byte *b;
10729       bfd_boolean swap_out_p;
10730
10731       BFD_ASSERT (sdyn != NULL);
10732
10733       for (b = sdyn->contents;
10734            b < sdyn->contents + sdyn->size;
10735            b += MIPS_ELF_DYN_SIZE (dynobj))
10736         {
10737           Elf_Internal_Dyn dyn;
10738           asection *s;
10739
10740           /* Read in the current dynamic entry.  */
10741           (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
10742
10743           /* Assume that we're going to modify it and write it out.  */
10744           swap_out_p = TRUE;
10745
10746           switch (dyn.d_tag)
10747             {
10748             case DT_RELSZ:
10749               /* Reduce DT_RELSZ to account for any relocations we
10750                  decided not to make.  This is for the n64 irix rld,
10751                  which doesn't seem to apply any relocations if there
10752                  are trailing null entries.  */
10753               s = mips_elf_rel_dyn_section (info, FALSE);
10754               dyn.d_un.d_val = (s->reloc_count
10755                                 * (ABI_64_P (output_bfd)
10756                                    ? sizeof (Elf64_Mips_External_Rel)
10757                                    : sizeof (Elf32_External_Rel)));
10758               /* Adjust the section size too.  Tools like the prelinker
10759                  can reasonably expect the values to the same.  */
10760               elf_section_data (s->output_section)->this_hdr.sh_size
10761                 = dyn.d_un.d_val;
10762               break;
10763
10764             default:
10765               swap_out_p = FALSE;
10766               break;
10767             }
10768
10769           if (swap_out_p)
10770             (*get_elf_backend_data (dynobj)->s->swap_dyn_out)
10771               (dynobj, &dyn, b);
10772         }
10773     }
10774
10775   {
10776     asection *s;
10777     Elf32_compact_rel cpt;
10778
10779     if (SGI_COMPAT (output_bfd))
10780       {
10781         /* Write .compact_rel section out.  */
10782         s = bfd_get_linker_section (dynobj, ".compact_rel");
10783         if (s != NULL)
10784           {
10785             cpt.id1 = 1;
10786             cpt.num = s->reloc_count;
10787             cpt.id2 = 2;
10788             cpt.offset = (s->output_section->filepos
10789                           + sizeof (Elf32_External_compact_rel));
10790             cpt.reserved0 = 0;
10791             cpt.reserved1 = 0;
10792             bfd_elf32_swap_compact_rel_out (output_bfd, &cpt,
10793                                             ((Elf32_External_compact_rel *)
10794                                              s->contents));
10795
10796             /* Clean up a dummy stub function entry in .text.  */
10797             if (htab->sstubs != NULL)
10798               {
10799                 file_ptr dummy_offset;
10800
10801                 BFD_ASSERT (htab->sstubs->size >= htab->function_stub_size);
10802                 dummy_offset = htab->sstubs->size - htab->function_stub_size;
10803                 memset (htab->sstubs->contents + dummy_offset, 0,
10804                         htab->function_stub_size);
10805               }
10806           }
10807       }
10808
10809     /* The psABI says that the dynamic relocations must be sorted in
10810        increasing order of r_symndx.  The VxWorks EABI doesn't require
10811        this, and because the code below handles REL rather than RELA
10812        relocations, using it for VxWorks would be outright harmful.  */
10813     if (!htab->is_vxworks)
10814       {
10815         s = mips_elf_rel_dyn_section (info, FALSE);
10816         if (s != NULL
10817             && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd))
10818           {
10819             reldyn_sorting_bfd = output_bfd;
10820
10821             if (ABI_64_P (output_bfd))
10822               qsort ((Elf64_External_Rel *) s->contents + 1,
10823                      s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel),
10824                      sort_dynamic_relocs_64);
10825             else
10826               qsort ((Elf32_External_Rel *) s->contents + 1,
10827                      s->reloc_count - 1, sizeof (Elf32_External_Rel),
10828                      sort_dynamic_relocs);
10829           }
10830       }
10831   }
10832
10833   if (htab->splt && htab->splt->size > 0)
10834     {
10835       if (htab->is_vxworks)
10836         {
10837           if (info->shared)
10838             mips_vxworks_finish_shared_plt (output_bfd, info);
10839           else
10840             mips_vxworks_finish_exec_plt (output_bfd, info);
10841         }
10842       else
10843         {
10844           BFD_ASSERT (!info->shared);
10845           mips_finish_exec_plt (output_bfd, info);
10846         }
10847     }
10848   return TRUE;
10849 }
10850
10851
10852 /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags.  */
10853
10854 static void
10855 mips_set_isa_flags (bfd *abfd)
10856 {
10857   flagword val;
10858
10859   switch (bfd_get_mach (abfd))
10860     {
10861     default:
10862     case bfd_mach_mips3000:
10863       val = E_MIPS_ARCH_1;
10864       break;
10865
10866     case bfd_mach_mips3900:
10867       val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900;
10868       break;
10869
10870     case bfd_mach_mips6000:
10871       val = E_MIPS_ARCH_2;
10872       break;
10873
10874     case bfd_mach_mips4000:
10875     case bfd_mach_mips4300:
10876     case bfd_mach_mips4400:
10877     case bfd_mach_mips4600:
10878       val = E_MIPS_ARCH_3;
10879       break;
10880
10881     case bfd_mach_mips4010:
10882       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010;
10883       break;
10884
10885     case bfd_mach_mips4100:
10886       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100;
10887       break;
10888
10889     case bfd_mach_mips4111:
10890       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111;
10891       break;
10892
10893     case bfd_mach_mips4120:
10894       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120;
10895       break;
10896
10897     case bfd_mach_mips4650:
10898       val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650;
10899       break;
10900
10901     case bfd_mach_mips5400:
10902       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400;
10903       break;
10904
10905     case bfd_mach_mips5500:
10906       val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500;
10907       break;
10908
10909     case bfd_mach_mips5900:
10910       val = E_MIPS_ARCH_3 | E_MIPS_MACH_5900;
10911       break;
10912
10913     case bfd_mach_mips9000:
10914       val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000;
10915       break;
10916
10917     case bfd_mach_mips5000:
10918     case bfd_mach_mips7000:
10919     case bfd_mach_mips8000:
10920     case bfd_mach_mips10000:
10921     case bfd_mach_mips12000:
10922     case bfd_mach_mips14000:
10923     case bfd_mach_mips16000:
10924       val = E_MIPS_ARCH_4;
10925       break;
10926
10927     case bfd_mach_mips5:
10928       val = E_MIPS_ARCH_5;
10929       break;
10930
10931     case bfd_mach_mips_loongson_2e:
10932       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2E;
10933       break;
10934
10935     case bfd_mach_mips_loongson_2f:
10936       val = E_MIPS_ARCH_3 | E_MIPS_MACH_LS2F;
10937       break;
10938
10939     case bfd_mach_mips_sb1:
10940       val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1;
10941       break;
10942
10943     case bfd_mach_mips_loongson_3a:
10944       val = E_MIPS_ARCH_64 | E_MIPS_MACH_LS3A;
10945       break;
10946
10947     case bfd_mach_mips_octeon:
10948     case bfd_mach_mips_octeonp:
10949       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON;
10950       break;
10951
10952     case bfd_mach_mips_xlr:
10953       val = E_MIPS_ARCH_64 | E_MIPS_MACH_XLR;
10954       break;
10955
10956     case bfd_mach_mips_octeon2:
10957       val = E_MIPS_ARCH_64R2 | E_MIPS_MACH_OCTEON2;
10958       break;
10959
10960     case bfd_mach_mipsisa32:
10961       val = E_MIPS_ARCH_32;
10962       break;
10963
10964     case bfd_mach_mipsisa64:
10965       val = E_MIPS_ARCH_64;
10966       break;
10967
10968     case bfd_mach_mipsisa32r2:
10969       val = E_MIPS_ARCH_32R2;
10970       break;
10971
10972     case bfd_mach_mipsisa64r2:
10973       val = E_MIPS_ARCH_64R2;
10974       break;
10975     }
10976   elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
10977   elf_elfheader (abfd)->e_flags |= val;
10978
10979 }
10980
10981
10982 /* The final processing done just before writing out a MIPS ELF object
10983    file.  This gets the MIPS architecture right based on the machine
10984    number.  This is used by both the 32-bit and the 64-bit ABI.  */
10985
10986 void
10987 _bfd_mips_elf_final_write_processing (bfd *abfd,
10988                                       bfd_boolean linker ATTRIBUTE_UNUSED)
10989 {
10990   unsigned int i;
10991   Elf_Internal_Shdr **hdrpp;
10992   const char *name;
10993   asection *sec;
10994
10995   /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former
10996      is nonzero.  This is for compatibility with old objects, which used
10997      a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH.  */
10998   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0)
10999     mips_set_isa_flags (abfd);
11000
11001   /* Set the sh_info field for .gptab sections and other appropriate
11002      info for each special section.  */
11003   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
11004        i < elf_numsections (abfd);
11005        i++, hdrpp++)
11006     {
11007       switch ((*hdrpp)->sh_type)
11008         {
11009         case SHT_MIPS_MSYM:
11010         case SHT_MIPS_LIBLIST:
11011           sec = bfd_get_section_by_name (abfd, ".dynstr");
11012           if (sec != NULL)
11013             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11014           break;
11015
11016         case SHT_MIPS_GPTAB:
11017           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11018           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11019           BFD_ASSERT (name != NULL
11020                       && CONST_STRNEQ (name, ".gptab."));
11021           sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1);
11022           BFD_ASSERT (sec != NULL);
11023           (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11024           break;
11025
11026         case SHT_MIPS_CONTENT:
11027           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11028           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11029           BFD_ASSERT (name != NULL
11030                       && CONST_STRNEQ (name, ".MIPS.content"));
11031           sec = bfd_get_section_by_name (abfd,
11032                                          name + sizeof ".MIPS.content" - 1);
11033           BFD_ASSERT (sec != NULL);
11034           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11035           break;
11036
11037         case SHT_MIPS_SYMBOL_LIB:
11038           sec = bfd_get_section_by_name (abfd, ".dynsym");
11039           if (sec != NULL)
11040             (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11041           sec = bfd_get_section_by_name (abfd, ".liblist");
11042           if (sec != NULL)
11043             (*hdrpp)->sh_info = elf_section_data (sec)->this_idx;
11044           break;
11045
11046         case SHT_MIPS_EVENTS:
11047           BFD_ASSERT ((*hdrpp)->bfd_section != NULL);
11048           name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section);
11049           BFD_ASSERT (name != NULL);
11050           if (CONST_STRNEQ (name, ".MIPS.events"))
11051             sec = bfd_get_section_by_name (abfd,
11052                                            name + sizeof ".MIPS.events" - 1);
11053           else
11054             {
11055               BFD_ASSERT (CONST_STRNEQ (name, ".MIPS.post_rel"));
11056               sec = bfd_get_section_by_name (abfd,
11057                                              (name
11058                                               + sizeof ".MIPS.post_rel" - 1));
11059             }
11060           BFD_ASSERT (sec != NULL);
11061           (*hdrpp)->sh_link = elf_section_data (sec)->this_idx;
11062           break;
11063
11064         }
11065     }
11066 }
11067 \f
11068 /* When creating an IRIX5 executable, we need REGINFO and RTPROC
11069    segments.  */
11070
11071 int
11072 _bfd_mips_elf_additional_program_headers (bfd *abfd,
11073                                           struct bfd_link_info *info ATTRIBUTE_UNUSED)
11074 {
11075   asection *s;
11076   int ret = 0;
11077
11078   /* See if we need a PT_MIPS_REGINFO segment.  */
11079   s = bfd_get_section_by_name (abfd, ".reginfo");
11080   if (s && (s->flags & SEC_LOAD))
11081     ++ret;
11082
11083   /* See if we need a PT_MIPS_OPTIONS segment.  */
11084   if (IRIX_COMPAT (abfd) == ict_irix6
11085       && bfd_get_section_by_name (abfd,
11086                                   MIPS_ELF_OPTIONS_SECTION_NAME (abfd)))
11087     ++ret;
11088
11089   /* See if we need a PT_MIPS_RTPROC segment.  */
11090   if (IRIX_COMPAT (abfd) == ict_irix5
11091       && bfd_get_section_by_name (abfd, ".dynamic")
11092       && bfd_get_section_by_name (abfd, ".mdebug"))
11093     ++ret;
11094
11095   /* Allocate a PT_NULL header in dynamic objects.  See
11096      _bfd_mips_elf_modify_segment_map for details.  */
11097   if (!SGI_COMPAT (abfd)
11098       && bfd_get_section_by_name (abfd, ".dynamic"))
11099     ++ret;
11100
11101   return ret;
11102 }
11103
11104 /* Modify the segment map for an IRIX5 executable.  */
11105
11106 bfd_boolean
11107 _bfd_mips_elf_modify_segment_map (bfd *abfd,
11108                                   struct bfd_link_info *info)
11109 {
11110   asection *s;
11111   struct elf_segment_map *m, **pm;
11112   bfd_size_type amt;
11113
11114   /* If there is a .reginfo section, we need a PT_MIPS_REGINFO
11115      segment.  */
11116   s = bfd_get_section_by_name (abfd, ".reginfo");
11117   if (s != NULL && (s->flags & SEC_LOAD) != 0)
11118     {
11119       for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11120         if (m->p_type == PT_MIPS_REGINFO)
11121           break;
11122       if (m == NULL)
11123         {
11124           amt = sizeof *m;
11125           m = bfd_zalloc (abfd, amt);
11126           if (m == NULL)
11127             return FALSE;
11128
11129           m->p_type = PT_MIPS_REGINFO;
11130           m->count = 1;
11131           m->sections[0] = s;
11132
11133           /* We want to put it after the PHDR and INTERP segments.  */
11134           pm = &elf_tdata (abfd)->segment_map;
11135           while (*pm != NULL
11136                  && ((*pm)->p_type == PT_PHDR
11137                      || (*pm)->p_type == PT_INTERP))
11138             pm = &(*pm)->next;
11139
11140           m->next = *pm;
11141           *pm = m;
11142         }
11143     }
11144
11145   /* For IRIX 6, we don't have .mdebug sections, nor does anything but
11146      .dynamic end up in PT_DYNAMIC.  However, we do have to insert a
11147      PT_MIPS_OPTIONS segment immediately following the program header
11148      table.  */
11149   if (NEWABI_P (abfd)
11150       /* On non-IRIX6 new abi, we'll have already created a segment
11151          for this section, so don't create another.  I'm not sure this
11152          is not also the case for IRIX 6, but I can't test it right
11153          now.  */
11154       && IRIX_COMPAT (abfd) == ict_irix6)
11155     {
11156       for (s = abfd->sections; s; s = s->next)
11157         if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS)
11158           break;
11159
11160       if (s)
11161         {
11162           struct elf_segment_map *options_segment;
11163
11164           pm = &elf_tdata (abfd)->segment_map;
11165           while (*pm != NULL
11166                  && ((*pm)->p_type == PT_PHDR
11167                      || (*pm)->p_type == PT_INTERP))
11168             pm = &(*pm)->next;
11169
11170           if (*pm == NULL || (*pm)->p_type != PT_MIPS_OPTIONS)
11171             {
11172               amt = sizeof (struct elf_segment_map);
11173               options_segment = bfd_zalloc (abfd, amt);
11174               options_segment->next = *pm;
11175               options_segment->p_type = PT_MIPS_OPTIONS;
11176               options_segment->p_flags = PF_R;
11177               options_segment->p_flags_valid = TRUE;
11178               options_segment->count = 1;
11179               options_segment->sections[0] = s;
11180               *pm = options_segment;
11181             }
11182         }
11183     }
11184   else
11185     {
11186       if (IRIX_COMPAT (abfd) == ict_irix5)
11187         {
11188           /* If there are .dynamic and .mdebug sections, we make a room
11189              for the RTPROC header.  FIXME: Rewrite without section names.  */
11190           if (bfd_get_section_by_name (abfd, ".interp") == NULL
11191               && bfd_get_section_by_name (abfd, ".dynamic") != NULL
11192               && bfd_get_section_by_name (abfd, ".mdebug") != NULL)
11193             {
11194               for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
11195                 if (m->p_type == PT_MIPS_RTPROC)
11196                   break;
11197               if (m == NULL)
11198                 {
11199                   amt = sizeof *m;
11200                   m = bfd_zalloc (abfd, amt);
11201                   if (m == NULL)
11202                     return FALSE;
11203
11204                   m->p_type = PT_MIPS_RTPROC;
11205
11206                   s = bfd_get_section_by_name (abfd, ".rtproc");
11207                   if (s == NULL)
11208                     {
11209                       m->count = 0;
11210                       m->p_flags = 0;
11211                       m->p_flags_valid = 1;
11212                     }
11213                   else
11214                     {
11215                       m->count = 1;
11216                       m->sections[0] = s;
11217                     }
11218
11219                   /* We want to put it after the DYNAMIC segment.  */
11220                   pm = &elf_tdata (abfd)->segment_map;
11221                   while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC)
11222                     pm = &(*pm)->next;
11223                   if (*pm != NULL)
11224                     pm = &(*pm)->next;
11225
11226                   m->next = *pm;
11227                   *pm = m;
11228                 }
11229             }
11230         }
11231       /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic,
11232          .dynstr, .dynsym, and .hash sections, and everything in
11233          between.  */
11234       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL;
11235            pm = &(*pm)->next)
11236         if ((*pm)->p_type == PT_DYNAMIC)
11237           break;
11238       m = *pm;
11239       if (m != NULL && IRIX_COMPAT (abfd) == ict_none)
11240         {
11241           /* For a normal mips executable the permissions for the PT_DYNAMIC
11242              segment are read, write and execute. We do that here since
11243              the code in elf.c sets only the read permission. This matters
11244              sometimes for the dynamic linker.  */
11245           if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
11246             {
11247               m->p_flags = PF_R | PF_W | PF_X;
11248               m->p_flags_valid = 1;
11249             }
11250         }
11251       /* GNU/Linux binaries do not need the extended PT_DYNAMIC section.
11252          glibc's dynamic linker has traditionally derived the number of
11253          tags from the p_filesz field, and sometimes allocates stack
11254          arrays of that size.  An overly-big PT_DYNAMIC segment can
11255          be actively harmful in such cases.  Making PT_DYNAMIC contain
11256          other sections can also make life hard for the prelinker,
11257          which might move one of the other sections to a different
11258          PT_LOAD segment.  */
11259       if (SGI_COMPAT (abfd)
11260           && m != NULL
11261           && m->count == 1
11262           && strcmp (m->sections[0]->name, ".dynamic") == 0)
11263         {
11264           static const char *sec_names[] =
11265           {
11266             ".dynamic", ".dynstr", ".dynsym", ".hash"
11267           };
11268           bfd_vma low, high;
11269           unsigned int i, c;
11270           struct elf_segment_map *n;
11271
11272           low = ~(bfd_vma) 0;
11273           high = 0;
11274           for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++)
11275             {
11276               s = bfd_get_section_by_name (abfd, sec_names[i]);
11277               if (s != NULL && (s->flags & SEC_LOAD) != 0)
11278                 {
11279                   bfd_size_type sz;
11280
11281                   if (low > s->vma)
11282                     low = s->vma;
11283                   sz = s->size;
11284                   if (high < s->vma + sz)
11285                     high = s->vma + sz;
11286                 }
11287             }
11288
11289           c = 0;
11290           for (s = abfd->sections; s != NULL; s = s->next)
11291             if ((s->flags & SEC_LOAD) != 0
11292                 && s->vma >= low
11293                 && s->vma + s->size <= high)
11294               ++c;
11295
11296           amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *);
11297           n = bfd_zalloc (abfd, amt);
11298           if (n == NULL)
11299             return FALSE;
11300           *n = *m;
11301           n->count = c;
11302
11303           i = 0;
11304           for (s = abfd->sections; s != NULL; s = s->next)
11305             {
11306               if ((s->flags & SEC_LOAD) != 0
11307                   && s->vma >= low
11308                   && s->vma + s->size <= high)
11309                 {
11310                   n->sections[i] = s;
11311                   ++i;
11312                 }
11313             }
11314
11315           *pm = n;
11316         }
11317     }
11318
11319   /* Allocate a spare program header in dynamic objects so that tools
11320      like the prelinker can add an extra PT_LOAD entry.
11321
11322      If the prelinker needs to make room for a new PT_LOAD entry, its
11323      standard procedure is to move the first (read-only) sections into
11324      the new (writable) segment.  However, the MIPS ABI requires
11325      .dynamic to be in a read-only segment, and the section will often
11326      start within sizeof (ElfNN_Phdr) bytes of the last program header.
11327
11328      Although the prelinker could in principle move .dynamic to a
11329      writable segment, it seems better to allocate a spare program
11330      header instead, and avoid the need to move any sections.
11331      There is a long tradition of allocating spare dynamic tags,
11332      so allocating a spare program header seems like a natural
11333      extension.
11334
11335      If INFO is NULL, we may be copying an already prelinked binary
11336      with objcopy or strip, so do not add this header.  */
11337   if (info != NULL
11338       && !SGI_COMPAT (abfd)
11339       && bfd_get_section_by_name (abfd, ".dynamic"))
11340     {
11341       for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL; pm = &(*pm)->next)
11342         if ((*pm)->p_type == PT_NULL)
11343           break;
11344       if (*pm == NULL)
11345         {
11346           m = bfd_zalloc (abfd, sizeof (*m));
11347           if (m == NULL)
11348             return FALSE;
11349
11350           m->p_type = PT_NULL;
11351           *pm = m;
11352         }
11353     }
11354
11355   return TRUE;
11356 }
11357 \f
11358 /* Return the section that should be marked against GC for a given
11359    relocation.  */
11360
11361 asection *
11362 _bfd_mips_elf_gc_mark_hook (asection *sec,
11363                             struct bfd_link_info *info,
11364                             Elf_Internal_Rela *rel,
11365                             struct elf_link_hash_entry *h,
11366                             Elf_Internal_Sym *sym)
11367 {
11368   /* ??? Do mips16 stub sections need to be handled special?  */
11369
11370   if (h != NULL)
11371     switch (ELF_R_TYPE (sec->owner, rel->r_info))
11372       {
11373       case R_MIPS_GNU_VTINHERIT:
11374       case R_MIPS_GNU_VTENTRY:
11375         return NULL;
11376       }
11377
11378   return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
11379 }
11380
11381 /* Update the got entry reference counts for the section being removed.  */
11382
11383 bfd_boolean
11384 _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED,
11385                              struct bfd_link_info *info ATTRIBUTE_UNUSED,
11386                              asection *sec ATTRIBUTE_UNUSED,
11387                              const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED)
11388 {
11389 #if 0
11390   Elf_Internal_Shdr *symtab_hdr;
11391   struct elf_link_hash_entry **sym_hashes;
11392   bfd_signed_vma *local_got_refcounts;
11393   const Elf_Internal_Rela *rel, *relend;
11394   unsigned long r_symndx;
11395   struct elf_link_hash_entry *h;
11396
11397   if (info->relocatable)
11398     return TRUE;
11399
11400   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11401   sym_hashes = elf_sym_hashes (abfd);
11402   local_got_refcounts = elf_local_got_refcounts (abfd);
11403
11404   relend = relocs + sec->reloc_count;
11405   for (rel = relocs; rel < relend; rel++)
11406     switch (ELF_R_TYPE (abfd, rel->r_info))
11407       {
11408       case R_MIPS16_GOT16:
11409       case R_MIPS16_CALL16:
11410       case R_MIPS_GOT16:
11411       case R_MIPS_CALL16:
11412       case R_MIPS_CALL_HI16:
11413       case R_MIPS_CALL_LO16:
11414       case R_MIPS_GOT_HI16:
11415       case R_MIPS_GOT_LO16:
11416       case R_MIPS_GOT_DISP:
11417       case R_MIPS_GOT_PAGE:
11418       case R_MIPS_GOT_OFST:
11419       case R_MICROMIPS_GOT16:
11420       case R_MICROMIPS_CALL16:
11421       case R_MICROMIPS_CALL_HI16:
11422       case R_MICROMIPS_CALL_LO16:
11423       case R_MICROMIPS_GOT_HI16:
11424       case R_MICROMIPS_GOT_LO16:
11425       case R_MICROMIPS_GOT_DISP:
11426       case R_MICROMIPS_GOT_PAGE:
11427       case R_MICROMIPS_GOT_OFST:
11428         /* ??? It would seem that the existing MIPS code does no sort
11429            of reference counting or whatnot on its GOT and PLT entries,
11430            so it is not possible to garbage collect them at this time.  */
11431         break;
11432
11433       default:
11434         break;
11435       }
11436 #endif
11437
11438   return TRUE;
11439 }
11440 \f
11441 /* Copy data from a MIPS ELF indirect symbol to its direct symbol,
11442    hiding the old indirect symbol.  Process additional relocation
11443    information.  Also called for weakdefs, in which case we just let
11444    _bfd_elf_link_hash_copy_indirect copy the flags for us.  */
11445
11446 void
11447 _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info,
11448                                     struct elf_link_hash_entry *dir,
11449                                     struct elf_link_hash_entry *ind)
11450 {
11451   struct mips_elf_link_hash_entry *dirmips, *indmips;
11452
11453   _bfd_elf_link_hash_copy_indirect (info, dir, ind);
11454
11455   dirmips = (struct mips_elf_link_hash_entry *) dir;
11456   indmips = (struct mips_elf_link_hash_entry *) ind;
11457   /* Any absolute non-dynamic relocations against an indirect or weak
11458      definition will be against the target symbol.  */
11459   if (indmips->has_static_relocs)
11460     dirmips->has_static_relocs = TRUE;
11461
11462   if (ind->root.type != bfd_link_hash_indirect)
11463     return;
11464
11465   dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs;
11466   if (indmips->readonly_reloc)
11467     dirmips->readonly_reloc = TRUE;
11468   if (indmips->no_fn_stub)
11469     dirmips->no_fn_stub = TRUE;
11470   if (indmips->fn_stub)
11471     {
11472       dirmips->fn_stub = indmips->fn_stub;
11473       indmips->fn_stub = NULL;
11474     }
11475   if (indmips->need_fn_stub)
11476     {
11477       dirmips->need_fn_stub = TRUE;
11478       indmips->need_fn_stub = FALSE;
11479     }
11480   if (indmips->call_stub)
11481     {
11482       dirmips->call_stub = indmips->call_stub;
11483       indmips->call_stub = NULL;
11484     }
11485   if (indmips->call_fp_stub)
11486     {
11487       dirmips->call_fp_stub = indmips->call_fp_stub;
11488       indmips->call_fp_stub = NULL;
11489     }
11490   if (indmips->global_got_area < dirmips->global_got_area)
11491     dirmips->global_got_area = indmips->global_got_area;
11492   if (indmips->global_got_area < GGA_NONE)
11493     indmips->global_got_area = GGA_NONE;
11494   if (indmips->has_nonpic_branches)
11495     dirmips->has_nonpic_branches = TRUE;
11496 }
11497 \f
11498 #define PDR_SIZE 32
11499
11500 bfd_boolean
11501 _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
11502                             struct bfd_link_info *info)
11503 {
11504   asection *o;
11505   bfd_boolean ret = FALSE;
11506   unsigned char *tdata;
11507   size_t i, skip;
11508
11509   o = bfd_get_section_by_name (abfd, ".pdr");
11510   if (! o)
11511     return FALSE;
11512   if (o->size == 0)
11513     return FALSE;
11514   if (o->size % PDR_SIZE != 0)
11515     return FALSE;
11516   if (o->output_section != NULL
11517       && bfd_is_abs_section (o->output_section))
11518     return FALSE;
11519
11520   tdata = bfd_zmalloc (o->size / PDR_SIZE);
11521   if (! tdata)
11522     return FALSE;
11523
11524   cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
11525                                             info->keep_memory);
11526   if (!cookie->rels)
11527     {
11528       free (tdata);
11529       return FALSE;
11530     }
11531
11532   cookie->rel = cookie->rels;
11533   cookie->relend = cookie->rels + o->reloc_count;
11534
11535   for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++)
11536     {
11537       if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
11538         {
11539           tdata[i] = 1;
11540           skip ++;
11541         }
11542     }
11543
11544   if (skip != 0)
11545     {
11546       mips_elf_section_data (o)->u.tdata = tdata;
11547       o->size -= skip * PDR_SIZE;
11548       ret = TRUE;
11549     }
11550   else
11551     free (tdata);
11552
11553   if (! info->keep_memory)
11554     free (cookie->rels);
11555
11556   return ret;
11557 }
11558
11559 bfd_boolean
11560 _bfd_mips_elf_ignore_discarded_relocs (asection *sec)
11561 {
11562   if (strcmp (sec->name, ".pdr") == 0)
11563     return TRUE;
11564   return FALSE;
11565 }
11566
11567 bfd_boolean
11568 _bfd_mips_elf_write_section (bfd *output_bfd,
11569                              struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
11570                              asection *sec, bfd_byte *contents)
11571 {
11572   bfd_byte *to, *from, *end;
11573   int i;
11574
11575   if (strcmp (sec->name, ".pdr") != 0)
11576     return FALSE;
11577
11578   if (mips_elf_section_data (sec)->u.tdata == NULL)
11579     return FALSE;
11580
11581   to = contents;
11582   end = contents + sec->size;
11583   for (from = contents, i = 0;
11584        from < end;
11585        from += PDR_SIZE, i++)
11586     {
11587       if ((mips_elf_section_data (sec)->u.tdata)[i] == 1)
11588         continue;
11589       if (to != from)
11590         memcpy (to, from, PDR_SIZE);
11591       to += PDR_SIZE;
11592     }
11593   bfd_set_section_contents (output_bfd, sec->output_section, contents,
11594                             sec->output_offset, sec->size);
11595   return TRUE;
11596 }
11597 \f
11598 /* microMIPS code retains local labels for linker relaxation.  Omit them
11599    from output by default for clarity.  */
11600
11601 bfd_boolean
11602 _bfd_mips_elf_is_target_special_symbol (bfd *abfd, asymbol *sym)
11603 {
11604   return _bfd_elf_is_local_label_name (abfd, sym->name);
11605 }
11606
11607 /* MIPS ELF uses a special find_nearest_line routine in order the
11608    handle the ECOFF debugging information.  */
11609
11610 struct mips_elf_find_line
11611 {
11612   struct ecoff_debug_info d;
11613   struct ecoff_find_line i;
11614 };
11615
11616 bfd_boolean
11617 _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section,
11618                                  asymbol **symbols, bfd_vma offset,
11619                                  const char **filename_ptr,
11620                                  const char **functionname_ptr,
11621                                  unsigned int *line_ptr)
11622 {
11623   asection *msec;
11624
11625   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
11626                                      filename_ptr, functionname_ptr,
11627                                      line_ptr))
11628     return TRUE;
11629
11630   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
11631                                      section, symbols, offset,
11632                                      filename_ptr, functionname_ptr,
11633                                      line_ptr, NULL, ABI_64_P (abfd) ? 8 : 0,
11634                                      &elf_tdata (abfd)->dwarf2_find_line_info))
11635     return TRUE;
11636
11637   msec = bfd_get_section_by_name (abfd, ".mdebug");
11638   if (msec != NULL)
11639     {
11640       flagword origflags;
11641       struct mips_elf_find_line *fi;
11642       const struct ecoff_debug_swap * const swap =
11643         get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
11644
11645       /* If we are called during a link, mips_elf_final_link may have
11646          cleared the SEC_HAS_CONTENTS field.  We force it back on here
11647          if appropriate (which it normally will be).  */
11648       origflags = msec->flags;
11649       if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS)
11650         msec->flags |= SEC_HAS_CONTENTS;
11651
11652       fi = elf_tdata (abfd)->find_line_info;
11653       if (fi == NULL)
11654         {
11655           bfd_size_type external_fdr_size;
11656           char *fraw_src;
11657           char *fraw_end;
11658           struct fdr *fdr_ptr;
11659           bfd_size_type amt = sizeof (struct mips_elf_find_line);
11660
11661           fi = bfd_zalloc (abfd, amt);
11662           if (fi == NULL)
11663             {
11664               msec->flags = origflags;
11665               return FALSE;
11666             }
11667
11668           if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d))
11669             {
11670               msec->flags = origflags;
11671               return FALSE;
11672             }
11673
11674           /* Swap in the FDR information.  */
11675           amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr);
11676           fi->d.fdr = bfd_alloc (abfd, amt);
11677           if (fi->d.fdr == NULL)
11678             {
11679               msec->flags = origflags;
11680               return FALSE;
11681             }
11682           external_fdr_size = swap->external_fdr_size;
11683           fdr_ptr = fi->d.fdr;
11684           fraw_src = (char *) fi->d.external_fdr;
11685           fraw_end = (fraw_src
11686                       + fi->d.symbolic_header.ifdMax * external_fdr_size);
11687           for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
11688             (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr);
11689
11690           elf_tdata (abfd)->find_line_info = fi;
11691
11692           /* Note that we don't bother to ever free this information.
11693              find_nearest_line is either called all the time, as in
11694              objdump -l, so the information should be saved, or it is
11695              rarely called, as in ld error messages, so the memory
11696              wasted is unimportant.  Still, it would probably be a
11697              good idea for free_cached_info to throw it away.  */
11698         }
11699
11700       if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap,
11701                                   &fi->i, filename_ptr, functionname_ptr,
11702                                   line_ptr))
11703         {
11704           msec->flags = origflags;
11705           return TRUE;
11706         }
11707
11708       msec->flags = origflags;
11709     }
11710
11711   /* Fall back on the generic ELF find_nearest_line routine.  */
11712
11713   return _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
11714                                      filename_ptr, functionname_ptr,
11715                                      line_ptr);
11716 }
11717
11718 bfd_boolean
11719 _bfd_mips_elf_find_inliner_info (bfd *abfd,
11720                                  const char **filename_ptr,
11721                                  const char **functionname_ptr,
11722                                  unsigned int *line_ptr)
11723 {
11724   bfd_boolean found;
11725   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
11726                                          functionname_ptr, line_ptr,
11727                                          & elf_tdata (abfd)->dwarf2_find_line_info);
11728   return found;
11729 }
11730
11731 \f
11732 /* When are writing out the .options or .MIPS.options section,
11733    remember the bytes we are writing out, so that we can install the
11734    GP value in the section_processing routine.  */
11735
11736 bfd_boolean
11737 _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section,
11738                                     const void *location,
11739                                     file_ptr offset, bfd_size_type count)
11740 {
11741   if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name))
11742     {
11743       bfd_byte *c;
11744
11745       if (elf_section_data (section) == NULL)
11746         {
11747           bfd_size_type amt = sizeof (struct bfd_elf_section_data);
11748           section->used_by_bfd = bfd_zalloc (abfd, amt);
11749           if (elf_section_data (section) == NULL)
11750             return FALSE;
11751         }
11752       c = mips_elf_section_data (section)->u.tdata;
11753       if (c == NULL)
11754         {
11755           c = bfd_zalloc (abfd, section->size);
11756           if (c == NULL)
11757             return FALSE;
11758           mips_elf_section_data (section)->u.tdata = c;
11759         }
11760
11761       memcpy (c + offset, location, count);
11762     }
11763
11764   return _bfd_elf_set_section_contents (abfd, section, location, offset,
11765                                         count);
11766 }
11767
11768 /* This is almost identical to bfd_generic_get_... except that some
11769    MIPS relocations need to be handled specially.  Sigh.  */
11770
11771 bfd_byte *
11772 _bfd_elf_mips_get_relocated_section_contents
11773   (bfd *abfd,
11774    struct bfd_link_info *link_info,
11775    struct bfd_link_order *link_order,
11776    bfd_byte *data,
11777    bfd_boolean relocatable,
11778    asymbol **symbols)
11779 {
11780   /* Get enough memory to hold the stuff */
11781   bfd *input_bfd = link_order->u.indirect.section->owner;
11782   asection *input_section = link_order->u.indirect.section;
11783   bfd_size_type sz;
11784
11785   long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section);
11786   arelent **reloc_vector = NULL;
11787   long reloc_count;
11788
11789   if (reloc_size < 0)
11790     goto error_return;
11791
11792   reloc_vector = bfd_malloc (reloc_size);
11793   if (reloc_vector == NULL && reloc_size != 0)
11794     goto error_return;
11795
11796   /* read in the section */
11797   sz = input_section->rawsize ? input_section->rawsize : input_section->size;
11798   if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz))
11799     goto error_return;
11800
11801   reloc_count = bfd_canonicalize_reloc (input_bfd,
11802                                         input_section,
11803                                         reloc_vector,
11804                                         symbols);
11805   if (reloc_count < 0)
11806     goto error_return;
11807
11808   if (reloc_count > 0)
11809     {
11810       arelent **parent;
11811       /* for mips */
11812       int gp_found;
11813       bfd_vma gp = 0x12345678;  /* initialize just to shut gcc up */
11814
11815       {
11816         struct bfd_hash_entry *h;
11817         struct bfd_link_hash_entry *lh;
11818         /* Skip all this stuff if we aren't mixing formats.  */
11819         if (abfd && input_bfd
11820             && abfd->xvec == input_bfd->xvec)
11821           lh = 0;
11822         else
11823           {
11824             h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE);
11825             lh = (struct bfd_link_hash_entry *) h;
11826           }
11827       lookup:
11828         if (lh)
11829           {
11830             switch (lh->type)
11831               {
11832               case bfd_link_hash_undefined:
11833               case bfd_link_hash_undefweak:
11834               case bfd_link_hash_common:
11835                 gp_found = 0;
11836                 break;
11837               case bfd_link_hash_defined:
11838               case bfd_link_hash_defweak:
11839                 gp_found = 1;
11840                 gp = lh->u.def.value;
11841                 break;
11842               case bfd_link_hash_indirect:
11843               case bfd_link_hash_warning:
11844                 lh = lh->u.i.link;
11845                 /* @@FIXME  ignoring warning for now */
11846                 goto lookup;
11847               case bfd_link_hash_new:
11848               default:
11849                 abort ();
11850               }
11851           }
11852         else
11853           gp_found = 0;
11854       }
11855       /* end mips */
11856       for (parent = reloc_vector; *parent != NULL; parent++)
11857         {
11858           char *error_message = NULL;
11859           bfd_reloc_status_type r;
11860
11861           /* Specific to MIPS: Deal with relocation types that require
11862              knowing the gp of the output bfd.  */
11863           asymbol *sym = *(*parent)->sym_ptr_ptr;
11864
11865           /* If we've managed to find the gp and have a special
11866              function for the relocation then go ahead, else default
11867              to the generic handling.  */
11868           if (gp_found
11869               && (*parent)->howto->special_function
11870               == _bfd_mips_elf32_gprel16_reloc)
11871             r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent,
11872                                                input_section, relocatable,
11873                                                data, gp);
11874           else
11875             r = bfd_perform_relocation (input_bfd, *parent, data,
11876                                         input_section,
11877                                         relocatable ? abfd : NULL,
11878                                         &error_message);
11879
11880           if (relocatable)
11881             {
11882               asection *os = input_section->output_section;
11883
11884               /* A partial link, so keep the relocs */
11885               os->orelocation[os->reloc_count] = *parent;
11886               os->reloc_count++;
11887             }
11888
11889           if (r != bfd_reloc_ok)
11890             {
11891               switch (r)
11892                 {
11893                 case bfd_reloc_undefined:
11894                   if (!((*link_info->callbacks->undefined_symbol)
11895                         (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11896                          input_bfd, input_section, (*parent)->address, TRUE)))
11897                     goto error_return;
11898                   break;
11899                 case bfd_reloc_dangerous:
11900                   BFD_ASSERT (error_message != NULL);
11901                   if (!((*link_info->callbacks->reloc_dangerous)
11902                         (link_info, error_message, input_bfd, input_section,
11903                          (*parent)->address)))
11904                     goto error_return;
11905                   break;
11906                 case bfd_reloc_overflow:
11907                   if (!((*link_info->callbacks->reloc_overflow)
11908                         (link_info, NULL,
11909                          bfd_asymbol_name (*(*parent)->sym_ptr_ptr),
11910                          (*parent)->howto->name, (*parent)->addend,
11911                          input_bfd, input_section, (*parent)->address)))
11912                     goto error_return;
11913                   break;
11914                 case bfd_reloc_outofrange:
11915                 default:
11916                   abort ();
11917                   break;
11918                 }
11919
11920             }
11921         }
11922     }
11923   if (reloc_vector != NULL)
11924     free (reloc_vector);
11925   return data;
11926
11927 error_return:
11928   if (reloc_vector != NULL)
11929     free (reloc_vector);
11930   return NULL;
11931 }
11932 \f
11933 static bfd_boolean
11934 mips_elf_relax_delete_bytes (bfd *abfd,
11935                              asection *sec, bfd_vma addr, int count)
11936 {
11937   Elf_Internal_Shdr *symtab_hdr;
11938   unsigned int sec_shndx;
11939   bfd_byte *contents;
11940   Elf_Internal_Rela *irel, *irelend;
11941   Elf_Internal_Sym *isym;
11942   Elf_Internal_Sym *isymend;
11943   struct elf_link_hash_entry **sym_hashes;
11944   struct elf_link_hash_entry **end_hashes;
11945   struct elf_link_hash_entry **start_hashes;
11946   unsigned int symcount;
11947
11948   sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
11949   contents = elf_section_data (sec)->this_hdr.contents;
11950
11951   irel = elf_section_data (sec)->relocs;
11952   irelend = irel + sec->reloc_count;
11953
11954   /* Actually delete the bytes.  */
11955   memmove (contents + addr, contents + addr + count,
11956            (size_t) (sec->size - addr - count));
11957   sec->size -= count;
11958
11959   /* Adjust all the relocs.  */
11960   for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++)
11961     {
11962       /* Get the new reloc address.  */
11963       if (irel->r_offset > addr)
11964         irel->r_offset -= count;
11965     }
11966
11967   BFD_ASSERT (addr % 2 == 0);
11968   BFD_ASSERT (count % 2 == 0);
11969
11970   /* Adjust the local symbols defined in this section.  */
11971   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11972   isym = (Elf_Internal_Sym *) symtab_hdr->contents;
11973   for (isymend = isym + symtab_hdr->sh_info; isym < isymend; isym++)
11974     if (isym->st_shndx == sec_shndx && isym->st_value > addr)
11975       isym->st_value -= count;
11976
11977   /* Now adjust the global symbols defined in this section.  */
11978   symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym)
11979               - symtab_hdr->sh_info);
11980   sym_hashes = start_hashes = elf_sym_hashes (abfd);
11981   end_hashes = sym_hashes + symcount;
11982
11983   for (; sym_hashes < end_hashes; sym_hashes++)
11984     {
11985       struct elf_link_hash_entry *sym_hash = *sym_hashes;
11986
11987       if ((sym_hash->root.type == bfd_link_hash_defined
11988            || sym_hash->root.type == bfd_link_hash_defweak)
11989           && sym_hash->root.u.def.section == sec)
11990         {
11991           bfd_vma value = sym_hash->root.u.def.value;
11992
11993           if (ELF_ST_IS_MICROMIPS (sym_hash->other))
11994             value &= MINUS_TWO;
11995           if (value > addr)
11996             sym_hash->root.u.def.value -= count;
11997         }
11998     }
11999
12000   return TRUE;
12001 }
12002
12003
12004 /* Opcodes needed for microMIPS relaxation as found in
12005    opcodes/micromips-opc.c.  */
12006
12007 struct opcode_descriptor {
12008   unsigned long match;
12009   unsigned long mask;
12010 };
12011
12012 /* The $ra register aka $31.  */
12013
12014 #define RA 31
12015
12016 /* 32-bit instruction format register fields.  */
12017
12018 #define OP32_SREG(opcode) (((opcode) >> 16) & 0x1f)
12019 #define OP32_TREG(opcode) (((opcode) >> 21) & 0x1f)
12020
12021 /* Check if a 5-bit register index can be abbreviated to 3 bits.  */
12022
12023 #define OP16_VALID_REG(r) \
12024   ((2 <= (r) && (r) <= 7) || (16 <= (r) && (r) <= 17))
12025
12026
12027 /* 32-bit and 16-bit branches.  */
12028
12029 static const struct opcode_descriptor b_insns_32[] = {
12030   { /* "b",     "p",            */ 0x40400000, 0xffff0000 }, /* bgez 0 */
12031   { /* "b",     "p",            */ 0x94000000, 0xffff0000 }, /* beq 0, 0 */
12032   { 0, 0 }  /* End marker for find_match().  */
12033 };
12034
12035 static const struct opcode_descriptor bc_insn_32 =
12036   { /* "bc(1|2)(ft)", "N,p",    */ 0x42800000, 0xfec30000 };
12037
12038 static const struct opcode_descriptor bz_insn_32 =
12039   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 };
12040
12041 static const struct opcode_descriptor bzal_insn_32 =
12042   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 };
12043
12044 static const struct opcode_descriptor beq_insn_32 =
12045   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 };
12046
12047 static const struct opcode_descriptor b_insn_16 =
12048   { /* "b",     "mD",           */ 0xcc00,     0xfc00 };
12049
12050 static const struct opcode_descriptor bz_insn_16 =
12051   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 };
12052
12053
12054 /* 32-bit and 16-bit branch EQ and NE zero.  */
12055
12056 /* NOTE: All opcode tables have BEQ/BNE in the same order: first the
12057    eq and second the ne.  This convention is used when replacing a
12058    32-bit BEQ/BNE with the 16-bit version.  */
12059
12060 #define BZC32_REG_FIELD(r) (((r) & 0x1f) << 16)
12061
12062 static const struct opcode_descriptor bz_rs_insns_32[] = {
12063   { /* "beqz",  "s,p",          */ 0x94000000, 0xffe00000 },
12064   { /* "bnez",  "s,p",          */ 0xb4000000, 0xffe00000 },
12065   { 0, 0 }  /* End marker for find_match().  */
12066 };
12067
12068 static const struct opcode_descriptor bz_rt_insns_32[] = {
12069   { /* "beqz",  "t,p",          */ 0x94000000, 0xfc01f000 },
12070   { /* "bnez",  "t,p",          */ 0xb4000000, 0xfc01f000 },
12071   { 0, 0 }  /* End marker for find_match().  */
12072 };
12073
12074 static const struct opcode_descriptor bzc_insns_32[] = {
12075   { /* "beqzc", "s,p",          */ 0x40e00000, 0xffe00000 },
12076   { /* "bnezc", "s,p",          */ 0x40a00000, 0xffe00000 },
12077   { 0, 0 }  /* End marker for find_match().  */
12078 };
12079
12080 static const struct opcode_descriptor bz_insns_16[] = {
12081   { /* "beqz",  "md,mE",        */ 0x8c00,     0xfc00 },
12082   { /* "bnez",  "md,mE",        */ 0xac00,     0xfc00 },
12083   { 0, 0 }  /* End marker for find_match().  */
12084 };
12085
12086 /* Switch between a 5-bit register index and its 3-bit shorthand.  */
12087
12088 #define BZ16_REG(opcode) ((((((opcode) >> 7) & 7) + 0x1e) & 0x17) + 2)
12089 #define BZ16_REG_FIELD(r) \
12090   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 7)
12091
12092
12093 /* 32-bit instructions with a delay slot.  */
12094
12095 static const struct opcode_descriptor jal_insn_32_bd16 =
12096   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 };
12097
12098 static const struct opcode_descriptor jal_insn_32_bd32 =
12099   { /* "jal",   "a",            */ 0xf4000000, 0xfc000000 };
12100
12101 static const struct opcode_descriptor jal_x_insn_32_bd32 =
12102   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 };
12103
12104 static const struct opcode_descriptor j_insn_32 =
12105   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 };
12106
12107 static const struct opcode_descriptor jalr_insn_32 =
12108   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff };
12109
12110 /* This table can be compacted, because no opcode replacement is made.  */
12111
12112 static const struct opcode_descriptor ds_insns_32_bd16[] = {
12113   { /* "jals",  "a",            */ 0x74000000, 0xfc000000 },
12114
12115   { /* "jalrs[.hb]", "t,s",     */ 0x00004f3c, 0xfc00efff },
12116   { /* "b(ge|lt)zals", "s,p",   */ 0x42200000, 0xffa00000 },
12117
12118   { /* "b(g|l)(e|t)z", "s,p",   */ 0x40000000, 0xff200000 },
12119   { /* "b(eq|ne)", "s,t,p",     */ 0x94000000, 0xdc000000 },
12120   { /* "j",     "a",            */ 0xd4000000, 0xfc000000 },
12121   { 0, 0 }  /* End marker for find_match().  */
12122 };
12123
12124 /* This table can be compacted, because no opcode replacement is made.  */
12125
12126 static const struct opcode_descriptor ds_insns_32_bd32[] = {
12127   { /* "jal[x]", "a",           */ 0xf0000000, 0xf8000000 },
12128
12129   { /* "jalr[.hb]", "t,s",      */ 0x00000f3c, 0xfc00efff },
12130   { /* "b(ge|lt)zal", "s,p",    */ 0x40200000, 0xffa00000 },
12131   { 0, 0 }  /* End marker for find_match().  */
12132 };
12133
12134
12135 /* 16-bit instructions with a delay slot.  */
12136
12137 static const struct opcode_descriptor jalr_insn_16_bd16 =
12138   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 };
12139
12140 static const struct opcode_descriptor jalr_insn_16_bd32 =
12141   { /* "jalr",  "my,mj",        */ 0x45c0,     0xffe0 };
12142
12143 static const struct opcode_descriptor jr_insn_16 =
12144   { /* "jr",    "mj",           */ 0x4580,     0xffe0 };
12145
12146 #define JR16_REG(opcode) ((opcode) & 0x1f)
12147
12148 /* This table can be compacted, because no opcode replacement is made.  */
12149
12150 static const struct opcode_descriptor ds_insns_16_bd16[] = {
12151   { /* "jalrs", "my,mj",        */ 0x45e0,     0xffe0 },
12152
12153   { /* "b",     "mD",           */ 0xcc00,     0xfc00 },
12154   { /* "b(eq|ne)z", "md,mE",    */ 0x8c00,     0xdc00 },
12155   { /* "jr",    "mj",           */ 0x4580,     0xffe0 },
12156   { 0, 0 }  /* End marker for find_match().  */
12157 };
12158
12159
12160 /* LUI instruction.  */
12161
12162 static const struct opcode_descriptor lui_insn =
12163  { /* "lui",    "s,u",          */ 0x41a00000, 0xffe00000 };
12164
12165
12166 /* ADDIU instruction.  */
12167
12168 static const struct opcode_descriptor addiu_insn =
12169   { /* "addiu", "t,r,j",        */ 0x30000000, 0xfc000000 };
12170
12171 static const struct opcode_descriptor addiupc_insn =
12172   { /* "addiu", "mb,$pc,mQ",    */ 0x78000000, 0xfc000000 };
12173
12174 #define ADDIUPC_REG_FIELD(r) \
12175   (((2 <= (r) && (r) <= 7) ? (r) : ((r) - 16)) << 23)
12176
12177
12178 /* Relaxable instructions in a JAL delay slot: MOVE.  */
12179
12180 /* The 16-bit move has rd in 9:5 and rs in 4:0.  The 32-bit moves
12181    (ADDU, OR) have rd in 15:11 and rs in 10:16.  */
12182 #define MOVE32_RD(opcode) (((opcode) >> 11) & 0x1f)
12183 #define MOVE32_RS(opcode) (((opcode) >> 16) & 0x1f)
12184
12185 #define MOVE16_RD_FIELD(r) (((r) & 0x1f) << 5)
12186 #define MOVE16_RS_FIELD(r) (((r) & 0x1f)     )
12187
12188 static const struct opcode_descriptor move_insns_32[] = {
12189   { /* "move",  "d,s",          */ 0x00000150, 0xffe007ff }, /* addu d,s,$0 */
12190   { /* "move",  "d,s",          */ 0x00000290, 0xffe007ff }, /* or   d,s,$0 */
12191   { 0, 0 }  /* End marker for find_match().  */
12192 };
12193
12194 static const struct opcode_descriptor move_insn_16 =
12195   { /* "move",  "mp,mj",        */ 0x0c00,     0xfc00 };
12196
12197
12198 /* NOP instructions.  */
12199
12200 static const struct opcode_descriptor nop_insn_32 =
12201   { /* "nop",   "",             */ 0x00000000, 0xffffffff };
12202
12203 static const struct opcode_descriptor nop_insn_16 =
12204   { /* "nop",   "",             */ 0x0c00,     0xffff };
12205
12206
12207 /* Instruction match support.  */
12208
12209 #define MATCH(opcode, insn) ((opcode & insn.mask) == insn.match)
12210
12211 static int
12212 find_match (unsigned long opcode, const struct opcode_descriptor insn[])
12213 {
12214   unsigned long indx;
12215
12216   for (indx = 0; insn[indx].mask != 0; indx++)
12217     if (MATCH (opcode, insn[indx]))
12218       return indx;
12219
12220   return -1;
12221 }
12222
12223
12224 /* Branch and delay slot decoding support.  */
12225
12226 /* If PTR points to what *might* be a 16-bit branch or jump, then
12227    return the minimum length of its delay slot, otherwise return 0.
12228    Non-zero results are not definitive as we might be checking against
12229    the second half of another instruction.  */
12230
12231 static int
12232 check_br16_dslot (bfd *abfd, bfd_byte *ptr)
12233 {
12234   unsigned long opcode;
12235   int bdsize;
12236
12237   opcode = bfd_get_16 (abfd, ptr);
12238   if (MATCH (opcode, jalr_insn_16_bd32) != 0)
12239     /* 16-bit branch/jump with a 32-bit delay slot.  */
12240     bdsize = 4;
12241   else if (MATCH (opcode, jalr_insn_16_bd16) != 0
12242            || find_match (opcode, ds_insns_16_bd16) >= 0)
12243     /* 16-bit branch/jump with a 16-bit delay slot.  */
12244     bdsize = 2;
12245   else
12246     /* No delay slot.  */
12247     bdsize = 0;
12248
12249   return bdsize;
12250 }
12251
12252 /* If PTR points to what *might* be a 32-bit branch or jump, then
12253    return the minimum length of its delay slot, otherwise return 0.
12254    Non-zero results are not definitive as we might be checking against
12255    the second half of another instruction.  */
12256
12257 static int
12258 check_br32_dslot (bfd *abfd, bfd_byte *ptr)
12259 {
12260   unsigned long opcode;
12261   int bdsize;
12262
12263   opcode = bfd_get_micromips_32 (abfd, ptr);
12264   if (find_match (opcode, ds_insns_32_bd32) >= 0)
12265     /* 32-bit branch/jump with a 32-bit delay slot.  */
12266     bdsize = 4;
12267   else if (find_match (opcode, ds_insns_32_bd16) >= 0)
12268     /* 32-bit branch/jump with a 16-bit delay slot.  */
12269     bdsize = 2;
12270   else
12271     /* No delay slot.  */
12272     bdsize = 0;
12273
12274   return bdsize;
12275 }
12276
12277 /* If PTR points to a 16-bit branch or jump with a 32-bit delay slot
12278    that doesn't fiddle with REG, then return TRUE, otherwise FALSE.  */
12279
12280 static bfd_boolean
12281 check_br16 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12282 {
12283   unsigned long opcode;
12284
12285   opcode = bfd_get_16 (abfd, ptr);
12286   if (MATCH (opcode, b_insn_16)
12287                                                 /* B16  */
12288       || (MATCH (opcode, jr_insn_16) && reg != JR16_REG (opcode))
12289                                                 /* JR16  */
12290       || (MATCH (opcode, bz_insn_16) && reg != BZ16_REG (opcode))
12291                                                 /* BEQZ16, BNEZ16  */
12292       || (MATCH (opcode, jalr_insn_16_bd32)
12293                                                 /* JALR16  */
12294           && reg != JR16_REG (opcode) && reg != RA))
12295     return TRUE;
12296
12297   return FALSE;
12298 }
12299
12300 /* If PTR points to a 32-bit branch or jump that doesn't fiddle with REG,
12301    then return TRUE, otherwise FALSE.  */
12302
12303 static bfd_boolean
12304 check_br32 (bfd *abfd, bfd_byte *ptr, unsigned long reg)
12305 {
12306   unsigned long opcode;
12307
12308   opcode = bfd_get_micromips_32 (abfd, ptr);
12309   if (MATCH (opcode, j_insn_32)
12310                                                 /* J  */
12311       || MATCH (opcode, bc_insn_32)
12312                                                 /* BC1F, BC1T, BC2F, BC2T  */
12313       || (MATCH (opcode, jal_x_insn_32_bd32) && reg != RA)
12314                                                 /* JAL, JALX  */
12315       || (MATCH (opcode, bz_insn_32) && reg != OP32_SREG (opcode))
12316                                                 /* BGEZ, BGTZ, BLEZ, BLTZ  */
12317       || (MATCH (opcode, bzal_insn_32)
12318                                                 /* BGEZAL, BLTZAL  */
12319           && reg != OP32_SREG (opcode) && reg != RA)
12320       || ((MATCH (opcode, jalr_insn_32) || MATCH (opcode, beq_insn_32))
12321                                                 /* JALR, JALR.HB, BEQ, BNE  */
12322           && reg != OP32_SREG (opcode) && reg != OP32_TREG (opcode)))
12323     return TRUE;
12324
12325   return FALSE;
12326 }
12327
12328 /* If the instruction encoding at PTR and relocations [INTERNAL_RELOCS,
12329    IRELEND) at OFFSET indicate that there must be a compact branch there,
12330    then return TRUE, otherwise FALSE.  */
12331
12332 static bfd_boolean
12333 check_relocated_bzc (bfd *abfd, const bfd_byte *ptr, bfd_vma offset,
12334                      const Elf_Internal_Rela *internal_relocs,
12335                      const Elf_Internal_Rela *irelend)
12336 {
12337   const Elf_Internal_Rela *irel;
12338   unsigned long opcode;
12339
12340   opcode = bfd_get_micromips_32 (abfd, ptr);
12341   if (find_match (opcode, bzc_insns_32) < 0)
12342     return FALSE;
12343
12344   for (irel = internal_relocs; irel < irelend; irel++)
12345     if (irel->r_offset == offset
12346         && ELF32_R_TYPE (irel->r_info) == R_MICROMIPS_PC16_S1)
12347       return TRUE;
12348
12349   return FALSE;
12350 }
12351
12352 /* Bitsize checking.  */
12353 #define IS_BITSIZE(val, N)                                              \
12354   (((((val) & ((1ULL << (N)) - 1)) ^ (1ULL << ((N) - 1)))               \
12355     - (1ULL << ((N) - 1))) == (val))
12356
12357 \f
12358 bfd_boolean
12359 _bfd_mips_elf_relax_section (bfd *abfd, asection *sec,
12360                              struct bfd_link_info *link_info,
12361                              bfd_boolean *again)
12362 {
12363   Elf_Internal_Shdr *symtab_hdr;
12364   Elf_Internal_Rela *internal_relocs;
12365   Elf_Internal_Rela *irel, *irelend;
12366   bfd_byte *contents = NULL;
12367   Elf_Internal_Sym *isymbuf = NULL;
12368
12369   /* Assume nothing changes.  */
12370   *again = FALSE;
12371
12372   /* We don't have to do anything for a relocatable link, if
12373      this section does not have relocs, or if this is not a
12374      code section.  */
12375
12376   if (link_info->relocatable
12377       || (sec->flags & SEC_RELOC) == 0
12378       || sec->reloc_count == 0
12379       || (sec->flags & SEC_CODE) == 0)
12380     return TRUE;
12381
12382   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12383
12384   /* Get a copy of the native relocations.  */
12385   internal_relocs = (_bfd_elf_link_read_relocs
12386                      (abfd, sec, NULL, (Elf_Internal_Rela *) NULL,
12387                       link_info->keep_memory));
12388   if (internal_relocs == NULL)
12389     goto error_return;
12390
12391   /* Walk through them looking for relaxing opportunities.  */
12392   irelend = internal_relocs + sec->reloc_count;
12393   for (irel = internal_relocs; irel < irelend; irel++)
12394     {
12395       unsigned long r_symndx = ELF32_R_SYM (irel->r_info);
12396       unsigned int r_type = ELF32_R_TYPE (irel->r_info);
12397       bfd_boolean target_is_micromips_code_p;
12398       unsigned long opcode;
12399       bfd_vma symval;
12400       bfd_vma pcrval;
12401       bfd_byte *ptr;
12402       int fndopc;
12403
12404       /* The number of bytes to delete for relaxation and from where
12405          to delete these bytes starting at irel->r_offset.  */
12406       int delcnt = 0;
12407       int deloff = 0;
12408
12409       /* If this isn't something that can be relaxed, then ignore
12410          this reloc.  */
12411       if (r_type != R_MICROMIPS_HI16
12412           && r_type != R_MICROMIPS_PC16_S1
12413           && r_type != R_MICROMIPS_26_S1)
12414         continue;
12415
12416       /* Get the section contents if we haven't done so already.  */
12417       if (contents == NULL)
12418         {
12419           /* Get cached copy if it exists.  */
12420           if (elf_section_data (sec)->this_hdr.contents != NULL)
12421             contents = elf_section_data (sec)->this_hdr.contents;
12422           /* Go get them off disk.  */
12423           else if (!bfd_malloc_and_get_section (abfd, sec, &contents))
12424             goto error_return;
12425         }
12426       ptr = contents + irel->r_offset;
12427
12428       /* Read this BFD's local symbols if we haven't done so already.  */
12429       if (isymbuf == NULL && symtab_hdr->sh_info != 0)
12430         {
12431           isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
12432           if (isymbuf == NULL)
12433             isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12434                                             symtab_hdr->sh_info, 0,
12435                                             NULL, NULL, NULL);
12436           if (isymbuf == NULL)
12437             goto error_return;
12438         }
12439
12440       /* Get the value of the symbol referred to by the reloc.  */
12441       if (r_symndx < symtab_hdr->sh_info)
12442         {
12443           /* A local symbol.  */
12444           Elf_Internal_Sym *isym;
12445           asection *sym_sec;
12446
12447           isym = isymbuf + r_symndx;
12448           if (isym->st_shndx == SHN_UNDEF)
12449             sym_sec = bfd_und_section_ptr;
12450           else if (isym->st_shndx == SHN_ABS)
12451             sym_sec = bfd_abs_section_ptr;
12452           else if (isym->st_shndx == SHN_COMMON)
12453             sym_sec = bfd_com_section_ptr;
12454           else
12455             sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
12456           symval = (isym->st_value
12457                     + sym_sec->output_section->vma
12458                     + sym_sec->output_offset);
12459           target_is_micromips_code_p = ELF_ST_IS_MICROMIPS (isym->st_other);
12460         }
12461       else
12462         {
12463           unsigned long indx;
12464           struct elf_link_hash_entry *h;
12465
12466           /* An external symbol.  */
12467           indx = r_symndx - symtab_hdr->sh_info;
12468           h = elf_sym_hashes (abfd)[indx];
12469           BFD_ASSERT (h != NULL);
12470
12471           if (h->root.type != bfd_link_hash_defined
12472               && h->root.type != bfd_link_hash_defweak)
12473             /* This appears to be a reference to an undefined
12474                symbol.  Just ignore it -- it will be caught by the
12475                regular reloc processing.  */
12476             continue;
12477
12478           symval = (h->root.u.def.value
12479                     + h->root.u.def.section->output_section->vma
12480                     + h->root.u.def.section->output_offset);
12481           target_is_micromips_code_p = (!h->needs_plt
12482                                         && ELF_ST_IS_MICROMIPS (h->other));
12483         }
12484
12485
12486       /* For simplicity of coding, we are going to modify the
12487          section contents, the section relocs, and the BFD symbol
12488          table.  We must tell the rest of the code not to free up this
12489          information.  It would be possible to instead create a table
12490          of changes which have to be made, as is done in coff-mips.c;
12491          that would be more work, but would require less memory when
12492          the linker is run.  */
12493
12494       /* Only 32-bit instructions relaxed.  */
12495       if (irel->r_offset + 4 > sec->size)
12496         continue;
12497
12498       opcode = bfd_get_micromips_32 (abfd, ptr);
12499
12500       /* This is the pc-relative distance from the instruction the
12501          relocation is applied to, to the symbol referred.  */
12502       pcrval = (symval
12503                 - (sec->output_section->vma + sec->output_offset)
12504                 - irel->r_offset);
12505
12506       /* R_MICROMIPS_HI16 / LUI relaxation to nil, performing relaxation
12507          of corresponding R_MICROMIPS_LO16 to R_MICROMIPS_HI0_LO16 or
12508          R_MICROMIPS_PC23_S2.  The R_MICROMIPS_PC23_S2 condition is
12509
12510            (symval % 4 == 0 && IS_BITSIZE (pcrval, 25))
12511
12512          where pcrval has first to be adjusted to apply against the LO16
12513          location (we make the adjustment later on, when we have figured
12514          out the offset).  */
12515       if (r_type == R_MICROMIPS_HI16 && MATCH (opcode, lui_insn))
12516         {
12517           bfd_boolean bzc = FALSE;
12518           unsigned long nextopc;
12519           unsigned long reg;
12520           bfd_vma offset;
12521
12522           /* Give up if the previous reloc was a HI16 against this symbol
12523              too.  */
12524           if (irel > internal_relocs
12525               && ELF32_R_TYPE (irel[-1].r_info) == R_MICROMIPS_HI16
12526               && ELF32_R_SYM (irel[-1].r_info) == r_symndx)
12527             continue;
12528
12529           /* Or if the next reloc is not a LO16 against this symbol.  */
12530           if (irel + 1 >= irelend
12531               || ELF32_R_TYPE (irel[1].r_info) != R_MICROMIPS_LO16
12532               || ELF32_R_SYM (irel[1].r_info) != r_symndx)
12533             continue;
12534
12535           /* Or if the second next reloc is a LO16 against this symbol too.  */
12536           if (irel + 2 >= irelend
12537               && ELF32_R_TYPE (irel[2].r_info) == R_MICROMIPS_LO16
12538               && ELF32_R_SYM (irel[2].r_info) == r_symndx)
12539             continue;
12540
12541           /* See if the LUI instruction *might* be in a branch delay slot.
12542              We check whether what looks like a 16-bit branch or jump is
12543              actually an immediate argument to a compact branch, and let
12544              it through if so.  */
12545           if (irel->r_offset >= 2
12546               && check_br16_dslot (abfd, ptr - 2)
12547               && !(irel->r_offset >= 4
12548                    && (bzc = check_relocated_bzc (abfd,
12549                                                   ptr - 4, irel->r_offset - 4,
12550                                                   internal_relocs, irelend))))
12551             continue;
12552           if (irel->r_offset >= 4
12553               && !bzc
12554               && check_br32_dslot (abfd, ptr - 4))
12555             continue;
12556
12557           reg = OP32_SREG (opcode);
12558
12559           /* We only relax adjacent instructions or ones separated with
12560              a branch or jump that has a delay slot.  The branch or jump
12561              must not fiddle with the register used to hold the address.
12562              Subtract 4 for the LUI itself.  */
12563           offset = irel[1].r_offset - irel[0].r_offset;
12564           switch (offset - 4)
12565             {
12566             case 0:
12567               break;
12568             case 2:
12569               if (check_br16 (abfd, ptr + 4, reg))
12570                 break;
12571               continue;
12572             case 4:
12573               if (check_br32 (abfd, ptr + 4, reg))
12574                 break;
12575               continue;
12576             default:
12577               continue;
12578             }
12579
12580           nextopc = bfd_get_micromips_32 (abfd, contents + irel[1].r_offset);
12581
12582           /* Give up unless the same register is used with both
12583              relocations.  */
12584           if (OP32_SREG (nextopc) != reg)
12585             continue;
12586
12587           /* Now adjust pcrval, subtracting the offset to the LO16 reloc
12588              and rounding up to take masking of the two LSBs into account.  */
12589           pcrval = ((pcrval - offset + 3) | 3) ^ 3;
12590
12591           /* R_MICROMIPS_LO16 relaxation to R_MICROMIPS_HI0_LO16.  */
12592           if (IS_BITSIZE (symval, 16))
12593             {
12594               /* Fix the relocation's type.  */
12595               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_HI0_LO16);
12596
12597               /* Instructions using R_MICROMIPS_LO16 have the base or
12598                  source register in bits 20:16.  This register becomes $0
12599                  (zero) as the result of the R_MICROMIPS_HI16 being 0.  */
12600               nextopc &= ~0x001f0000;
12601               bfd_put_16 (abfd, (nextopc >> 16) & 0xffff,
12602                           contents + irel[1].r_offset);
12603             }
12604
12605           /* R_MICROMIPS_LO16 / ADDIU relaxation to R_MICROMIPS_PC23_S2.
12606              We add 4 to take LUI deletion into account while checking
12607              the PC-relative distance.  */
12608           else if (symval % 4 == 0
12609                    && IS_BITSIZE (pcrval + 4, 25)
12610                    && MATCH (nextopc, addiu_insn)
12611                    && OP32_TREG (nextopc) == OP32_SREG (nextopc)
12612                    && OP16_VALID_REG (OP32_TREG (nextopc)))
12613             {
12614               /* Fix the relocation's type.  */
12615               irel[1].r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC23_S2);
12616
12617               /* Replace ADDIU with the ADDIUPC version.  */
12618               nextopc = (addiupc_insn.match
12619                          | ADDIUPC_REG_FIELD (OP32_TREG (nextopc)));
12620
12621               bfd_put_micromips_32 (abfd, nextopc,
12622                                     contents + irel[1].r_offset);
12623             }
12624
12625           /* Can't do anything, give up, sigh...  */
12626           else
12627             continue;
12628
12629           /* Fix the relocation's type.  */
12630           irel->r_info = ELF32_R_INFO (r_symndx, R_MIPS_NONE);
12631
12632           /* Delete the LUI instruction: 4 bytes at irel->r_offset.  */
12633           delcnt = 4;
12634           deloff = 0;
12635         }
12636
12637       /* Compact branch relaxation -- due to the multitude of macros
12638          employed by the compiler/assembler, compact branches are not
12639          always generated.  Obviously, this can/will be fixed elsewhere,
12640          but there is no drawback in double checking it here.  */
12641       else if (r_type == R_MICROMIPS_PC16_S1
12642                && irel->r_offset + 5 < sec->size
12643                && ((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12644                    || (fndopc = find_match (opcode, bz_rt_insns_32)) >= 0)
12645                && MATCH (bfd_get_16 (abfd, ptr + 4), nop_insn_16))
12646         {
12647           unsigned long reg;
12648
12649           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12650
12651           /* Replace BEQZ/BNEZ with the compact version.  */
12652           opcode = (bzc_insns_32[fndopc].match
12653                     | BZC32_REG_FIELD (reg)
12654                     | (opcode & 0xffff));               /* Addend value.  */
12655
12656           bfd_put_micromips_32 (abfd, opcode, ptr);
12657
12658           /* Delete the 16-bit delay slot NOP: two bytes from
12659              irel->offset + 4.  */
12660           delcnt = 2;
12661           deloff = 4;
12662         }
12663
12664       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC10_S1.  We need
12665          to check the distance from the next instruction, so subtract 2.  */
12666       else if (r_type == R_MICROMIPS_PC16_S1
12667                && IS_BITSIZE (pcrval - 2, 11)
12668                && find_match (opcode, b_insns_32) >= 0)
12669         {
12670           /* Fix the relocation's type.  */
12671           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC10_S1);
12672
12673           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12674           bfd_put_16 (abfd,
12675                       (b_insn_16.match
12676                        | (opcode & 0x3ff)),             /* Addend value.  */
12677                       ptr);
12678
12679           /* Delete 2 bytes from irel->r_offset + 2.  */
12680           delcnt = 2;
12681           deloff = 2;
12682         }
12683
12684       /* R_MICROMIPS_PC16_S1 relaxation to R_MICROMIPS_PC7_S1.  We need
12685          to check the distance from the next instruction, so subtract 2.  */
12686       else if (r_type == R_MICROMIPS_PC16_S1
12687                && IS_BITSIZE (pcrval - 2, 8)
12688                && (((fndopc = find_match (opcode, bz_rs_insns_32)) >= 0
12689                     && OP16_VALID_REG (OP32_SREG (opcode)))
12690                    || ((fndopc = find_match (opcode, bz_rt_insns_32)) >= 0
12691                        && OP16_VALID_REG (OP32_TREG (opcode)))))
12692         {
12693           unsigned long reg;
12694
12695           reg = OP32_SREG (opcode) ? OP32_SREG (opcode) : OP32_TREG (opcode);
12696
12697           /* Fix the relocation's type.  */
12698           irel->r_info = ELF32_R_INFO (r_symndx, R_MICROMIPS_PC7_S1);
12699
12700           /* Replace the 32-bit opcode with a 16-bit opcode.  */
12701           bfd_put_16 (abfd,
12702                       (bz_insns_16[fndopc].match
12703                        | BZ16_REG_FIELD (reg)
12704                        | (opcode & 0x7f)),              /* Addend value.  */
12705                       ptr);
12706
12707           /* Delete 2 bytes from irel->r_offset + 2.  */
12708           delcnt = 2;
12709           deloff = 2;
12710         }
12711
12712       /* R_MICROMIPS_26_S1 -- JAL to JALS relaxation for microMIPS targets.  */
12713       else if (r_type == R_MICROMIPS_26_S1
12714                && target_is_micromips_code_p
12715                && irel->r_offset + 7 < sec->size
12716                && MATCH (opcode, jal_insn_32_bd32))
12717         {
12718           unsigned long n32opc;
12719           bfd_boolean relaxed = FALSE;
12720
12721           n32opc = bfd_get_micromips_32 (abfd, ptr + 4);
12722
12723           if (MATCH (n32opc, nop_insn_32))
12724             {
12725               /* Replace delay slot 32-bit NOP with a 16-bit NOP.  */
12726               bfd_put_16 (abfd, nop_insn_16.match, ptr + 4);
12727
12728               relaxed = TRUE;
12729             }
12730           else if (find_match (n32opc, move_insns_32) >= 0)
12731             {
12732               /* Replace delay slot 32-bit MOVE with 16-bit MOVE.  */
12733               bfd_put_16 (abfd,
12734                           (move_insn_16.match
12735                            | MOVE16_RD_FIELD (MOVE32_RD (n32opc))
12736                            | MOVE16_RS_FIELD (MOVE32_RS (n32opc))),
12737                           ptr + 4);
12738
12739               relaxed = TRUE;
12740             }
12741           /* Other 32-bit instructions relaxable to 16-bit
12742              instructions will be handled here later.  */
12743
12744           if (relaxed)
12745             {
12746               /* JAL with 32-bit delay slot that is changed to a JALS
12747                  with 16-bit delay slot.  */
12748               bfd_put_micromips_32 (abfd, jal_insn_32_bd16.match, ptr);
12749
12750               /* Delete 2 bytes from irel->r_offset + 6.  */
12751               delcnt = 2;
12752               deloff = 6;
12753             }
12754         }
12755
12756       if (delcnt != 0)
12757         {
12758           /* Note that we've changed the relocs, section contents, etc.  */
12759           elf_section_data (sec)->relocs = internal_relocs;
12760           elf_section_data (sec)->this_hdr.contents = contents;
12761           symtab_hdr->contents = (unsigned char *) isymbuf;
12762
12763           /* Delete bytes depending on the delcnt and deloff.  */
12764           if (!mips_elf_relax_delete_bytes (abfd, sec,
12765                                             irel->r_offset + deloff, delcnt))
12766             goto error_return;
12767
12768           /* That will change things, so we should relax again.
12769              Note that this is not required, and it may be slow.  */
12770           *again = TRUE;
12771         }
12772     }
12773
12774   if (isymbuf != NULL
12775       && symtab_hdr->contents != (unsigned char *) isymbuf)
12776     {
12777       if (! link_info->keep_memory)
12778         free (isymbuf);
12779       else
12780         {
12781           /* Cache the symbols for elf_link_input_bfd.  */
12782           symtab_hdr->contents = (unsigned char *) isymbuf;
12783         }
12784     }
12785
12786   if (contents != NULL
12787       && elf_section_data (sec)->this_hdr.contents != contents)
12788     {
12789       if (! link_info->keep_memory)
12790         free (contents);
12791       else
12792         {
12793           /* Cache the section contents for elf_link_input_bfd.  */
12794           elf_section_data (sec)->this_hdr.contents = contents;
12795         }
12796     }
12797
12798   if (internal_relocs != NULL
12799       && elf_section_data (sec)->relocs != internal_relocs)
12800     free (internal_relocs);
12801
12802   return TRUE;
12803
12804  error_return:
12805   if (isymbuf != NULL
12806       && symtab_hdr->contents != (unsigned char *) isymbuf)
12807     free (isymbuf);
12808   if (contents != NULL
12809       && elf_section_data (sec)->this_hdr.contents != contents)
12810     free (contents);
12811   if (internal_relocs != NULL
12812       && elf_section_data (sec)->relocs != internal_relocs)
12813     free (internal_relocs);
12814
12815   return FALSE;
12816 }
12817 \f
12818 /* Create a MIPS ELF linker hash table.  */
12819
12820 struct bfd_link_hash_table *
12821 _bfd_mips_elf_link_hash_table_create (bfd *abfd)
12822 {
12823   struct mips_elf_link_hash_table *ret;
12824   bfd_size_type amt = sizeof (struct mips_elf_link_hash_table);
12825
12826   ret = bfd_zmalloc (amt);
12827   if (ret == NULL)
12828     return NULL;
12829
12830   if (!_bfd_elf_link_hash_table_init (&ret->root, abfd,
12831                                       mips_elf_link_hash_newfunc,
12832                                       sizeof (struct mips_elf_link_hash_entry),
12833                                       MIPS_ELF_DATA))
12834     {
12835       free (ret);
12836       return NULL;
12837     }
12838
12839   return &ret->root.root;
12840 }
12841
12842 /* Likewise, but indicate that the target is VxWorks.  */
12843
12844 struct bfd_link_hash_table *
12845 _bfd_mips_vxworks_link_hash_table_create (bfd *abfd)
12846 {
12847   struct bfd_link_hash_table *ret;
12848
12849   ret = _bfd_mips_elf_link_hash_table_create (abfd);
12850   if (ret)
12851     {
12852       struct mips_elf_link_hash_table *htab;
12853
12854       htab = (struct mips_elf_link_hash_table *) ret;
12855       htab->use_plts_and_copy_relocs = TRUE;
12856       htab->is_vxworks = TRUE;
12857     }
12858   return ret;
12859 }
12860
12861 /* A function that the linker calls if we are allowed to use PLTs
12862    and copy relocs.  */
12863
12864 void
12865 _bfd_mips_elf_use_plts_and_copy_relocs (struct bfd_link_info *info)
12866 {
12867   mips_elf_hash_table (info)->use_plts_and_copy_relocs = TRUE;
12868 }
12869 \f
12870 /* We need to use a special link routine to handle the .reginfo and
12871    the .mdebug sections.  We need to merge all instances of these
12872    sections together, not write them all out sequentially.  */
12873
12874 bfd_boolean
12875 _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info)
12876 {
12877   asection *o;
12878   struct bfd_link_order *p;
12879   asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec;
12880   asection *rtproc_sec;
12881   Elf32_RegInfo reginfo;
12882   struct ecoff_debug_info debug;
12883   struct mips_htab_traverse_info hti;
12884   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12885   const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap;
12886   HDRR *symhdr = &debug.symbolic_header;
12887   void *mdebug_handle = NULL;
12888   asection *s;
12889   EXTR esym;
12890   unsigned int i;
12891   bfd_size_type amt;
12892   struct mips_elf_link_hash_table *htab;
12893
12894   static const char * const secname[] =
12895   {
12896     ".text", ".init", ".fini", ".data",
12897     ".rodata", ".sdata", ".sbss", ".bss"
12898   };
12899   static const int sc[] =
12900   {
12901     scText, scInit, scFini, scData,
12902     scRData, scSData, scSBss, scBss
12903   };
12904
12905   /* Sort the dynamic symbols so that those with GOT entries come after
12906      those without.  */
12907   htab = mips_elf_hash_table (info);
12908   BFD_ASSERT (htab != NULL);
12909
12910   if (!mips_elf_sort_hash_table (abfd, info))
12911     return FALSE;
12912
12913   /* Create any scheduled LA25 stubs.  */
12914   hti.info = info;
12915   hti.output_bfd = abfd;
12916   hti.error = FALSE;
12917   htab_traverse (htab->la25_stubs, mips_elf_create_la25_stub, &hti);
12918   if (hti.error)
12919     return FALSE;
12920
12921   /* Get a value for the GP register.  */
12922   if (elf_gp (abfd) == 0)
12923     {
12924       struct bfd_link_hash_entry *h;
12925
12926       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
12927       if (h != NULL && h->type == bfd_link_hash_defined)
12928         elf_gp (abfd) = (h->u.def.value
12929                          + h->u.def.section->output_section->vma
12930                          + h->u.def.section->output_offset);
12931       else if (htab->is_vxworks
12932                && (h = bfd_link_hash_lookup (info->hash,
12933                                              "_GLOBAL_OFFSET_TABLE_",
12934                                              FALSE, FALSE, TRUE))
12935                && h->type == bfd_link_hash_defined)
12936         elf_gp (abfd) = (h->u.def.section->output_section->vma
12937                          + h->u.def.section->output_offset
12938                          + h->u.def.value);
12939       else if (info->relocatable)
12940         {
12941           bfd_vma lo = MINUS_ONE;
12942
12943           /* Find the GP-relative section with the lowest offset.  */
12944           for (o = abfd->sections; o != NULL; o = o->next)
12945             if (o->vma < lo
12946                 && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL))
12947               lo = o->vma;
12948
12949           /* And calculate GP relative to that.  */
12950           elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (info);
12951         }
12952       else
12953         {
12954           /* If the relocate_section function needs to do a reloc
12955              involving the GP value, it should make a reloc_dangerous
12956              callback to warn that GP is not defined.  */
12957         }
12958     }
12959
12960   /* Go through the sections and collect the .reginfo and .mdebug
12961      information.  */
12962   reginfo_sec = NULL;
12963   mdebug_sec = NULL;
12964   gptab_data_sec = NULL;
12965   gptab_bss_sec = NULL;
12966   for (o = abfd->sections; o != NULL; o = o->next)
12967     {
12968       if (strcmp (o->name, ".reginfo") == 0)
12969         {
12970           memset (&reginfo, 0, sizeof reginfo);
12971
12972           /* We have found the .reginfo section in the output file.
12973              Look through all the link_orders comprising it and merge
12974              the information together.  */
12975           for (p = o->map_head.link_order; p != NULL; p = p->next)
12976             {
12977               asection *input_section;
12978               bfd *input_bfd;
12979               Elf32_External_RegInfo ext;
12980               Elf32_RegInfo sub;
12981
12982               if (p->type != bfd_indirect_link_order)
12983                 {
12984                   if (p->type == bfd_data_link_order)
12985                     continue;
12986                   abort ();
12987                 }
12988
12989               input_section = p->u.indirect.section;
12990               input_bfd = input_section->owner;
12991
12992               if (! bfd_get_section_contents (input_bfd, input_section,
12993                                               &ext, 0, sizeof ext))
12994                 return FALSE;
12995
12996               bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub);
12997
12998               reginfo.ri_gprmask |= sub.ri_gprmask;
12999               reginfo.ri_cprmask[0] |= sub.ri_cprmask[0];
13000               reginfo.ri_cprmask[1] |= sub.ri_cprmask[1];
13001               reginfo.ri_cprmask[2] |= sub.ri_cprmask[2];
13002               reginfo.ri_cprmask[3] |= sub.ri_cprmask[3];
13003
13004               /* ri_gp_value is set by the function
13005                  mips_elf32_section_processing when the section is
13006                  finally written out.  */
13007
13008               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13009                  elf_link_input_bfd ignores this section.  */
13010               input_section->flags &= ~SEC_HAS_CONTENTS;
13011             }
13012
13013           /* Size has been set in _bfd_mips_elf_always_size_sections.  */
13014           BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo));
13015
13016           /* Skip this section later on (I don't think this currently
13017              matters, but someday it might).  */
13018           o->map_head.link_order = NULL;
13019
13020           reginfo_sec = o;
13021         }
13022
13023       if (strcmp (o->name, ".mdebug") == 0)
13024         {
13025           struct extsym_info einfo;
13026           bfd_vma last;
13027
13028           /* We have found the .mdebug section in the output file.
13029              Look through all the link_orders comprising it and merge
13030              the information together.  */
13031           symhdr->magic = swap->sym_magic;
13032           /* FIXME: What should the version stamp be?  */
13033           symhdr->vstamp = 0;
13034           symhdr->ilineMax = 0;
13035           symhdr->cbLine = 0;
13036           symhdr->idnMax = 0;
13037           symhdr->ipdMax = 0;
13038           symhdr->isymMax = 0;
13039           symhdr->ioptMax = 0;
13040           symhdr->iauxMax = 0;
13041           symhdr->issMax = 0;
13042           symhdr->issExtMax = 0;
13043           symhdr->ifdMax = 0;
13044           symhdr->crfd = 0;
13045           symhdr->iextMax = 0;
13046
13047           /* We accumulate the debugging information itself in the
13048              debug_info structure.  */
13049           debug.line = NULL;
13050           debug.external_dnr = NULL;
13051           debug.external_pdr = NULL;
13052           debug.external_sym = NULL;
13053           debug.external_opt = NULL;
13054           debug.external_aux = NULL;
13055           debug.ss = NULL;
13056           debug.ssext = debug.ssext_end = NULL;
13057           debug.external_fdr = NULL;
13058           debug.external_rfd = NULL;
13059           debug.external_ext = debug.external_ext_end = NULL;
13060
13061           mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info);
13062           if (mdebug_handle == NULL)
13063             return FALSE;
13064
13065           esym.jmptbl = 0;
13066           esym.cobol_main = 0;
13067           esym.weakext = 0;
13068           esym.reserved = 0;
13069           esym.ifd = ifdNil;
13070           esym.asym.iss = issNil;
13071           esym.asym.st = stLocal;
13072           esym.asym.reserved = 0;
13073           esym.asym.index = indexNil;
13074           last = 0;
13075           for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++)
13076             {
13077               esym.asym.sc = sc[i];
13078               s = bfd_get_section_by_name (abfd, secname[i]);
13079               if (s != NULL)
13080                 {
13081                   esym.asym.value = s->vma;
13082                   last = s->vma + s->size;
13083                 }
13084               else
13085                 esym.asym.value = last;
13086               if (!bfd_ecoff_debug_one_external (abfd, &debug, swap,
13087                                                  secname[i], &esym))
13088                 return FALSE;
13089             }
13090
13091           for (p = o->map_head.link_order; p != NULL; p = p->next)
13092             {
13093               asection *input_section;
13094               bfd *input_bfd;
13095               const struct ecoff_debug_swap *input_swap;
13096               struct ecoff_debug_info input_debug;
13097               char *eraw_src;
13098               char *eraw_end;
13099
13100               if (p->type != bfd_indirect_link_order)
13101                 {
13102                   if (p->type == bfd_data_link_order)
13103                     continue;
13104                   abort ();
13105                 }
13106
13107               input_section = p->u.indirect.section;
13108               input_bfd = input_section->owner;
13109
13110               if (!is_mips_elf (input_bfd))
13111                 {
13112                   /* I don't know what a non MIPS ELF bfd would be
13113                      doing with a .mdebug section, but I don't really
13114                      want to deal with it.  */
13115                   continue;
13116                 }
13117
13118               input_swap = (get_elf_backend_data (input_bfd)
13119                             ->elf_backend_ecoff_debug_swap);
13120
13121               BFD_ASSERT (p->size == input_section->size);
13122
13123               /* The ECOFF linking code expects that we have already
13124                  read in the debugging information and set up an
13125                  ecoff_debug_info structure, so we do that now.  */
13126               if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section,
13127                                                    &input_debug))
13128                 return FALSE;
13129
13130               if (! (bfd_ecoff_debug_accumulate
13131                      (mdebug_handle, abfd, &debug, swap, input_bfd,
13132                       &input_debug, input_swap, info)))
13133                 return FALSE;
13134
13135               /* Loop through the external symbols.  For each one with
13136                  interesting information, try to find the symbol in
13137                  the linker global hash table and save the information
13138                  for the output external symbols.  */
13139               eraw_src = input_debug.external_ext;
13140               eraw_end = (eraw_src
13141                           + (input_debug.symbolic_header.iextMax
13142                              * input_swap->external_ext_size));
13143               for (;
13144                    eraw_src < eraw_end;
13145                    eraw_src += input_swap->external_ext_size)
13146                 {
13147                   EXTR ext;
13148                   const char *name;
13149                   struct mips_elf_link_hash_entry *h;
13150
13151                   (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext);
13152                   if (ext.asym.sc == scNil
13153                       || ext.asym.sc == scUndefined
13154                       || ext.asym.sc == scSUndefined)
13155                     continue;
13156
13157                   name = input_debug.ssext + ext.asym.iss;
13158                   h = mips_elf_link_hash_lookup (mips_elf_hash_table (info),
13159                                                  name, FALSE, FALSE, TRUE);
13160                   if (h == NULL || h->esym.ifd != -2)
13161                     continue;
13162
13163                   if (ext.ifd != -1)
13164                     {
13165                       BFD_ASSERT (ext.ifd
13166                                   < input_debug.symbolic_header.ifdMax);
13167                       ext.ifd = input_debug.ifdmap[ext.ifd];
13168                     }
13169
13170                   h->esym = ext;
13171                 }
13172
13173               /* Free up the information we just read.  */
13174               free (input_debug.line);
13175               free (input_debug.external_dnr);
13176               free (input_debug.external_pdr);
13177               free (input_debug.external_sym);
13178               free (input_debug.external_opt);
13179               free (input_debug.external_aux);
13180               free (input_debug.ss);
13181               free (input_debug.ssext);
13182               free (input_debug.external_fdr);
13183               free (input_debug.external_rfd);
13184               free (input_debug.external_ext);
13185
13186               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13187                  elf_link_input_bfd ignores this section.  */
13188               input_section->flags &= ~SEC_HAS_CONTENTS;
13189             }
13190
13191           if (SGI_COMPAT (abfd) && info->shared)
13192             {
13193               /* Create .rtproc section.  */
13194               rtproc_sec = bfd_get_linker_section (abfd, ".rtproc");
13195               if (rtproc_sec == NULL)
13196                 {
13197                   flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY
13198                                     | SEC_LINKER_CREATED | SEC_READONLY);
13199
13200                   rtproc_sec = bfd_make_section_anyway_with_flags (abfd,
13201                                                                    ".rtproc",
13202                                                                    flags);
13203                   if (rtproc_sec == NULL
13204                       || ! bfd_set_section_alignment (abfd, rtproc_sec, 4))
13205                     return FALSE;
13206                 }
13207
13208               if (! mips_elf_create_procedure_table (mdebug_handle, abfd,
13209                                                      info, rtproc_sec,
13210                                                      &debug))
13211                 return FALSE;
13212             }
13213
13214           /* Build the external symbol information.  */
13215           einfo.abfd = abfd;
13216           einfo.info = info;
13217           einfo.debug = &debug;
13218           einfo.swap = swap;
13219           einfo.failed = FALSE;
13220           mips_elf_link_hash_traverse (mips_elf_hash_table (info),
13221                                        mips_elf_output_extsym, &einfo);
13222           if (einfo.failed)
13223             return FALSE;
13224
13225           /* Set the size of the .mdebug section.  */
13226           o->size = bfd_ecoff_debug_size (abfd, &debug, swap);
13227
13228           /* Skip this section later on (I don't think this currently
13229              matters, but someday it might).  */
13230           o->map_head.link_order = NULL;
13231
13232           mdebug_sec = o;
13233         }
13234
13235       if (CONST_STRNEQ (o->name, ".gptab."))
13236         {
13237           const char *subname;
13238           unsigned int c;
13239           Elf32_gptab *tab;
13240           Elf32_External_gptab *ext_tab;
13241           unsigned int j;
13242
13243           /* The .gptab.sdata and .gptab.sbss sections hold
13244              information describing how the small data area would
13245              change depending upon the -G switch.  These sections
13246              not used in executables files.  */
13247           if (! info->relocatable)
13248             {
13249               for (p = o->map_head.link_order; p != NULL; p = p->next)
13250                 {
13251                   asection *input_section;
13252
13253                   if (p->type != bfd_indirect_link_order)
13254                     {
13255                       if (p->type == bfd_data_link_order)
13256                         continue;
13257                       abort ();
13258                     }
13259
13260                   input_section = p->u.indirect.section;
13261
13262                   /* Hack: reset the SEC_HAS_CONTENTS flag so that
13263                      elf_link_input_bfd ignores this section.  */
13264                   input_section->flags &= ~SEC_HAS_CONTENTS;
13265                 }
13266
13267               /* Skip this section later on (I don't think this
13268                  currently matters, but someday it might).  */
13269               o->map_head.link_order = NULL;
13270
13271               /* Really remove the section.  */
13272               bfd_section_list_remove (abfd, o);
13273               --abfd->section_count;
13274
13275               continue;
13276             }
13277
13278           /* There is one gptab for initialized data, and one for
13279              uninitialized data.  */
13280           if (strcmp (o->name, ".gptab.sdata") == 0)
13281             gptab_data_sec = o;
13282           else if (strcmp (o->name, ".gptab.sbss") == 0)
13283             gptab_bss_sec = o;
13284           else
13285             {
13286               (*_bfd_error_handler)
13287                 (_("%s: illegal section name `%s'"),
13288                  bfd_get_filename (abfd), o->name);
13289               bfd_set_error (bfd_error_nonrepresentable_section);
13290               return FALSE;
13291             }
13292
13293           /* The linker script always combines .gptab.data and
13294              .gptab.sdata into .gptab.sdata, and likewise for
13295              .gptab.bss and .gptab.sbss.  It is possible that there is
13296              no .sdata or .sbss section in the output file, in which
13297              case we must change the name of the output section.  */
13298           subname = o->name + sizeof ".gptab" - 1;
13299           if (bfd_get_section_by_name (abfd, subname) == NULL)
13300             {
13301               if (o == gptab_data_sec)
13302                 o->name = ".gptab.data";
13303               else
13304                 o->name = ".gptab.bss";
13305               subname = o->name + sizeof ".gptab" - 1;
13306               BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL);
13307             }
13308
13309           /* Set up the first entry.  */
13310           c = 1;
13311           amt = c * sizeof (Elf32_gptab);
13312           tab = bfd_malloc (amt);
13313           if (tab == NULL)
13314             return FALSE;
13315           tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd);
13316           tab[0].gt_header.gt_unused = 0;
13317
13318           /* Combine the input sections.  */
13319           for (p = o->map_head.link_order; p != NULL; p = p->next)
13320             {
13321               asection *input_section;
13322               bfd *input_bfd;
13323               bfd_size_type size;
13324               unsigned long last;
13325               bfd_size_type gpentry;
13326
13327               if (p->type != bfd_indirect_link_order)
13328                 {
13329                   if (p->type == bfd_data_link_order)
13330                     continue;
13331                   abort ();
13332                 }
13333
13334               input_section = p->u.indirect.section;
13335               input_bfd = input_section->owner;
13336
13337               /* Combine the gptab entries for this input section one
13338                  by one.  We know that the input gptab entries are
13339                  sorted by ascending -G value.  */
13340               size = input_section->size;
13341               last = 0;
13342               for (gpentry = sizeof (Elf32_External_gptab);
13343                    gpentry < size;
13344                    gpentry += sizeof (Elf32_External_gptab))
13345                 {
13346                   Elf32_External_gptab ext_gptab;
13347                   Elf32_gptab int_gptab;
13348                   unsigned long val;
13349                   unsigned long add;
13350                   bfd_boolean exact;
13351                   unsigned int look;
13352
13353                   if (! (bfd_get_section_contents
13354                          (input_bfd, input_section, &ext_gptab, gpentry,
13355                           sizeof (Elf32_External_gptab))))
13356                     {
13357                       free (tab);
13358                       return FALSE;
13359                     }
13360
13361                   bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab,
13362                                                 &int_gptab);
13363                   val = int_gptab.gt_entry.gt_g_value;
13364                   add = int_gptab.gt_entry.gt_bytes - last;
13365
13366                   exact = FALSE;
13367                   for (look = 1; look < c; look++)
13368                     {
13369                       if (tab[look].gt_entry.gt_g_value >= val)
13370                         tab[look].gt_entry.gt_bytes += add;
13371
13372                       if (tab[look].gt_entry.gt_g_value == val)
13373                         exact = TRUE;
13374                     }
13375
13376                   if (! exact)
13377                     {
13378                       Elf32_gptab *new_tab;
13379                       unsigned int max;
13380
13381                       /* We need a new table entry.  */
13382                       amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab);
13383                       new_tab = bfd_realloc (tab, amt);
13384                       if (new_tab == NULL)
13385                         {
13386                           free (tab);
13387                           return FALSE;
13388                         }
13389                       tab = new_tab;
13390                       tab[c].gt_entry.gt_g_value = val;
13391                       tab[c].gt_entry.gt_bytes = add;
13392
13393                       /* Merge in the size for the next smallest -G
13394                          value, since that will be implied by this new
13395                          value.  */
13396                       max = 0;
13397                       for (look = 1; look < c; look++)
13398                         {
13399                           if (tab[look].gt_entry.gt_g_value < val
13400                               && (max == 0
13401                                   || (tab[look].gt_entry.gt_g_value
13402                                       > tab[max].gt_entry.gt_g_value)))
13403                             max = look;
13404                         }
13405                       if (max != 0)
13406                         tab[c].gt_entry.gt_bytes +=
13407                           tab[max].gt_entry.gt_bytes;
13408
13409                       ++c;
13410                     }
13411
13412                   last = int_gptab.gt_entry.gt_bytes;
13413                 }
13414
13415               /* Hack: reset the SEC_HAS_CONTENTS flag so that
13416                  elf_link_input_bfd ignores this section.  */
13417               input_section->flags &= ~SEC_HAS_CONTENTS;
13418             }
13419
13420           /* The table must be sorted by -G value.  */
13421           if (c > 2)
13422             qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare);
13423
13424           /* Swap out the table.  */
13425           amt = (bfd_size_type) c * sizeof (Elf32_External_gptab);
13426           ext_tab = bfd_alloc (abfd, amt);
13427           if (ext_tab == NULL)
13428             {
13429               free (tab);
13430               return FALSE;
13431             }
13432
13433           for (j = 0; j < c; j++)
13434             bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j);
13435           free (tab);
13436
13437           o->size = c * sizeof (Elf32_External_gptab);
13438           o->contents = (bfd_byte *) ext_tab;
13439
13440           /* Skip this section later on (I don't think this currently
13441              matters, but someday it might).  */
13442           o->map_head.link_order = NULL;
13443         }
13444     }
13445
13446   /* Invoke the regular ELF backend linker to do all the work.  */
13447   if (!bfd_elf_final_link (abfd, info))
13448     return FALSE;
13449
13450   /* Now write out the computed sections.  */
13451
13452   if (reginfo_sec != NULL)
13453     {
13454       Elf32_External_RegInfo ext;
13455
13456       bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext);
13457       if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext))
13458         return FALSE;
13459     }
13460
13461   if (mdebug_sec != NULL)
13462     {
13463       BFD_ASSERT (abfd->output_has_begun);
13464       if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug,
13465                                                swap, info,
13466                                                mdebug_sec->filepos))
13467         return FALSE;
13468
13469       bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info);
13470     }
13471
13472   if (gptab_data_sec != NULL)
13473     {
13474       if (! bfd_set_section_contents (abfd, gptab_data_sec,
13475                                       gptab_data_sec->contents,
13476                                       0, gptab_data_sec->size))
13477         return FALSE;
13478     }
13479
13480   if (gptab_bss_sec != NULL)
13481     {
13482       if (! bfd_set_section_contents (abfd, gptab_bss_sec,
13483                                       gptab_bss_sec->contents,
13484                                       0, gptab_bss_sec->size))
13485         return FALSE;
13486     }
13487
13488   if (SGI_COMPAT (abfd))
13489     {
13490       rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc");
13491       if (rtproc_sec != NULL)
13492         {
13493           if (! bfd_set_section_contents (abfd, rtproc_sec,
13494                                           rtproc_sec->contents,
13495                                           0, rtproc_sec->size))
13496             return FALSE;
13497         }
13498     }
13499
13500   return TRUE;
13501 }
13502 \f
13503 /* Structure for saying that BFD machine EXTENSION extends BASE.  */
13504
13505 struct mips_mach_extension {
13506   unsigned long extension, base;
13507 };
13508
13509
13510 /* An array describing how BFD machines relate to one another.  The entries
13511    are ordered topologically with MIPS I extensions listed last.  */
13512
13513 static const struct mips_mach_extension mips_mach_extensions[] = {
13514   /* MIPS64r2 extensions.  */
13515   { bfd_mach_mips_octeon2, bfd_mach_mips_octeonp },
13516   { bfd_mach_mips_octeonp, bfd_mach_mips_octeon },
13517   { bfd_mach_mips_octeon, bfd_mach_mipsisa64r2 },
13518
13519   /* MIPS64 extensions.  */
13520   { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 },
13521   { bfd_mach_mips_sb1, bfd_mach_mipsisa64 },
13522   { bfd_mach_mips_xlr, bfd_mach_mipsisa64 },
13523   { bfd_mach_mips_loongson_3a, bfd_mach_mipsisa64 },
13524
13525   /* MIPS V extensions.  */
13526   { bfd_mach_mipsisa64, bfd_mach_mips5 },
13527
13528   /* R10000 extensions.  */
13529   { bfd_mach_mips12000, bfd_mach_mips10000 },
13530   { bfd_mach_mips14000, bfd_mach_mips10000 },
13531   { bfd_mach_mips16000, bfd_mach_mips10000 },
13532
13533   /* R5000 extensions.  Note: the vr5500 ISA is an extension of the core
13534      vr5400 ISA, but doesn't include the multimedia stuff.  It seems
13535      better to allow vr5400 and vr5500 code to be merged anyway, since
13536      many libraries will just use the core ISA.  Perhaps we could add
13537      some sort of ASE flag if this ever proves a problem.  */
13538   { bfd_mach_mips5500, bfd_mach_mips5400 },
13539   { bfd_mach_mips5400, bfd_mach_mips5000 },
13540
13541   /* MIPS IV extensions.  */
13542   { bfd_mach_mips5, bfd_mach_mips8000 },
13543   { bfd_mach_mips10000, bfd_mach_mips8000 },
13544   { bfd_mach_mips5000, bfd_mach_mips8000 },
13545   { bfd_mach_mips7000, bfd_mach_mips8000 },
13546   { bfd_mach_mips9000, bfd_mach_mips8000 },
13547
13548   /* VR4100 extensions.  */
13549   { bfd_mach_mips4120, bfd_mach_mips4100 },
13550   { bfd_mach_mips4111, bfd_mach_mips4100 },
13551
13552   /* MIPS III extensions.  */
13553   { bfd_mach_mips_loongson_2e, bfd_mach_mips4000 },
13554   { bfd_mach_mips_loongson_2f, bfd_mach_mips4000 },
13555   { bfd_mach_mips8000, bfd_mach_mips4000 },
13556   { bfd_mach_mips4650, bfd_mach_mips4000 },
13557   { bfd_mach_mips4600, bfd_mach_mips4000 },
13558   { bfd_mach_mips4400, bfd_mach_mips4000 },
13559   { bfd_mach_mips4300, bfd_mach_mips4000 },
13560   { bfd_mach_mips4100, bfd_mach_mips4000 },
13561   { bfd_mach_mips4010, bfd_mach_mips4000 },
13562   { bfd_mach_mips5900, bfd_mach_mips4000 },
13563
13564   /* MIPS32 extensions.  */
13565   { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 },
13566
13567   /* MIPS II extensions.  */
13568   { bfd_mach_mips4000, bfd_mach_mips6000 },
13569   { bfd_mach_mipsisa32, bfd_mach_mips6000 },
13570
13571   /* MIPS I extensions.  */
13572   { bfd_mach_mips6000, bfd_mach_mips3000 },
13573   { bfd_mach_mips3900, bfd_mach_mips3000 }
13574 };
13575
13576
13577 /* Return true if bfd machine EXTENSION is an extension of machine BASE.  */
13578
13579 static bfd_boolean
13580 mips_mach_extends_p (unsigned long base, unsigned long extension)
13581 {
13582   size_t i;
13583
13584   if (extension == base)
13585     return TRUE;
13586
13587   if (base == bfd_mach_mipsisa32
13588       && mips_mach_extends_p (bfd_mach_mipsisa64, extension))
13589     return TRUE;
13590
13591   if (base == bfd_mach_mipsisa32r2
13592       && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension))
13593     return TRUE;
13594
13595   for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++)
13596     if (extension == mips_mach_extensions[i].extension)
13597       {
13598         extension = mips_mach_extensions[i].base;
13599         if (extension == base)
13600           return TRUE;
13601       }
13602
13603   return FALSE;
13604 }
13605
13606
13607 /* Return true if the given ELF header flags describe a 32-bit binary.  */
13608
13609 static bfd_boolean
13610 mips_32bit_flags_p (flagword flags)
13611 {
13612   return ((flags & EF_MIPS_32BITMODE) != 0
13613           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32
13614           || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32
13615           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1
13616           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2
13617           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32
13618           || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2);
13619 }
13620
13621
13622 /* Merge object attributes from IBFD into OBFD.  Raise an error if
13623    there are conflicting attributes.  */
13624 static bfd_boolean
13625 mips_elf_merge_obj_attributes (bfd *ibfd, bfd *obfd)
13626 {
13627   obj_attribute *in_attr;
13628   obj_attribute *out_attr;
13629   bfd *abi_fp_bfd;
13630
13631   abi_fp_bfd = mips_elf_tdata (obfd)->abi_fp_bfd;
13632   in_attr = elf_known_obj_attributes (ibfd)[OBJ_ATTR_GNU];
13633   if (!abi_fp_bfd && in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13634     mips_elf_tdata (obfd)->abi_fp_bfd = ibfd;
13635
13636   if (!elf_known_obj_attributes_proc (obfd)[0].i)
13637     {
13638       /* This is the first object.  Copy the attributes.  */
13639       _bfd_elf_copy_obj_attributes (ibfd, obfd);
13640
13641       /* Use the Tag_null value to indicate the attributes have been
13642          initialized.  */
13643       elf_known_obj_attributes_proc (obfd)[0].i = 1;
13644
13645       return TRUE;
13646     }
13647
13648   /* Check for conflicting Tag_GNU_MIPS_ABI_FP attributes and merge
13649      non-conflicting ones.  */
13650   out_attr = elf_known_obj_attributes (obfd)[OBJ_ATTR_GNU];
13651   if (in_attr[Tag_GNU_MIPS_ABI_FP].i != out_attr[Tag_GNU_MIPS_ABI_FP].i)
13652     {
13653       out_attr[Tag_GNU_MIPS_ABI_FP].type = 1;
13654       if (out_attr[Tag_GNU_MIPS_ABI_FP].i == 0)
13655         out_attr[Tag_GNU_MIPS_ABI_FP].i = in_attr[Tag_GNU_MIPS_ABI_FP].i;
13656       else if (in_attr[Tag_GNU_MIPS_ABI_FP].i != 0)
13657         switch (out_attr[Tag_GNU_MIPS_ABI_FP].i)
13658           {
13659           case 1:
13660             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13661               {
13662               case 2:
13663                 _bfd_error_handler
13664                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13665                    obfd, abi_fp_bfd, ibfd, "-mdouble-float", "-msingle-float");
13666                 break;
13667
13668               case 3:
13669                 _bfd_error_handler
13670                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13671                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13672                 break;
13673
13674               case 4:
13675                 _bfd_error_handler
13676                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13677                    obfd, abi_fp_bfd, ibfd,
13678                    "-mdouble-float", "-mips32r2 -mfp64");
13679                 break;
13680
13681               default:
13682                 _bfd_error_handler
13683                   (_("Warning: %B uses %s (set by %B), "
13684                      "%B uses unknown floating point ABI %d"),
13685                    obfd, abi_fp_bfd, ibfd,
13686                    "-mdouble-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13687                 break;
13688               }
13689             break;
13690
13691           case 2:
13692             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13693               {
13694               case 1:
13695                 _bfd_error_handler
13696                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13697                    obfd, abi_fp_bfd, ibfd, "-msingle-float", "-mdouble-float");
13698                 break;
13699
13700               case 3:
13701                 _bfd_error_handler
13702                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13703                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13704                 break;
13705
13706               case 4:
13707                 _bfd_error_handler
13708                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13709                    obfd, abi_fp_bfd, ibfd,
13710                    "-msingle-float", "-mips32r2 -mfp64");
13711                 break;
13712
13713               default:
13714                 _bfd_error_handler
13715                   (_("Warning: %B uses %s (set by %B), "
13716                      "%B uses unknown floating point ABI %d"),
13717                    obfd, abi_fp_bfd, ibfd,
13718                    "-msingle-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13719                 break;
13720               }
13721             break;
13722
13723           case 3:
13724             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13725               {
13726               case 1:
13727               case 2:
13728               case 4:
13729                 _bfd_error_handler
13730                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13731                    obfd, abi_fp_bfd, ibfd, "-msoft-float", "-mhard-float");
13732                 break;
13733
13734               default:
13735                 _bfd_error_handler
13736                   (_("Warning: %B uses %s (set by %B), "
13737                      "%B uses unknown floating point ABI %d"),
13738                    obfd, abi_fp_bfd, ibfd,
13739                    "-msoft-float", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13740                 break;
13741               }
13742             break;
13743
13744           case 4:
13745             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13746               {
13747               case 1:
13748                 _bfd_error_handler
13749                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13750                    obfd, abi_fp_bfd, ibfd,
13751                    "-mips32r2 -mfp64", "-mdouble-float");
13752                 break;
13753
13754               case 2:
13755                 _bfd_error_handler
13756                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13757                    obfd, abi_fp_bfd, ibfd,
13758                    "-mips32r2 -mfp64", "-msingle-float");
13759                 break;
13760
13761               case 3:
13762                 _bfd_error_handler
13763                   (_("Warning: %B uses %s (set by %B), %B uses %s"),
13764                    obfd, abi_fp_bfd, ibfd, "-mhard-float", "-msoft-float");
13765                 break;
13766
13767               default:
13768                 _bfd_error_handler
13769                   (_("Warning: %B uses %s (set by %B), "
13770                      "%B uses unknown floating point ABI %d"),
13771                    obfd, abi_fp_bfd, ibfd,
13772                    "-mips32r2 -mfp64", in_attr[Tag_GNU_MIPS_ABI_FP].i);
13773                 break;
13774               }
13775             break;
13776
13777           default:
13778             switch (in_attr[Tag_GNU_MIPS_ABI_FP].i)
13779               {
13780               case 1:
13781                 _bfd_error_handler
13782                   (_("Warning: %B uses unknown floating point ABI %d "
13783                      "(set by %B), %B uses %s"),
13784                    obfd, abi_fp_bfd, ibfd,
13785                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mdouble-float");
13786                 break;
13787
13788               case 2:
13789                 _bfd_error_handler
13790                   (_("Warning: %B uses unknown floating point ABI %d "
13791                      "(set by %B), %B uses %s"),
13792                    obfd, abi_fp_bfd, ibfd,
13793                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msingle-float");
13794                 break;
13795
13796               case 3:
13797                 _bfd_error_handler
13798                   (_("Warning: %B uses unknown floating point ABI %d "
13799                      "(set by %B), %B uses %s"),
13800                    obfd, abi_fp_bfd, ibfd,
13801                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-msoft-float");
13802                 break;
13803
13804               case 4:
13805                 _bfd_error_handler
13806                   (_("Warning: %B uses unknown floating point ABI %d "
13807                      "(set by %B), %B uses %s"),
13808                    obfd, abi_fp_bfd, ibfd,
13809                    out_attr[Tag_GNU_MIPS_ABI_FP].i, "-mips32r2 -mfp64");
13810                 break;
13811
13812               default:
13813                 _bfd_error_handler
13814                   (_("Warning: %B uses unknown floating point ABI %d "
13815                      "(set by %B), %B uses unknown floating point ABI %d"),
13816                    obfd, abi_fp_bfd, ibfd,
13817                    out_attr[Tag_GNU_MIPS_ABI_FP].i,
13818                    in_attr[Tag_GNU_MIPS_ABI_FP].i);
13819                 break;
13820               }
13821             break;
13822           }
13823     }
13824
13825   /* Merge Tag_compatibility attributes and any common GNU ones.  */
13826   _bfd_elf_merge_object_attributes (ibfd, obfd);
13827
13828   return TRUE;
13829 }
13830
13831 /* Merge backend specific data from an object file to the output
13832    object file when linking.  */
13833
13834 bfd_boolean
13835 _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
13836 {
13837   flagword old_flags;
13838   flagword new_flags;
13839   bfd_boolean ok;
13840   bfd_boolean null_input_bfd = TRUE;
13841   asection *sec;
13842
13843   /* Check if we have the same endianness.  */
13844   if (! _bfd_generic_verify_endian_match (ibfd, obfd))
13845     {
13846       (*_bfd_error_handler)
13847         (_("%B: endianness incompatible with that of the selected emulation"),
13848          ibfd);
13849       return FALSE;
13850     }
13851
13852   if (!is_mips_elf (ibfd) || !is_mips_elf (obfd))
13853     return TRUE;
13854
13855   if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0)
13856     {
13857       (*_bfd_error_handler)
13858         (_("%B: ABI is incompatible with that of the selected emulation"),
13859          ibfd);
13860       return FALSE;
13861     }
13862
13863   if (!mips_elf_merge_obj_attributes (ibfd, obfd))
13864     return FALSE;
13865
13866   new_flags = elf_elfheader (ibfd)->e_flags;
13867   elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER;
13868   old_flags = elf_elfheader (obfd)->e_flags;
13869
13870   if (! elf_flags_init (obfd))
13871     {
13872       elf_flags_init (obfd) = TRUE;
13873       elf_elfheader (obfd)->e_flags = new_flags;
13874       elf_elfheader (obfd)->e_ident[EI_CLASS]
13875         = elf_elfheader (ibfd)->e_ident[EI_CLASS];
13876
13877       if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
13878           && (bfd_get_arch_info (obfd)->the_default
13879               || mips_mach_extends_p (bfd_get_mach (obfd),
13880                                       bfd_get_mach (ibfd))))
13881         {
13882           if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
13883                                    bfd_get_mach (ibfd)))
13884             return FALSE;
13885         }
13886
13887       return TRUE;
13888     }
13889
13890   /* Check flag compatibility.  */
13891
13892   new_flags &= ~EF_MIPS_NOREORDER;
13893   old_flags &= ~EF_MIPS_NOREORDER;
13894
13895   /* Some IRIX 6 BSD-compatibility objects have this bit set.  It
13896      doesn't seem to matter.  */
13897   new_flags &= ~EF_MIPS_XGOT;
13898   old_flags &= ~EF_MIPS_XGOT;
13899
13900   /* MIPSpro generates ucode info in n64 objects.  Again, we should
13901      just be able to ignore this.  */
13902   new_flags &= ~EF_MIPS_UCODE;
13903   old_flags &= ~EF_MIPS_UCODE;
13904
13905   /* DSOs should only be linked with CPIC code.  */
13906   if ((ibfd->flags & DYNAMIC) != 0)
13907     new_flags |= EF_MIPS_PIC | EF_MIPS_CPIC;
13908
13909   if (new_flags == old_flags)
13910     return TRUE;
13911
13912   /* Check to see if the input BFD actually contains any sections.
13913      If not, its flags may not have been initialised either, but it cannot
13914      actually cause any incompatibility.  */
13915   for (sec = ibfd->sections; sec != NULL; sec = sec->next)
13916     {
13917       /* Ignore synthetic sections and empty .text, .data and .bss sections
13918          which are automatically generated by gas.  Also ignore fake
13919          (s)common sections, since merely defining a common symbol does
13920          not affect compatibility.  */
13921       if ((sec->flags & SEC_IS_COMMON) == 0
13922           && strcmp (sec->name, ".reginfo")
13923           && strcmp (sec->name, ".mdebug")
13924           && (sec->size != 0
13925               || (strcmp (sec->name, ".text")
13926                   && strcmp (sec->name, ".data")
13927                   && strcmp (sec->name, ".bss"))))
13928         {
13929           null_input_bfd = FALSE;
13930           break;
13931         }
13932     }
13933   if (null_input_bfd)
13934     return TRUE;
13935
13936   ok = TRUE;
13937
13938   if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)
13939       != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0))
13940     {
13941       (*_bfd_error_handler)
13942         (_("%B: warning: linking abicalls files with non-abicalls files"),
13943          ibfd);
13944       ok = TRUE;
13945     }
13946
13947   if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC))
13948     elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC;
13949   if (! (new_flags & EF_MIPS_PIC))
13950     elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC;
13951
13952   new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13953   old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC);
13954
13955   /* Compare the ISAs.  */
13956   if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags))
13957     {
13958       (*_bfd_error_handler)
13959         (_("%B: linking 32-bit code with 64-bit code"),
13960          ibfd);
13961       ok = FALSE;
13962     }
13963   else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd)))
13964     {
13965       /* OBFD's ISA isn't the same as, or an extension of, IBFD's.  */
13966       if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd)))
13967         {
13968           /* Copy the architecture info from IBFD to OBFD.  Also copy
13969              the 32-bit flag (if set) so that we continue to recognise
13970              OBFD as a 32-bit binary.  */
13971           bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd));
13972           elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH);
13973           elf_elfheader (obfd)->e_flags
13974             |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13975
13976           /* Copy across the ABI flags if OBFD doesn't use them
13977              and if that was what caused us to treat IBFD as 32-bit.  */
13978           if ((old_flags & EF_MIPS_ABI) == 0
13979               && mips_32bit_flags_p (new_flags)
13980               && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI))
13981             elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI;
13982         }
13983       else
13984         {
13985           /* The ISAs aren't compatible.  */
13986           (*_bfd_error_handler)
13987             (_("%B: linking %s module with previous %s modules"),
13988              ibfd,
13989              bfd_printable_name (ibfd),
13990              bfd_printable_name (obfd));
13991           ok = FALSE;
13992         }
13993     }
13994
13995   new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13996   old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE);
13997
13998   /* Compare ABIs.  The 64-bit ABI does not use EF_MIPS_ABI.  But, it
13999      does set EI_CLASS differently from any 32-bit ABI.  */
14000   if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI)
14001       || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14002           != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14003     {
14004       /* Only error if both are set (to different values).  */
14005       if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI))
14006           || (elf_elfheader (ibfd)->e_ident[EI_CLASS]
14007               != elf_elfheader (obfd)->e_ident[EI_CLASS]))
14008         {
14009           (*_bfd_error_handler)
14010             (_("%B: ABI mismatch: linking %s module with previous %s modules"),
14011              ibfd,
14012              elf_mips_abi_name (ibfd),
14013              elf_mips_abi_name (obfd));
14014           ok = FALSE;
14015         }
14016       new_flags &= ~EF_MIPS_ABI;
14017       old_flags &= ~EF_MIPS_ABI;
14018     }
14019
14020   /* Compare ASEs.  Forbid linking MIPS16 and microMIPS ASE modules together
14021      and allow arbitrary mixing of the remaining ASEs (retain the union).  */
14022   if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE))
14023     {
14024       int old_micro = old_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14025       int new_micro = new_flags & EF_MIPS_ARCH_ASE_MICROMIPS;
14026       int old_m16 = old_flags & EF_MIPS_ARCH_ASE_M16;
14027       int new_m16 = new_flags & EF_MIPS_ARCH_ASE_M16;
14028       int micro_mis = old_m16 && new_micro;
14029       int m16_mis = old_micro && new_m16;
14030
14031       if (m16_mis || micro_mis)
14032         {
14033           (*_bfd_error_handler)
14034             (_("%B: ASE mismatch: linking %s module with previous %s modules"),
14035              ibfd,
14036              m16_mis ? "MIPS16" : "microMIPS",
14037              m16_mis ? "microMIPS" : "MIPS16");
14038           ok = FALSE;
14039         }
14040
14041       elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE;
14042
14043       new_flags &= ~ EF_MIPS_ARCH_ASE;
14044       old_flags &= ~ EF_MIPS_ARCH_ASE;
14045     }
14046
14047   /* Warn about any other mismatches */
14048   if (new_flags != old_flags)
14049     {
14050       (*_bfd_error_handler)
14051         (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"),
14052          ibfd, (unsigned long) new_flags,
14053          (unsigned long) old_flags);
14054       ok = FALSE;
14055     }
14056
14057   if (! ok)
14058     {
14059       bfd_set_error (bfd_error_bad_value);
14060       return FALSE;
14061     }
14062
14063   return TRUE;
14064 }
14065
14066 /* Function to keep MIPS specific file flags like as EF_MIPS_PIC.  */
14067
14068 bfd_boolean
14069 _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags)
14070 {
14071   BFD_ASSERT (!elf_flags_init (abfd)
14072               || elf_elfheader (abfd)->e_flags == flags);
14073
14074   elf_elfheader (abfd)->e_flags = flags;
14075   elf_flags_init (abfd) = TRUE;
14076   return TRUE;
14077 }
14078
14079 char *
14080 _bfd_mips_elf_get_target_dtag (bfd_vma dtag)
14081 {
14082   switch (dtag)
14083     {
14084     default: return "";
14085     case DT_MIPS_RLD_VERSION:
14086       return "MIPS_RLD_VERSION";
14087     case DT_MIPS_TIME_STAMP:
14088       return "MIPS_TIME_STAMP";
14089     case DT_MIPS_ICHECKSUM:
14090       return "MIPS_ICHECKSUM";
14091     case DT_MIPS_IVERSION:
14092       return "MIPS_IVERSION";
14093     case DT_MIPS_FLAGS:
14094       return "MIPS_FLAGS";
14095     case DT_MIPS_BASE_ADDRESS:
14096       return "MIPS_BASE_ADDRESS";
14097     case DT_MIPS_MSYM:
14098       return "MIPS_MSYM";
14099     case DT_MIPS_CONFLICT:
14100       return "MIPS_CONFLICT";
14101     case DT_MIPS_LIBLIST:
14102       return "MIPS_LIBLIST";
14103     case DT_MIPS_LOCAL_GOTNO:
14104       return "MIPS_LOCAL_GOTNO";
14105     case DT_MIPS_CONFLICTNO:
14106       return "MIPS_CONFLICTNO";
14107     case DT_MIPS_LIBLISTNO:
14108       return "MIPS_LIBLISTNO";
14109     case DT_MIPS_SYMTABNO:
14110       return "MIPS_SYMTABNO";
14111     case DT_MIPS_UNREFEXTNO:
14112       return "MIPS_UNREFEXTNO";
14113     case DT_MIPS_GOTSYM:
14114       return "MIPS_GOTSYM";
14115     case DT_MIPS_HIPAGENO:
14116       return "MIPS_HIPAGENO";
14117     case DT_MIPS_RLD_MAP:
14118       return "MIPS_RLD_MAP";
14119     case DT_MIPS_DELTA_CLASS:
14120       return "MIPS_DELTA_CLASS";
14121     case DT_MIPS_DELTA_CLASS_NO:
14122       return "MIPS_DELTA_CLASS_NO";
14123     case DT_MIPS_DELTA_INSTANCE:
14124       return "MIPS_DELTA_INSTANCE";
14125     case DT_MIPS_DELTA_INSTANCE_NO:
14126       return "MIPS_DELTA_INSTANCE_NO";
14127     case DT_MIPS_DELTA_RELOC:
14128       return "MIPS_DELTA_RELOC";
14129     case DT_MIPS_DELTA_RELOC_NO:
14130       return "MIPS_DELTA_RELOC_NO";
14131     case DT_MIPS_DELTA_SYM:
14132       return "MIPS_DELTA_SYM";
14133     case DT_MIPS_DELTA_SYM_NO:
14134       return "MIPS_DELTA_SYM_NO";
14135     case DT_MIPS_DELTA_CLASSSYM:
14136       return "MIPS_DELTA_CLASSSYM";
14137     case DT_MIPS_DELTA_CLASSSYM_NO:
14138       return "MIPS_DELTA_CLASSSYM_NO";
14139     case DT_MIPS_CXX_FLAGS:
14140       return "MIPS_CXX_FLAGS";
14141     case DT_MIPS_PIXIE_INIT:
14142       return "MIPS_PIXIE_INIT";
14143     case DT_MIPS_SYMBOL_LIB:
14144       return "MIPS_SYMBOL_LIB";
14145     case DT_MIPS_LOCALPAGE_GOTIDX:
14146       return "MIPS_LOCALPAGE_GOTIDX";
14147     case DT_MIPS_LOCAL_GOTIDX:
14148       return "MIPS_LOCAL_GOTIDX";
14149     case DT_MIPS_HIDDEN_GOTIDX:
14150       return "MIPS_HIDDEN_GOTIDX";
14151     case DT_MIPS_PROTECTED_GOTIDX:
14152       return "MIPS_PROTECTED_GOT_IDX";
14153     case DT_MIPS_OPTIONS:
14154       return "MIPS_OPTIONS";
14155     case DT_MIPS_INTERFACE:
14156       return "MIPS_INTERFACE";
14157     case DT_MIPS_DYNSTR_ALIGN:
14158       return "DT_MIPS_DYNSTR_ALIGN";
14159     case DT_MIPS_INTERFACE_SIZE:
14160       return "DT_MIPS_INTERFACE_SIZE";
14161     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
14162       return "DT_MIPS_RLD_TEXT_RESOLVE_ADDR";
14163     case DT_MIPS_PERF_SUFFIX:
14164       return "DT_MIPS_PERF_SUFFIX";
14165     case DT_MIPS_COMPACT_SIZE:
14166       return "DT_MIPS_COMPACT_SIZE";
14167     case DT_MIPS_GP_VALUE:
14168       return "DT_MIPS_GP_VALUE";
14169     case DT_MIPS_AUX_DYNAMIC:
14170       return "DT_MIPS_AUX_DYNAMIC";
14171     case DT_MIPS_PLTGOT:
14172       return "DT_MIPS_PLTGOT";
14173     case DT_MIPS_RWPLT:
14174       return "DT_MIPS_RWPLT";
14175     }
14176 }
14177
14178 bfd_boolean
14179 _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr)
14180 {
14181   FILE *file = ptr;
14182
14183   BFD_ASSERT (abfd != NULL && ptr != NULL);
14184
14185   /* Print normal ELF private data.  */
14186   _bfd_elf_print_private_bfd_data (abfd, ptr);
14187
14188   /* xgettext:c-format */
14189   fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
14190
14191   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32)
14192     fprintf (file, _(" [abi=O32]"));
14193   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64)
14194     fprintf (file, _(" [abi=O64]"));
14195   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32)
14196     fprintf (file, _(" [abi=EABI32]"));
14197   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64)
14198     fprintf (file, _(" [abi=EABI64]"));
14199   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI))
14200     fprintf (file, _(" [abi unknown]"));
14201   else if (ABI_N32_P (abfd))
14202     fprintf (file, _(" [abi=N32]"));
14203   else if (ABI_64_P (abfd))
14204     fprintf (file, _(" [abi=64]"));
14205   else
14206     fprintf (file, _(" [no abi set]"));
14207
14208   if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1)
14209     fprintf (file, " [mips1]");
14210   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2)
14211     fprintf (file, " [mips2]");
14212   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3)
14213     fprintf (file, " [mips3]");
14214   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4)
14215     fprintf (file, " [mips4]");
14216   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5)
14217     fprintf (file, " [mips5]");
14218   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32)
14219     fprintf (file, " [mips32]");
14220   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64)
14221     fprintf (file, " [mips64]");
14222   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2)
14223     fprintf (file, " [mips32r2]");
14224   else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2)
14225     fprintf (file, " [mips64r2]");
14226   else
14227     fprintf (file, _(" [unknown ISA]"));
14228
14229   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX)
14230     fprintf (file, " [mdmx]");
14231
14232   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16)
14233     fprintf (file, " [mips16]");
14234
14235   if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MICROMIPS)
14236     fprintf (file, " [micromips]");
14237
14238   if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE)
14239     fprintf (file, " [32bitmode]");
14240   else
14241     fprintf (file, _(" [not 32bitmode]"));
14242
14243   if (elf_elfheader (abfd)->e_flags & EF_MIPS_NOREORDER)
14244     fprintf (file, " [noreorder]");
14245
14246   if (elf_elfheader (abfd)->e_flags & EF_MIPS_PIC)
14247     fprintf (file, " [PIC]");
14248
14249   if (elf_elfheader (abfd)->e_flags & EF_MIPS_CPIC)
14250     fprintf (file, " [CPIC]");
14251
14252   if (elf_elfheader (abfd)->e_flags & EF_MIPS_XGOT)
14253     fprintf (file, " [XGOT]");
14254
14255   if (elf_elfheader (abfd)->e_flags & EF_MIPS_UCODE)
14256     fprintf (file, " [UCODE]");
14257
14258   fputc ('\n', file);
14259
14260   return TRUE;
14261 }
14262
14263 const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] =
14264 {
14265   { STRING_COMMA_LEN (".lit4"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14266   { STRING_COMMA_LEN (".lit8"),   0, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14267   { STRING_COMMA_LEN (".mdebug"), 0, SHT_MIPS_DEBUG, 0 },
14268   { STRING_COMMA_LEN (".sbss"),  -2, SHT_NOBITS,     SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14269   { STRING_COMMA_LEN (".sdata"), -2, SHT_PROGBITS,   SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL },
14270   { STRING_COMMA_LEN (".ucode"),  0, SHT_MIPS_UCODE, 0 },
14271   { NULL,                     0,  0, 0,              0 }
14272 };
14273
14274 /* Merge non visibility st_other attributes.  Ensure that the
14275    STO_OPTIONAL flag is copied into h->other, even if this is not a
14276    definiton of the symbol.  */
14277 void
14278 _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h,
14279                                       const Elf_Internal_Sym *isym,
14280                                       bfd_boolean definition,
14281                                       bfd_boolean dynamic ATTRIBUTE_UNUSED)
14282 {
14283   if ((isym->st_other & ~ELF_ST_VISIBILITY (-1)) != 0)
14284     {
14285       unsigned char other;
14286
14287       other = (definition ? isym->st_other : h->other);
14288       other &= ~ELF_ST_VISIBILITY (-1);
14289       h->other = other | ELF_ST_VISIBILITY (h->other);
14290     }
14291
14292   if (!definition
14293       && ELF_MIPS_IS_OPTIONAL (isym->st_other))
14294     h->other |= STO_OPTIONAL;
14295 }
14296
14297 /* Decide whether an undefined symbol is special and can be ignored.
14298    This is the case for OPTIONAL symbols on IRIX.  */
14299 bfd_boolean
14300 _bfd_mips_elf_ignore_undef_symbol (struct elf_link_hash_entry *h)
14301 {
14302   return ELF_MIPS_IS_OPTIONAL (h->other) ? TRUE : FALSE;
14303 }
14304
14305 bfd_boolean
14306 _bfd_mips_elf_common_definition (Elf_Internal_Sym *sym)
14307 {
14308   return (sym->st_shndx == SHN_COMMON
14309           || sym->st_shndx == SHN_MIPS_ACOMMON
14310           || sym->st_shndx == SHN_MIPS_SCOMMON);
14311 }
14312
14313 /* Return address for Ith PLT stub in section PLT, for relocation REL
14314    or (bfd_vma) -1 if it should not be included.  */
14315
14316 bfd_vma
14317 _bfd_mips_elf_plt_sym_val (bfd_vma i, const asection *plt,
14318                            const arelent *rel ATTRIBUTE_UNUSED)
14319 {
14320   return (plt->vma
14321           + 4 * ARRAY_SIZE (mips_o32_exec_plt0_entry)
14322           + i * 4 * ARRAY_SIZE (mips_exec_plt_entry));
14323 }
14324
14325 void
14326 _bfd_mips_post_process_headers (bfd *abfd, struct bfd_link_info *link_info)
14327 {
14328   struct mips_elf_link_hash_table *htab;
14329   Elf_Internal_Ehdr *i_ehdrp;
14330
14331   i_ehdrp = elf_elfheader (abfd);
14332   if (link_info)
14333     {
14334       htab = mips_elf_hash_table (link_info);
14335       BFD_ASSERT (htab != NULL);
14336
14337       if (htab->use_plts_and_copy_relocs && !htab->is_vxworks)
14338         i_ehdrp->e_ident[EI_ABIVERSION] = 1;
14339     }
14340 }